text stringlengths 14 6.51M |
|---|
unit RenderEnvironment;
interface
uses Windows, Graphics, dglOpenGL, BasicMathsTypes, BasicRenderingTypes, Camera, SysUtils,
Model, Actor, BasicFunctions, JPEG, PNGImage, GIFImage, FTGifAnimate, DDS,
ShaderBank;
{$INCLUDE source/Global_Conditionals.inc}
type
PRenderEnvironment = ^TRenderEnvironment;
TRenderEnvironment = class
private
// Rendering
FUpdateWorld : boolean;
// Constructors and destructors.
procedure CleanUpCameras;
procedure CleanUpActors;
procedure CleanUpVariableNames;
// Screenshot
procedure MakeMeAScreenshotName(var Filename: string; Ext : string);
procedure ScreenshotJPG(const _Filename: string; _Compression: integer);
procedure ScreenShotPNG(const _Filename : string; _Compression: integer);
procedure ScreenShotTGA(const _Filename : string);
procedure ScreenShotBMP(const _Filename : string);
procedure ScreenShotGIF(_GIFImage : TGIFImage; const _Filename : string);
procedure ScreenShotDDS(const _Filename : string);
// procedure ScreenShotViaGl2PS(const _FileName,_Ext: String; OutputType: GLInt);
public
Next : PRenderEnvironment;
ActorList: PActor;
CameraList : PCamera;
CurrentActor : PActor;
CurrentCamera : PCamera;
Handle : THandle;
DC : HDC;
RC: HGLRC;
// Font related
FontListBase : GLuint;
// Common Multipliers
Width : longword;
Height: longword;
// Time
FFrequency : int64;
FoldTime : int64;
DesiredTimeRate : int64;
// Colours
BackgroundColour,FontColour : TVector3f;
// Counters
FPS : single;
// Rendering display text
RenderingVariableNames: array of string;
RenderingVariableValues: array of string;
// Debug related.
ShowDepth, ShowSpeed, ShowPolyCount, ShowRotations : boolean;
IsEnabled : boolean;
PolygonMode: integer;
IsBackFaceCullingEnabled: boolean;
// Screenshot & Animation related.
ScreenTexture : cardinal;
ScreenType : TScreenshotType;
ScreenshotCompression: integer;
ScreenFilename: string;
AnimFrameCounter: integer;
AnimFrameMax : integer;
AnimFrameTime: integer; // in centiseconds.
NonScreenCamera : PCamera;
// Ambient Lighting
LightAmb : TVector4f;
LightDif : TVector4f;
// Shaders
ShaderBank : TShaderBank;
// Constructors;
constructor Create(_Handle : THandle; _FirstRC: HGLRC; _width, _height : longword; const _ShaderDirectory: string);
destructor Destroy; override;
// Renders and Related
procedure Render;
procedure RenderVectorial;
procedure DrawCacheTexture(Texture : Cardinal; X,Y : Single; Width,Height,AWidth,AHeight : Cardinal; XOff : Cardinal = 0; YOff : Cardinal = 0; XOffWidth : Cardinal = Cardinal(-1); YOffHeight : Cardinal = Cardinal(-1));
procedure Resize(_width, _height: longword);
procedure RenderNormals;
procedure RenderColours;
procedure ForceRefresh;
procedure ForceRefreshActors;
procedure SetIsEnabled(_value: boolean);
procedure EnableBackFaceCulling(_value: boolean);
// Adds
function AddCamera: PCamera;
function AddActor: PActor;
procedure AddRenderingVariable(const _Name, _Value: string);
procedure RemoveCamera(var _Camera : PCamera);
procedure RemoveActor(var _Actor : PActor);
// Shader related
function IsShaderEnabled: boolean;
procedure EnableShaders(_value: boolean);
// Miscelaneuos Text Related
procedure BuildFont;
procedure KillFont;
procedure glPrint(_text : pchar);
procedure SetBackgroundColour(const _Colour: TVector3f); overload;
procedure SetBackgroundColour(const _Colour: TColor); overload;
procedure SetFontColour(const _Colour: TVector3f);
procedure SetPolygonMode(const _value: integer);
// Screenshot related
function GetScreenShot : TBitmap;
procedure TakeScreenshot(const _Filename: string; _type: TScreenshotType; _Compression: integer = 0);
procedure TakeAnimation(const _Filename: string; _NumFrames, _FrameDelay: integer; _type: TScreenshotType);
procedure Take360Animation(const _Filename: string; _NumFrames, _FrameDelay: integer; _type: TScreenshotType);
procedure StartAnimation;
procedure AddFrame;
procedure FinishAnimation;
function IsScreenshoting: boolean;
end;
implementation
{$ifdef TEXTURE_DEBUG}
uses FormMain;
{$endif}
uses Math3d;
// Constructors;
constructor TRenderEnvironment.Create(_Handle: Cardinal; _FirstRC: HGLRC; _width, _height : longword; const _ShaderDirectory: string);
begin
// The basics, to avoid memory issues.
Next := nil;
IsEnabled := false;
// Environment colours.
BackGroundColour := SetVector(0.549,0.666,0.921); // RGB(140,170,235)
FontColour := SetVector(1,1,1);
// Setup rendering context.
Handle := _Handle;
DC := GetDC(Handle);
RC := CreateRenderingContext(DC,[opDoubleBuffered],32,24,0,0,0,0);
if _FirstRC <> 0 then
wglShareLists(_FirstRC,RC);
ActivateRenderingContext(DC, RC);
// Load shaders
wglMakeCurrent(dc,rc); // Make the DC the rendering Context
ShaderBank := TShaderBank.Create(_ShaderDirectory);
// Setup GL settings
// glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glClearColor(BackGroundColour.X, BackGroundColour.Y, BackGroundColour.Z, 1.0);
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glClearDepth(1.0); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enable Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //Realy Nice perspective calculations
PolygonMode := GL_FILL;
// Build font
BuildFont;
glCullFace(GL_BACK);
IsBackFaceCullingEnabled := false;
// Setup camera.
CameraList := nil;
AddCamera;
// Start without models
ActorList := nil;
// Setup time.
QueryPerformanceFrequency(FFrequency); // get high-resolution Frequency
QueryPerformanceCounter(FoldTime);
DesiredTimeRate := 0;
// Lighting settings
LightAmb := SetVector4f(134/255, 134/255, 134/255, 1.0);
LightDif := SetVector4f(172/255, 172/255, 172/255, 1.0);
wglSwapIntervalEXT(0);
// Prepare screenshot variables.
ScreenTexture := 0;
AnimFrameCounter := 0;
AnimFrameMax := 0;
AnimFrameTime := 3; //about 30fps.
// Setup perspective and text settings.
Resize(_width,_height);
ShowDepth := true;
ShowSpeed := true;
ShowPolyCount := true;
ShowRotations := false;
// The render is ready to work.
IsEnabled := true;
end;
destructor TRenderEnvironment.Destroy;
begin
IsEnabled := false;
KillFont;
CleanUpActors;
CleanUpCameras;
CleanUpVariableNames;
ShaderBank.Free;
DeactivateRenderingContext;
wglDeleteContext(rc);
ReleaseDC(Handle, DC);
inherited Destroy;
end;
procedure TRenderEnvironment.CleanUpCameras;
var
MyCamera,NextCamera : PCamera;
begin
MyCamera := CameraList;
while MyCamera <> nil do
begin
NextCamera := MyCamera^.Next;
RemoveCamera(MyCamera);
MyCamera := NextCamera;
end;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.CleanUpActors;
var
MyActor,NextActor : PActor;
begin
MyActor := ActorList;
while MyActor <> nil do
begin
NextActor := MyActor^.Next;
RemoveActor(MyActor);
MyActor := NextActor;
end;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.CleanUpVariableNames;
var
i: integer;
begin
for i := Low(RenderingVariableNames) to High(RenderingVariableNames) do
begin
RenderingVariableNames[i] := '';
RenderingVariableValues[i] := '';
end;
SetLength(RenderingVariableNames, 0);
SetLength(RenderingVariableValues, 0);
end;
// Renders
procedure TRenderEnvironment.Render;
var
temp : int64;
t2 : double;
i: integer;
Actor : PActor;
VariableText: string;
begin
// Here's the don't waste time checkup.
if not IsEnabled then exit;
if CurrentCamera = nil then exit;
// Get time before rendering scene.
QueryPerformanceCounter(FoldTime);
// Make the DC the rendering Context
wglMakeCurrent(dc,rc);
// Rendering starts here
// -------------------------------------------------------
// Clear The Screen And The Depth Buffer
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glClearColor(BackGroundColour.X, BackGroundColour.Y, BackGroundColour.Z, 1.0);
if IsBackFaceCullingEnabled then
begin
glEnable(GL_CULL_FACE);
end
else
begin
glDisable(GL_CULL_FACE);
end;
glMatrixMode(GL_MODELVIEW);
// Process Camera
CurrentCamera^.ProcessNextFrame;
FUpdateWorld := FUpdateWorld or CurrentCamera^.GetRequestUpdateWorld;
// Process Actors
Actor := ActorList;
while Actor <> nil do
begin
Actor^.ProcessNextFrame;
FUpdateWorld := FUpdateWorld or Actor^.GetRequestUpdateWorld;
Actor := Actor^.Next;
end;
// Enable Lighting.
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, @LightAmb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, @LightDif);
if FUpdateWorld then
begin
glPolygonMode(GL_FRONT_AND_BACK,PolygonMode);
FUpdateWorld := false;
CurrentCamera^.MoveCamera;
CurrentCamera^.RotateCamera;
// Render all models.
Actor := ActorList;
while Actor <> nil do
begin
Actor^.Render();
Actor := Actor^.Next;
end;
glColor4f(1,1,1,0);
glNormal3f(0,0,0);
// Here we cache the existing scene in a texture.
glEnable(GL_TEXTURE_2D);
if ScreenTexture <> 0 then
glDeleteTextures(1,@ScreenTexture);
glGenTextures(1, @ScreenTexture);
{$ifdef TEXTURE_DEBUG}
FrmMain.DebugFile.Add('Render Environment: ' + IntToStr(Cardinal(Addr(ScreenTexture))) + ', Handle: ' + IntToStr(Handle) + ', ScreenTexture ID: ' + IntToStr(ScreenTexture));
{$endif}
glBindTexture(GL_TEXTURE_2D, ScreenTexture);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, GetPow2Size(Width),GetPow2Size(Height), 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glDisable(GL_TEXTURE_2D);
// End of texture caching.
end;
glLoadIdentity;
// Final rendering part.
glDisable(GL_LIGHT0);
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glDisable(GL_CULL_FACE);
glPushMatrix;
glLoadIdentity;
glOrtho(0, Width, 0, Height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadIdentity;
// Draw texture caching.
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glEnable(GL_TEXTURE_2D);
glColor4f(1,1,1,0);
DrawCacheTexture(ScreenTexture,0,0,Width,Height,GetPow2Size(Width),GetPow2Size(Height));
glDisable(GL_TEXTURE_2D);
// End of draw texture caching.
// Are we screenshoting?
if AnimFrameMax = 0 then
begin
glColor4f(FontColour.X, FontColour.Y, FontColour.Z,1);
// No, we are not screenshoting, so show normal stats.
glRasterPos2i(1, 2);
VariableText := '';
if High(RenderingVariableNames) >= 0 then
begin
for i := Low(RenderingVariableNames) to 0 do
begin
VariableText := VariableText + RenderingVariableNames[i] + ': ' + RenderingVariableValues[i];
end;
for i := 1 to High(RenderingVariableNames) do
begin
VariableText := VariableText + ' - ' + RenderingVariableNames[i] + ': ' + RenderingVariableValues[i];
end;
end;
glPrint(PChar(VariableText));
if (ShowDepth) then
begin
glRasterPos2i(1, 13);
glPrint(PChar('Depth: ' + IntToStr(trunc(CurrentCamera^.Position.Z))));
end;
if (ShowSpeed) then
begin
glRasterPos2i(1, Height - 9);
glPrint(PChar('FPS: ' + IntToStr(trunc(FPS))));
end;
if ShowRotations then
begin
glRasterPos2i(1, Height - 19);
glPrint(PChar('Camera - XRot:' + floattostr(CurrentCamera^.Rotation.X) + ' YRot:' + floattostr(CurrentCamera^.Rotation.Y) + ' ZRot:' + floattostr(CurrentCamera^.Rotation.Z)));
end;
end
else // We are screenshoting!
begin
// Let's check if the animation is over or not.
if AnimFrameCounter < AnimFrameMax then
begin
// We are still animating. Simply add the frame.
AddFrame;
inc(AnimFrameCounter);
end
else
begin
// Reset animation variables.
AnimFrameCounter := 0;
AnimFrameMax := 0;
// Animation is over. Let's conclude the movie.
FinishAnimation;
end;
end;
glMatrixMode(GL_PROJECTION);
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
glEnable(GL_DEPTH_TEST);
// Rendering starts here
// -------------------------------------------------------
SwapBuffers(DC); // Display the scene
// Calculate time and FPS
QueryPerformanceCounter(temp);
t2 := temp - FoldTime;
if DesiredTimeRate > 0 then
begin
if t2 < DesiredTimeRate then
begin
sleep(Round(1000 * (DesiredTimeRate - t2) / FFrequency));
QueryPerformanceCounter(temp);
t2 := temp - FoldTime;
end;
end;
FPS := FFrequency/t2;
end;
procedure TRenderEnvironment.RenderVectorial;
var
Actor : PActor;
begin
if CurrentCamera = nil then exit;
wglMakeCurrent(dc,rc); // Make the DC the rendering Context
glActiveTexture(GL_TEXTURE0);
glDisable(GL_TEXTURE_2D);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glClearColor(BackGroundColour.X, BackGroundColour.Y, BackGroundColour.Z, 1.0);
glDisable(GL_CULL_FACE);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
// Enable Lighting.
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, @LightAmb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, @LightDif);
glPolygonMode(GL_FRONT_AND_BACK,PolygonMode);
CurrentCamera^.MoveCamera;
CurrentCamera^.RotateCamera;
// Render all models.
Actor := ActorList;
while Actor <> nil do
begin
Actor^.RenderVectorial();
Actor := Actor^.Next;
end;
// Final rendering part.
glDisable(GL_LIGHT0);
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
// Rendering starts here
// -------------------------------------------------------
SwapBuffers(DC); // Display the scene
end;
// Borrowed from OS: Voxel Viewer 1.80+, coded by Stucuk.
procedure TRenderEnvironment.DrawCacheTexture(Texture : Cardinal; X,Y : Single; Width,Height,AWidth,AHeight : Cardinal; XOff : Cardinal = 0; YOff : Cardinal = 0; XOffWidth : Cardinal = Cardinal(-1); YOffHeight : Cardinal = Cardinal(-1));
var
TexCoordX,
TexCoordY,
TexCoordOffX,
TexCoordOffY : Single;
begin
if XOffWidth = Cardinal(-1) then
XOffWidth := Width;
if YOffHeight = Cardinal(-1) then
YOffHeight := Height;
TexCoordX := XOffWidth/AWidth;
TexCoordY := YOffHeight/AHeight;
TexCoordOffX := XOff/AWidth;
TexCoordOffY := YOff/AHeight;
glBindTexture(GL_TEXTURE_2D, Texture);
glBegin(GL_QUADS);
//1
glTexCoord2f(TexCoordOffX, TexCoordOffY);
glVertex2f(X, Y);
//2
glTexCoord2f(TexCoordOffX+TexCoordX, TexCoordOffY);
glVertex2f(X+Width, Y);
//3
glTexCoord2f(TexCoordOffX+TexCoordX, TexCoordOffY+TexCoordY);
glVertex2f(X+Width, Y+Height);
//4
glTexCoord2f(TexCoordOffX, TexCoordOffY+TexCoordY);
glVertex2f(X, Y+Height);
glEnd;
end;
procedure TRenderEnvironment.Resize(_width, _height: longword);
begin
wglMakeCurrent(dc,rc); // Make the DC the rendering Context
Width := _Width;
Height := _Height;
if Height = 0 then // prevent divide by zero exception
Height := 1;
glViewport(0, 0, Width, Height); // Set the viewport for the OpenGL window
glMatrixMode(GL_PROJECTION); // Change Matrix Mode to Projection
glLoadIdentity(); // Reset View
gluPerspective(45.0, Width/Height, 1.0, 4000.0); // Do the perspective calculations. Last value = max clipping depth
glMatrixMode(GL_MODELVIEW); // Return to the modelview matrix
FUpdateWorld := true;
end;
procedure TRenderEnvironment.RenderNormals;
var
Actor : PActor;
begin
Actor := ActorList;
while Actor <> nil do
begin
Actor^.SetNormalsModeRendering;
Actor := Actor^.Next;
end;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.RenderColours;
var
Actor : PActor;
begin
Actor := ActorList;
while Actor <> nil do
begin
Actor^.SetColourModeRendering;
Actor := Actor^.Next;
end;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.ForceRefresh;
begin
FUpdateWorld := true;
end;
procedure TRenderEnvironment.ForceRefreshActors;
var
Actor : PActor;
begin
Actor := ActorList;
while Actor <> nil do
begin
Actor^.Refresh;
Actor := Actor^.Next;
end;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.SetIsEnabled(_value: boolean);
begin
IsEnabled := _value;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.EnableBackFaceCulling(_value: boolean);
begin
IsBackFaceCullingEnabled := _value;
// Due to texture caching, the background colour will only update in the second
// render.
FUpdateWorld := true;
Render;
FUpdateWorld := true;
end;
// Adds
function TRenderEnvironment.AddCamera: PCamera;
var
NewCamera,PreviousCamera : PCamera;
begin
new(NewCamera);
NewCamera^ := TCamera.Create;
if CameraList = nil then
begin
CameraList := NewCamera;
end
else
begin
PreviousCamera := CameraList;
while PreviousCamera^.Next <> nil do
PreviousCamera := PreviousCamera^.Next;
PreviousCamera^.Next := NewCamera;
end;
CurrentCamera := NewCamera;
Result := NewCamera;
FUpdateWorld := true;
end;
function TRenderEnvironment.AddActor: PActor;
var
NewActor,PreviousActor : PActor;
begin
new(NewActor);
NewActor^ := TActor.Create(Addr(ShaderBank));
if ActorList = nil then
begin
ActorList := NewActor;
end
else
begin
PreviousActor := ActorList;
while PreviousActor^.Next <> nil do
PreviousActor := PreviousActor^.Next;
PreviousActor^.Next := NewActor;
end;
CurrentActor := NewActor;
Result := NewActor;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.AddRenderingVariable(const _Name, _Value: string);
begin
SetLength(RenderingVariableNames, High(RenderingVariableNames) + 2);
SetLength(RenderingVariableValues, High(RenderingVariableNames) + 1);
RenderingVariableNames[High(RenderingVariableNames)] := copyString(_Name);
RenderingVariableValues[High(RenderingVariableNames)] := copyString(_Value);
end;
// Removes
procedure TRenderEnvironment.RemoveCamera(var _Camera : PCamera);
var
PreviousCamera : PCamera;
begin
if CameraList = nil then exit; // Can't delete from an empty list.
if _Camera <> nil then
begin
// Check if it is the first camera.
if _Camera = CameraList then
begin
CameraList := _Camera^.Next;
end
else // It could be inside the list, but it's not the first.
begin
PreviousCamera := CameraList;
while (PreviousCamera^.Next <> nil) and (PreviousCamera^.Next <> _Camera) do
begin
PreviousCamera := PreviousCamera^.Next;
end;
if PreviousCamera^.Next = _Camera then
begin
PreviousCamera^.Next := _Camera^.Next;
end
else // nil -- not from this list.
exit;
end;
// If it has past this stage, the camera is valid and was part of the list.
// Now we dispose the camera.
_Camera^.Free;
// Now let's unlink other variables.
if CurrentCamera = _Camera then
CurrentCamera := CameraList;
FUpdateWorld := true;
end;
end;
procedure TRenderEnvironment.RemoveActor(var _Actor : PActor);
var
PreviousActor : PActor;
begin
if ActorList = nil then exit; // Can't delete from an empty list.
if _Actor <> nil then
begin
// Check if it is the first actor.
if _Actor = ActorList then
begin
ActorList := _Actor^.Next;
end
else // It could be inside the list, but it's not the first.
begin
PreviousActor := ActorList;
while (PreviousActor^.Next <> nil) and (PreviousActor^.Next <> _Actor) do
begin
PreviousActor := PreviousActor^.Next;
end;
if PreviousActor^.Next = _Actor then
begin
PreviousActor^.Next := _Actor^.Next;
end
else // nil -- not from this list.
exit;
end;
// If it has past this stage, the camera is valid and was part of the list.
// Now we dispose the actor.
_Actor^.Free;
// Now let's unlink other variables.
if CurrentActor = _Actor then
CurrentActor := ActorList;
FUpdateWorld := true;
end;
end;
// Miscelaneous Text Related
procedure TRenderEnvironment.BuildFont; // Build Our Bitmap Font
var
font: HFONT; // Windows Font ID
begin
FontListBase := glGenLists(256); // Storage For 96 Characters
glColor3f(FontColour.X,FontColour.Y,FontColour.Z);
font := CreateFont(9, 0,0,0, FW_NORMAL, 0, 0, 0, OEM_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY , FF_DONTCARE + DEFAULT_PITCH, 'Terminal');
SelectObject(DC, font);
wglUseFontBitmaps(DC, 0, 127, FontListBase);
end;
procedure TRenderEnvironment.KillFont; // Delete The Font
begin
glDeleteLists(FontListBase, 256); // Delete All 96 Characters
end;
procedure TRenderEnvironment.glPrint(_text : pchar); // Custom GL "Print" Routine
begin
if (_Text = '') then // If There's No Text
Exit; // Do Nothing
glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits
glListBase(FontListBase); // Sets The Base Character
glColor3f(FontColour.X,FontColour.Y,FontColour.Z);
glCallLists(length(_Text), GL_UNSIGNED_BYTE, _Text); // Draws The Display List Text
glPopAttrib(); // Pops The Display List Bits
end;
procedure TRenderEnvironment.SetBackgroundColour(const _Colour: TVector3f);
begin
BackgroundColour.X := _Colour.X;
BackgroundColour.Y := _Colour.Y;
BackgroundColour.Z := _Colour.Z;
// Due to texture caching, the background colour will only update in the second
// render.
FUpdateWorld := true;
Render;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.SetBackgroundColour(const _Colour: TColor);
begin
BackgroundColour.X := (_Colour and $FF) / 255;
BackgroundColour.Y := ((_Colour shr 8) and $FF) / 255;
BackgroundColour.Z := ((_Colour shr 16) and $FF) / 255;
// Due to texture caching, the background colour will only update in the second
// render.
FUpdateWorld := true;
Render;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.SetFontColour(const _Colour: TVector3f);
begin
FontColour.X := _Colour.X;
FontColour.Y := _Colour.Y;
FontColour.Z := _Colour.Z;
KillFont;
BuildFont;
// Due to texture caching, the background colour will only update in the second
// render.
FUpdateWorld := true;
Render;
FUpdateWorld := true;
end;
procedure TRenderEnvironment.SetPolygonMode(const _value: integer);
begin
PolygonMode := _Value;
// Due to texture caching, the background colour will only update in the second
// render.
FUpdateWorld := true;
Render;
FUpdateWorld := true;
end;
// Shaders related
function TRenderEnvironment.IsShaderEnabled: boolean;
begin
Result := ShaderBank.isShaderEnabled;
end;
procedure TRenderEnvironment.EnableShaders(_value: boolean);
begin
ShaderBank.EnableShaders(_value);
// Due to texture caching, the background colour will only update in the second
// render.
ForceRefreshActors;
Render;
FUpdateWorld := true;
end;
// Screenshot related
procedure TRenderEnvironment.MakeMeAScreenshotName(var Filename: string; Ext : string);
var
i: integer;
t, FN, FN2 : string;
SSDir : string;
begin
// create the screenshots directory if it doesn't exist
SSDir := extractfiledir(Paramstr(0))+'\ScreenShots\';
FN2 := extractfilename(Filename);
FN2 := copy(FN2,1,length(FN2)-length(Extractfileext(FN2)));
ForceDirectories(SSDir);
FN := SSDir+FN2;
for i := 0 to 999 do
begin
t := inttostr(i);
if length(t) < 3 then
t := '00'+t
else if length(t) < 2 then
t := '0'+t;
if not fileexists(FN+'_'+t+Ext) then
begin
Filename := FN+'_'+t+Ext;
break;
end;
end;
end;
// Borrowed and adapted from Stucuk's code from OS: Voxel Viewer 1.80+ without AllWhite.
function TRenderEnvironment.GetScreenShot : TBitmap;
var
RGBBits : PRGBQuad;
Pixel : PRGBQuad;
BMP : TBitmap;
x,y : Integer;
Pow2Width, Pow2Height, maxx, maxy : cardinal;
begin
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,ScreenTexture);
Pow2Width := GetPow2Size(Width);
Pow2Height:= GetPow2Size(Height);
GetMem(RGBBits, Pow2Width * Pow2Height * 4);
glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE, RGBBits);
glDisable(GL_TEXTURE_2D);
BMP := TBitmap.Create;
BMP.PixelFormat := pf32Bit;
BMP.Width := Pow2Width;
BMP.Height := Pow2Height;
Pixel := RGBBits;
maxy := Pow2Height-1;
maxx := Pow2Width-1;
for y := 0 to maxy do
for x := 0 to maxx do
begin
Bmp.Canvas.Pixels[x,maxy-y] := RGB(Pixel.rgbBlue,Pixel.rgbGreen,Pixel.rgbRed);
inc(Pixel);
end;
FreeMem(RGBBits);
Result := TBitmap.Create;
Result.Width := Width;
Result.Height := Height;
Result.Canvas.Draw(0,-(Pow2Height-Height),BMP);
BMP.Free;
end;
procedure TRenderEnvironment.ScreenShotJPG(const _Filename : string; _Compression : integer);
var
Filename : string;
JPEGImage: TJPEGImage;
Bitmap : TBitmap;
begin
// Get filename.
Filename := CopyString(_Filename);
MakeMeAScreenshotName(Filename,'.jpg');
if Filename = '' then
exit;
Bitmap := GetScreenShot;
JPEGImage := TJPEGImage.Create;
JPEGImage.Assign(Bitmap);
JPEGImage.CompressionQuality := _Compression;
JPEGImage.SaveToFile(Filename);
Bitmap.Free;
JPEGImage.Free;
end;
procedure TRenderEnvironment.ScreenShotPNG(const _Filename : string; _Compression: integer);
var
Filename : string;
PNGImage: TPNGObject;
Bitmap : TBitmap;
begin
// Get filename.
Filename := CopyString(_Filename);
MakeMeAScreenshotName(Filename,'.png');
if Filename = '' then
exit;
Bitmap := GetScreenShot;
PNGImage := TPNGObject.Create;
PNGImage.Assign(Bitmap);
// The next line is commented out, since it causes infinite loop.
// PNGImage.CompressionLevel := _Compression;
PNGImage.SaveToFile(Filename);
Bitmap.Free;
PNGImage.Free;
end;
procedure TRenderEnvironment.ScreenShotDDS(const _Filename : string);
var
Filename : string;
DDSImage : TDDSImage;
begin
// Get filename.
Filename := CopyString(_Filename);
MakeMeAScreenshotName(Filename,'.dds');
if Filename = '' then
exit;
DDSImage := TDDSImage.Create;
DDSImage.SaveToFile(Filename,ScreenTexture);
DDSImage.Free;
end;
procedure TRenderEnvironment.ScreenShotTGA(const _Filename : string);
var
Filename : string;
buffer: array of byte;
i, c, temp: integer;
f: file;
begin
// Get filename.
Filename := CopyString(_Filename);
MakeMeAScreenshotName(Filename,'.tga');
if Filename = '' then
exit;
try
SetLength(buffer, (Width * Height * 4) + 18);
begin
for i := 0 to 17 do
buffer[i] := 0;
buffer[2] := 2; //uncompressed type
buffer[12] := Width and $ff;
buffer[13] := Width shr 8;
buffer[14] := Height and $ff;
buffer[15] := Height shr 8;
buffer[16] := 24; //pixel size
glReadPixels(0, 0, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, Pointer(Cardinal(buffer) + 18));
AssignFile(f, Filename);
Rewrite(f, 1);
for i := 0 to 17 do
BlockWrite(f, buffer[i], sizeof(byte) , temp);
c := 18;
for i := 0 to (Width * Height)-1 do
begin
BlockWrite(f, buffer[c+2], sizeof(byte) , temp);
BlockWrite(f, buffer[c+1], sizeof(byte) , temp);
BlockWrite(f, buffer[c], sizeof(byte) , temp);
inc(c,4);
end;
closefile(f);
end;
finally
finalize(buffer);
end;
end;
procedure TRenderEnvironment.ScreenShotBMP(const _Filename : string);
var
Filename : string;
Bitmap : TBitmap;
begin
// Get filename.
Filename := CopyString(_Filename);
MakeMeAScreenshotName(Filename,'.bmp');
if Filename = '' then
exit;
Bitmap := GetScreenShot;
Bitmap.SaveToFile(Filename);
Bitmap.Free;
end;
procedure TRenderEnvironment.ScreenShotGIF(_GIFImage : TGIFImage; const _Filename : string);
var
Filename : string;
begin
// Get filename.
Filename := CopyString(_Filename);
MakeMeAScreenshotName(Filename,'.gif');
if Filename = '' then
exit;
_GIFImage.SaveToFile(Filename);
_GIFImage.Free;
end;
(*
procedure TRenderEnvironment.ScreenShotViaGl2PS(const _FileName,_Ext: String; OutputType: GLInt);
var
buffsize, state: GLInt;
viewport: GLVWarray;
pViewport : PGLVWarray;
Filename : string;
begin
Filename := CopyString(_Filename);
MakeMeAScreenshotName(Filename,_Ext);
gl2psCreateStream(FileName);
buffsize := 0;
state := GL2PS_OVERFLOW;
glGetIntegerv(GL_VIEWPORT, @viewport);
pViewport := @viewport;
while( state = GL2PS_OVERFLOW ) do
begin
buffsize := 1000*width*height;
state := gl2psBeginPage (_FileName, 'Voxel Section Editor III', pViewport,
OutputType,
//GL2PS_SIMPLE_SORT, GL2PS_SIMPLE_LINE_OFFSET OR GL2PS_NO_PS3_SHADING,
GL2PS_NO_SORT, GL2PS_SILENT OR GL2PS_SIMPLE_LINE_OFFSET OR GL2PS_OCCLUSION_CULL OR GL2PS_BEST_ROOT,
GL_RGBA, 0, nil, 0, 0, 0, buffsize, Filename);
RenderVectorial();
state := gl2psEndPage();
end;
gl2psDestroyStream();
end;
*)
procedure TRenderEnvironment.TakeScreenshot(const _Filename: string; _type: TScreenshotType; _Compression: integer = 0);
begin
ScreenFilename:= CopyString(_Filename);
ScreenshotCompression := 100-_Compression;
AnimFrameMax := 1;
AnimFrameTime := 10;
NonScreenCamera := CurrentCamera;
ScreenType := _type;
StartAnimation;
end;
procedure TRenderEnvironment.TakeAnimation(const _Filename: string; _NumFrames, _FrameDelay: integer; _type: TScreenshotType);
begin
ScreenFilename:= CopyString(_Filename);
AnimFrameMax := _NumFrames;
AnimFrameTime := _FrameDelay;
NonScreenCamera := CurrentCamera;
ScreenType := _type;
StartAnimation;
end;
procedure TRenderEnvironment.Take360Animation(const _Filename: string; _NumFrames, _FrameDelay: integer; _type: TScreenshotType);
begin
ScreenFilename:= CopyString(_Filename);
AnimFrameMax := _NumFrames;
AnimFrameTime := _FrameDelay;
NonScreenCamera := CurrentCamera;
CurrentCamera := AddCamera;
CurrentCamera^.SetPosition(NonScreenCamera^.Position);
CurrentCamera^.SetPositionSpeed(0,0,0);
CurrentCamera^.SetPositionAcceleration(0,0,0);
CurrentCamera^.SetRotation(NonScreenCamera^.Rotation);
CurrentCamera^.SetRotationSpeed(0,(360.0 / _NumFrames),0);
CurrentCamera^.SetRotationAcceleration(0,0,0);
ScreenType := _type;
StartAnimation;
end;
procedure TRenderEnvironment.StartAnimation;
begin
AnimFrameCounter := 0;
if ScreenType = stGif then
begin
GifAnimateBegin;
end;
end;
procedure TRenderEnvironment.AddFrame;
begin
case ScreenType of
stBmp:
begin
ScreenShotBMP(ScreenFilename);
end;
stTga:
begin
ScreenShotTGA(ScreenFilename);
end;
stJpg:
begin
ScreenShotJPG(ScreenFilename,ScreenshotCompression);
end;
stGif:
begin
GifAnimateAddImage(GetScreenShot, False, AnimFrameTime);
end;
stPng:
begin
ScreenShotPNG(ScreenFilename,ScreenshotCompression);
end;
stDDS:
begin
ScreenShotDDS(ScreenFilename);
end;
stPS:
begin
// ScreenShotViaGl2PS(ScreenFilename,'.ps',GL2PS_PS);
end;
stPDF:
begin
// ScreenShotViaGl2PS(ScreenFilename,'.pdf',GL2PS_PDF);
end;
stEPS:
begin
// ScreenShotViaGl2PS(ScreenFilename,'.eps',GL2PS_EPS);
end;
stSVG:
begin
// ScreenShotViaGl2PS(ScreenFilename,'.svg',GL2PS_SVG);
end;
end;
end;
procedure TRenderEnvironment.FinishAnimation;
begin
case ScreenType of
stBmp:
begin
ScreenShotBMP(ScreenFilename);
end;
stTga:
begin
ScreenShotTGA(ScreenFilename);
end;
stJpg:
begin
ScreenShotJPG(ScreenFilename,ScreenshotCompression);
end;
stGif:
begin
ScreenShotGIF(GifAnimateEndGif, ScreenFilename);
end;
stPng:
begin
ScreenShotPNG(ScreenFilename,ScreenshotCompression);
end;
stDDS:
begin
ScreenShotDDS(ScreenFilename);
end;
(*
stPS:
begin
ScreenShotViaGl2PS(ScreenFilename,'.ps',GL2PS_PS);
end;
stPDF:
begin
ScreenShotViaGl2PS(ScreenFilename,'.pdf',GL2PS_PDF);
end;
stEPS:
begin
ScreenShotViaGl2PS(ScreenFilename,'.eps',GL2PS_EPS);
end;
stSVG:
begin
ScreenShotViaGl2PS(ScreenFilename,'.svg',GL2PS_SVG);
end;
*)
end;
AnimFrameMax := 0;
ScreenType := stNone;
if CurrentCamera <> NonScreenCamera then
begin
RemoveCamera(CurrentCamera);
CurrentCamera := NonScreenCamera;
end;
end;
function TRenderEnvironment.IsScreenshoting: boolean;
begin
Result := AnimFrameMax <> 0;
end;
end.
|
unit uNTierClasses;
interface
uses MConnect, uMRParam;
const
SERVER_NAME = 'MRAppServer.RDMApplicationHub';
SERVER_GUID = '{572F6870-260E-4D79-8E86-63F8F0BA0948}';
type
TNTierConnectionService = class
private
FConnectionParams: TMRParams;
FActiveConnection: TDispatchConnection;
procedure ActiveConnAfterConnect(Sender: TObject);
procedure ActiveConnBeforeDisconnect(Sender: TObject);
public
destructor Destroy; override;
property ConnectionParams: TMRParams read FConnectionParams write FConnectionParams;
property ActiveConnection: TDispatchConnection read FActiveConnection write FActiveConnection;
function CreateNTierConnection: TDispatchConnection;
procedure CloseConnection;
procedure OpenConnection;
end;
implementation
uses uNTierConsts, SConnect, SysUtils, uOperationSystem;
function TNTierConnectionService.CreateNTierConnection: TDispatchConnection;
var
ConType, sHost, sPort, ClientID: String;
begin
ConType := FConnectionParams.KeyByName(CON_PARAM_TYPE).AsString;
ClientID := FConnectionParams.KeyByName(CON_PARAM_CLIENT_ID).AsString;
sHost := FConnectionParams.KeyByName(CON_PARAM_HOST).AsString;
sPort := FConnectionParams.KeyByName(CON_PARAM_PORT).AsString;
if ConType = CON_TYPE_SOCKET then
begin
FActiveConnection := TSocketConnection.Create(nil);
TSocketConnection(FActiveConnection).Host := sHost;
TSocketConnection(FActiveConnection).Port := strToIntDef(sPort, 211);
end
else
if ConType = CON_TYPE_DCOM then
begin
FActiveConnection := TDCOMConnection.Create(nil);
TDCOMConnection(FActiveConnection).ComputerName := sHost;
end
else
if ConType = CON_TYPE_WEB then
begin
FActiveConnection := TWebConnection.Create(nil);
TWebConnection(FActiveConnection).Proxy := sHost;
end;
FActiveConnection.ServerName := SERVER_NAME;
FActiveConnection.ServerGUID := SERVER_GUID;
Result := FActiveConnection;
FActiveConnection.AfterConnect := ActiveConnAfterConnect;
FActiveConnection.BeforeDisconnect := ActiveConnBeforeDisconnect;
end;
procedure TNTierConnectionService.CloseConnection;
begin
if FActiveConnection.Connected then
FActiveConnection.Connected := False;
end;
procedure TNTierConnectionService.OpenConnection;
begin
if not FActiveConnection.Connected then
try
FActiveConnection.Connected := True;
except
on E: Exception do
raise Exception.Create('It was not possible to establish connection with the server.');
end;
end;
procedure TNTierConnectionService.ActiveConnAfterConnect(Sender: TObject);
begin
FActiveConnection.AppServer.LogIn(FConnectionParams.KeyByName(CON_PARAM_CLIENT_ID).AsString,
FConnectionParams.KeyByName(CON_PARAM_SOFTWARE).AsString);
end;
procedure TNTierConnectionService.ActiveConnBeforeDisconnect(
Sender: TObject);
begin
FActiveConnection.AppServer.LogOut(FConnectionParams.KeyByName(CON_PARAM_CLIENT_ID).AsString,
FConnectionParams.KeyByName(CON_PARAM_SOFTWARE).AsString);
end;
destructor TNTierConnectionService.Destroy;
begin
FreeAndNil(FActiveConnection);
inherited;
end;
end.
|
unit Unit_SD_TP06_EX01;
interface
type
TData = record
val : Integer;
end;
PItem = ^TItem;
TItem = record
data : TData;
pSuiv : PItem;
end;
TPile = record
pSommet : PItem;
nb : Integer;
end;
TFile = file of TData;
procedure init(var p : TPile);
function estVide(p : TPile) : Boolean;
procedure affiche(p : TPile);
procedure empile(var p : TPile; e : TData);
procedure sommet(p : TPile; var e : TData; var b : Boolean);
procedure depile(var p : TPile; var e : TData; var b : Boolean);
procedure sauvegarde(p : TPile);
procedure lireFichier();
function charge(nom : String): TPile;
implementation
procedure init(var p : TPile);
begin
p.nb := 0;
p.pSommet := NIL;
end;
function estVide(p : TPile) : Boolean;
begin
estVide := (p.pSommet = NIL);
end;
procedure affData(e : TData);
begin
writeln(e.val);
end;
procedure affiche(p : TPile);
var
pCour : PItem;
begin
pCour := p.pSommet;
while (pCour <> NIL) do
begin
affData((pCour^).data);
pCour := (pCour^).pSuiv;
end;
end;
procedure empile(var p : TPile; e : TData);
var
pTemp : PItem;
begin
new(pTemp);
pTemp^.data := e;
pTemp^.pSuiv := p.pSommet;
p.nb := p.nb + 1;
p.pSommet := pTemp;
end;
procedure sommet(p : TPile; var e : TData; var b : Boolean);
begin
if (estVide(p)) then
begin
b := False;
end
else
begin
b := True;
e := (p.pSommet^).data;
end;
end;
procedure depile(var p : TPile; var e : TData; var b : Boolean);
var
pTemp : PItem;
begin
if (estVide(p)) then
begin
b := False;
end
else
begin
b := True;
e := (p.pSommet^).data;
pTemp := p.pSommet;
p.nb := p.nb - 1;
p.pSommet := (pTemp^).pSuiv;
dispose(pTemp);
end;
end;
procedure sauvegarde(p : TPile);
var
f : TFile;
pCour : PItem;
begin
assign(f,'dataTItem.bin');
rewrite(f);
pCour := p.pSommet;
while pCour <> NIL do
begin
write(f, (pCour^).data);
pCour := (pCour^).pSuiv;
end;
close(f);
end;
procedure lireFichier();
var
e : TData;
f : TFile;
begin
assign(f,'dataTItem.bin');
reset(f);
while not eof(f) do begin
read(f, e);
affData(e);
end;
end;
function charge(nom : String): TPile;
var
e : TData;
f : TFile;
p : TPile;
begin
assign(f, 'dataTItem.bin');
reset(f);
init(p);
while not eof(f) do
begin
read(f, e);
empile(p, e);
end;
charge := p;
end;
end.
|
(* LEBUFF.PAS - Copyright (c) 1995-1996, Eminent Domain Software *)
unit LEBuff;
{-LEdit buffer manager for EDSSpell component}
interface
uses
Classes, Controls, Graphics, SysUtils, Forms, StdCtrls,
WinProcs, WinTypes,
{$IFDEF Win32}
LeDlp32,
{$ELSE}
LeDlp,
{$ENDIF}
AbsBuff, MemoUtil, SpellGbl;
{Note: To support all the neat syntax highlighting available in LEdit, }
{ we decided to get each line of the LEdit component and spell }
{ check each line. This also lowers the overhead of the spell }
{ checker from 65535 bytes of memory down to a sphelt 8k of memory }
type
TLEditBuffer = class (TPCharBuffer) {LEdit Buffer Manager}
private {any descendant of TLEdit}
{ Private declarations }
FNumLine: Longint; {current line number}
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create (AParent: TControl); override;
function GetTextBufferSize: integer; override;
{-returns the maximum size of the buffer}
function IsModified: Boolean; override;
{-returns TRUE if parent had been modified}
procedure SetModified (NowModified: Boolean); override;
{-sets parents modified flag}
function GetYPos: integer; override;
{-gets the current y location of the highlighted word (absolute screen)}
procedure SetSelectedText; override;
{-highlights the current word using BeginPos & EndPos}
function GetNextWord: string; override;
{-returns the next word in the buffer}
function InheritedGetNextWord: String;
{-special inherited GetNextWord call for XSpell}
procedure UpdateBuffer; override;
{-updates the buffer from the parent component, if any}
procedure ReplaceWord (WithWord: string); override;
{-replaces the current word with the word provided}
property NumLine: Longint read FNumLine write FNumLine;
{-current line number we're workin' on}
end; { TLEditBuffer }
implementation
{LEdit Buffer Manager}
constructor TLEditBuffer.Create (AParent: TControl);
begin
FNumLine := 1;
inherited Create (AParent);
end; { TOrpheusEditor.Create }
function TLEditBuffer.GetTextBufferSize: integer;
{-returns the maximum size of the buffer}
begin
Result := 8 * 1024; {8K}
end; { TLEditBuffer.GetTextBufferSize }
function TLEditBuffer.IsModified: Boolean;
{-returns TRUE if parent had been modified}
begin
Result := TLEdit (Parent).Modified;
end; { TLEditBuffer.IsModified }
procedure TLEditBuffer.SetModified (NowModified: Boolean);
{-sets parents modified flag}
begin
TLEdit (Parent).Modified := NowModified;
end; { TLEditBuffer.SetModified }
function TLEditBuffer.GetYPos: integer;
{-gets the current y location of the highlighted word (absolute screen)}
begin
(* not supported with LEdit *)
Result := 0;
end; { TLEditBuffer.GetYPos }
procedure TLEditBuffer.SetSelectedText;
{-highlights the current word using FBeginPos & FEndPos}
begin
TLEdit (Parent).StartLine := NumLine;
TLEdit (Parent).EndLine := NumLine;
TLEdit (Parent).StartPos := BeginPos - 1;
TLEdit (Parent).EndPos := EndPos - 1;
TLEdit (Parent).SetSelection;
end; { TLEditBuffer.SetSelectedText }
function TLEditBuffer.GetNextWord: string;
{-returns the next word in the buffer}
var
St: String;
CurLine: Longint;
begin
St := inherited GetNextWord;
while St = '' do
begin
with TLEdit (Parent) do
begin
CurLine := LineCount;
if NumLine < CurLine then
begin {get the next line}
inc (FNumLine);
InitParms;
UpdateBuffer;
St := inherited GetNextWord;
end {:} else
Break;
end; { with }
end; { while }
Result := St;
end; { TLEditBuffer.GetNextWord }
function TLEditBuffer.InheritedGetNextWord: String;
{-special GetNextWord call for XSpell}
begin
Result := inherited GetNextWord;
end; { TLEditBuffer.InheritedGetNextWord }
procedure TLEditBuffer.UpdateBuffer;
{-updates the buffer from the parent component, if any}
begin
with TLEdit (Parent) do
BufSize := GetLine (@Buffer^[1], NumLine);
if BufSize > 0 then
begin
Buffer^[BufSize + 1] := #0;
BufSize := BufSize + 1;
end; { if... }
end; { TLEditBuffer.UpdateBuffer }
procedure TLEditBuffer.ReplaceWord (WithWord: string);
{-replaces the current word with the word provided}
begin
with TLEdit (Parent) do
InsertStr (WithWord);
end; { TLEditBuffer.ReplaceWord }
end. { OvcBuff }
|
unit UIlsMapEditorServiceFrm;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, IdComponent,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Ils.Logger,
Vcl.AppEvnts, Vcl.StdCtrls, IdHTTPWebBrokerBridge, Web.HTTPApp, System.IniFiles,
UMapEditor, Ils.Utils.Debug, Winapi.ActiveX, IdContext, IdException,
IdHTTP, IdSSLOpenSSL,uGeneral, Ils.Utils.Svc;
type
TILSSaaSMapEditorWebService = class(TService)
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceShutdown(Sender: TService);
procedure ServiceBeforeInstall(Sender: TService);
procedure ServiceAfterInstall(Sender: TService);
private
FServer: TIdHTTPWebBrokerBridge;
procedure StartServer;
procedure StopServer;
procedure RestartServer;
procedure IDServerException(
AContext: TIdContext;
AException: Exception
);
function GetHttpreqwestResult(strHttpReqwest: string): string;
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
ILSSaaSMapEditorWebService: TILSSaaSMapEditorWebService;
const
CServiceVer = '7.3.03 2019.12.31';
CServiceName = 'ILSSaaSMapEditorWebService';
CServiceDisplayName = 'ILS SaaS MapEditor Web';
implementation
{$R *.dfm}
uses
Winapi.ShellApi, IlsMapEditorWebModule;
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
ILSSaaSMapEditorWebService.Controller(CtrlCode);
end;
function TILSSaaSMapEditorWebService.GetHttpreqwestResult(
strHttpReqwest: string): string;
var
HTTPReqw : TIdHTTP;
IDSSL : TIdSSLIOHandlerSocketOpenSSL;
strResultReqw : string;
begin
HTTPReqw := TIdHTTP.Create;
IDSSL := TIdSSLIOHandlerSocketOpenSSL.Create;
try
try
HTTPReqw.IOHandler := IDSSL;
HTTPReqw.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko';
HTTPReqw.Request.Accept := 'text/html';
HTTPReqw.Request.AcceptLanguage := 'ru,en-us;q=0.7,en;q=0.3';
HTTPReqw.Request.AcceptCharSet := 'windows-1251,utf-8;q=0.7,*;q=0.7';
HTTPReqw.ReadTimeout :=50000;
HTTPReqw.ConnectTimeout := 50000;
strResultReqw := HTTPReqw.Get(Trim(strHttpReqwest));
if Pos('200 OK', HTTPReqw.Response.ResponseText) <> 0 then
begin
Result := strResultReqw;
end else
begin
Result := '';
end;
except
on E: Exception do
begin
ToLog('Ошибка при выполнении Http запроса:' + strHttpReqwest + ' ('+ E.Message + ')');
Result := '';
end;
end;
finally
HTTPReqw.Free;
IDSSL.Free;
end;
end;
function TILSSaaSMapEditorWebService.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TILSSaaSMapEditorWebService.StopServer;
begin
// ToLog('TILSMapEditorWebService.StopServer. FServer.SessionList.ComponentCount='+
// IntToStr(FServer.SessionList.ComponentCount));
TGeneral.Stop;
Sleep(1000);
FServer.Active := False;
ToLog('TILSMapEditorWebService.StopServer. FServer.Active');
FServer.Bindings.Clear;
ToLog('TILSMapEditorWebService.StopServer. FServer.Bindings.Clear');
FServer.Free;
ToLog('=============WebServer Stop=============');
// TMapEditor.Stop;
end;
procedure TILSSaaSMapEditorWebService.IDServerException(AContext: TIdContext;
AException: Exception);
begin
ToLog('TILSSaaSMapEditorWebService.IDServerException:"' + AException.ClassName + '" ' +
AException.Message + ' Context:' + AContext.ToString);
if AException is EIdConnClosedGracefully then
Exit;
if TGeneral.FStop then
Exit;
ToLog('Ошибка работы сервера:'#13#10'"' + AException.ClassName + '" ' + AException.Message);
// RestartServer();
end;
procedure TILSSaaSMapEditorWebService.RestartServer;
begin
try
ToLog('Начинаем перезагрузку системы приёма (http server) - остановка');
// TMapEditor.Stop;
FreeAndNil(FServer);
ToLog('Запуск системы приёма');
StartServer;
ToLog('Перезагрузка системы приёма успешно завершена');
except
on Ex: Exception do
begin
ToLog('Ошибка перезагрузки системы приёма:'#13#10'"' + Ex.ClassName + '" ' + Ex.Message);
end;
end;
end;
procedure TILSSaaSMapEditorWebService.ServiceAfterInstall(Sender: TService);
begin
SvcAfterInstall(CServiceName);
end;
procedure TILSSaaSMapEditorWebService.ServiceBeforeInstall(Sender: TService);
begin
SvcBeforeInstallUninstall(Self, CServiceName, CServiceDisplayName);
ToLog('SvcBeforeInstallUninstall ' + CServiceName + ', ' + CServiceDisplayName);
end;
procedure TILSSaaSMapEditorWebService.ServiceShutdown(Sender: TService);
begin
ToLog('=============Service Shutdown=============');
StopServer;
end;
procedure TILSSaaSMapEditorWebService.ServiceStart(Sender: TService;
var Started: Boolean);
begin
ToLog(ParamStr(0));
Started := False;
CoInitialize(nil);
{$IFDEF DEBUG}
SleepIfIdeRunning(20000);
{$ENDIF}
ToLog(ParamStr(0));
ToLog('==== запускается ====');
// CoInitialize(nil);
ToLog('Version ' + CServiceVer);
SleepIfIdeRunning(10000);
ToLog('=============Start Service=============');
StartServer;
ToLog('============ запущена ============');
Started := True;
end;
procedure TILSSaaSMapEditorWebService.ServiceStop(Sender: TService;
var Stopped: Boolean);
begin
ToLog('=============Начинаем остановку службы=============');
StopServer;
ToLog('=============Stop Service=============');
Stopped := True;
CoUninitialize();
end;
procedure TILSSaaSMapEditorWebService.StartServer;
begin
TGeneral.Start(ChangeFileExt(GetModuleName(HInstance),GetConfigSuffix() + '.ini'));
TGeneral.FSuffix := GetConfigSuffix();
if not Assigned(FServer) then
FServer := TIdHTTPWebBrokerBridge.Create(Self);
if not FServer.Active then
begin
FServer.Bindings.Clear;
FServer.DefaultPort := TGeneral.FPort;
// FServer.OnException := IDServerException;
FServer.Active := True;
// FServer.BeginWork(wmRead);
GetHttpreqwestResult('http://localhost:'+IntToStr(TGeneral.FPort)+'/?{"Type":"GetZonesProgress","Account":{"Current":"1","Parents":[]}}');
// WebModuleClass.Create(Self);
// TMapEditor.Start;
end;
if FServer.Active then
ToLog('Web Server started')
else
ToLog('Web Server not started');
end;
end.
|
Unit Scheduler;
{ * Scheduler: *
* *
* Esta Unidad esta destinada a planificar la tarea que se ejecutara *
* segun la implementacion de 2 algotimos FIFO Y ROUND ROBIN , se *
* de captar las IRQ del relog e incrementar el contador *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* *
* 04 / 01 / 06 : Es reescrito el modelo de planificacion *
* *
* 26 / 04 / 05 : Es reescrito todo el planificador y la mayor parte *
* del esquema de planificacion , tambien con creadas nuevas sys *
* calls para manipular el scheduler . *
* *
* 6 / 12 / 03 : Version Inicial *
* *
*********************************************************************
}
interface
{DEFINE DEBUG}
{$I ../include/toro/procesos.inc}
{$I ../include/head/irq.h}
{$I ../include/head/gdt.h}
{$I ../include/head/idt.h}
{$I ../include/head/asm.h}
{$I ../include/head/procesos.h}
{$I ../include/head/itimer.h}
{$I ../include/head/ktimer.h}
{$I ../include/head/signal.h}
{$I ../include/head/printk_.h}
{$DEFINE Use_Tail}
{$DEFINE Use_Hash}
{$DEFINE nodo_struct := p_tarea_struc }
{$DEFINE next_nodo := next_tarea }
{$DEFINE prev_nodo := prev_tarea }
{ colas aqui manipuladas }
const tq_rr : p_tarea_struc = nil ;
tq_fifo : p_tarea_struc = nil ;
var Tarea_Actual : p_tarea_struc;
need_sched : boolean;
procedure Scheduling ;
implementation
{$I ../include/head/ioport.h}
{$I ../include/head/list.h}
procedure load_task(tarea : p_tarea_struc);inline;
begin
FARJUMP((Tarea^.tss_descp-1)*8,nil);
end;
{ * Agrega una tarea a alguna de las dos colas de tareas convencionales * }
procedure add_task(tarea:p_tarea_struc) ; [public ,alias : 'ADD_TASK'];
begin
case Tarea^.politica of
Sched_RR : Push_Node(Tarea,Tq_rr);
Sched_FIFO : Push_node (Tarea,Tq_FIFO);
end;
end;
{ * Quita una tarea de alguna de las dos colas de tareas convecionales * }
procedure remove_task(tarea:p_tarea_struc) ; [public , alias : 'REMOVE_TASK'];
begin
case Tarea^.politica of
Sched_RR : Pop_Node (Tarea,Tq_rr);
Sched_FIFO : Pop_Node (Tarea , Tq_FIFO);
end;
end;
{ * agrega una tarea que estubo bloqueada a la cola de listas * }
procedure add_interrupt_task ( tarea : p_tarea_struc ) ; [public , alias : 'ADD_INTERRUPT_TASK'];
begin
if tarea^.politica = sched_fifo then push_node_first (tarea , tq_fifo)
else push_node_first (tarea ,tq_rr);
end;
{ * Scheduler_Handler: *
* *
* Este procedimiento declarado como interrupt , se encarga de captar las *
* interrupciones generadas por el relog del sistma IRQ 0 , suma el *
* contador de quantums de la tarea actual y si su tiempo expira llama al *
* scheduling que planifica otra tarea *
* *
**************************************************************************
}
procedure scheduler_handler;interrupt;[public , alias :'SCHEDULER_HANDLER'];
label _back , _sched ;
begin
enviar_byte ($20,$20);
{ or la ejecucion de timers del nucleo }
do_ktimer ;
{ Incremento el contador de tiemers de usuarios }
timer_inc;
{ incremento del tiempo virtual del proceso }
Tarea_Actual^.virtual_time += 1;
{ Se solicito que se llame al planificador }
if need_sched then goto _sched ;
{ las tareas fifo no poseen quantums y no pueden ser desalojadas }
if Tarea_Actual^.politica = Sched_FIFO then goto _back;
Tarea_Actual^.quantum_a += 1;
if (Tarea_Actual^.quantum_a <> quantum) then goto _back;
_sched :
{ La tarea vuelve a la cola listos , solo las rr llegan aqui}
push_node (Tarea_Actual,Tq_rr);
Tarea_Actual^.estado := Tarea_Lista ;
Scheduling;
_back:
{ Se verifican las se¤ales pendientes }
Signaling;
end;
{ * Scheduling: *
* *
* Aqui se encuentra todo el proceso de planificacion se poseen dos al *
* goritmos FIFO y RR *
* *
* Versiones : *
* *
* 04 / 01 / 2006 : Es modificada la planificacion para optimizar los *
* procesos con mucha io *
* *
* 05 / 04 / 2005 : Se aplica el nuevo modelo de planificacion *
* *
* ?? / ?? / ???? : Primera Version *
*************************************************************************
}
procedure scheduling ; [public , alias :'SCHEDULING'];
label _load , _fifo ;
var task_sched : p_tarea_struc ;
begin
cerrar;
{ las fifo se encuentran por sobre las RR }
_fifo :
if Tq_fifo <> nil then
begin
task_sched := Tq_fifo ;
goto _load ;
end;
{ si no hay ninguna tarea aguardo por alguna irq }
if tq_rr = nil then
begin
abrir ;
while (tq_rr = nil ) do if (tq_fifo <> nil) then goto _fifo ;
end;
{ simple turno rotatorio RR }
Task_sched := Tq_rr ;
_load :
remove_task (Task_sched);
need_sched:= false ;
Task_sched^.quantum_a := 0 ;
if (Tarea_Actual = task_sched ) then exit ;
Tarea_Actual := Task_sched ;
Tarea_Actual^.estado := Tarea_Corriendo;
Tarea_Actual^.tss_p^.tipo := TSS_SIST_LIBRE;
Load_Task ( Tarea_Actual );
end;
{ * Sys_SetScheduler : *
* *
* Pid : Pid de la tarea que modificara su scheduler *
* politica : Numero planificador *
* prioridad : No implementada *
* Retorno : 0 si ok o -1 si falla *
* *
* Llamada al sistema que modifica el planificador de la tarea dada en *
* pid , dado que se trabaja con prioridad estaticas por ahora no se *
* implementa el campo prioridad *
* *
***********************************************************************
}
function sys_setscheduler ( pid , politica , prioridad : dword ) : dword ; cdecl ; [public , alias : 'SYS_SETSCHEDULER'];
var task : p_tarea_struc ;
begin
task := Hash_Get (pid) ;
set_errno := -ESRCH ;
if task = nil then exit(-1);
{solo las propias tareas y los padres pueden modificar un planificador}
if tarea_actual^.pid = task^.pid then
else if (Tarea_Actual^.pid <> task^.padre_pid) then
begin
set_errno := -ECHILD ;
exit (-1);
end;
set_errno := -EINVAL ;
case politica of
SCHED_RR : begin
task^.politica := SCHED_RR ;
task^.estado := Tarea_Lista ;
clear_errno ;
end;
SCHED_FIFO : begin
task^.politica := SCHED_FIFO ;
task^.estado := Tarea_Lista ;
Push_Node (task,Tq_fifo);
Scheduling;
clear_errno ;
end;
else exit(-1);
exit(0);
end;
exit(0);
end;
{ * Sys_GetScheduler : *
* *
* Pid : Pid de la tarea de la que se devolvera el planificador *
* Retorno : la politica o -1 si falla *
* *
* Llamada al sistema que devuelve la politica implementada en la tarea*
* dada en pid *
* *
***********************************************************************
}
function sys_getscheduler (pid : dword ) : dword ; cdecl ; [public , alias : 'SYS_GETSCHEDULER'];
var task : p_tarea_struc ;
begin
set_errno := -ESRCH ;
task := Hash_Get (pid) ;
if (task = nil) then exit(-1);
clear_errno;
exit(task^.politica);
end;
{ * Scheduler_Init : *
* *
* Procediemiento que inicializa la tarea del sched y crear sus reg *
* coloca la INT CALL en la IDT al manejador del INT del relog , inicia *
* el PIT a 1000HZ y Habilita la IRQ 0 *
* *
************************************************************************
}
procedure scheduler_init;[public,alias :'SCHEDULER_INIT'];
begin
contador := 0;
Wait_Short_Irq(0,@Scheduler_Handler);
need_sched := false;
Iniciar_Relog;
end;
end.
|
unit CommonConstPublic;
interface
uses Forms,Windows;
var
HintTitle: string = '金蝶提示';
WarnTitle: string = '金蝶提示';
ErrorTitle: string = '金蝶提示';
AskTitle: string = '金蝶提示';
const
//----------对话框窗体标题分类---------
M_Warn: Cardinal = MB_Ok or MB_ICONWARNING;
M_Error: Cardinal = MB_Ok or MB_ICONERROR;
M_Hint: Cardinal = MB_Ok or MB_ICONINFORMATION;
M_YesNo: Cardinal = MB_YESNO or MB_ICONQUESTION;
M_YewNoCancel: Cardinal = MB_YESNOCANCEL or MB_ICONQUESTION;
implementation
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit uCmdLine;
interface
{$I ConTEXT.inc}
uses
Messages, SysUtils, Windows, Classes, uCommon, JclFileUtils, uProject,
Dialogs;
type
TCmdLineCmd = (cmdNone, cmdOpenFile, cmdSaveFile, cmdCloseFile, cmdExit, cmdFileList, cmdPrjFile, cmdPrintFile, cmdCursorPos, cmdRunMacro, cmdReadOnly);
TCmdLineParam = record
cmd :TCmdLineCmd;
p_int1 :integer;
p_int2 :integer;
p_fname :string;
p_fnames :TStringList;
p_str :string;
end;
pTCmdLineParam = ^TCmdLineParam;
procedure CmdLine_Init;
procedure CmdLine_Done;
function CmdLine_Analyze(str:TStringList):boolean;
procedure CmdLine_Execute;
implementation
uses
fMain, fEditor;
var
Cmds :TList;
CmdLineParams :TStringList;
Params :TStringList;
ptr :integer;
//------------------------------------------------------------------------------------------
procedure CmdLine_Init;
begin
Cmds:=TList.Create;
Params:=TStringList.Create;
ptr:=0;
end;
//------------------------------------------------------------------------------------------
procedure CmdLine_Done;
var
i :integer;
C :pTCmdLineParam;
begin
if Assigned(Cmds) then begin
for i:=0 to Cmds.Count-1 do begin
C:=pTCmdLineParam(Cmds[i]);
if Assigned(C.p_fnames) then
C.p_fnames.Free;
FreeMem(C);
end;
Cmds.Free;
end;
if Assigned(Params) then
Params.Free;
end;
//------------------------------------------------------------------------------------------
function GetFileNames(s:string):TStringList;
var
rec :TSearchRec;
n :integer;
ss :TStringList;
begin
ss:=TStringList.Create;
if (Pos('*',s)>0) or (Pos('?',s)>0) then begin
n:=FindFirst(s, faAnyFile-faDirectory, rec);
while (n=0) do begin
ss.Add(GetFileLongName(ExtractFilePath(s)+rec.Name));
n:=FindNext(rec);
end;
end else
ss.Add(s);
result:=ss;
end;
//------------------------------------------------------------------------------------------
function GetFileNamesFromFile(s:string):TStringList;
var
str :TStringList;
i :integer;
path :string;
dir :string;
begin
path:=ExtractFilePath(GetFileLongName(s));
dir:=GetCurrentDir;
str:=TStringList.Create;
try
str.LoadFromFile(s);
SetCurrentDir(ExtractFilePath(s));
// pobrišimo prazne redove
i:=0;
while (i<str.Count) do begin
str[i]:=Trim(str[i]);
if (Length(str[i])=0) then
str.Delete(i)
else begin
str[i]:=GetFileLongName(str[i]);
inc(i);
end;
end;
except
DlgErrorOpenFile(s);
end;
SetCurrentDir(dir);
result:=str;
end;
//------------------------------------------------------------------------------------------
function GetNextParam(var s:string):boolean;
begin
result:=(ptr<Params.Count);
if result then begin
s:=Params[ptr];
inc(ptr);
end;
end;
//------------------------------------------------------------------------------------------
procedure ResolveParams;
var
i, ii :integer;
s :string;
ss :TStringList;
begin
Params.Clear;
ss:=TStringList.Create;
for i:=0 to CmdLineParams.Count-1 do begin
s:=CmdLineParams[i];
if (Length(s)>0) then begin
if (s[1]='/') then begin
ii:=2;
while (ii<=Length(s)) do begin
if (s[ii]='/') then begin
Insert(#13#10,s,ii);
inc(ii,2);
end;
inc(ii);
end;
ss.Text:=s;
for ii:=0 to ss.Count-1 do
if (Length(ss[ii])>1) then
Params.Add(ss[ii]);
end else
Params.Add(s);
end;
end;
ss.Free;
end;
//------------------------------------------------------------------------------------------
function CmdLine_Analyze(str:TStringList):boolean;
var
s,ss :string;
C :pTCmdLineParam;
X,Y :integer;
i :integer;
begin
result:=FALSE;
i:=0;
while (i<str.Count) do begin
if (str[i]='.') or (str[i]='..') then
str.Delete(i)
else
inc(i);
end;
CmdLineParams:=str;
if (CmdLineParams.Count=0) then EXIT;
ResolveParams;
while GetNextParam(s) do begin
C:=AllocMem(SizeOf(TCmdLineParam));
if (s[1]='/') then begin
s:=UpperCase(s);
Delete(s,1,1);
if (Length(s)=0) then CONTINUE;
if (s='P') then begin
if GetNextParam(s) then begin
C.cmd:=cmdPrintFile;
C.p_fnames:=GetFileNames(s);
Cmds.Add(C);
end;
CONTINUE;
end;
if (s[1]='G') then begin
i:=2;
// parametar X
ss:='';
while (i<=Length(s)) and (s[i] in ['0'..'9']) do begin
ss:=ss+s[i];
inc(i);
end;
// separator
X:=StrToIntDef(ss,1)-1;
while (i<=Length(s)) and (not (s[i] in ['0'..'9'])) do inc(i);
// parametar Y
ss:='';
while (i<=Length(s)) and (s[i] in ['0'..'9']) do begin
ss:=ss+s[i];
inc(i);
end;
Y:=StrToIntDef(ss,1)-1;
C.cmd:=cmdCursorPos;
C.p_int1:=X;
C.p_int2:=Y;
Cmds.Add(C);
CONTINUE;
end;
if (s='M') then begin
if GetNextParam(s) then begin
C.cmd:=cmdRunMacro;
C.p_str:=RemoveQuote(s);
Cmds.Add(C);
end;
CONTINUE;
end;
if (s='I') then begin
if GetNextParam(s) then begin
C.cmd:=cmdFileList;
C.p_fnames:=GetFileNamesFromFile(s);
Cmds.Add(C);
end;
CONTINUE;
end;
if (s='R') then begin
C.cmd:=cmdReadOnly;
Cmds.Add(C);
CONTINUE;
end;
if (s='S') then begin
C.cmd:=cmdSaveFile;
Cmds.Add(C);
CONTINUE;
end;
if (s='C') then begin
C.cmd:=cmdCloseFile;
Cmds.Add(C);
CONTINUE;
end;
if (s='E') then begin
C.cmd:=cmdExit;
Cmds.Add(C);
CONTINUE;
end;
// ako smo došli do ovdje, parametar je nepoznat
FreeMem(C);
end else begin
C.p_fnames:=GetFileNames(s);
if (C.p_fnames.Count=1) and (IsProjectFile(C.p_fnames[0])) then begin
C.cmd:=cmdPrjFile;
C.p_fname:=C.p_fnames[0];
C.p_fnames.Clear;
end else
C.cmd:=cmdOpenFile;
Cmds.Add(C);
end;
end;
result:=TRUE;
end;
//------------------------------------------------------------------------------------------
procedure CmdLine_Execute;
var
i, ii :integer;
cmd :pTCmdLineParam;
editors :TList;
print_only :boolean;
open_count :integer;
locked :boolean;
begin
editors:=TList.Create;
open_count:=0;
for i:=0 to Cmds.Count-1 do begin
cmd:=pTCmdLineParam(Cmds[i]);
if (cmd^.cmd in [cmdOpenFile, cmdFileList]) then
inc(open_count,cmd.p_fnames.Count);
end;
locked:=open_count>2;
if locked then
fmMain.LockPainting(FALSE);
print_only:=TRUE;
for i:=0 to Cmds.Count-1 do begin
cmd:=pTCmdLineParam(Cmds[i]);
case cmd.cmd of
cmdOpenFile, cmdFileList:
begin
editors.Clear;
if (cmd.p_fnames.Count>1) then begin
for ii:=0 to cmd.p_fnames.Count-1 do begin
fmMain.OpenFile(cmd.p_fnames[ii]);
editors.Add(fmMain.ActiveEditor);
end;
end else begin
for ii:=0 to cmd.p_fnames.Count-1 do begin
fmMain.OpenFileFromCommandLine(cmd.p_fnames[ii]);
editors.Add(fmMain.ActiveEditor);
end;
end;
end;
cmdPrjFile:
begin
editors.Free;
fmMain.OpenProjectFile(cmd.p_fname);
editors:=fmMain.PrjManager.GetOpenFilesWindows;
end;
cmdPrintFile:
begin
editors.Clear;
for ii:=0 to cmd.p_fnames.Count-1 do
if (Length(cmd.p_fnames[ii])>0) then
fmMain.OpenPrintAndCloseFile(cmd.p_fnames[ii]);
end;
cmdCursorPos:
for ii:=0 to editors.Count-1 do
with TfmEditor(editors[ii]) do begin
memo.LeftChar:=0;
SetCursorPos(cmd.p_int1, cmd.p_int2);
SetCurrentLineAtCenter;
end;
cmdRunMacro:
for ii:=0 to editors.Count-1 do
fmMain.Macros.PlaybyName(TfmEditor(editors[ii]), cmd.p_str);
cmdReadOnly:
for ii:=0 to editors.Count-1 do
TfmEditor(editors[ii]).Locked:=TRUE;
cmdSaveFile:
for ii:=0 to editors.Count-1 do
TfmEditor(editors[ii]).Save;
cmdCloseFile:
begin
for ii:=0 to editors.Count-1 do
TfmEditor(editors[ii]).Close;
editors.Clear;
end;
cmdExit:
begin
PostMessage(fmMain.Handle, WM_CLOSE, 0, 0);
end;
end;
print_only:=print_only and (cmd.cmd=cmdPrintFile);
end;
if locked then
fmMain.UnlockPainting(FALSE);
if (Cmds.Count>0) and print_only and (fmMain.MDIChildCount=0) then
PostMessage(fmMain.Handle, WM_CLOSE, 0, 0);
editors.Free;
end;
//------------------------------------------------------------------------------------------
end.
|
(*
*****************************************************************
Delphi-OpenCV
Copyright (C) 2013 Project Delphi-OpenCV
****************************************************************
Contributor:
Laentir Valetov
email:laex@bk.ru
****************************************************************
You may retrieve the latest version of this file at the GitHub,
located at git://github.com/Laex/Delphi-OpenCV.git
****************************************************************
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_1Final.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.
*******************************************************************
*)
unit ocv.cls.types;
{$I OpenCV.inc}
interface
Type
TOpenCVClass = Pointer;
IOCVCommon = interface
function _InternalData: TOpenCVClass;
end;
TOCVCommon = class(TInterfacedObject, IOCVCommon)
protected
FData: TOpenCVClass;
public
constructor Create(const OpenCVClass: TOpenCVClass);
function _InternalData: TOpenCVClass;
end;
TStringAnsiHelper = record helper for
String
function AsPAnsiChar: PAnsiChar;
end;
implementation
Uses ocv.utils;
{ TOCVCommon }
constructor TOCVCommon.Create(const OpenCVClass: TOpenCVClass);
begin
FData := OpenCVClass;
end;
function TOCVCommon._InternalData: TOpenCVClass;
begin
Result := FData;
end;
{ TStringAnsiHelper }
function TStringAnsiHelper.AsPAnsiChar: PAnsiChar;
begin
Result := c_str(Self);
end;
end.
|
Unit CallbackStreamImpl;
Interface
Uses
Classes, SysUtils;
Type
TCallbackStream = Class;
TCallbackStreamOnRead = Function (ABuffer:Pointer; ALength:Cardinal; AStream:TCallbackStream; AReadContext:Pointer):Cardinal; Cdecl;
TCallbackStreamOnWrite = Function (ABuffer:Pointer; ALength:Cardinal; AStream:TCallbackStream; AWriteContext:Pointer):Cardinal; Cdecl;
TCallbackStream = Class (TStream)
Private
FReadCallback : TCallbackStreamOnRead;
FReadContext : Pointer;
FWriteCallback : TCallbackStreamOnWrite;
FWriteContext : Pointer;
Public
Constructor Create(AReadCallback:TCallbackStreamOnRead; AWriteCallback:TCallbackStreamOnRead; AReadContext:Pointer = Nil; AWriteContext:Pointer = Nil); Reintroduce;
Function Read(var Buffer; Count: Longint): Longint; Override;
Function Write(const Buffer; Count: Longint): Longint; Override;
end;
Implementation
Constructor TCallbackStream.Create(AReadCallback:TCallbackStreamOnRead; AWriteCallback:TCallbackStreamOnRead; AReadContext:Pointer = Nil; AWriteContext:Pointer = Nil);
begin
Inherited Create;
FReadCallback := AReadCallback;
FReadContext := AReadContext;
FWriteCallback := AWriteCallback;
FWriteContext := AWriteContext;
end;
Function TCallbackStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := FReadCallback(@Buffer, Count, Self, FReadContext);
end;
Function TCallbackStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := FWriteCallback(@Buffer, Count, Self, FWriteContext);
end;
End.
|
unit ibSHTXTLoaderActions;
interface
uses
SysUtils, Classes, Menus,
SHDesignIntf, ibSHDesignIntf;
type
TibSHTXTLoaderPaletteAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHTXTLoaderFormAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHTXTLoaderToolbarAction_ = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHTXTLoaderToolbarAction_Run = class(TibSHTXTLoaderToolbarAction_)
end;
TibSHTXTLoaderToolbarAction_Pause = class(TibSHTXTLoaderToolbarAction_)
end;
TibSHTXTLoaderToolbarAction_Commit = class(TibSHTXTLoaderToolbarAction_)
end;
TibSHTXTLoaderToolbarAction_Rollback = class(TibSHTXTLoaderToolbarAction_)
end;
TibSHTXTLoaderToolbarAction_Open = class(TibSHTXTLoaderToolbarAction_)
end;
implementation
uses
ibSHConsts,
ibSHTXTLoaderFrm;
{ TibSHTXTLoaderPaletteAction }
constructor TibSHTXTLoaderPaletteAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallPalette;
Category := Format('%s', ['Tools']);
Caption := Format('%s', [SCallTXTLoader]);
ShortCut := TextToShortCut(EmptyStr);
end;
function TibSHTXTLoaderPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID);
end;
procedure TibSHTXTLoaderPaletteAction.EventExecute(Sender: TObject);
begin
Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHTXTLoader, EmptyStr);
end;
procedure TibSHTXTLoaderPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHTXTLoaderPaletteAction.EventUpdate(Sender: TObject);
begin
Enabled := Assigned(Designer.CurrentDatabase) and
(Designer.CurrentDatabase as ISHRegistration).Connected and
SupportComponent(Designer.CurrentDatabase.BranchIID);
end;
{ TibSHTXTLoaderFormAction }
constructor TibSHTXTLoaderFormAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallForm;
Caption := SCallDMLStatement;
SHRegisterComponentForm(IibSHTXTLoader, Caption, TibSHTXTLoaderForm);
end;
function TibSHTXTLoaderFormAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHTXTLoader);
end;
procedure TibSHTXTLoaderFormAction.EventExecute(Sender: TObject);
begin
Designer.ChangeNotification(Designer.CurrentComponent, Caption, opInsert);
end;
procedure TibSHTXTLoaderFormAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHTXTLoaderFormAction.EventUpdate(Sender: TObject);
begin
FDefault := Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, Caption);
end;
{ TibSHTXTLoaderToolbarAction_ }
constructor TibSHTXTLoaderToolbarAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
Caption := '-';
if Self is TibSHTXTLoaderToolbarAction_Run then Tag := 1;
if Self is TibSHTXTLoaderToolbarAction_Pause then Tag := 2;
if Self is TibSHTXTLoaderToolbarAction_Commit then Tag := 3;
if Self is TibSHTXTLoaderToolbarAction_Rollback then Tag := 4;
if Self is TibSHTXTLoaderToolbarAction_Open then Tag := 5;
case Tag of
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Stop']);
ShortCut := TextToShortCut('Ctrl+BkSp');
end;
3:
begin
Caption := Format('%s', ['Commit']);
ShortCut := TextToShortCut('Shift+Ctrl+C');
end;
4:
begin
Caption := Format('%s', ['Rollback']);
ShortCut := TextToShortCut('Shift+Ctrl+R');
end;
5:
begin
Caption := Format('%s', ['Open']);
ShortCut := TextToShortCut('Ctrl+O');
end;
end;
if Tag <> 0 then Hint := Caption;
end;
function TibSHTXTLoaderToolbarAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHTXTLoader);
end;
procedure TibSHTXTLoaderToolbarAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Pause
2: (Designer.CurrentComponentForm as ISHRunCommands).Pause;
// Commit
3: (Designer.CurrentComponentForm as ISHRunCommands).Commit;
// Rollback
4: (Designer.CurrentComponentForm as ISHRunCommands).Rollback;
// Open
5: (Designer.CurrentComponentForm as ISHFileCommands).Open;
end;
end;
procedure TibSHTXTLoaderToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHTXTLoaderToolbarAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDMLStatement) and
Supports(Designer.CurrentComponent, IibSHTXTLoader) then
begin
case Tag of
// Separator
0:
begin
Visible := True;
end;
// Run
1:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
end;
// Pause
2:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause;
end;
// Commit
3:
begin
Visible := not (Designer.CurrentComponent as IibSHTXTLoader).CommitEachLine;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanCommit and
(Designer.CurrentComponentForm as ISHRunCommands).CanRun;
end;
// Rollback
4:
begin
Visible := not (Designer.CurrentComponent as IibSHTXTLoader).CommitEachLine;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRollback and
(Designer.CurrentComponentForm as ISHRunCommands).CanRun;
end;
// Open
5:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHFileCommands).CanOpen;
end;
end;
end else
Visible := False;
end;
end.
|
unit UnitSlideShowScanDirectoryThread;
interface
uses
Classes,
Forms,
ActiveX,
uConstants,
uMemory,
uThreadEx,
uThreadForm,
uDBUtils,
uDBContext,
uDBEntities,
uAssociations;
type
TSlideShowScanDirectoryThread = class(TThreadEx)
private
{ Private declarations }
FContext: IDBContext;
FSender: TForm;
BaseFileName: string;
Info: TMediaItemCollection;
FSID: TGUID;
protected
procedure Execute; override;
public
constructor Create(Context: IDBContext; Sender: TThreadForm; SID: TGUID; aBaseFileName: string);
procedure SynchNotify;
end;
implementation
uses SlideShow, SysUtils;
constructor TSlideShowScanDirectoryThread.Create(Context: IDBContext;
Sender: TThreadForm; SID: TGUID; aBaseFileName: string);
begin
inherited Create(Sender, SID);
FContext := Context;
FSID := SID;
FSender := Sender;
BaseFileName := ABaseFileName;
end;
procedure TSlideShowScanDirectoryThread.Execute;
var
N: Integer;
begin
inherited;
FreeOnTerminate := True;
CoInitializeEx(nil, COM_MODE);
try
Info := TMediaItemCollection.Create;
try
GetFileListByMask(FContext, BaseFileName, TFileAssociations.Instance.ExtensionList, Info, N, True);
SynchronizeEx(SynchNotify);
finally
F(Info);
end;
finally
CoUninitialize;
end;
end;
procedure TSlideShowScanDirectoryThread.SynchNotify;
begin
ViewerForm.WaitingList := False;
ViewerForm.ExecuteW(Self, Info, BaseFileName);
end;
end.
|
// Raytracer demo - demonstrates XD Pascal methods and interfaces
{$APPTYPE CONSOLE}
program Raytracer;
type
TVec = array [1..3] of Real;
function add for u: TVec (var v: TVec): TVec;
var i: Integer;
begin
for i := 1 to 3 do Result[i] := u[i] + v[i];
end;
function sub for u: TVec (var v: TVec): TVec;
var i: Integer;
begin
for i := 1 to 3 do Result[i] := u[i] - v[i];
end;
function mul for v: TVec (a: Real): TVec;
var i: Integer;
begin
for i := 1 to 3 do Result[i] := a * v[i];
end;
function dot for u: TVec (var v: TVec): Real;
var i: Integer;
begin
Result := 0;
for i := 1 to 3 do Result := Result + u[i] * v[i];
end;
function elementwise for u: TVec (var v: TVec): TVec;
var i: Integer;
begin
for i := 1 to 3 do Result[i] := u[i] * v[i];
end;
function norm(var v: TVec): Real;
begin
Result := sqrt(v.dot(v));
end;
function normalize(var v: TVec): TVec;
begin
Result := v.mul(1.0 / norm(v));
end;
function rand: TVec;
var i: Integer;
begin
for i := 1 to 3 do Result[i] := Random - 0.5;
end;
type
TColor = TVec;
TRay = record
Origin, Dir: TVec;
end;
TGenericBody = record
Center: TVec;
Color: TColor;
Diffuseness: Real;
IsLamp: Boolean;
end;
PGenericBody = ^TGenericBody;
function LambertFactor for b: TGenericBody (Lambert: Real): Real;
begin
Result := 1.0 - (1.0 - Lambert) * b.Diffuseness;
end;
type
TBox = record
GenericBody: TGenericBody;
HalfSize: TVec;
end;
function GetGenericBody for b: TBox: PGenericBody;
begin
Result := @b.GenericBody;
end;
function Intersect for b: TBox (var Ray: TRay; var Point, Normal: TVec): Boolean;
function IntersectFace(i, j, k: Integer): Boolean;
function Within(x, y, xmin, ymin, xmax, ymax: Real): Boolean;
begin
Result := (x > xmin) and (x < xmax) and (y > ymin) and (y < ymax);
end;
var
Side, Factor: Real;
begin // IntersectFace
Result := FALSE;
if abs(Ray.Dir[k]) > 1e-9 then
begin
Side := 1.0;
if Ray.Dir[k] > 0.0 then Side := -1.0;
Factor := (b.GenericBody.Center[k] + Side * b.HalfSize[k] - Ray.Origin[k]) / Ray.Dir[k];
if Factor > 0.1 then
begin
Point := Ray.Origin.add(Ray.Dir.mul(Factor));
if Within(Point[i], Point[j],
b.GenericBody.Center[i] - b.HalfSize[i], b.GenericBody.Center[j] - b.HalfSize[j],
b.GenericBody.Center[i] + b.HalfSize[i], b.GenericBody.Center[j] + b.HalfSize[j])
then
begin
Normal[i] := 0; Normal[j] := 0; Normal[k] := Side;
Result := TRUE;
end;
end;
end;
end;
begin // Intersect
Result := IntersectFace(1, 2, 3) or IntersectFace(3, 1, 2) or IntersectFace(2, 3, 1);
end;
type
TSphere = record
GenericBody: TGenericBody;
Radius: Real;
end;
function GetGenericBody for s: TSphere: PGenericBody;
begin
Result := @s.GenericBody;
end;
function Intersect for s: TSphere (var Ray: TRay; var Point, Normal: TVec): Boolean;
var
Displacement: TVec;
Proj, Discr, Factor: Real;
begin
Displacement := s.GenericBody.Center.sub(Ray.Origin);
Proj := Displacement.dot(Ray.Dir);
Discr := sqr(s.Radius) + sqr(Proj) - Displacement.dot(Displacement);
if Discr > 0 then
begin
Factor := Proj - sqrt(Discr);
if Factor > 0.1 then
begin
Point := Ray.Origin.add(Ray.Dir.mul(Factor));
Normal := Point.sub(s.GenericBody.Center).mul(1.0 / s.Radius);
Result := TRUE;
Exit;
end;
end;
Result := FALSE;
end;
type
IBody = interface
GetGenericBody: function: PGenericBody;
Intersect: function (var Ray: TRay; var Point, Normal: TVec): Boolean;
end;
const
MAXBODIES = 10;
type
TScene = record
AmbientColor: TColor;
Body: array [1..MAXBODIES] of IBody;
NumBodies: Integer;
end;
function Trace for sc: TScene (var Ray: TRay; Depth: Integer): TColor;
var
BestBody: PGenericBody;
Point, Normal, BestPoint, BestNormal, SpecularDir, DiffuseDir: TVec;
DiffuseRay: TRay;
Dist, BestDist, Lambert: Real;
BestIndex, i: Integer;
begin
if Depth > 3 then
begin
Result := sc.AmbientColor;
Exit;
end;
// Find nearest intersection
BestDist := 1e9;
BestIndex := 0;
for i := 1 to sc.NumBodies do
begin
if sc.Body[i].Intersect(Ray, Point, Normal) then
begin
Dist := norm(Point.sub(Ray.Origin));
if Dist < BestDist then
begin
BestDist := Dist;
BestIndex := i;
BestPoint := Point;
BestNormal := Normal;
end;
end;
end;
// Reflect rays
if BestIndex > 0 then
begin
BestBody := sc.Body[BestIndex].GetGenericBody();
if BestBody^.IsLamp then
begin
Result := BestBody^.Color;
Exit;
end;
SpecularDir := Ray.Dir.sub(BestNormal.mul(2.0 * (Ray.Dir.dot(BestNormal))));
DiffuseDir := normalize(SpecularDir.add(rand.mul(2.0 * BestBody^.Diffuseness)));
Lambert := DiffuseDir.dot(BestNormal);
if Lambert < 0 then
begin
DiffuseDir := DiffuseDir.sub(BestNormal.mul(2.0 * Lambert));
Lambert := -Lambert;
end;
DiffuseRay.Origin := BestPoint;
DiffuseRay.Dir := DiffuseDir;
with BestBody^ do
Result := sc.Trace(DiffuseRay, Depth + 1).mul(LambertFactor(Lambert)).elementwise(Color);
Exit;
end;
Result := sc.AmbientColor;
end;
// Main program
const
// Define scene
Box1: TBox =
(
GenericBody:
(
Center: (500, -100, 1200);
Color: (0.4, 0.7, 1.0);
Diffuseness: 0.1;
IsLamp: FALSE
);
HalfSize: (400 / 2, 600 / 2, 300 / 2)
);
Box2: TBox =
(
GenericBody:
(
Center: (550, 210, 1100);
Color: (0.9, 1.0, 0.6);
Diffuseness: 0.3;
IsLamp: FALSE
);
HalfSize: (1000 / 2, 20 / 2, 1000 / 2)
);
Sphere1: TSphere =
(
GenericBody:
(
Center: (600, 0, 700);
Color: (1.0, 0.4, 0.6);
Diffuseness: 0.2;
IsLamp: FALSE
);
Radius: 200
);
Sphere2: TSphere =
(
GenericBody:
(
Center: (330, 150, 700);
Color: (1.0, 1.0, 0.3);
Diffuseness: 0.15;
IsLamp: FALSE
);
Radius: 50
);
// Define light
Lamp1: TSphere =
(
GenericBody:
(
Center: (500, -1000, -700);
Color: (1.0, 1.0, 1.0);
Diffuseness: 1.0;
IsLamp: TRUE
);
Radius: 800
);
AmbientLightColor: TColor = (0.2, 0.2, 0.2);
// Define eye
Pos: TVec = (0, 0, 0);
Azimuth = 30.0 * pi / 180.0;
Width = 640;
Height = 480;
Focal = 500;
Antialiasing = 1.0;
// Output file
FileName = 'scene.ppm';
var
Scene: TScene;
Dir, RotDir, RandomDir: TVec;
Color: TColor;
Ray: TRay;
sinAz, cosAz: Real;
F: Text;
Rays, i, j, r: Integer;
StartTime, StopTime: LongInt;
begin
WriteLn('Raytracer demo');
WriteLn;
Write('Rays per pixel (recommended 1 to 100): '); ReadLn(Rays);
WriteLn;
Randomize;
with Scene do
begin
AmbientColor := AmbientLightColor;
Body[1] := Box1;
Body[2] := Box2;
Body[3] := Sphere1;
Body[4] := Sphere2;
Body[5] := Lamp1;
NumBodies := 5;
end;
sinAz := sin(Azimuth); cosAz := cos(Azimuth);
Assign(F, FileName);
Rewrite(F);
WriteLn(F, 'P3');
WriteLn(F, Width, ' ', Height);
WriteLn(F, 255);
StartTime := GetTickCount;
for i := 0 to Height - 1 do
begin
for j := 0 to Width - 1 do
begin
Color[1] := 0;
Color[2] := 0;
Color[3] := 0;
Dir[1] := j - Width / 2;
Dir[2] := i - Height / 2;
Dir[3] := Focal;
RotDir[1] := Dir[1] * cosAz + Dir[3] * sinAz;
RotDir[2] := Dir[2];
RotDir[3] := -Dir[1] * sinAz + Dir[3] * cosAz;
for r := 1 to Rays do
begin
RandomDir := RotDir.add(rand.mul(Antialiasing));
Ray.Origin := Pos;
Ray.Dir := normalize(RandomDir);
Color := Color.add(Scene.Trace(Ray, 0));
end;
Color := Color.mul(255.0 / Rays);
Write(F, Round(Color[1]), ' ', Round(Color[2]), ' ', Round(Color[3]), ' ');
end;
WriteLn(F);
WriteLn(i + 1, '/', Height);
end;
StopTime := GetTickCount;
Close(F);
WriteLn;
WriteLn('Rendering time: ', (StopTime - StartTime) / 1000 :5:1, ' s');
WriteLn('Done. See ' + FileName);
ReadLn;
end.
|
unit SDTdxForm;
interface
uses
Windows, Forms, BaseForm, Classes, Controls, Sysutils, StdCtrls;
win.diskfile;
type
TfrmSDTdx = class(TfrmBase)
btnImport: TButton;
procedure btnImportClick(Sender: TObject);
protected
procedure ImportDayData;
procedure ImportTxtData; overload;
procedure ImportTxtData(AFileUrl: string); overload;
procedure ImportLcData;
public
end;
implementation
{$R *.dfm}
uses
define_datasrc,
define_price,
StockMinuteDataAccess,
StockMinuteData_Save;
type
TTdxMinuteDataHead = packed record // 26 字节
// 570 的话表示9:30分(570/60=9.5)
DealTime: Word; // 2
PriceNow: Integer; // 4
PriceAverage: Integer; // 4 均价
Volume: Word; // 2 个或 4 个字节
end;
TTdxMinuteDataSection = packed record
DataHead: TTdxMinuteDataHead;
DataReserve: array[0..26 - 1 - SizeOf(TTdxMinuteDataHead)] of Byte;
end;
TTdxDayHead = packed record
dDate: DWORD; //交易日期
fOpen: DWORD; //开盘价(元)
fHigh: DWORD; //最高价(元)
fLow: DWORD; //最低价(元)
fClose: DWORD; //收盘价(元)
fAmount: DWORD; //成交额(元)
dVol: DWORD ; //成交量(股)
end;
TTdxDayDataSection = packed record
DataHead: TTdxDayHead;
Reservation: DWORD; //保留未用
end;
TTdxDataHead = packed record
end;
PTdxData = ^TTdxData;
TTdxData = packed record
MinuteData: array[0..65565] of TTdxMinuteDataSection;
end;
(*//
通达信日线和分时图数据格式
http://blog.csdn.net/coollzt/article/details/7245298
http://blog.csdn.net/coollzt/article/details/7245312
http://blog.csdn.net/coollzt/article/details/7245304
http://www.tdx.com.cn/list_66_68.html
原来 招商证券 通达信 可以直接导出 那就直接导出好了
//*)
procedure TfrmSDTdx.ImportLcData;
var
tmpFileUrl: string;
begin
tmpFileUrl := 'E:\StockApp\sdata\sh999999.lc5';
end;
procedure TfrmSDTdx.ImportDayData;
var
tmpFileUrl: string;
//tmpWinFile: PWinFile;
tmpFileData: PTdxData;
begin
// Vipdoc\sh\lday\*.day
(*
tmpFileUrl := 'E:\StockApp\sdata\sh600000.day';
tmpWinFile := CheckOutWinFile;
try
if WinFileOpen(tmpWinFile, tmpFileUrl, false) then
begin
if WinFileOpenMap(tmpWinFile) then
begin
tmpFileData := tmpWinFile.FileMapRootView;
if nil <> tmpFileData then
begin
end;
end;
end;
finally
CheckInWinFile(tmpWinFile);
end;
//*)
end;
type
PDateTimeParseRecord = ^TDateTimeParseRecord;
TDateTimeParseRecord = record
Year: Word;
Month: Word;
Day: Word;
Hour: Word;
Minute: Word;
Second: Word;
MSecond: Word;
Date: TDate;
Time: TTime;
end;
procedure ParseDateTime(ADateTimeParse: PDateTimeParseRecord; ADateTimeString: AnsiString);
var
i: integer;
tmpStrDate: AnsiString;
tmpStrTime: AnsiString;
tmpStrHead: AnsiString;
tmpStrEnd: AnsiString;
tmpFormat: TFormatSettings;
begin
// 2014/06/12-10:30
i := Pos('-', ADateTimeString);
if 0 < i then
begin
tmpStrDate := Copy(ADateTimeString, 1, i - 1);
tmpStrTime := Copy(ADateTimeString, i + 1, maxint);
FillChar(tmpFormat, SizeOf(tmpFormat), 0);
tmpFormat.DateSeparator := '/';
tmpFormat.TimeSeparator := ':';
tmpFormat.ShortDateFormat := 'yyyy/mm/dd';
tmpFormat.LongDateFormat := 'yyyy/mm/dd';
tmpFormat.ShortTimeFormat := 'hh:nn:ss';
tmpFormat.LongTimeFormat := 'hh:nn:ss';
ADateTimeParse.Date := StrToDateDef(tmpStrDate, 0, tmpFormat);
ADateTimeParse.Time := StrToTimeDef(tmpStrTime, 0, tmpFormat);
if 0 < ADateTimeParse.Date then
DecodeDate(ADateTimeParse.Date, ADateTimeParse.Year, ADateTimeParse.Month, ADateTimeParse.Day);
if 0 < ADateTimeParse.Time then
DecodeTime(ADateTimeParse.Time, ADateTimeParse.Hour, ADateTimeParse.Minute, ADateTimeParse.Second, ADateTimeParse.MSecond);
end;
end;
procedure TfrmSDTdx.ImportTxtData();
var
tmpFileUrl: string;
begin
tmpFileUrl := 'E:\StockApp\sdata\999999.txt';
end;
procedure TfrmSDTdx.ImportTxtData(AFileUrl: string);
type
TColumns = (colTime, colOpen, colHigh, colLow, colClose, colVolume);
TColumnsHeader = array[TColumns] of string;
TColumnsIndex = array[TColumns] of Integer;
const
ColumnsHeader: TColumnsHeader =
('时间','开盘','最高','最低','收盘','成交量');
var
tmpFileName: string;
tmpRowData: string;
tmpTime: string;
tmpFileContent: TStringList;
tmpRowDatas: TStringList;
tmpColumnIndex: TColumnsIndex;
tmpIsReadHead: Boolean;
iCol: TColumns;
i, j: integer;
tmpDateTimeParse: TDateTimeParseRecord;
tmpMinuteDataAccess: TStockMinuteDataAccess;
begin
if not FileExists(AFileUrl) then
exit;
tmpFileName := ExtractFileName(AFileUrl);
tmpMinuteDataAccess := nil;
tmpFileContent := TStringList.Create;
tmpRowDatas := TStringList.Create;
try
tmpFileContent.LoadFromFile(AFileUrl);
tmpIsReadHead := false;
for iCol := Low(TColumns) to High(TColumns) do
tmpColumnIndex[iCol] := -1;
for i := 0 to tmpFileContent.Count - 1 do
begin
tmpRowData := Trim(tmpFileContent[i]);
if '' <> tmpRowData then
begin
// 上证指数 (999999)
// '时间'#9' 开盘'#9' 最高'#9' 最低'#9' 收盘'#9' 成交量'#9'BOLL-M.BOLL '#9'BOLL-M.UB '#9'BOLL-M.LB '#9' VOL.VOLUME'#9' VOL.MAVOL1'#9' VOL.MAVOL2'#9' CYHT.高抛 '#9' CYHT.SK '#9' CYHT.SD '#9' CYHT.低吸 '#9' CYHT.强弱分界'#9' CYHT.卖出 '#9' CYHT.买进 '#9' BDZX.AK '#9' BDZX.AD1 '#9' BDZX.AJ '#9' BDZX.aa '#9' BDZX.bb '#9' BDZX.cc '#9' BDZX.买进 '#9' BDZX.卖出'
tmpRowDatas.Text := StringReplace(tmpRowData, #9, #13#10, [rfReplaceAll]);
if not tmpIsReadHead then
begin
for iCol := Low(TColumns) to High(TColumns) do
begin
for j := 0 to tmpRowDatas.Count - 1 do
begin
if SameText(ColumnsHeader[iCol], Trim(tmpRowDatas[j])) then
begin
tmpIsReadHead := True;
tmpColumnIndex[iCol] := j;
end;
end;
end;
end else
begin
FillChar(tmpDateTimeParse, SizeOf(tmpDateTimeParse), 0);
tmpTime := '';
if 0 <= tmpColumnIndex[colTime] then
begin
tmpTime := tmpRowDatas[tmpColumnIndex[colTime]];
// 2014/06/12-10:30
end;
if '' <> tmpTime then
begin
ParseDateTime(@tmpDateTimeParse, tmpTime);
end;
if (0 < tmpDateTimeParse.Date) and (0 < tmpDateTimeParse.Time) then
begin
if nil = tmpMinuteDataAccess then
begin
tmpMinuteDataAccess := TStockMinuteDataAccess.Create(nil, DataSrc_TongDaXin, weightNone);
end;
//tmpMinuteDataAccess.CheckOutRecord(ADate: Word): PRT_Quote_M1_Day;
end;
end;
end;
end;
//except
finally
tmpRowDatas.Clear;
tmpRowDatas.Free;
tmpFileContent.Free;
end;
end;
procedure TfrmSDTdx.btnImportClick(Sender: TObject);
begin
inherited;
//tmpFileUrl := 'E:\StockApp\sdata\20160617\sh160617.mhq';
//tmpFileUrl := 'E:\StockApp\sdata\20160617\sh160617.ref';
//tmpFileUrl := 'E:\StockApp\sdata\20160617\20160617.tic';
ImportTxtData;
end;
end.
|
unit regexDemo;
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.CheckLst;
type
TForm1 = class(TForm)
Panel1: TPanel;
memDocument: TMemo;
Splitter1: TSplitter;
clbFlags: TCheckListBox;
lblExpression: TLabel;
lblFlags: TLabel;
memExpression: TMemo;
Search: TButton;
memResults: TMemo;
Splitter2: TSplitter;
procedure SearchClick(Sender: TObject);
private
function Expression: string;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses System.RegularExpressions;
{$R *.dfm}
function TForm1.Expression: string;
begin
result := string(memExpression.text).replace(#13#10,'');
end;
procedure TForm1.SearchClick(Sender: TObject);
begin
var match := TRegex.match(memDocument.text, Expression);
memResults.text := match.value;
end;
end.
|
unit AdjustQtyReasonUpsertView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, AdjustReasonCls;
type
TvwAdjustQtyReasonUpsert = class(TForm)
pnBottom: TPanel;
bbtnAdd: TBitBtn;
btnCancel: TBitBtn;
lblReason: TLabel;
edtReason: TEdit;
chkHidden: TCheckBox;
chkSystem: TCheckBox;
chkActive: TCheckBox;
procedure bbtnAddClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
reason: TAdjustReason;
isInsert: Boolean;
procedure MsgResultCmd();
procedure ClearScreen();
procedure MoveScreenToObject();
procedure MoveObjectToScreen();
public
{ Public declarations }
function Start(argId: Integer): Boolean;
end;
var
vwAdjustQtyReasonUpsert: TvwAdjustQtyReasonUpsert;
implementation
{$R *.dfm}
uses uDM;
{ TForm1 }
function TvwAdjustQtyReasonUpsert.Start(argId: Integer): Boolean;
begin
self.isInsert := ( argId = 0 );
if ( not self.isInsert ) then begin
Caption := 'Update Reason';
reason := dm.ReadReason(argId);
MoveObjectToScreen()
end else begin
Caption := 'Insert Reason';
reason := TAdjustReason.Create();
end;
result := ( ShowModal = mrOK );
end;
procedure TvwAdjustQtyReasonUpsert.bbtnAddClick(Sender: TObject);
begin
try
MoveScreenToObject();
if ( self.isInsert ) then begin
dm.CreateReason(self.reason);
ClearScreen();
end else begin
dm.UpdateReason(self.reason);
end;
MsgResultCmd()
except
on
e: Exception do begin
raise e.Create('Failed to save record ' + e.Message);
end;
end;
end;
procedure TvwAdjustQtyReasonUpsert.MsgResultCmd();
begin
if ( self.isInsert ) then begin
ShowMessage('Successfully inserted!');
end else begin
ShowMessage('Successfully updated!');
end;
end;
procedure TvwAdjustQtyReasonUpsert.ClearScreen;
begin
edtReason.Clear();
chkHidden.Checked := FALSE;
chkSystem.Checked := FALSE;
chkActive.Checked := FALSE;
end;
procedure TvwAdjustQtyReasonUpsert.MoveObjectToScreen();
begin
edtReason.Text := reason.Reason;
chkHidden.Checked := reason.Hidden = 1;
chkSystem.Checked := reason.System = 1;
chkActive.Checked := reason.Activated = 1;
end;
procedure TvwAdjustQtyReasonUpsert.MoveScreenToObject();
begin
reason.Reason := edtReason.Text;
reason.Hidden := 0;
reason.System := 0;
reason.Activated := 0;
if ( chkHidden.Checked ) then begin
reason.Hidden := 1;
end;
if ( chkSystem.Checked ) then begin
reason.System := 1;
end;
if ( chkActive.Checked ) then begin
reason.Activated := 1;
end;
end;
procedure TvwAdjustQtyReasonUpsert.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ( reason <> nil ) then begin
FreeAndNil(reason);
end;
end;
end.
|
unit InflatablesList_Types;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Graphics,
AuxTypes;
const
KiB = 1024;
MiB = 1024 * KiB;
IL_ITEM_NUM_TAG_MIN = -99999;
IL_ITEM_NUM_TAG_MAX = +99999;
//==============================================================================
//- event prototypes -----------------------------------------------------------
type
TILObjectL1Event = procedure(Sender: TObject; O1: TObject) of object;
TILObjectL2Event = procedure(Sender: TObject; O1,O2: TObject) of object;
TILIndexedObjectL1Event = procedure(Sender: TObject; IndexedObj: TObject; Index: Integer) of object;
TILIndexedObjectL2Event = procedure(Sender: TObject; Obj: TObject; IndexedObj: TObject; Index: Integer) of object;
//==============================================================================
//- reconverted string ---------------------------------------------------------
type
TILReconvString = record
Str: String;
UTF8Reconv: String;
AnsiReconv: String;
end;
Function IL_UTF8Reconvert(const Str: String): String;
Function IL_ANSIReconvert(const Str: String): String;
Function IL_ReconvString(const Str: String; RemoveNullChars: Boolean = True): TILReconvString;
Function IL_ReconvCompareStr(const A,B: TILReconvString): Integer;
Function IL_ReconvCompareText(const A,B: TILReconvString): Integer;
Function IL_ReconvSameStr(const A,B: TILReconvString): Boolean;
Function IL_ReconvSameText(const A,B: TILReconvString): Boolean;
procedure IL_UniqueReconvStr(var Str: TILReconvString);
Function IL_ThreadSafeCopy(const Str: TILReconvString): TILReconvString; overload;
//==============================================================================
//- items ----------------------------------------------------------------------
type
TLIItemPictureKind = (ilipkUnknown,ilipkMain,ilipkSecondary,ilipkPackage);
TLIItemPictureKinds = set of TLIItemPictureKind;
TILItemType = (ilitUnknown,ilitRing,ilitRingWithHandles,ilitRingSpecial,
ilitBall,ilitRider,ilitLounger,ilitLoungerChair,ilitSeat,
ilitWings,ilitToy,ilitIsland,ilitIslandExtra,ilitBoat,
ilitMattress,ilitBed,ilitChair,ilitSofa,ilitBalloon,ilitOther);
TILItemManufacturer = (ilimUnknown,ilimBestway,ilimCrivit{Lidl},ilimIntex,
ilimHappyPeople,ilimMondo,ilimPolygroup,ilimSummerWaves,
ilimSwimline,ilimVetroPlus,ilimWehncke,ilimWIKY,ilimOthers);
TILItemFlag = (ilifOwned,ilifWanted,ilifOrdered,ilifBoxed,ilifElsewhere,
ilifUntested,ilifTesting,ilifTested,ilifDamaged,ilifRepaired,
ilifPriceChange,ilifAvailChange,ilifNotAvailable,ilifLost,
ilifDiscarded);
TILItemFlags = set of TILItemFlag;
TILItemMaterial = (ilimtUnknown,ilimtPolyvinylchloride{PVC},ilimtPolyester{PES},
ilimtPolyetylene{PE},ilimtPolypropylene{PP},
ilimtAcrylonitrileButadieneStyrene{ABS},ilimtPolystyren{PS},
ilimtPolyurethane{PUR},ilimtLatex,ilimtSilicone,
ilimtGumoTex,ilimtOther);
TILItemSurfaceFinish = (ilisfUnknown,ilisfGlossy,ilisfSemiGloss,ilisfMatte,
ilisfSemiMatte,ilisfPearlscent,ilisfMetalic,
ilisfFlocked,ilisfCombined,ilisfOther);
Function IL_ItemPictureKindToStr(PictureKind: TLIItemPictureKind; FullString: Boolean = False): String;
Function IL_ItemTypeToNum(ItemType: TILItemType): Int32;
Function IL_NumToItemType(Num: Int32): TILItemType;
Function IL_ItemManufacturerToNum(ItemManufacturer: TILItemManufacturer): Int32;
Function IL_NumToItemManufacturer(Num: Int32): TILItemManufacturer;
Function IL_SetItemFlagValue(var ItemFlags: TILItemFlags; ItemFlag: TILItemFlag; NewValue: Boolean): Boolean;
Function IL_EncodeItemFlags(ItemFlags: TILItemFlags): UInt32;
Function IL_DecodeItemFlags(Flags: UInt32): TILItemFlags;
Function IL_ItemMaterialToNum(Material: TILItemMaterial): Int32;
Function IL_NumToItemMaterial(Num: Int32): TILItemMaterial;
Function IL_ItemSurfaceFinishToNum(SurfaceFinish: TILItemSurfaceFinish): Int32;
Function IL_NumToItemSurfaceFinish(Num: Int32): TILItemSurfaceFinish;
//==============================================================================
//- item shop parsing ----------------------------------------------------------
const
IL_ITEMSHOP_PARSING_VARS_COUNT = 8; // never change the number (8 is enough for everyone :P)!
type
TILItemShopParsingExtrFrom = (ilpefText,ilpefNestedText,ilpefAttrValue);
TILItemShopParsingExtrMethod = (ilpemFirstInteger,ilpemFirstIntegerTag,
ilpemNegTagIsCount,ilpemFirstNumber,
ilpemFirstNumberTag);
TILItemShopParsingExtrSett = record
ExtractFrom: TILItemShopParsingExtrFrom;
ExtractionMethod: TILItemShopParsingExtrMethod;
ExtractionData: String;
NegativeTag: String;
end;
PILItemShopParsingExtrSett = ^TILItemShopParsingExtrSett;
TILItemShopParsingExtrSettList = array of TILItemShopParsingExtrSett;
TILItemShopParsingVariables = record
Vars: array[0..Pred(IL_ITEMSHOP_PARSING_VARS_COUNT)] of String;
end;
Function IL_ExtractFromToNum(ExtractFrom: TILItemShopParsingExtrFrom): Int32;
Function IL_NumToExtractFrom(Num: Int32): TILItemShopParsingExtrFrom;
Function IL_ExtrMethodToNum(ExtrMethod: TILItemShopParsingExtrMethod): Int32;
Function IL_NumToExtrMethod(Num: Int32): TILItemShopParsingExtrMethod;
Function IL_ThreadSafeCopy(const Value: TILItemShopParsingExtrSett): TILItemShopParsingExtrSett; overload;
Function IL_ThreadSafeCopy(const Value: TILItemShopParsingVariables): TILItemShopParsingVariables; overload;
//==============================================================================
//- item shop ------------------------------------------------------------------
type
TILItemShopUpdateResult = (
ilisurSuccess, // lime ilurSuccess
ilisurMildSucc, // green ilurSuccess on untracked
ilisurDataFail, // blue ilurNoLink, ilurNoData
ilisurSoftFail, // yellow ilurFailAvailSearch, ilurFailAvailValGet
ilisurHardFail, // orange ilurFailSearch, ilurFailValGet
ilisurDownload, // purple ilurFailDown
ilisurParsing, // red ilurFailParse
ilisurFatal); // black ilurFail, unknown state
TILItemShopHistoryEntry = record
Value: Int32;
Time: TDateTIme;
end;
TILItemShopHistory = array of TILItemShopHistoryEntry;
Function IL_ItemShopUpdateResultToNum(UpdateResult: TILItemShopUpdateResult): Int32;
Function IL_NumToItemShopUpdateResult(Num: Int32): TILItemShopUpdateResult;
Function IL_ItemShopUpdateResultToColor(UpdateResult: TILItemShopUpdateResult): TColor;
//==============================================================================
//- searching ------------------------------------------------------------------
type
{
when adding new item to search result:
- add to enumeration
- add to item contains check (TILItem_Comp.Contains)
- add to second check method if the value is editable
- add to search highlight in item frame (TfrmItemFrame.HighLight)
- no need to add to saving or conversion (not saved)
}
TILItemSearchResult = (ilisrNone,ilisrItemPicFile,ilisrSecondaryPicFile,
ilisrPackagePicFile,ilisrType,ilisrTypeSpec,ilisrPieces,ilisrUserID,
ilisrManufacturer,ilisrManufacturerStr,ilisrTextID,ilisrNumID,
ilisrFlagOwned,ilisrFlagWanted,ilisrFlagOrdered,ilisrFlagBoxed,
ilisrFlagElsewhere,ilisrFlagUntested,ilisrFlagTesting,ilisrFlagTested,
ilisrFlagDamaged,ilisrFlagRepaired,ilisrFlagPriceChange,
ilisrFlagAvailChange,ilisrFlagNotAvailable,ilisrFlagLost,ilisrFlagDiscarded,
ilisrTextTag,ilisrNumTag,ilisrWantedLevel,ilisrVariant,ilisrVariantTag,
ilisrSurfaceFinish,ilisrMaterial,ilisrThickness,ilisrSizeX,ilisrSizeY,
ilisrSizeZ,ilisrUnitWeight,ilisrNotes,ilisrReviewURL,ilisrUnitPriceDefault,
ilisrRating,ilisrRatingDetails,ilisrSelectedShop);
Function IL_WrapSearchResult(Val: TILItemSearchResult): TILItemSearchResult;
type
{
when adding new item to advanced search result:
- add to enumeration
- add to data (conversion to string)
- add to item search (TILItem_Search.SearchField)
- no need to add to saving or conversion (not saved)
}
TILAdvItemSearchResult = (ilaisrListIndex,ilaisrUniqueID,ilaisrTimeOfAdd,
ilaisrDescriptor,ilaisrTitleStr,ilaisrPictures,ilaisrMainPictureFile,
ilaisrCurrSecPictureFile,ilaisrPackagePictureFile,ilaisrType,ilaisrTypeSpec,
ilaisrTypeStr,ilaisrPieces,ilaisrUserID,ilaisrManufacturer,
ilaisrManufacturerStr,ilaisrManufacturerTag,ilaisrTextID,ilaisrNumID,
ilaisrIDStr,ilaisrFlags,ilaisrFlagOwned,ilaisrFlagWanted,ilaisrFlagOrdered,
ilaisrFlagBoxed,ilaisrFlagElsewhere,ilaisrFlagUntested,ilaisrFlagTesting,
ilaisrFlagTested,ilaisrFlagDamaged,ilaisrFlagRepaired,ilaisrFlagPriceChange,
ilaisrFlagAvailChange,ilaisrFlagNotAvailable,ilaisrFlagLost,
ilaisrFlagDiscarded,ilaisrTextTag,ilaisrNumTag,ilaisrWantedLevel,
ilaisrVariant,ilaisrVariantTag,ilaisrSurfaceFinish,ilaisrMaterial,
ilaisrThickness,ilaisrSizeX,ilaisrSizeY,ilaisrSizeZ,ilaisrTotalSize,
ilaisrSizeStr,ilaisrUnitWeight,ilaisrTotalWeight,ilaisrTotalWeightStr,
ilaisrNotes,ilaisrReviewURL,ilaisrUnitPriceDefault,ilaisrRating,
ilaisrRatingDetails,ilaisrUnitPrice,ilaisrUnitPriceLowest,
ilaisrTotalPriceLowest,ilaisrUnitPriceHighest,ilaisrTotalPriceHighest,
ilaisrUnitPriceSel,ilaisrTotalPriceSel,ilaisrTotalPrice,
ilaisrAvailableLowest,ilaisrAvailableHighest,ilaisrAvailableSel,
ilaisrShopCount,ilaisrShopCountStr,ilaisrUsefulShopCount,
ilaisrUsefulShopRatio,ilaisrSelectedShop,ilaisrWorstUpdateResult);
TILAdvItemSearchResults = set of TILAdvItemSearchResult;
TILAdvShopSearchResult = (ilassrListIndex,ilassrSelected,ilassrUntracked,
ilassrAltDownMethod,ilassrName,ilassrShopURL,ilassrItemURL,ilassrAvailable,
ilassrPrice,ilassrNotes,ilassrLastUpdResult,ilassrLastUpdMessage,
ilassrLastUpdTime,ilassrParsingVariables,ilassrParsingTemplateRef,
ilassrIgnoreParsErrors,{deep scan...}ilassrAvailHistory,ilassrPriceHistory,
ilassrAvailExtrSettings,ilassrPriceExtrSettings,ilassrAvailFinder,
ilassrPriceFinder);
TILAdvShopSearchResults = set of TILAdvShopSearchResult;
TILAdvSearchParsTemplResolve = Function(const Template: String): Pointer of object;
TILAdvSearchCompareFunc = Function(const Value: String; IsText,IsEditable,IsCalculated: Boolean; const UnitStr: String = ''): Boolean of object;
TILAdvSearchSettings = record
Text: String;
PartialMatch: Boolean;
CaseSensitive: Boolean;
TextsOnly: Boolean;
EditablesOnly: Boolean;
SearchCalculated: Boolean;
IncludeUnits: Boolean;
SearchShops: Boolean;
DeepScan: Boolean; // parsing settings, variables, incl. references
// internals
ParsTemplResolve: TILAdvSearchParsTemplResolve;
CompareFunc: TILAdvSearchCompareFunc;
end;
TILAdvSearchResultShop = record
ShopIndex: Integer;
ShopValue: TILAdvShopSearchResults;
end;
TILAdvSearchResult = record
ItemIndex: Integer;
ItemValue: TILAdvItemSearchResults;
Shops: array of TILAdvSearchResultShop;
end;
TILAdvSearchResults = array of TILAdvSearchResult;
Function IL_ThreadSafeCopy(const Value: TILAdvSearchSettings): TILAdvSearchSettings; overload;
//==============================================================================
//- sorting --------------------------------------------------------------------
type
{
when adding new item value tag:
- add to enumeration
- add to type <-> number conversion functions
- add to data (conversion to string)
- add to item comparison (TILItem_Comp.Compare)
- no need to add to saving (it is managed trough conversion)
}
TILItemValueTag = (
ilivtNone,ilivtItemEncrypted,ilivtUniqueID,ilivtTimeOfAdd,ilivtDescriptor,
ilivtMainPicFilePres,ilivtMainPictureFile,ilivtMainPictureThumb,
ilivtPackPicFilePres,ilivtPackPictureFile,ilivtPackPictureThumb,
ilivtCurrSecPicPres,ilivtCurrSecPicFile,ilivtCurrSecPicThumb,
ilivtPictureCount,ilivtSecPicCount,ilivtSecPicThumbCount,ilivtItemType,
ilivtItemTypeSpec,ilivtPieces,ilivtUserID,ilivtManufacturer,
ilivtManufacturerStr,ilivtTextID,ilivtNumID,ilivtIDStr,ilivtFlagOwned,
ilivtFlagWanted,ilivtFlagOrdered,ilivtFlagBoxed,ilivtFlagElsewhere,
ilivtFlagUntested,ilivtFlagTesting,ilivtFlagTested,ilivtFlagDamaged,
ilivtFlagRepaired,ilivtFlagPriceChange,ilivtFlagAvailChange,
ilivtFlagNotAvailable,ilivtFlagLost,ilivtFlagDiscarded,ilivtTextTag,
ilivtNumTag,ilivtWantedLevel,ilivtVariant,ilivtVariantTag,ilivtSurfaceFinish,
ilivtMaterial,ilivtThickness,ilivtSizeX,ilivtSizeY,ilivtSizeZ,ilivtTotalSize,
ilivtUnitWeight,ilivtTotalWeight,ilivtNotes,ilivtReviewURL,ilivtReview,
ilivtUnitPriceDefault,ilivtRating,ilivtRatingDetails,ilivtSomethingUnknown,
ilivtUnitPriceLowest,ilivtTotalPriceLowest,ilivtUnitPriceSel,
ilivtTotalPriceSel,ilivtTotalPrice,ilivtAvailable,ilivtShopCount,
ilivtUsefulShopCount,ilivtUsefulShopRatio,ilivtSelectedShop,
ilivtWorstUpdateResult);{$message 'add "Is available" - not flagged'}
TILSortingItem = record
ItemValueTag: TILItemValueTag;
Reversed: Boolean;
end;
TILSortingSettings = record
Count: Integer;
Items: array[0..29] of TILSortingItem; // length of this array will newer change ;)
end;
TILSortingProfile = record
Name: String;
Settings: TILSortingSettings;
end;
TILSortingProfiles = array of TILSortingProfile;
Function IL_SameSortingSettings(A,B: TILSortingSettings): Boolean;
Function IL_ItemValueTagToNum(ItemValueTag: TILItemValueTag): Int32;
Function IL_NumToItemValueTag(Num: Int32): TILItemValueTag;
Function IL_ThreadSafeCopy(const Value: TILSortingProfile): TILSortingProfile; overload;
//==============================================================================
//- sum filters ----------------------------------------------------------------
type
TILFilterOperator = (ilfoAND,ilfoOR,ilfoXOR);
TILFilterFlag = (
ilffOwnedSet,ilffOwnedClr,ilffWantedSet,ilffWantedClr,
ilffOrderedSet,ilffOrderedClr,ilffBoxedSet,ilffBoxedClr,
ilffElsewhereSet,ilffElsewhereClr,ilffUntestedSet,ilffUntestedClr,
ilffTestingSet,ilffTestingClr,ilffTestedSet,ilffTestedClr,
ilffDamagedSet,ilffDamagedClr,ilffRepairedSet,ilffRepairedClr,
ilffPriceChangeSet,ilffPriceChangeClr,ilffAvailChangeSet,ilffAvailChangeClr,
ilffNotAvailableSet,ilffNotAvailableClr,ilffLostSet,ilffLostClr,
ilffDiscardedSet,ilffDiscardedClr);
TILFilterFlags = set of TILFilterFlag;
TILFilterSettings = record
Operator: TILFilterOperator;
Flags: TILFilterFlags;
end;
Function IL_FilterOperatorToNum(Operator: TILFilterOperator): Int32;
Function IL_NumToFilterOperator(Num: Int32): TILFilterOperator;
Function IL_SetFilterSettingsFlagValue(var FilterFlags: TILFilterFlags; FilterFlag: TILFilterFlag; NewValue: Boolean): Boolean;
Function IL_EncodeFilterFlags(FilterFlags: TILFilterFlags): UInt32;
Function IL_DecodeFilterFlags(Flags: UInt32): TILFilterFlags;
//==============================================================================
//- sums -----------------------------------------------------------------------
type
TILSumRec = record
Items: Integer;
Pieces: Integer;
UnitWeigth: Integer;
TotalWeight: Integer;
UnitPriceLow: Integer;
UnitPriceSel: Integer;
TotalPriceLow: Integer;
TotalPriceSel: Integer;
TotalPrice: Integer;
end;
TILSumsByType = array[TILItemType] of TILSumRec;
TILSumsByManufacturer = array[TILItemManufacturer] of TILSumRec;
TILSumsArray = array of TILSumRec;
//==============================================================================
//- static settings ------------------------------------------------------------
const
IL_STATIC_SETTINGS_TAGS: array[0..8] of String =
('NPC','TSC','SVP','LDP','NSV','NBC','NUL','LOR','NPR');
IL_DYNAMIC_SETTINGS_TAGS: array[0..4] of String =
('l.cmp','l.enc','l.sav','s.rev','s.cas');
type
TILStaticManagerSettings = record
// command-line options
NoPictures: Boolean;
TestCode: Boolean;
SavePages: Boolean;
LoadPages: Boolean;
NoSave: Boolean;
NoBackup: Boolean;
NoUpdateAutoLog: Boolean;
ListOverride: Boolean;
NoParse: Boolean;
// automatically filled
DefaultPath: String; // initialized to program path
ListPath: String; // filled with list path (without file name)
ListFile: String; // file, where the list will be saved, or was loaded from
ListName: String; // list file without extension
InstanceID: String; // string unique for the program instance (calculated from ListPath)
// folders
PicturesPath: String;
BackupPath: String;
SavedPagesPath: String;
TempPath: String; // path to program temporary folder
end;
Function IL_ThreadSafeCopy(const Value: TILStaticManagerSettings): TILStaticManagerSettings; overload;
//==============================================================================
//- preload information --------------------------------------------------------
type
TILPreloadInfoVersion = packed record
case Boolean of
True: (Full: Int64);
False: (Major: UInt16;
Minor: UInt16;
Release: UInt16;
Build: UInt16);
end;
TILPreloadResultFlag = (ilprfError,ilprfInvalidFile,ilprfExtInfo,ilprfEncrypted,
ilprfCompressed,ilprfPictures,ilprfSlowLoad);
TILPreloadResultFlags = set of TILPreloadResultFlag;
TILPreloadInfo = record
// basic info
ResultFlags: TILPreloadResultFlags;
FileSize: UInt64;
Signature: UInt32;
Structure: UInt32;
// extended info, valid only when ResultFlags contains ilprfExtInfo
Flags: UInt32;
Version: TILPreloadInfoVersion;
TimeRaw: Int64;
Time: TDateTime;
TimeStr: String;
end;
Function IL_ThreadSafeCopy(const Value: TILPreloadInfo): TILPreloadInfo; overload;
//==============================================================================
//- threaded IO ----------------------------------------------------------------
type
TILLoadingResult = (illrSuccess,illrFailed,illrWrongPassword);
TILLoadingDoneEvent = procedure(LoadingResult: TILLoadingResult) of object;
//==============================================================================
//- list and item flags --------------------------------------------------------
const
IL_LIST_FLAG_BITMASK_ENCRYPTED = UInt32($00000001);
IL_LIST_FLAG_BITMASK_COMPRESSED = UInt32($00000002);
IL_ITEM_FLAG_BITMASK_ENCRYPTED = UInt32($00000001);
//==============================================================================
//- encryption -----------------------------------------------------------------
type
TILPasswordRequest = Function(Sender: TObject; out Pswd: String): Boolean of object;
implementation
uses
SysUtils,
BitOps, StrRect;
//==============================================================================
//- reconverted string ---------------------------------------------------------
Function IL_UTF8Reconvert(const Str: String): String;
var
UTF8Temp: UTF8String;
AnsiTemp: AnsiString;
begin
If Length(Str) > 0 then
begin
AnsiTemp := AnsiString(StrToUnicode(Str));
SetLength(UTF8Temp,Length(AnsiTemp));
Move(PAnsiChar(AnsiTemp)^,PUTF8Char(UTF8Temp)^,Length(UTF8Temp));
Result := UnicodeToStr(UTF8Decode(UTF8Temp))
end
else
Result := '';
end;
//------------------------------------------------------------------------------
Function IL_ANSIReconvert(const Str: String): String;
var
UTF8Temp: UTF8String;
AnsiTemp: AnsiString;
begin
If Length(Str) > 0 then
begin
UTF8Temp := UTF8Encode(StrToUnicode(Str));
SetLength(AnsiTemp,Length(UTF8Temp));
Move(PUTF8Char(UTF8Temp)^,PAnsiChar(AnsiTemp)^,Length(AnsiTemp));
Result := UnicodeToStr(UnicodeString(AnsiTemp))
end
else
Result := '';
end;
//------------------------------------------------------------------------------
Function IL_ReconvString(const Str: String; RemoveNullChars: Boolean = True): TILReconvString;
var
i: Integer;
begin
Result.Str := Str;
UniqueString(Result.Str);
// null characters might break some functions
If RemoveNullChars then
For i := 1 to Length(Result.Str) do
If Ord(Result.Str[i]) = 0 then
Result.Str[i] := Char(' ');
Result.UTF8Reconv := IL_UTF8Reconvert(Str);
Result.AnsiReconv := IL_ANSIReconvert(Str);
end;
//------------------------------------------------------------------------------
Function IL_ReconvCompareStr(const A,B: TILReconvString): Integer;
begin
Result := AnsiCompareStr(A.Str,B.Str);
end;
//------------------------------------------------------------------------------
Function IL_ReconvCompareText(const A,B: TILReconvString): Integer;
begin
Result := AnsiCompareText(A.Str,B.Str);
end;
//------------------------------------------------------------------------------
Function IL_ReconvSameStr(const A,B: TILReconvString): Boolean;
begin
Result := AnsiSameStr(A.Str,B.Str);
end;
//------------------------------------------------------------------------------
Function IL_ReconvSameText(const A,B: TILReconvString): Boolean;
begin
Result := AnsiSameText(A.Str,B.Str);
end;
//------------------------------------------------------------------------------
procedure IL_UniqueReconvStr(var Str: TILReconvString);
begin
UniqueString(Str.Str);
UniqueString(Str.UTF8Reconv);
UniqueString(Str.AnsiReconv);
end;
//------------------------------------------------------------------------------
Function IL_ThreadSafeCopy(const Str: TILReconvString): TILReconvString;
begin
Result := Str;
IL_UniqueReconvStr(Result);
end;
//==============================================================================
//- list item ------------------------------------------------------------------
Function IL_ItemPictureKindToStr(PictureKind: TLIItemPictureKind; FullString: Boolean = False): String;
begin
case PictureKind of
ilipkMain: If FullString then Result := 'Item picture'
else Result := 'item';
ilipkSecondary: If FullString then Result := 'Secondary picture'
else Result := 'secondary';
ilipkPackage: If FullString then Result := 'Package picture'
else Result := 'package';
else
Result := '';
end;
end;
//------------------------------------------------------------------------------
Function IL_ItemTypeToNum(ItemType: TILItemType): Int32;
begin
case ItemType of
ilitRing: Result := 1;
ilitRingWithHandles: Result := 2;
ilitBall: Result := 3;
ilitRider: Result := 4;
ilitLounger: Result := 5;
ilitLoungerChair: Result := 6;
ilitChair: Result := 7;
ilitSeat: Result := 8;
ilitMattress: Result := 9;
ilitIsland: Result := 10;
ilitBed: Result := 11;
ilitBoat: Result := 12;
ilitToy: Result := 13;
ilitWings: Result := 14;
ilitOther: Result := 15;
ilitBalloon: Result := 16;
ilitIslandExtra: Result := 17;
ilitRingSpecial: Result := 18;
ilitSofa: Result := 19;
else
{ilitUnknown}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToItemType(Num: Int32): TILItemType;
begin
case Num of
1: Result := ilitRing;
2: Result := ilitRingWithHandles;
3: Result := ilitBall;
4: Result := ilitRider;
5: Result := ilitLounger;
6: Result := ilitLoungerChair;
7: Result := ilitChair;
8: Result := ilitSeat;
9: Result := ilitMattress;
10: Result := ilitIsland;
11: Result := ilitBed;
12: Result := ilitBoat;
13: Result := ilitToy;
14: Result := ilitWings;
15: Result := ilitOther;
16: Result := ilitBalloon;
17: Result := ilitIslandExtra;
18: Result := ilitRingSpecial;
19: Result := ilitSofa;
else
Result := ilitUnknown;
end;
end;
//------------------------------------------------------------------------------
Function IL_ItemManufacturerToNum(ItemManufacturer: TILItemManufacturer): Int32;
begin
case ItemManufacturer of
ilimIntex: Result := 1;
ilimBestway: Result := 2;
ilimWIKY: Result := 3;
ilimHappyPeople: Result := 4;
ilimSwimline: Result := 5;
ilimMondo: Result := 6;
ilimWehncke: Result := 7;
ilimVetroPlus: Result := 8;
ilimPolygroup: Result := 9;
ilimSummerWaves: Result := 10;
ilimCrivit: Result := 11;
ilimOthers: Result := 0;
else
{ilimUnknown}
Result := 12
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToItemManufacturer(Num: Int32): TILItemManufacturer;
begin
case Num of
1: Result := ilimIntex;
2: Result := ilimBestway;
3: Result := ilimWIKY;
4: Result := ilimHappyPeople;
5: Result := ilimSwimline;
6: Result := ilimMondo;
7: Result := ilimWehncke;
8: Result := ilimVetroPlus;
9: Result := ilimPolygroup;
10: Result := ilimSummerWaves;
11: Result := ilimCrivit;
0: Result := ilimOthers;
else
Result := ilimUnknown;
end;
end;
//------------------------------------------------------------------------------
Function IL_SetItemFlagValue(var ItemFlags: TILItemFlags; ItemFlag: TILItemFlag; NewValue: Boolean): Boolean;
begin
Result := ItemFlag in ItemFlags;
If NewValue then
Include(ItemFlags,ItemFlag)
else
Exclude(ItemFlags,ItemFlag);
end;
//------------------------------------------------------------------------------
Function IL_EncodeItemFlags(ItemFlags: TILItemFlags): UInt32;
begin
Result := 0;
SetFlagStateValue(Result,$00000001,ilifOwned in ItemFlags);
SetFlagStateValue(Result,$00000002,ilifWanted in ItemFlags);
SetFlagStateValue(Result,$00000004,ilifOrdered in ItemFlags);
SetFlagStateValue(Result,$00000008,ilifBoxed in ItemFlags);
SetFlagStateValue(Result,$00000010,ilifElsewhere in ItemFlags);
SetFlagStateValue(Result,$00000020,ilifUntested in ItemFlags);
SetFlagStateValue(Result,$00000040,ilifTesting in ItemFlags);
SetFlagStateValue(Result,$00000080,ilifTested in ItemFlags);
SetFlagStateValue(Result,$00000100,ilifDamaged in ItemFlags);
SetFlagStateValue(Result,$00000200,ilifRepaired in ItemFlags);
SetFlagStateValue(Result,$00000400,ilifPriceChange in ItemFlags);
SetFlagStateValue(Result,$00000800,ilifAvailChange in ItemFlags);
SetFlagStateValue(Result,$00001000,ilifNotAvailable in ItemFlags);
SetFlagStateValue(Result,$00002000,ilifLost in ItemFlags);
SetFlagStateValue(Result,$00004000,ilifDiscarded in ItemFlags);
end;
//------------------------------------------------------------------------------
Function IL_DecodeItemFlags(Flags: UInt32): TILItemFlags;
begin
Result := [];
IL_SetItemFlagValue(Result,ilifOwned,GetFlagState(Flags,$00000001));
IL_SetItemFlagValue(Result,ilifWanted,GetFlagState(Flags,$00000002));
IL_SetItemFlagValue(Result,ilifOrdered,GetFlagState(Flags,$00000004));
IL_SetItemFlagValue(Result,ilifBoxed,GetFlagState(Flags,$00000008));
IL_SetItemFlagValue(Result,ilifElsewhere,GetFlagState(Flags,$00000010));
IL_SetItemFlagValue(Result,ilifUntested,GetFlagState(Flags,$00000020));
IL_SetItemFlagValue(Result,ilifTesting,GetFlagState(Flags,$00000040));
IL_SetItemFlagValue(Result,ilifTested,GetFlagState(Flags,$00000080));
IL_SetItemFlagValue(Result,ilifDamaged,GetFlagState(Flags,$00000100));
IL_SetItemFlagValue(Result,ilifRepaired,GetFlagState(Flags,$00000200));
IL_SetItemFlagValue(Result,ilifPriceChange,GetFlagState(Flags,$00000400));
IL_SetItemFlagValue(Result,ilifAvailChange,GetFlagState(Flags,$00000800));
IL_SetItemFlagValue(Result,ilifNotAvailable,GetFlagState(Flags,$00001000));
IL_SetItemFlagValue(Result,ilifLost,GetFlagState(Flags,$00002000));
IL_SetItemFlagValue(Result,ilifDiscarded,GetFlagState(Flags,$00004000));
end;
//------------------------------------------------------------------------------
Function IL_ItemMaterialToNum(Material: TILItemMaterial): Int32;
begin
case Material of
ilimtOther: Result := 1;
ilimtPolyvinylchloride: Result := 2;
//ilimtFlockedPVC: Result := 3; removed
ilimtLatex: Result := 4;
ilimtSilicone: Result := 5;
ilimtGumoTex: Result := 6;
ilimtPolyester: Result := 7;
ilimtPolyetylene: Result := 8;
ilimtPolypropylene: Result := 9;
ilimtAcrylonitrileButadieneStyrene: Result := 10;
ilimtPolystyren: Result := 11;
ilimtPolyurethane: Result := 12;
else
{ilimUnknown}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToItemMaterial(Num: Int32): TILItemMaterial;
begin
case Num of
1: Result := ilimtOther;
2: Result := ilimtPolyvinylchloride;
3: Result := ilimtPolyvinylchloride;
4: Result := ilimtLatex;
5: Result := ilimtSilicone;
6: Result := ilimtGumoTex;
7: Result := ilimtPolyester;
8: Result := ilimtPolyetylene;
9: Result := ilimtPolypropylene;
10: Result := ilimtAcrylonitrileButadieneStyrene;
11: Result := ilimtPolystyren;
12: Result := ilimtPolyurethane;
else
Result := ilimtUnknown;
end;
end;
//------------------------------------------------------------------------------
Function IL_ItemSurfaceFinishToNum(SurfaceFinish: TILItemSurfaceFinish): Int32;
begin
case SurfaceFinish of
ilisfGlossy: Result := 1;
ilisfSemiGloss: Result := 4;
ilisfMatte: Result := 2;
ilisfSemiMatte: Result := 5;
ilisfPearlscent: Result := 6;
ilisfMetalic: Result := 7;
ilisfFlocked: Result := 9;
ilisfCombined: Result := 3;
ilisfOther: Result := 8;
else
{ilisfUnknown}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToItemSurfaceFinish(Num: Int32): TILItemSurfaceFinish;
begin
case Num of
1: Result := ilisfGlossy;
4: Result := ilisfSemiGloss;
2: Result := ilisfMatte;
5: Result := ilisfSemiMatte;
6: Result := ilisfPearlscent;
7: Result := ilisfMetalic;
9: Result := ilisfFlocked;
3: Result := ilisfCombined;
8: Result := ilisfOther;
else
Result := ilisfUnknown;
end;
end;
//==============================================================================
//- item shop parsing ----------------------------------------------------------
Function IL_ExtractFromToNum(ExtractFrom: TILItemShopParsingExtrFrom): Int32;
begin
case ExtractFrom of
ilpefNestedText: Result := 1;
ilpefAttrValue: Result := 2;
else
{ilpefText}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToExtractFrom(Num: Int32): TILItemShopParsingExtrFrom;
begin
case Num of
1: Result := ilpefNestedText;
2: Result := ilpefAttrValue;
else
Result := ilpefText;
end;
end;
//------------------------------------------------------------------------------
Function IL_ExtrMethodToNum(ExtrMethod: TILItemShopParsingExtrMethod): Int32;
begin
case ExtrMethod of
ilpemFirstIntegerTag: Result := 1;
ilpemNegTagIsCount: Result := 2;
ilpemFirstNumber: Result := 3;
ilpemFirstNumberTag: Result := 4;
else
{ilpemFirstInteger}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToExtrMethod(Num: Int32): TILItemShopParsingExtrMethod;
begin
case Num of
1: Result := ilpemFirstIntegerTag;
2: Result := ilpemNegTagIsCount;
3: Result := ilpemFirstNumber;
4: Result := ilpemFirstNumberTag;
else
Result := ilpemFirstInteger;
end;
end;
//------------------------------------------------------------------------------
Function IL_ThreadSafeCopy(const Value: TILItemShopParsingExtrSett): TILItemShopParsingExtrSett;
begin
Result := Value;
UniqueString(Result.ExtractionData);
UniqueString(Result.NegativeTag);
end;
//------------------------------------------------------------------------------
Function IL_ThreadSafeCopy(const Value: TILItemShopParsingVariables): TILItemShopParsingVariables;
var
i: Integer;
begin
For i := Low(Value.Vars) to High(Value.Vars) do
begin
Result.Vars[i] := Value.Vars[i];
UniqueString(Result.Vars[i]);
end;
end;
//==============================================================================
//- item shop ------------------------------------------------------------------
Function IL_ItemShopUpdateResultToNum(UpdateResult: TILItemShopUpdateResult): Int32;
begin
case UpdateResult of
ilisurMildSucc: Result := 1;
ilisurDataFail: Result := 2;
ilisurSoftFail: Result := 3;
ilisurHardFail: Result := 4;
ilisurParsing: Result := 5;
ilisurFatal: Result := 6;
ilisurDownload: Result := 7;
else
{ilisurSuccess}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToItemShopUpdateResult(Num: Int32): TILItemShopUpdateResult;
begin
case Num of
1: Result := ilisurMildSucc;
2: Result := ilisurDataFail;
3: Result := ilisurSoftFail;
4: Result := ilisurHardFail;
5: Result := ilisurParsing;
6: Result := ilisurFatal;
7: Result := ilisurDownload;
else
Result := ilisurSuccess;
end;
end;
//------------------------------------------------------------------------------
Function IL_ItemShopUpdateResultToColor(UpdateResult: TILItemShopUpdateResult): TColor;
begin
case UpdateResult of
ilisurMildSucc: Result := clGreen;
ilisurDataFail: Result := clBlue;
ilisurSoftFail: Result := clYellow;
ilisurHardFail: Result := $00409BFF; // orange
ilisurDownload: Result := clPurple;
ilisurParsing: Result := clRed;
ilisurFatal: Result := clBlack;
else
{ilisurSuccess}
Result := clLime;
end;
end;
//==============================================================================
//- searching ------------------------------------------------------------------
Function IL_WrapSearchResult(Val: TILItemSearchResult): TILItemSearchResult;
begin
If Ord(Val) < Ord(Low(TILItemSearchResult)) then
Result := High(TILItemSearchResult)
else If Ord(Val) > Ord(High(TILItemSearchResult)) then
Result := Low(TILItemSearchResult)
else
Result := Val;
end;
//------------------------------------------------------------------------------
Function IL_ThreadSafeCopy(const Value: TILAdvSearchSettings): TILAdvSearchSettings;
begin
Result := Value;
UniqueString(Result.Text);
end;
//==============================================================================
//- sorting --------------------------------------------------------------------
Function IL_SameSortingSettings(A,B: TILSortingSettings): Boolean;
var
i: Integer;
begin
If A.Count = B.Count then
begin
Result := True;
For i := 0 to Pred(A.Count) do
If (A.Items[i].ItemValueTag <> B.Items[i].ItemValueTag) or
(A.Items[i].Reversed <> B.Items[i].Reversed) then
begin
Result := False;
Break{For i};
end;
end
else Result := False;
end;
//------------------------------------------------------------------------------
Function IL_ItemValueTagToNum(ItemValueTag: TILItemValueTag): Int32;
begin
{
no, the numbers are not in the correct order
MAX = 72
}
case ItemValueTag of
ilivtItemEncrypted: Result := 63;
ilivtUniqueID: Result := 57;
ilivtTimeOfAdd: Result := 3;
ilivtDescriptor: Result := 66;
ilivtMainPicFilePres: Result := 36;
ilivtMainPictureFile: Result := 35;
ilivtMainPictureThumb: Result := 1;
ilivtPackPicFilePres: Result := 38;
ilivtPackPictureFile: Result := 37;
ilivtPackPictureThumb: Result := 2;
ilivtCurrSecPicPres: Result := 61;
ilivtCurrSecPicFile: Result := 60;
ilivtCurrSecPicThumb: Result := 59;
ilivtPictureCount: Result := 67;
ilivtSecPicCount: Result := 68;
ilivtSecPicThumbCount: Result := 69;
ilivtItemType: Result := 4;
ilivtItemTypeSpec: Result := 5;
ilivtPieces: Result := 6;
ilivtUserID: Result := 64;
ilivtManufacturer: Result := 7;
ilivtManufacturerStr: Result := 8;
ilivtTextID: Result := 55;
ilivtNumID: Result := 9;
ilivtIDStr: Result := 56;
ilivtFlagOwned: Result := 10;
ilivtFlagWanted: Result := 11;
ilivtFlagOrdered: Result := 12;
ilivtFlagBoxed: Result := 13;
ilivtFlagElsewhere: Result := 14;
ilivtFlagUntested: Result := 15;
ilivtFlagTesting: Result := 16;
ilivtFlagTested: Result := 17;
ilivtFlagDamaged: Result := 18;
ilivtFlagRepaired: Result := 19;
ilivtFlagPriceChange: Result := 20;
ilivtFlagAvailChange: Result := 21;
ilivtFlagNotAvailable: Result := 22;
ilivtFlagLost: Result := 48;
ilivtFlagDiscarded: Result := 54;
ilivtTextTag: Result := 23;
ilivtNumTag: Result := 58;
ilivtWantedLevel: Result := 24;
ilivtVariant: Result := 25;
ilivtVariantTag: Result := 65;
ilivtSurfaceFinish: Result := 71;
ilivtMaterial: Result := 52;
ilivtThickness: Result := 53;
ilivtSizeX: Result := 26;
ilivtSizeY: Result := 27;
ilivtSizeZ: Result := 28;
ilivtTotalSize: Result := 29;
ilivtUnitWeight: Result := 30;
ilivtTotalWeight: Result := 31;
ilivtNotes: Result := 32;
ilivtReviewURL: Result := 33;
ilivtReview: Result := 34;
ilivtUnitPriceDefault: Result := 39;
ilivtRating: Result := 62;
ilivtRatingDetails: Result := 70;
ilivtSomethingUnknown: REsult := 72;
ilivtUnitPriceLowest: Result := 40;
ilivtTotalPriceLowest: Result := 41;
ilivtUnitPriceSel: Result := 42;
ilivtTotalPriceSel: Result := 43;
ilivtTotalPrice: Result := 44;
ilivtAvailable: Result := 45;
ilivtShopCount: Result := 46;
ilivtUsefulShopCount: Result := 50;
ilivtUsefulShopRatio: Result := 51;
ilivtSelectedShop: Result := 47;
ilivtWorstUpdateResult: Result := 49;
else
{ilivtNone}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToItemValueTag(Num: Int32): TILItemValueTag;
begin
case Num of
63: Result := ilivtItemEncrypted;
57: Result := ilivtUniqueID;
3: Result := ilivtTimeOfAdd;
66: Result := ilivtDescriptor;
36: Result := ilivtMainPicFilePres;
35: Result := ilivtMainPictureFile;
1: Result := ilivtMainPictureThumb;
38: Result := ilivtPackPicFilePres;
37: Result := ilivtPackPictureFile;
2: Result := ilivtPackPictureThumb;
61: Result := ilivtCurrSecPicPres;
60: Result := ilivtCurrSecPicFile;
59: Result := ilivtCurrSecPicThumb;
67: Result := ilivtPictureCount;
68: Result := ilivtSecPicCount;
69: Result := ilivtSecPicThumbCount;
4: Result := ilivtItemType;
5: Result := ilivtItemTypeSpec;
6: Result := ilivtPieces;
64: Result := ilivtUserID;
7: Result := ilivtManufacturer;
8: Result := ilivtManufacturerStr;
55: Result := ilivtTextID;
9: Result := ilivtNumID;
56: Result := ilivtIDStr;
10: Result := ilivtFlagOwned;
11: Result := ilivtFlagWanted;
12: Result := ilivtFlagOrdered;
13: Result := ilivtFlagBoxed;
14: Result := ilivtFlagElsewhere;
15: Result := ilivtFlagUntested;
16: Result := ilivtFlagTesting;
17: Result := ilivtFlagTested;
18: Result := ilivtFlagDamaged;
19: Result := ilivtFlagRepaired;
20: Result := ilivtFlagPriceChange;
21: Result := ilivtFlagAvailChange;
22: Result := ilivtFlagNotAvailable;
48: Result := ilivtFlagLost;
54: Result := ilivtFlagDiscarded;
23: Result := ilivtTextTag;
58: Result := ilivtNumTag;
24: Result := ilivtWantedLevel;
25: Result := ilivtVariant;
65: Result := ilivtVariantTag;
71: Result := ilivtSurfaceFinish;
52: Result := ilivtMaterial;
53: Result := ilivtThickness;
26: Result := ilivtSizeX;
27: Result := ilivtSizeY;
28: Result := ilivtSizeZ;
29: Result := ilivtTotalSize;
30: Result := ilivtUnitWeight;
31: Result := ilivtTotalWeight;
32: Result := ilivtNotes;
33: Result := ilivtReviewURL;
34: Result := ilivtReview;
39: Result := ilivtUnitPriceDefault;
62: Result := ilivtRating;
70: Result := ilivtRatingDetails;
72: Result := ilivtSomethingUnknown;
40: Result := ilivtUnitPriceLowest;
41: Result := ilivtTotalPriceLowest;
42: Result := ilivtUnitPriceSel;
43: Result := ilivtTotalPriceSel;
44: Result := ilivtTotalPrice;
45: Result := ilivtAvailable;
46: Result := ilivtShopCount;
50: Result := ilivtUsefulShopCount;
51: Result := ilivtUsefulShopRatio;
47: Result := ilivtSelectedShop;
49: Result := ilivtWorstUpdateResult;
else
Result := ilivtNone;
end;
end;
//------------------------------------------------------------------------------
Function IL_ThreadSafeCopy(const Value: TILSortingProfile): TILSortingProfile;
begin
Result := Value;
UniqueString(Result.Name);
end;
//==============================================================================
//- sum filters ----------------------------------------------------------------
Function IL_FilterOperatorToNum(Operator: TILFilterOperator): Int32;
begin
case Operator of
ilfoOR: Result := 1;
ilfoXOR: Result := 2;
else
{ilfoAND}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToFilterOperator(Num: Int32): TILFilterOperator;
begin
case Num of
1: Result := ilfoOR;
2: Result := ilfoXOR;
else
Result := ilfoAND;
end;
end;
//------------------------------------------------------------------------------
Function IL_SetFilterSettingsFlagValue(var FilterFlags: TILFilterFlags; FilterFlag: TILFilterFlag; NewValue: Boolean): Boolean;
begin
Result := FilterFlag in FilterFlags;
If NewValue then
Include(FilterFlags,FilterFlag)
else
Exclude(FilterFlags,FilterFlag);
end;
//------------------------------------------------------------------------------
Function IL_EncodeFilterFlags(FilterFlags: TILFilterFlags): UInt32;
begin
Result := 0;
SetFlagStateValue(Result,$00000001,ilffOwnedSet in FilterFlags);
SetFlagStateValue(Result,$00000002,ilffOwnedClr in FilterFlags);
SetFlagStateValue(Result,$00000004,ilffWantedSet in FilterFlags);
SetFlagStateValue(Result,$00000008,ilffWantedClr in FilterFlags);
SetFlagStateValue(Result,$00000010,ilffOrderedSet in FilterFlags);
SetFlagStateValue(Result,$00000020,ilffOrderedClr in FilterFlags);
SetFlagStateValue(Result,$00000040,ilffBoxedSet in FilterFlags);
SetFlagStateValue(Result,$00000080,ilffBoxedClr in FilterFlags);
SetFlagStateValue(Result,$00000100,ilffElsewhereSet in FilterFlags);
SetFlagStateValue(Result,$00000200,ilffElsewhereClr in FilterFlags);
SetFlagStateValue(Result,$00000400,ilffUntestedSet in FilterFlags);
SetFlagStateValue(Result,$00000800,ilffUntestedClr in FilterFlags);
SetFlagStateValue(Result,$00001000,ilffTestingSet in FilterFlags);
SetFlagStateValue(Result,$00002000,ilffTestingClr in FilterFlags);
SetFlagStateValue(Result,$00004000,ilffTestedSet in FilterFlags);
SetFlagStateValue(Result,$00008000,ilffTestedClr in FilterFlags);
SetFlagStateValue(Result,$00010000,ilffDamagedSet in FilterFlags);
SetFlagStateValue(Result,$00020000,ilffDamagedClr in FilterFlags);
SetFlagStateValue(Result,$00040000,ilffRepairedSet in FilterFlags);
SetFlagStateValue(Result,$00080000,ilffRepairedClr in FilterFlags);
SetFlagStateValue(Result,$00100000,ilffPriceChangeSet in FilterFlags);
SetFlagStateValue(Result,$00200000,ilffPriceChangeClr in FilterFlags);
SetFlagStateValue(Result,$00400000,ilffAvailChangeSet in FilterFlags);
SetFlagStateValue(Result,$00800000,ilffAvailChangeClr in FilterFlags);
SetFlagStateValue(Result,$01000000,ilffNotAvailableSet in FilterFlags);
SetFlagStateValue(Result,$02000000,ilffNotAvailableClr in FilterFlags);
SetFlagStateValue(Result,$04000000,ilffLostSet in FilterFlags);
SetFlagStateValue(Result,$08000000,ilffLostClr in FilterFlags);
SetFlagStateValue(Result,$10000000,ilffDiscardedSet in FilterFlags);
SetFlagStateValue(Result,$20000000,ilffDiscardedClr in FilterFlags);
end;
//------------------------------------------------------------------------------
Function IL_DecodeFilterFlags(Flags: UInt32): TILFilterFlags;
begin
Result := [];
IL_SetFilterSettingsFlagValue(Result,ilffOwnedSet,GetFlagState(Flags,$00000001));
IL_SetFilterSettingsFlagValue(Result,ilffOwnedClr,GetFlagState(Flags,$00000002));
IL_SetFilterSettingsFlagValue(Result,ilffWantedSet,GetFlagState(Flags,$00000004));
IL_SetFilterSettingsFlagValue(Result,ilffWantedClr,GetFlagState(Flags,$00000008));
IL_SetFilterSettingsFlagValue(Result,ilffOrderedSet,GetFlagState(Flags,$00000010));
IL_SetFilterSettingsFlagValue(Result,ilffOrderedClr,GetFlagState(Flags,$00000020));
IL_SetFilterSettingsFlagValue(Result,ilffBoxedSet,GetFlagState(Flags,$00000040));
IL_SetFilterSettingsFlagValue(Result,ilffBoxedClr,GetFlagState(Flags,$00000080));
IL_SetFilterSettingsFlagValue(Result,ilffElsewhereSet,GetFlagState(Flags,$00000100));
IL_SetFilterSettingsFlagValue(Result,ilffElsewhereClr,GetFlagState(Flags,$00000200));
IL_SetFilterSettingsFlagValue(Result,ilffUntestedSet,GetFlagState(Flags,$00000400));
IL_SetFilterSettingsFlagValue(Result,ilffUntestedClr,GetFlagState(Flags,$00000800));
IL_SetFilterSettingsFlagValue(Result,ilffTestingSet,GetFlagState(Flags,$00001000));
IL_SetFilterSettingsFlagValue(Result,ilffTestingClr,GetFlagState(Flags,$00002000));
IL_SetFilterSettingsFlagValue(Result,ilffTestedSet,GetFlagState(Flags,$00004000));
IL_SetFilterSettingsFlagValue(Result,ilffTestedClr,GetFlagState(Flags,$00008000));
IL_SetFilterSettingsFlagValue(Result,ilffDamagedSet,GetFlagState(Flags,$00010000));
IL_SetFilterSettingsFlagValue(Result,ilffDamagedClr,GetFlagState(Flags,$00020000));
IL_SetFilterSettingsFlagValue(Result,ilffRepairedSet,GetFlagState(Flags,$00040000));
IL_SetFilterSettingsFlagValue(Result,ilffRepairedClr,GetFlagState(Flags,$00080000));
IL_SetFilterSettingsFlagValue(Result,ilffPriceChangeSet,GetFlagState(Flags,$00100000));
IL_SetFilterSettingsFlagValue(Result,ilffPriceChangeClr,GetFlagState(Flags,$00200000));
IL_SetFilterSettingsFlagValue(Result,ilffAvailChangeSet,GetFlagState(Flags,$00400000));
IL_SetFilterSettingsFlagValue(Result,ilffAvailChangeClr,GetFlagState(Flags,$00800000));
IL_SetFilterSettingsFlagValue(Result,ilffNotAvailableSet,GetFlagState(Flags,$01000000));
IL_SetFilterSettingsFlagValue(Result,ilffNotAvailableClr,GetFlagState(Flags,$02000000));
IL_SetFilterSettingsFlagValue(Result,ilffLostSet,GetFlagState(Flags,$04000000));
IL_SetFilterSettingsFlagValue(Result,ilffLostClr,GetFlagState(Flags,$08000000));
IL_SetFilterSettingsFlagValue(Result,ilffDiscardedSet,GetFlagState(Flags,$10000000));
IL_SetFilterSettingsFlagValue(Result,ilffDiscardedClr,GetFlagState(Flags,$20000000));
end;
//==============================================================================
//- static settings ------------------------------------------------------------
Function IL_ThreadSafeCopy(const Value: TILStaticManagerSettings): TILStaticManagerSettings;
begin
Result := Value;
UniqueString(Result.TempPath);
UniqueString(Result.DefaultPath);
UniqueString(Result.ListPath);
UniqueString(Result.ListFile);
UniqueString(Result.ListName);
UniqueString(Result.InstanceID);
UniqueString(Result.PicturesPath);
UniqueString(Result.BackupPath);
UniqueString(Result.SavedPagesPath);
end;
//==============================================================================
//- preload information --------------------------------------------------------
Function IL_ThreadSafeCopy(const Value: TILPreloadInfo): TILPreloadInfo;
begin
Result := Value;
UniqueString(Result.TimeStr);
end;
end.
|
unit DP.EventGeo;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils,
Cache.Root,
ZConnection, ZDataset,
Event.Cnst;
//------------------------------------------------------------------------------
type
TGeoEventType = (etDepot, etZone);
//------------------------------------------------------------------------------
//! ключ списка кэшей гео-событий
//------------------------------------------------------------------------------
TEventGeoKey = packed record
IMEI: Int64;
ID: Integer;
EventType: TGeoEventType;
end;
//------------------------------------------------------------------------------
//! класс данных гео-событий
//------------------------------------------------------------------------------
TEventGeo = class(TDataObj)
private
FKey: TEventGeoKey;
FDTMark: TDateTime;
FEventType: Integer;
FDuration: Double;
FTill: TDateTime;
FChanged: Boolean;
procedure SetDuration(const Value: Double);
procedure SetTill(const Value: TDateTime);
protected
//!
function GetDTMark(): TDateTime; override;
public
constructor Create(
const AIMEI: Int64;
const ADTMark: TDateTime;
const AEventType: Integer;
const AID: Integer;
const ADuration: Double
); overload;
constructor Create(
const AKey: TEventGeoKey;
const ADTMark: TDateTime;
const AEventType: Integer;
const ADuration: Double
); overload;
constructor Create(
ASource: TEventGeo
); overload;
function Clone(): IDataObj; override;
procedure ClearChanged();
property Key: TEventGeoKey read FKey;
property IMEI: Int64 read FKey.IMEI;
property ID: Integer read FKey.ID;
property EventType: Integer read FEventType;
property Duration: Double read FDuration write SetDuration;
property Till: TDateTime read FTill write SetTill;
property Changed: Boolean read FChanged;
end;
//------------------------------------------------------------------------------
//! класс кэша гео-событий
//------------------------------------------------------------------------------
TCacheEventGeo = class(TCacheRoot)
protected
FIdFieldName: string;
//! вставить запись в БД
procedure ExecDBInsert(
const AObj: IDataObj
); override;
//! обновить запись в БД
procedure ExecDBUpdate(
const AObj: IDataObj
); override;
//! преобразователь из записи БД в объект
function MakeObjFromReadReq(
const AQuery: TZQuery
): IDataObj; override;
public
constructor Create(
const AKey: TEventGeoKey;
const AReadConnection: TZConnection;
const AWriteConnection: TZConnection;
const ADBWriteback: Boolean;
const AMaxKeepCount: Integer;
const ALoadDelta: Double
);
end;
//------------------------------------------------------------------------------
//! класс списка кэшей гео-событий
//------------------------------------------------------------------------------
TEventGeoHash = TCacheDictionaryRoot<TEventGeoKey>;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
// TEventGeo
//------------------------------------------------------------------------------
constructor TEventGeo.Create(
const AIMEI: Int64;
const ADTMark: TDateTime;
const AEventType: Integer;
const AID: Integer;
// const AZoneID: Integer;
// const ADepotID: Integer;
const ADuration: Double
);
function MakeGeoEventType(AEventType: Integer): TGeoEventType;
begin
Result := etDepot;
case AEventType of
Ord(egzEnterZone),
Ord(egzLeaveZone): Result := etZone;
end;
end;
begin
inherited Create();
//
FKey.IMEI := AIMEI;
FKey.ID := AID;
FKey.EventType := MakeGeoEventType(AEventType);
FDTMark := ADTMark;
FEventType := AEventType;
FDuration := ADuration;
FTill := ADuration + ADTMark;
end;
constructor TEventGeo.Create(
const AKey: TEventGeoKey;
const ADTMark: TDateTime;
const AEventType: Integer;
const ADuration: Double
);
begin
inherited Create();
//
FKey := AKey;
FDTMark := ADTMark;
FEventType := AEventType;
FDuration := ADuration;
FTill := ADuration + ADTMark;
end;
constructor TEventGeo.Create(
ASource: TEventGeo
);
begin
inherited Create();
//
FKey := ASource.Key;
FDTMark := ASource.DTMark;
FEventType := ASource.EventType;
FDuration := ASource.Duration;
FTill := ASource.Till;
end;
function TEventGeo.Clone(): IDataObj;
begin
Result := TEventGeo.Create(Self);
end;
function TEventGeo.GetDTMark(): TDateTime;
begin
Result := FDTMark;
end;
procedure TEventGeo.SetDuration(
const Value: Double
);
begin
if (FDuration <> Value) then
begin
FDuration := Value;
FTill := Value + DTMark;
FChanged := True;
end;
end;
procedure TEventGeo.SetTill(
const Value: TDateTime
);
begin
if (FTill <> Value) then
begin
FTill := Value;
FDuration := Value - DTMark;
FChanged := True;
end;
end;
procedure TEventGeo.ClearChanged();
begin
FChanged := False;
end;
//------------------------------------------------------------------------------
// TCacheEventGeo
//------------------------------------------------------------------------------
constructor TCacheEventGeo.Create(
const AKey: TEventGeoKey;
const AReadConnection: TZConnection;
const AWriteConnection: TZConnection;
const ADBWriteback: Boolean;
const AMaxKeepCount: Integer;
const ALoadDelta: Double
);
var
TableName: string;
SQLReadRange: string;
SQLReadBefore: string;
SQLReadAfter: string;
SQLInsert: string;
SQLUpdate: string;
SQLDeleteRange: string;
SQLLastPresentDT: string;
begin
case AKey.EventType of
etDepot: begin
TableName := 'event_geodepot';
FIdFieldName := 'DepotID';
end;
etZone: begin
TableName := 'event_geozone';
FIdFieldName := 'ZoneID';
end;
end;
SQLReadRange := 'SELECT *'
+ ' FROM ' + TableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT >= :dt_from'
+ ' AND DT <= :dt_to';
SQLReadBefore := 'SELECT *'
+ ' FROM ' + TableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT < :dt'
+ ' ORDER BY DT DESC'
+ ' LIMIT 1';
SQLReadAfter := 'SELECT *'
+ ' FROM ' + TableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT > :dt'
+ ' ORDER BY DT'
+ ' LIMIT 1';
SQLInsert := 'INSERT INTO ' + TableName
+ ' (IMEI, DT, ' + FIdFieldName + ', EventGeoTypeID, Duration)'
+ ' VALUES (:imei, :dt, :id, :t_id, :dur)';
SQLUpdate := 'UPDATE ' + TableName
+ ' SET Duration = :dur'
+ ' ,EventGeoTypeID = :t_id'
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT = :dt';
SQLDeleteRange := 'DELETE FROM ' + TableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id'
+ ' AND DT >= :dt_from'
+ ' AND DT <= :dt_to';
SQLLastPresentDT := 'SELECT MAX(DT) AS DT'
+ ' FROM ' + TableName
+ ' WHERE IMEI = :imei'
+ ' AND ' + FIdFieldName + ' = :id';
inherited Create(
AReadConnection, AWriteConnection, ADBWriteback, AMaxKeepCount, ALoadDelta,
SQLReadRange, SQLReadBefore, SQLReadAfter, SQLInsert, SQLUpdate, SQLDeleteRange, SQLLastPresentDT
);
FQueryReadRange.ParamByName('imei').AsLargeInt := AKey.IMEI;
FQueryReadBefore.ParamByName('imei').AsLargeInt := AKey.IMEI;
FQueryReadAfter.ParamByName('imei').AsLargeInt := AKey.IMEI;
FQueryInsert.ParamByName('imei').AsLargeInt := AKey.IMEI;
FQueryUpdate.ParamByName('imei').AsLargeInt := AKey.IMEI;
FQueryDeleteRange.ParamByName('imei').AsLargeInt := AKey.IMEI;
FQueryLastPresentDT.ParamByName('imei').AsLargeInt := AKey.IMEI;
FQueryReadRange.ParamByName('id').AsLargeInt := AKey.ID;
FQueryReadBefore.ParamByName('id').AsLargeInt := AKey.ID;
FQueryReadAfter.ParamByName('id').AsLargeInt := AKey.ID;
FQueryInsert.ParamByName('id').AsLargeInt := AKey.ID;
FQueryUpdate.ParamByName('id').AsLargeInt := AKey.ID;
FQueryDeleteRange.ParamByName('id').AsLargeInt := AKey.ID;
FQueryLastPresentDT.ParamByName('id').AsLargeInt := AKey.ID;
end;
procedure TCacheEventGeo.ExecDBInsert(
const AObj: IDataObj
);
begin
with (AObj as TEventGeo), FQueryInsert do
begin
Active := False;
ParamByName('dt').AsDateTime := FDTMark;
ParamByName('t_id').AsInteger := FEventType;
ParamByName('dur').AsFloat := FDuration;
ExecSQL();
end;
end;
procedure TCacheEventGeo.ExecDBUpdate(
const AObj: IDataObj
);
begin
with (AObj as TEventGeo), FQueryUpdate do
begin
Active := False;
ParamByName('dt').AsDateTime := FDTMark;
ParamByName('t_id').AsInteger := FEventType;
ParamByName('dur').AsFloat := FDuration;
ExecSQL();
end;
end;
function TCacheEventGeo.MakeObjFromReadReq(
const AQuery: TZQuery
): IDataObj;
begin
with AQuery do
begin
Result := TEventGeo.Create(
FieldByName('IMEI').AsLargeInt,
FieldByName('DT').AsDateTime,
FieldByName('EventGeoTypeID').AsInteger,
FieldByName(FIdFieldName).AsInteger,
FieldByName('Duration').AsFloat
);
end;
end;
end.
|
program questao10;
{
Autor: Hugo Deiró Data: 02/06/2012
- Este programa converte uma temperatura em Celcius para Fahrenheit
Fórmula: Fahrenheit = celcius * 18 + 32.
}
var
celcius : real;
begin
write('Insira uma temperatura em Celcius: ');
readln(celcius);
writeln;
writeln(celcius:6:2,'°C = ',celcius * 18 + 32 :6:2,'°F');
end.
|
{
Double Commander
-------------------------------------------------------------------------
Multi-Rename Tool dialog window
Copyright (C) 2007-2022 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Original comment:
----------------------------
Seksi Commander
----------------------------
Licence : GNU GPL v 2.0
Author : Pavel Letko (letcuv@centrum.cz)
Advanced multi rename tool
contributors:
Copyright (C) 2007-2018 Alexander Koblov (alexx2000@mail.ru)
}
unit fMultiRename;
{$mode objfpc}{$H+}
interface
uses
//Lazarus, Free-Pascal, etc.
LazUtf8, SysUtils, Classes, Graphics, Forms, StdCtrls, Menus, Controls,
LCLType, StringHashList, Grids, ExtCtrls, Buttons, ActnList, EditBtn,
KASButton, KASToolPanel,
//DC
DCXmlConfig, uOSForms, uRegExprW, uFileProperty, uFormCommands,
uFileSourceSetFilePropertyOperation, DCStringHashListUtf8, uClassesEx, uFile,
uFileSource, DCClassesUtf8, uHotkeyManager;
const
HotkeysCategoryMultiRename = 'MultiRename'; // <--Not displayed to user, stored in .scf (Shortcut Configuration File)
type
{ TMultiRenamePreset }
TMultiRenamePreset = class(TObject)
private
FPresetName: string;
FFileName: string;
FExtension: string;
FFileNameStyle: integer;
FExtensionStyle: integer;
FFind: string;
FReplace: string;
FRegExp: boolean;
FUseSubs: boolean;
FCaseSens: Boolean;
FOnlyFirst: Boolean;
FCounter: string;
FInterval: string;
FWidth: integer;
FLog: boolean;
FLogFile: string;
FLogAppend: boolean;
public
property PresetName: string read FPresetName write FPresetName;
property FileName: string read FFileName write FFileName;
property Extension: string read FExtension write FExtension;
property FileNameStyle: integer read FFileNameStyle write FFileNameStyle;
property ExtensionStyle: integer read FExtensionStyle write FExtensionStyle;
property Find: string read FFind write FFind;
property Replace: string read FReplace write FReplace;
property RegExp: boolean read FRegExp write FRegExp;
property UseSubs: boolean read FUseSubs write FUseSubs;
property CaseSens: Boolean read FCaseSens write FCaseSens;
property OnlyFirst: Boolean read FOnlyFirst write FOnlyFirst;
property Counter: string read FCounter write FCounter;
property Interval: string read FInterval write FInterval;
property Width: integer read FWidth write FWidth;
property Log: boolean read FLog write FLog;
property LogFile: string read FLogFile write FLogFile;
property LogAppend: boolean read FLogAppend write FLogAppend;
constructor Create;
destructor Destroy; override;
end;
{ TMultiRenamePresetList }
TMultiRenamePresetList = class(TList)
private
function GetMultiRenamePreset(Index: integer): TMultiRenamePreset;
public
property MultiRenamePreset[Index: integer]: TMultiRenamePreset read GetMultiRenamePreset;
procedure Delete(Index: integer);
procedure Clear; override;
function Find(sPresetName: string): integer;
end;
{ tTargetForMask }
//Used to indicate of a mask is used for the "Filename" or the "Extension".
tTargetForMask = (tfmFilename, tfmExtension);
{ tRenameMaskToUse }
//Used as a parameter type to indicate the kind of field the mask is related to.
tRenameMaskToUse = (rmtuFilename, rmtuExtension, rmtuCounter, rmtuDate, rmtuTime, rmtuPlugins);
{ tSourceOfInformation }
tSourceOfInformation = (soiFilename, soiExtension, soiCounter, soiGUID, soiVariable, soiDate, soiTime, soiPlugins, soiFullName, soiPath);
{ tMenuActionStyle }
//Used to help to group common or similar action done for each mask.
tMenuActionStyle = (masStraight, masXCharacters, masXYCharacters, masAskVariable, masDirectorySelector);
{ TfrmMultiRename }
TfrmMultiRename = class(TAloneForm, IFormCommands)
cbCaseSens: TCheckBox;
cbRegExp: TCheckBox;
cbUseSubs: TCheckBox;
cbOnlyFirst: TCheckBox;
pnlFindReplace: TPanel;
pnlButtons: TPanel;
StringGrid: TStringGrid;
pnlOptions: TPanel;
pnlOptionsLeft: TPanel;
gbMaska: TGroupBox;
lbName: TLabel;
cbName: TComboBox;
btnAnyNameMask: TKASButton;
cbNameMaskStyle: TComboBox;
lbExt: TLabel;
cbExt: TComboBox;
btnAnyExtMask: TKASButton;
cmbExtensionStyle: TComboBox;
gbPresets: TGroupBox;
cbPresets: TComboBox;
btnPresets: TKASButton;
spltMainSplitter: TSplitter;
pnlOptionsRight: TKASToolPanel;
gbFindReplace: TGroupBox;
lbFind: TLabel;
edFind: TEdit;
lbReplace: TLabel;
edReplace: TEdit;
gbCounter: TGroupBox;
lbStNb: TLabel;
edPoc: TEdit;
lbInterval: TLabel;
edInterval: TEdit;
lbWidth: TLabel;
cmbxWidth: TComboBox;
btnRestore: TBitBtn;
btnRename: TBitBtn;
btnConfig: TBitBtn;
btnEditor: TBitBtn;
btnClose: TBitBtn;
cbLog: TCheckBox;
cbLogAppend: TCheckBox;
fneRenameLogFileFilename: TFileNameEdit;
btnRelativeRenameLogFile: TSpeedButton;
btnViewRenameLogFile: TSpeedButton;
mmMainMenu: TMainMenu;
miActions: TMenuItem;
miResetAll: TMenuItem;
miEditor: TMenuItem;
miLoadNamesFromFile: TMenuItem;
miEditNames: TMenuItem;
miEditNewNames: TMenuItem;
miSeparator1: TMenuItem;
miConfiguration: TMenuItem;
miSeparator2: TMenuItem;
miRename: TMenuItem;
miClose: TMenuItem;
pmPresets: TPopupMenu;
pmFloatingMainMaskMenu: TPopupMenu;
pmDynamicMasks: TPopupMenu;
pmEditDirect: TPopupMenu;
mnuLoadFromFile: TMenuItem;
mnuEditNames: TMenuItem;
mnuEditNewNames: TMenuItem;
pmPathToBeRelativeToHelper: TPopupMenu;
actList: TActionList;
actResetAll: TAction;
actInvokeEditor: TAction;
actLoadNamesFromFile: TAction;
actLoadNamesFromClipboard: TAction;
actEditNames: TAction;
actEditNewNames: TAction;
actConfig: TAction;
actRename: TAction;
actClose: TAction;
actShowPresetsMenu: TAction;
actDropDownPresetList: TAction;
actLoadLastPreset: TAction;
actLoadPreset: TAction;
actLoadPreset1: TAction;
actLoadPreset2: TAction;
actLoadPreset3: TAction;
actLoadPreset4: TAction;
actLoadPreset5: TAction;
actLoadPreset6: TAction;
actLoadPreset7: TAction;
actLoadPreset8: TAction;
actLoadPreset9: TAction;
actSavePreset: TAction;
actSavePresetAs: TAction;
actRenamePreset: TAction;
actDeletePreset: TAction;
actSortPresets: TAction;
actAnyNameMask: TAction;
actNameNameMask: TAction;
actExtNameMask: TAction;
actDateNameMask: TAction;
actTimeNameMask: TAction;
actCtrNameMask: TAction;
actPlgnNameMask: TAction;
actClearNameMask: TAction;
actAnyExtMask: TAction;
actNameExtMask: TAction;
actExtExtMask: TAction;
actDateExtMask: TAction;
actTimeExtMask: TAction;
actCtrExtMask: TAction;
actPlgnExtMask: TAction;
actClearExtMask: TAction;
actInvokeRelativePath: TAction;
actViewRenameLogFile: TAction;
procedure FormCreate({%H-}Sender: TObject);
procedure FormCloseQuery({%H-}Sender: TObject; var CanClose: boolean);
procedure FormClose({%H-}Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
procedure StringGridKeyDown({%H-}Sender: TObject; var Key: word; Shift: TShiftState);
procedure StringGridMouseDown({%H-}Sender: TObject; Button: TMouseButton; {%H-}Shift: TShiftState; X, Y: integer);
procedure StringGridMouseUp({%H-}Sender: TObject; Button: TMouseButton; {%H-}Shift: TShiftState; {%H-}X, {%H-}Y: integer);
procedure StringGridSelection({%H-}Sender: TObject; {%H-}aCol, aRow: integer);
procedure StringGridTopLeftChanged({%H-}Sender: TObject);
procedure cbNameStyleChange({%H-}Sender: TObject);
procedure cbPresetsChange({%H-}Sender: TObject);
procedure cbPresetsCloseUp({%H-}Sender: TObject);
procedure edFindChange({%H-}Sender: TObject);
procedure edReplaceChange({%H-}Sender: TObject);
procedure cbRegExpChange({%H-}Sender: TObject);
procedure edPocChange({%H-}Sender: TObject);
procedure edIntervalChange({%H-}Sender: TObject);
procedure cbLogClick({%H-}Sender: TObject);
procedure actExecute(Sender: TObject);
procedure actInvokeRelativePathExecute(Sender: TObject);
private
IniPropStorage: TIniPropStorageEx;
FCommands: TFormCommands;
FActuallyRenamingFile: boolean;
FSourceRow: integer;
FMoveRow: boolean;
FFileSource: IFileSource;
FFiles: TFiles;
FNewNames: TStringHashListUtf8;
FOldNames: TStringHashListUtf8;
FNames: TStringList;
FslVariableNames, FslVariableValues, FslVariableSuggestionName, FslVariableSuggestionValue: TStringList;
FRegExp: TRegExprW;
FFindText: TStringList;
FReplaceText: TStringList;
FPluginDispatcher: tTargetForMask;
FMultiRenamePresetList: TMultiRenamePresetList;
FParamPresetToLoadOnStart: string;
FLastPreset: string;
FbRememberLog, FbRememberAppend: boolean;
FsRememberRenameLogFilename: string;
FLog: TStringListEx;
property Commands: TFormCommands read FCommands implements IFormCommands;
procedure RestoreProperties(Sender: TObject);
procedure SetConfigurationState(bConfigurationSaved: boolean);
function GetPresetNameForCommand(const Params: array of string): string;
procedure LoadPresetsXml(AConfig: TXmlConfig);
function isOkToLosePresetModification: boolean;
procedure SavePreset(PresetName: string);
procedure SavePresetsXml(AConfig: TXmlConfig);
procedure SavePresets;
procedure DeletePreset(PresetName: string);
procedure FillPresetsList(const WantedSelectedPresetName: string = '');
procedure RefreshActivePresetCommands;
procedure InitializeMaskHelper;
procedure PopulateMainMenu;
procedure PopulateFilenameMenu(AMenuSomething: TComponent);
procedure PopulateExtensionMenu(AMenuSomething: TComponent);
procedure BuildMaskMenu(AMenuSomething: TComponent; iTarget: tTargetForMask; iMenuTypeMask: tRenameMaskToUse);
procedure BuildPresetsMenu(AMenuSomething: TComponent);
procedure BuildMenuAndPopup(iTarget: tTargetForMask; iMenuTypeMask: tRenameMaskToUse);
function GetMaskCategoryName(aRenameMaskToUse: tRenameMaskToUse): string;
function GetImageIndexCategoryName(aRenameMaskToUse: tRenameMaskToUse): integer;
function GetCategoryAction(TargetForMask: tTargetForMask; aRenameMask: tRenameMaskToUse): TAction;
function AppendSubMenuToThisMenu(ATargetMenu: TMenuItem; sCaption: string; iImageIndex: integer): TMenuItem;
function AppendActionMenuToThisMenu(ATargetMenu: TMenuItem; paramAction: TAction): TMenuItem;
procedure MenuItemXCharactersMaskClick(Sender: TObject);
procedure MenuItemVariableMaskClick(Sender: TObject);
procedure MenuItemStraightMaskClick(Sender: TObject);
procedure MenuItemDirectorySelectorMaskClick(Sender: TObject);
procedure PopupDynamicMenuAtThisControl(APopUpMenu: TPopupMenu; AControl: TControl);
procedure miPluginClick(Sender: TObject);
procedure InsertMask(const Mask: string; edChoose: TComboBox);
procedure InsertMask(const Mask: string; TargetForMask: tTargetForMask);
function sReplace(sMask: string; ItemNr: integer): string;
function sReplaceXX(const sFormatStr, sOrig: string): string;
function sReplaceVariable(const sFormatStr: string): string;
function sReplaceBadChars(const sPath: string): string;
function IsLetter(AChar: AnsiChar): boolean;
function ApplyStyle(InputString: string; Style: integer): string;
function FirstCharToUppercaseUTF8(InputString: string): string;
function FirstCharOfFirstWordToUppercaseUTF8(InputString: string): string;
function FirstCharOfEveryWordToUppercaseUTF8(InputString: string): string;
procedure LoadNamesFromList(const AFileList: TStrings);
procedure LoadNamesFromFile(const AFileName: string);
function FreshText(ItemIndex: integer): string;
function sHandleFormatString(const sFormatStr: string; ItemNr: integer): string;
procedure SetFilePropertyResult(Index: integer; aFile: TFile; aTemplate: TFileProperty; Result: TSetFilePropertyResult);
procedure SetOutputGlobalRenameLogFilename;
public
{ Public declarations }
constructor Create(TheOwner: TComponent); override; //Not used for actual renaming file. Present there just for the "TfrmOptionsHotkeys.FillCommandList" function who need to create the form in memory to extract internal commands from it.
constructor Create(TheOwner: TComponent; aFileSource: IFileSource; var aFiles: TFiles; const paramPreset: string); reintroduce;
destructor Destroy; override;
published
procedure cm_ResetAll(const Params: array of string);
procedure cm_InvokeEditor(const {%H-}Params: array of string);
procedure cm_LoadNamesFromFile(const {%H-}Params: array of string);
procedure cm_LoadNamesFromClipboard(const {%H-}Params: array of string);
procedure cm_EditNames(const {%H-}Params: array of string);
procedure cm_EditNewNames(const {%H-}Params: array of string);
procedure cm_Config(const {%H-}Params: array of string);
procedure cm_Rename(const {%H-}Params: array of string);
procedure cm_Close(const {%H-}Params: array of string);
procedure cm_ShowPresetsMenu(const {%H-}Params: array of string);
procedure cm_DropDownPresetList(const {%H-}Params: array of string);
procedure cm_LoadPreset(const Params: array of string);
procedure cm_LoadLastPreset(const {%H-}Params: array of string);
procedure cm_LoadPreset1(const {%H-}Params: array of string);
procedure cm_LoadPreset2(const {%H-}Params: array of string);
procedure cm_LoadPreset3(const {%H-}Params: array of string);
procedure cm_LoadPreset4(const {%H-}Params: array of string);
procedure cm_LoadPreset5(const {%H-}Params: array of string);
procedure cm_LoadPreset6(const {%H-}Params: array of string);
procedure cm_LoadPreset7(const {%H-}Params: array of string);
procedure cm_LoadPreset8(const {%H-}Params: array of string);
procedure cm_LoadPreset9(const {%H-}Params: array of string);
procedure cm_SavePreset(const Params: array of string);
procedure cm_SavePresetAs(const Params: array of string);
procedure cm_RenamePreset(const Params: array of string);
procedure cm_DeletePreset(const Params: array of string);
procedure cm_SortPresets(const Params: array of string);
procedure cm_AnyNameMask(const {%H-}Params: array of string);
procedure cm_NameNameMask(const {%H-}Params: array of string);
procedure cm_ExtNameMask(const {%H-}Params: array of string);
procedure cm_CtrNameMask(const {%H-}Params: array of string);
procedure cm_DateNameMask(const {%H-}Params: array of string);
procedure cm_TimeNameMask(const {%H-}Params: array of string);
procedure cm_PlgnNameMask(const {%H-}Params: array of string);
procedure cm_ClearNameMask(const {%H-}Params: array of string);
procedure cm_AnyExtMask(const {%H-}Params: array of string);
procedure cm_NameExtMask(const {%H-}Params: array of string);
procedure cm_ExtExtMask(const {%H-}Params: array of string);
procedure cm_CtrExtMask(const {%H-}Params: array of string);
procedure cm_DateExtMask(const {%H-}Params: array of string);
procedure cm_TimeExtMask(const {%H-}Params: array of string);
procedure cm_PlgnExtMask(const {%H-}Params: array of string);
procedure cm_ClearExtMask(const {%H-}Params: array of string);
procedure cm_ViewRenameLogFile(const {%H-}Params: array of string);
end;
{initialization function}
function ShowMultiRenameForm(aFileSource: IFileSource; var aFiles: TFiles; const PresetToLoad: string = ''): boolean;
implementation
{$R *.lfm}
uses
//Lazarus, Free-Pascal, etc.
Dialogs, Math, Clipbrd,
//DC
fMain, uFileSourceOperation, uOperationsManager, uOSUtils, uDCUtils, uDebug,
DCOSUtils, DCStrUtils, uLng, uGlobs, uSpecialDir, uFileProcs, uShowForm,
fSelectTextRange, fSelectPathRange, uShowMsg, uFileFunctions, dmCommonData,
fMultiRenameWait, fSortAnything, DCConvertEncoding;
type
tMaskHelper = record
sMenuItem: string;
sKeyword: string;
MenuActionStyle: tMenuActionStyle;
iMenuType: tRenameMaskToUse;
iSourceOfInformation: tSourceOfInformation;
end;
const
sPresetsSection = 'MultiRenamePresets';
sLASTPRESET = '{BC322BF1-2185-47F6-9F99-D27ED1E23E53}';
sFRESHMASKS = '{40422152-9D05-469E-9B81-791AF8C369D8}';
iTARGETMASK = $00000001;
sREFRESHCOMMANDS = 'refreshcommands';
sDEFAULTLOGFILENAME = 'default.log';
CONFIG_NOTSAVED = False;
CONFIG_SAVED = True;
NBMAXHELPERS = 30;
var
//Sequence of operation to add a new mask:
// 1. Add its entry below in the "MaskHelpers" array.
// 2. Go immediately set its translatable string for the user in the function "InitializeMaskHelper" and the text in unit "uLng".
// 3. When editing "InitializeMaskHelper", make sure to update the TWO columns of indexes.
// 4. In the procedure "BuildMaskMenu", there is good chance you need to associated to the "AMenuItem.OnClick" the correct function based on "MaskHelpers[iSeekIndex].MenuActionStyle".
// 5. If it's a NEW procedure, you'll need to write it. You may check "MenuItemXCharactersMaskClick" for inspiration.
// 6. There is good chance you need to edit "sHandleFormatString" to add your new mask and action to do with it.
MaskHelpers: array[0..pred(NBMAXHELPERS)] of tMaskHelper =
(
(sMenuItem: ''; sKeyword: '[N]'; MenuActionStyle: masStraight; iMenuType: rmtuFilename; iSourceOfInformation: soiFilename),
(sMenuItem: ''; sKeyword: '[Nx]'; MenuActionStyle: masXCharacters; iMenuType: rmtuFilename; iSourceOfInformation: soiFilename),
(sMenuItem: ''; sKeyword: '[Nx:y]'; MenuActionStyle: masXYCharacters; iMenuType: rmtuFilename; iSourceOfInformation: soiFilename),
(sMenuItem: ''; sKeyword: '[A]'; MenuActionStyle: masStraight; iMenuType: rmtuFilename; iSourceOfInformation: soiFullName),
(sMenuItem: ''; sKeyword: '[Ax:y]'; MenuActionStyle: masXYCharacters; iMenuType: rmtuFilename; iSourceOfInformation: soiFullName),
(sMenuItem: ''; sKeyword: '[P]'; MenuActionStyle: masDirectorySelector; iMenuType: rmtuFilename; iSourceOfInformation: soiPath),
(sMenuItem: ''; sKeyword: '[E]'; MenuActionStyle: masStraight; iMenuType: rmtuExtension; iSourceOfInformation: soiExtension),
(sMenuItem: ''; sKeyword: '[Ex]'; MenuActionStyle: masXCharacters; iMenuType: rmtuExtension; iSourceOfInformation: soiExtension),
(sMenuItem: ''; sKeyword: '[Ex:y]'; MenuActionStyle: masXYCharacters; iMenuType: rmtuExtension; iSourceOfInformation: soiExtension),
(sMenuItem: ''; sKeyword: '[C]'; MenuActionStyle: masStraight; iMenuType: rmtuCounter; iSourceOfInformation: soiCounter),
(sMenuItem: ''; sKeyword: '[G]'; MenuActionStyle: masStraight; iMenuType: rmtuCounter; iSourceOfInformation: soiGUID),
(sMenuItem: ''; sKeyword: '[V:x]'; MenuActionStyle: masAskVariable; iMenuType: rmtuCounter; iSourceOfInformation: soiVariable),
(sMenuItem: ''; sKeyword: '[Y]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[YYYY]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[M]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[MM]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[MMM]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[MMMM]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[D]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[DD]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[DDD]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[DDDD]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[YYYY]-[MM]-[DD]'; MenuActionStyle: masStraight; iMenuType: rmtuDate; iSourceOfInformation: soiDate),
(sMenuItem: ''; sKeyword: '[h]'; MenuActionStyle: masStraight; iMenuType: rmtuTime; iSourceOfInformation: soiTime),
(sMenuItem: ''; sKeyword: '[hh]'; MenuActionStyle: masStraight; iMenuType: rmtuTime; iSourceOfInformation: soiTime),
(sMenuItem: ''; sKeyword: '[n]'; MenuActionStyle: masStraight; iMenuType: rmtuTime; iSourceOfInformation: soiTime),
(sMenuItem: ''; sKeyword: '[nn]'; MenuActionStyle: masStraight; iMenuType: rmtuTime; iSourceOfInformation: soiTime),
(sMenuItem: ''; sKeyword: '[s]'; MenuActionStyle: masStraight; iMenuType: rmtuTime; iSourceOfInformation: soiTime),
(sMenuItem: ''; sKeyword: '[ss]'; MenuActionStyle: masStraight; iMenuType: rmtuTime; iSourceOfInformation: soiTime),
(sMenuItem: ''; sKeyword: '[hh]-[nn]-[ss]'; MenuActionStyle: masStraight; iMenuType: rmtuTime; iSourceOfInformation: soiTime)
);
{ TMultiRenamePreset.Create }
constructor TMultiRenamePreset.Create;
begin
FPresetName := '';
FFileName := '[N]';
FExtension := '[E]';
FFileNameStyle := 0;
FExtensionStyle := 0;
FFind := '';
FReplace := '';
FRegExp := False;
FUseSubs := False;
FCaseSens := False;
FOnlyFirst := False;
FCounter := '1';
FInterval := '1';
FWidth := 0;
FLog := False;
FLogFile := '';
FLogAppend := False;
end;
{ TMultiRenamePreset.Destory }
// Not so necessary, but useful with a breakpoint to validate object is really free from memory when deleting an element from the list of clearing that list.
destructor TMultiRenamePreset.Destroy;
begin
inherited Destroy;
end;
{ TMultiRenamePresetList.GetMultiRenamePreset }
function TMultiRenamePresetList.GetMultiRenamePreset(Index: integer): TMultiRenamePreset;
begin
Result := TMultiRenamePreset(Items[Index]);
end;
{ TMultiRenamePresetList.Delete }
procedure TMultiRenamePresetList.Delete(Index: integer);
begin
TMultiRenamePreset(Items[Index]).Free;
inherited Delete(Index);
end;
{ TMultiRenamePresetList.Clear }
procedure TMultiRenamePresetList.Clear;
var
Index: integer;
begin
for Index := pred(Count) downto 0 do
TMultiRenamePreset(Items[Index]).Free;
inherited Clear;
end;
{ TMultiRenamePresetList.Find }
function TMultiRenamePresetList.Find(sPresetName: string): integer;
var
iSeeker: integer = 0;
begin
Result := -1;
while (Result = -1) and (iSeeker < Count) do
if SameText(sPresetName, MultiRenamePreset[iSeeker].PresetName) then
Result := iSeeker
else
Inc(iSeeker);
end;
{ TfrmMultiRename.Create }
//Not used for actual renaming file.
//Present there just for the "TfrmOptionsHotkeys.FillCommandList" function who need to create the form in memory to extract internal commands from it.
constructor TfrmMultiRename.Create(TheOwner: TComponent);
var
FDummyFiles: TFiles;
begin
FDummyFiles := TFiles.Create(''); //Will be self destroyed by the "TfrmMultiRename" object itself.
Create(TheOwner, nil, FDummyFiles, '');
end;
{ TfrmMultiRename.Create }
constructor TfrmMultiRename.Create(TheOwner: TComponent; aFileSource: IFileSource; var aFiles: TFiles; const paramPreset: string);
begin
FActuallyRenamingFile := False;
FRegExp := TRegExprW.Create;
FNames := TStringList.Create;
FFindText := TStringList.Create;
FFindText.StrictDelimiter := True;
FFindText.Delimiter := '|';
FReplaceText := TStringList.Create;
FReplaceText.StrictDelimiter := True;
FReplaceText.Delimiter := '|';
FMultiRenamePresetList := TMultiRenamePresetList.Create;
FNewNames := TStringHashListUtf8.Create(FileNameCaseSensitive);
FOldNames := TStringHashListUtf8.Create(FileNameCaseSensitive);
FslVariableNames := TStringList.Create;
FslVariableValues := TStringList.Create;
FslVariableSuggestionName := TStringList.Create;
FslVariableSuggestionValue := TStringList.Create;
FFileSource := aFileSource;
FFiles := aFiles;
aFiles := nil;
FSourceRow := -1;
FMoveRow := False;
FParamPresetToLoadOnStart := paramPreset;
inherited Create(TheOwner);
FCommands := TFormCommands.Create(Self, actList);
end;
{ TfrmMultiRename.Destroy }
destructor TfrmMultiRename.Destroy;
begin
inherited Destroy;
FMultiRenamePresetList.Clear;
FreeAndNil(FMultiRenamePresetList);
FreeAndNil(FNewNames);
FreeAndNil(FOldNames);
FreeAndNil(FslVariableNames);
FreeAndNil(FslVariableValues);
FreeAndNil(FslVariableSuggestionName);
FreeAndNil(FslVariableSuggestionValue);
FreeAndNil(FFiles);
FreeAndNil(FNames);
FreeAndNil(FRegExp);
FreeAndNil(FFindText);
FreeAndNil(FReplaceText);
end;
{ TfrmMultiRename.FormCreate }
procedure TfrmMultiRename.FormCreate({%H-}Sender: TObject);
var
HMMultiRename: THMForm;
begin
// Localize File name style ComboBox
ParseLineToList(rsMulRenFileNameStyleList, cbNameMaskStyle.Items);
ParseLineToList(rsMulRenFileNameStyleList, cmbExtensionStyle.Items);
InitializeMaskHelper;
// Set row count
StringGrid.RowCount := FFiles.Count + 1;
StringGrid.FocusRectVisible := False;
// Initialize property storage
IniPropStorage := InitPropStorage(Self);
IniPropStorage.OnRestoreProperties := @RestoreProperties;
IniPropStorage.StoredValues.Add.DisplayName := 'lsvwFile_Columns.Item0_Width';
IniPropStorage.StoredValues.Add.DisplayName := 'lsvwFile_Columns.Item1_Width';
IniPropStorage.StoredValues.Add.DisplayName := 'lsvwFile_Columns.Item2_Width';
if gMulRenShowMenuBarOnTop then
Menu := mmMainMenu
else
Menu := nil;
if not gIconsInMenus then
begin
mmMainMenu.Images := nil;
pmDynamicMasks.Images := nil;
pmEditDirect.Images := nil;
pmPresets.Images := nil;
end;
HMMultiRename := HotMan.Register(Self, HotkeysCategoryMultiRename);
HMMultiRename.RegisterActionList(actList);
cbExt.Items.Assign(glsRenameExtMaskHistory);
cbName.Items.Assign(glsRenameNameMaskHistory);
// Set default values for controls.
cm_ResetAll([sREFRESHCOMMANDS + '=0']);
// Initialize presets.
LoadPresetsXml(gConfig);
if (FParamPresetToLoadOnStart <> '') and (FMultiRenamePresetList.Find(FParamPresetToLoadOnStart) <> -1) then
begin
FillPresetsList(FParamPresetToLoadOnStart);
end
else
begin
case gMulRenLaunchBehavior of
mrlbLastMaskUnderLastOne: FillPresetsList(sLASTPRESET);
mrlbLastPreset: FillPresetsList(FLastPreset);
mrlbFreshNew: FillPresetsList(sFRESHMASKS);
end;
end;
PopulateMainMenu;
gSpecialDirList.PopulateMenuWithSpecialDir(pmPathToBeRelativeToHelper, mp_PATHHELPER, nil);
FPluginDispatcher := tfmFilename;
end;
{ TfrmMultiRename.FormCloseQuery }
procedure TfrmMultiRename.FormCloseQuery(Sender: TObject; var CanClose: boolean);
begin
if not isOkToLosePresetModification then
CanClose := False;
end;
{ TfrmMultiRename.FormClose }
procedure TfrmMultiRename.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
SavePreset(sLASTPRESET);
glsRenameExtMaskHistory.Assign(cbExt.Items);
glsRenameNameMaskHistory.Assign(cbName.Items);
CloseAction := caFree;
with StringGrid.Columns do
begin
IniPropStorage.StoredValue['lsvwFile_Columns.Item0_Width'] := IntToStr(Items[0].Width);
IniPropStorage.StoredValue['lsvwFile_Columns.Item1_Width'] := IntToStr(Items[1].Width);
IniPropStorage.StoredValue['lsvwFile_Columns.Item2_Width'] := IntToStr(Items[2].Width);
end;
end;
procedure TfrmMultiRename.FormShow(Sender: TObject);
var
APoint: TPoint;
begin
{$IF DEFINED(LCLQT5)}
gbPresets.Constraints.MaxHeight:= cbPresets.Height + (gbPresets.Height - gbPresets.ClientHeight) +
gbPresets.ChildSizing.TopBottomSpacing * 2;
{$ENDIF}
APoint:= TPoint.Create(cbUseSubs.Left, 0);
fneRenameLogFileFilename.BorderSpacing.Left:= gbFindReplace.ClientToParent(APoint, pnlOptionsRight).X;
end;
{ TfrmMultiRename.StringGridKeyDown }
procedure TfrmMultiRename.StringGridKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
var
tmpFile: TFile;
DestRow: integer;
begin
DestRow := StringGrid.Row;
if (Shift = [ssShift]) then
begin
case Key of
VK_UP:
begin
DestRow := StringGrid.Row - 1;
end;
VK_DOWN:
begin
DestRow := StringGrid.Row + 1;
end;
end;
if (DestRow <> StringGrid.Row) and (0 < DestRow) and (DestRow < StringGrid.RowCount) then
begin
tmpFile := FFiles.Items[DestRow - 1];
FFiles.Items[DestRow - 1] := FFiles.Items[StringGrid.Row - 1];
FFiles.Items[StringGrid.Row - 1] := tmpFile;
StringGridTopLeftChanged(StringGrid);
end;
end;
end;
{ TfrmMultiRename.StringGridMouseDown }
procedure TfrmMultiRename.StringGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
var
SourceCol: integer = 0;
begin
if (Button = mbLeft) then
begin
StringGrid.MouseToCell(X, Y, SourceCol, FSourceRow);
if (FSourceRow > 0) then
begin
FMoveRow := True;
end;
end;
end;
{ TfrmMultiRename.StringGridMouseUp }
procedure TfrmMultiRename.StringGridMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
if Button = mbLeft then
begin
FMoveRow := False;
end;
end;
{ TfrmMultiRename.StringGridSelection }
procedure TfrmMultiRename.StringGridSelection(Sender: TObject; aCol, aRow: integer);
var
tmpFile: TFile;
begin
if FMoveRow and (aRow <> FSourceRow) then
begin
tmpFile := FFiles.Items[aRow - 1];
FFiles.Items[aRow - 1] := FFiles.Items[FSourceRow - 1];
FFiles.Items[FSourceRow - 1] := tmpFile;
FSourceRow := aRow;
StringGridTopLeftChanged(StringGrid);
end;
end;
{ TfrmMultiRename.StringGridTopLeftChanged }
procedure TfrmMultiRename.StringGridTopLeftChanged(Sender: TObject);
var
I, iRowCount: integer;
begin
iRowCount := StringGrid.TopRow + StringGrid.VisibleRowCount;
if iRowCount > FFiles.Count then
iRowCount := FFiles.Count;
for I := StringGrid.TopRow to iRowCount do
begin
StringGrid.Cells[0, I] := FFiles[I - 1].Name;
StringGrid.Cells[1, I] := FreshText(I - 1);
StringGrid.Cells[2, I] := FFiles[I - 1].Path;
end;
end;
{ TfrmMultiRename.cbNameStyleChange }
procedure TfrmMultiRename.cbNameStyleChange(Sender: TObject);
begin
StringGridTopLeftChanged(StringGrid);
if ActiveControl <> cbPresets then
SetConfigurationState(CONFIG_NOTSAVED);
end;
{ TfrmMultiRename.cbPresetsChange }
procedure TfrmMultiRename.cbPresetsChange(Sender: TObject);
begin
if cbPresets.ItemIndex <> 0 then
cm_LoadPreset(['name=' + cbPresets.Items.Strings[cbPresets.ItemIndex]])
else
cm_LoadPreset(['name=' + sLASTPRESET]);
RefreshActivePresetCommands;
end;
{ TfrmMultiRename.cbPresetsCloseUp }
procedure TfrmMultiRename.cbPresetsCloseUp(Sender: TObject);
begin
if cbName.Enabled and gbMaska.Enabled then ActiveControl := cbName;
cbName.SelStart := UTF8Length(cbName.Text);
end;
{ TfrmMultiRename.edFindChange }
procedure TfrmMultiRename.edFindChange(Sender: TObject);
begin
if cbRegExp.Checked then
FRegExp.Expression := CeUtf8ToUtf16(edFind.Text)
else
begin
FFindText.DelimitedText := edFind.Text;
end;
SetConfigurationState(CONFIG_NOTSAVED);
StringGridTopLeftChanged(StringGrid);
end;
{ TfrmMultiRename.edReplaceChange }
procedure TfrmMultiRename.edReplaceChange(Sender: TObject);
begin
if not cbRegExp.Checked then
begin
FReplaceText.DelimitedText := edReplace.Text;
end;
SetConfigurationState(CONFIG_NOTSAVED);
StringGridTopLeftChanged(StringGrid);
end;
{ TfrmMultiRename.cbRegExpChange }
procedure TfrmMultiRename.cbRegExpChange(Sender: TObject);
begin
if cbRegExp.Checked then
cbUseSubs.Checked := boolean(cbUseSubs.Tag)
else
begin
cbUseSubs.Tag := integer(cbUseSubs.Checked);
cbUseSubs.Checked := False;
end;
cbUseSubs.Enabled := cbRegExp.Checked;
edFindChange(edFind);
edReplaceChange(edReplace);
end;
{ TfrmMultiRename.edPocChange }
procedure TfrmMultiRename.edPocChange(Sender: TObject);
var
c: integer;
begin
c := StrToIntDef(edPoc.Text, maxint);
if c = MaxInt then
with edPoc do //editbox only for numbers
begin
Text := '1';
SelectAll;
end;
SetConfigurationState(CONFIG_NOTSAVED);
StringGridTopLeftChanged(StringGrid);
end;
{ TfrmMultiRename.edIntervalChange }
procedure TfrmMultiRename.edIntervalChange(Sender: TObject);
var
c: integer;
begin
c := StrToIntDef(edInterval.Text, maxint);
if c = MaxInt then
with edInterval do //editbox only for numbers
begin
Text := '1';
SelectAll;
end;
SetConfigurationState(CONFIG_NOTSAVED);
StringGridTopLeftChanged(StringGrid);
end;
{ TfrmMultiRename.cbLogClick }
procedure TfrmMultiRename.cbLogClick(Sender: TObject);
begin
fneRenameLogFileFilename.Enabled := cbLog.Checked;
actInvokeRelativePath.Enabled := cbLog.Checked;
actViewRenameLogFile.Enabled := cbLog.Checked;
cbLogAppend.Enabled := cbLog.Checked;
SetConfigurationState(CONFIG_NOTSAVED);
end;
{ TfrmMultiRename.actExecute }
procedure TfrmMultiRename.actExecute(Sender: TObject);
var
cmd: string;
begin
cmd := (Sender as TAction).Name;
cmd := 'cm_' + Copy(cmd, 4, Length(cmd) - 3);
Commands.ExecuteCommand(cmd, []);
end;
{ TfrmMultiRename.actInvokeRelativePathExecute }
procedure TfrmMultiRename.actInvokeRelativePathExecute(Sender: TObject);
begin
fneRenameLogFileFilename.SetFocus;
gSpecialDirList.SetSpecialDirRecipientAndItsType(fneRenameLogFileFilename, pfFILE);
pmPathToBeRelativeToHelper.PopUp(Mouse.CursorPos.X, Mouse.CursorPos.Y);
end;
{ TfrmMultiRename.RestoreProperties }
procedure TfrmMultiRename.RestoreProperties(Sender: TObject);
begin
with StringGrid.Columns do
begin
Items[0].Width := StrToIntDef(IniPropStorage.StoredValue['lsvwFile_Columns.Item0_Width'], Items[0].Width);
Items[1].Width := StrToIntDef(IniPropStorage.StoredValue['lsvwFile_Columns.Item1_Width'], Items[1].Width);
Items[2].Width := StrToIntDef(IniPropStorage.StoredValue['lsvwFile_Columns.Item2_Width'], Items[2].Width);
end;
end;
{ TfrmMultiRename.SetConfigurationState }
procedure TfrmMultiRename.SetConfigurationState(bConfigurationSaved: boolean);
begin
if not cbPresets.DroppedDown then
begin
if bConfigurationSaved or (cbPresets.ItemIndex <> 0) then
begin
if cbPresets.Enabled <> bConfigurationSaved then
begin
cbPresets.Enabled := bConfigurationSaved;
end;
end;
end;
end;
{ TfrmMultiRename.GetPresetNameForCommand }
// Wanted preset may be given via "name=presetname" or via "index=indexno".
function TfrmMultiRename.GetPresetNameForCommand(const Params: array of string): string;
var
Param, sValue: string;
iIndex: integer;
begin
Result := '';
for Param in Params do
begin
if GetParamValue(Param, 'name', sValue) then
Result := sValue
else
if GetParamValue(Param, 'index', sValue) then
begin
iIndex := StrToIntDef(sValue, -1);
if (iIndex >= 0) and (iIndex < cbPresets.items.Count) then
if iIndex = 0 then
Result := sLASTPRESET
else
Result := cbPresets.Items.Strings[iIndex];
end;
end;
end;
{ TfrmMultiRename.LoadPresetsXml }
procedure TfrmMultiRename.LoadPresetsXml(AConfig: TXmlConfig);
var
PresetName: string;
AMultiRenamePreset: TMultiRenamePreset;
ANode: TXmlNode;
PresetIndex: integer;
begin
FMultiRenamePresetList.Clear;
ANode := AConfig.FindNode(AConfig.RootNode, sPresetsSection);
FLastPreset := AConfig.GetValue(ANode, 'LastPreset', sLASTPRESET);
ANode := AConfig.FindNode(ANode, 'Presets');
if Assigned(ANode) then
begin
ANode := ANode.FirstChild;
while Assigned(ANode) do
begin
if ANode.CompareName('Preset') = 0 then
begin
if AConfig.TryGetValue(ANode, 'Name', PresetName) then
begin
if FMultiRenamePresetList.Find(PresetName) = -1 then //Make sure we don't load preset with the same name.
begin
AMultiRenamePreset := TMultiRenamePreset.Create;
AMultiRenamePreset.PresetName := PresetName;
FMultiRenamePresetList.Add(AMultiRenamePreset);
AMultiRenamePreset.FileName := AConfig.GetValue(ANode, 'Filename', '[N]');
AMultiRenamePreset.Extension := AConfig.GetValue(ANode, 'Extension', '[E]');
AMultiRenamePreset.FileNameStyle := AConfig.GetValue(ANode, 'FilenameStyle', 0);
AMultiRenamePreset.ExtensionStyle := AConfig.GetValue(ANode, 'ExtensionStyle', 0);
AMultiRenamePreset.Find := AConfig.GetValue(ANode, 'Find', '');
AMultiRenamePreset.Replace := AConfig.GetValue(ANode, 'Replace', '');
AMultiRenamePreset.RegExp := AConfig.GetValue(ANode, 'RegExp', False);
AMultiRenamePreset.UseSubs := AConfig.GetValue(ANode, 'UseSubs', False);
AMultiRenamePreset.CaseSens := AConfig.GetValue(ANode, 'CaseSensitive', False);
AMultiRenamePreset.OnlyFirst := AConfig.GetValue(ANode, 'OnlyFirst', False);
AMultiRenamePreset.Counter := AConfig.GetValue(ANode, 'Counter', '1');
AMultiRenamePreset.Interval := AConfig.GetValue(ANode, 'Interval', '1');
AMultiRenamePreset.Width := AConfig.GetValue(ANode, 'Width', 0);
AMultiRenamePreset.Log := AConfig.GetValue(ANode, 'Log/Enabled', False);
AMultiRenamePreset.LogAppend := AConfig.GetValue(ANode, 'Log/Append', False);
AMultiRenamePreset.LogFile := AConfig.GetValue(ANode, 'Log/File', '');
end;
end
else
DCDebug('Invalid entry in configuration: ' + AConfig.GetPathFromNode(ANode) + '.');
end;
ANode := ANode.NextSibling;
end;
end;
//Make sure the "sLASTPRESET" is at position 0.
PresetIndex := FMultiRenamePresetList.Find(sLASTPRESET);
if PresetIndex <> 0 then
begin
if PresetIndex <> -1 then
begin
//If it's present but not at zero, move it to 0.
FMultiRenamePresetList.Move(PresetIndex, 0);
end
else
begin
AMultiRenamePreset := TMultiRenamePreset.Create;
AMultiRenamePreset.PresetName := sLASTPRESET;
FMultiRenamePresetList.Insert(0, AMultiRenamePreset);
end;
end;
end;
{ TfrmMultiRename.isOkToLosePresetModification }
function TfrmMultiRename.isOkToLosePresetModification: boolean;
var
MyMsgResult: TMyMsgResult;
begin
Result := False;
if (cbPresets.ItemIndex <= 0) or (cbPresets.Enabled) or (not Visible) then
Result := True
else
begin
case gMulRenExitModifiedPreset of
mrempIgnoreSaveLast:
begin
Result := True;
end;
mrempSaveAutomatically:
begin
if cbPresets.ItemIndex > 0 then
cm_SavePreset(['name=' + cbPresets.Items.Strings[cbPresets.ItemIndex]]);
Result := True;
end;
mrempPromptUser:
begin
MyMsgResult := msgYesNoCancel(Format(rsMulRenSaveModifiedPreset, [cbPresets.Items.Strings[cbPresets.ItemIndex]]), msmbCancel);
case MyMsgResult of
mmrYes:
begin
cm_SavePreset([]);
Result := True;
end;
mmrNo: Result := True;
mmrCancel: ;
end;
end;
end;
end;
end;
{ TfrmMultiRename.SavePreset }
procedure TfrmMultiRename.SavePreset(PresetName: string);
var
PresetIndex: integer;
AMultiRenamePresetObject: TMultiRenamePreset;
begin
if PresetName <> '' then
begin
PresetIndex := FMultiRenamePresetList.Find(PresetName);
if PresetIndex = -1 then
begin
AMultiRenamePresetObject := TMultiRenamePreset.Create;
AMultiRenamePresetObject.PresetName := PresetName;
PresetIndex := FMultiRenamePresetList.Add(AMultiRenamePresetObject);
end;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].FileName := cbName.Text;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Extension := cbExt.Text;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].FileNameStyle := cbNameMaskStyle.ItemIndex;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].ExtensionStyle := cmbExtensionStyle.ItemIndex;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Find := edFind.Text;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Replace := edReplace.Text;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].RegExp := cbRegExp.Checked;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].UseSubs := cbUseSubs.Checked;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].CaseSens := cbCaseSens.Checked;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].OnlyFirst := cbOnlyFirst.Checked;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Counter := edPoc.Text;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Interval := edInterval.Text;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Width := cmbxWidth.ItemIndex;
case gMulRenSaveRenamingLog of
mrsrlPerPreset:
begin
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Log := cbLog.Checked;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogFile := fneRenameLogFileFilename.FileName;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogAppend := cbLogAppend.Checked;
end;
mrsrlAppendSameLog:
begin
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Log := FbRememberLog;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogAppend := FbRememberAppend;
FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogFile := FsRememberRenameLogFilename;
end;
end;
SavePresets;
end;
end;
{ TfrmMultiRename.SavePresetsXml }
procedure TfrmMultiRename.SavePresetsXml(AConfig: TXmlConfig);
var
i: integer;
ANode, SubNode: TXmlNode;
begin
ANode := AConfig.FindNode(AConfig.RootNode, sPresetsSection, True);
AConfig.ClearNode(ANode);
if cbPresets.ItemIndex = 0 then
AConfig.SetValue(ANode, 'LastPreset', sLASTPRESET)
else
AConfig.SetValue(ANode, 'LastPreset', cbPresets.Items.Strings[cbPresets.ItemIndex]);
ANode := AConfig.FindNode(ANode, 'Presets', True);
for i := 0 to pred(FMultiRenamePresetList.Count) do
begin
SubNode := AConfig.AddNode(ANode, 'Preset');
AConfig.AddValue(SubNode, 'Name', FMultiRenamePresetList.MultiRenamePreset[i].PresetName);
AConfig.AddValue(SubNode, 'Filename', FMultiRenamePresetList.MultiRenamePreset[i].FileName);
AConfig.AddValue(SubNode, 'Extension', FMultiRenamePresetList.MultiRenamePreset[i].Extension);
AConfig.AddValue(SubNode, 'FilenameStyle', FMultiRenamePresetList.MultiRenamePreset[i].FileNameStyle);
AConfig.AddValue(SubNode, 'ExtensionStyle', FMultiRenamePresetList.MultiRenamePreset[i].ExtensionStyle);
AConfig.AddValue(SubNode, 'Find', FMultiRenamePresetList.MultiRenamePreset[i].Find);
AConfig.AddValue(SubNode, 'Replace', FMultiRenamePresetList.MultiRenamePreset[i].Replace);
AConfig.AddValue(SubNode, 'RegExp', FMultiRenamePresetList.MultiRenamePreset[i].RegExp);
AConfig.AddValue(SubNode, 'UseSubs', FMultiRenamePresetList.MultiRenamePreset[i].UseSubs);
AConfig.AddValue(SubNode, 'CaseSensitive', FMultiRenamePresetList.MultiRenamePreset[i].CaseSens);
AConfig.AddValue(SubNode, 'OnlyFirst', FMultiRenamePresetList.MultiRenamePreset[i].OnlyFirst);
AConfig.AddValue(SubNode, 'Counter', FMultiRenamePresetList.MultiRenamePreset[i].Counter);
AConfig.AddValue(SubNode, 'Interval', FMultiRenamePresetList.MultiRenamePreset[i].Interval);
AConfig.AddValue(SubNode, 'Width', FMultiRenamePresetList.MultiRenamePreset[i].Width);
AConfig.SetValue(SubNode, 'Log/Enabled', FMultiRenamePresetList.MultiRenamePreset[i].Log);
AConfig.SetValue(SubNode, 'Log/Append', FMultiRenamePresetList.MultiRenamePreset[i].LogAppend);
AConfig.SetValue(SubNode, 'Log/File', FMultiRenamePresetList.MultiRenamePreset[i].LogFile);
end;
end;
{ TfrmMultiRename.SavePresets }
procedure TfrmMultiRename.SavePresets;
begin
SavePresetsXml(gConfig);
gConfig.Save;
end;
{ TfrmMultiRename.DeletePreset }
procedure TfrmMultiRename.DeletePreset(PresetName: string);
var
PresetIndex: integer;
begin
if PresetName <> '' then
begin
PresetIndex := FMultiRenamePresetList.Find(PresetName);
if PresetIndex <> -1 then
begin
FMultiRenamePresetList.Delete(PresetIndex);
SavePresets;
end;
end;
end;
{ TfrmMultiRename.FillPresetsList }
//We fill the preset drop list with the element in memory.
//If it's specified when called, will attempt to load the specified preset in parameter.
//If it's not specified, will attempt to re-select the one that was initially selected.
//If nothing is still selected, we'll select the [Last One].
procedure TfrmMultiRename.FillPresetsList(const WantedSelectedPresetName: string = '');
var
i: integer;
sRememberSelection, PresetName: string;
begin
sRememberSelection := '';
if WantedSelectedPresetName <> '' then
sRememberSelection := WantedSelectedPresetName;
if sRememberSelection = '' then
if cbPresets.ItemIndex <> -1 then
if cbPresets.ItemIndex < cbPresets.Items.Count then
sRememberSelection := cbPresets.Items.Strings[cbPresets.ItemIndex];
cbPresets.Clear;
cbPresets.Items.Add(rsMulRenLastPreset);
for i := 0 to pred(FMultiRenamePresetList.Count) do
begin
PresetName := FMultiRenamePresetList.MultiRenamePreset[i].PresetName;
if (PresetName <> sLASTPRESET) then
if cbPresets.Items.IndexOf(PresetName) = -1 then
cbPresets.Items.Add(PresetName);
end;
if (WantedSelectedPresetName = sLASTPRESET) or (WantedSelectedPresetName = sFRESHMASKS) then
cbPresets.ItemIndex := 0
else
if sRememberSelection <> '' then
if cbPresets.Items.IndexOf(sRememberSelection) <> -1 then
cbPresets.ItemIndex := cbPresets.Items.IndexOf(sRememberSelection);
if cbPresets.ItemIndex = -1 then
if cbPresets.Items.Count > 0 then
cbPresets.ItemIndex := 0;
if WantedSelectedPresetName <> sFRESHMASKS then
begin
cbPresetsChange(cbPresets);
RefreshActivePresetCommands;
end;
end;
{ TfrmMultiRename.RefreshActivePresetCommands }
procedure TfrmMultiRename.RefreshActivePresetCommands;
begin
//"Load last preset" is always available since it's the [Last One].
actLoadPreset1.Enabled := (cbPresets.Items.Count > 1) and (cbPresets.Enabled);
actLoadPreset2.Enabled := (cbPresets.Items.Count > 2) and (cbPresets.Enabled);
actLoadPreset3.Enabled := (cbPresets.Items.Count > 3) and (cbPresets.Enabled);
actLoadPreset4.Enabled := (cbPresets.Items.Count > 4) and (cbPresets.Enabled);
actLoadPreset5.Enabled := (cbPresets.Items.Count > 5) and (cbPresets.Enabled);
actLoadPreset6.Enabled := (cbPresets.Items.Count > 6) and (cbPresets.Enabled);
actLoadPreset7.Enabled := (cbPresets.Items.Count > 7) and (cbPresets.Enabled);
actLoadPreset8.Enabled := (cbPresets.Items.Count > 8) and (cbPresets.Enabled);
actLoadPreset9.Enabled := (cbPresets.Items.Count > 9) and (cbPresets.Enabled);
actSavePreset.Enabled := (cbPresets.ItemIndex > 0);
//"Save as is always available so we may save the [Last One]
actRenamePreset.Enabled := (cbPresets.ItemIndex > 0);
actDeletePreset.Enabled := (cbPresets.ItemIndex > 0);
end;
{ TfrmMultiRename.InitializeMaskHelper }
procedure TfrmMultiRename.InitializeMaskHelper;
begin
if MaskHelpers[00].sMenuItem = '' then //"MaskHelpers" are no tin the object but generic, so we just need to initialize once.
begin
MaskHelpers[00].sMenuItem := MaskHelpers[00].sKeyword + ' ' + rsMulRenMaskName;
MaskHelpers[01].sMenuItem := MaskHelpers[01].sKeyword + ' ' + rsMulRenMaskCharAtPosX;
MaskHelpers[02].sMenuItem := MaskHelpers[02].sKeyword + ' ' + rsMulRenMaskCharAtPosXtoY;
MaskHelpers[03].sMenuItem := MaskHelpers[03].sKeyword + ' ' + rsMulRenMaskFullName;
MaskHelpers[04].sMenuItem := MaskHelpers[04].sKeyword + ' ' + rsMulRenMaskFullNameCharAtPosXtoY;
MaskHelpers[05].sMenuItem := MaskHelpers[05].sKeyword + ' ' + rsMulRenMaskParent;
MaskHelpers[06].sMenuItem := MaskHelpers[06].sKeyword + ' ' + rsMulRenMaskExtension;
MaskHelpers[07].sMenuItem := MaskHelpers[07].sKeyword + ' ' + rsMulRenMaskCharAtPosX;
MaskHelpers[08].sMenuItem := MaskHelpers[08].sKeyword + ' ' + rsMulRenMaskCharAtPosXtoY;
MaskHelpers[09].sMenuItem := MaskHelpers[09].sKeyword + ' ' + rsMulRenMaskCounter;
MaskHelpers[10].sMenuItem := MaskHelpers[10].sKeyword + ' ' + rsMulRenMaskGUID;
MaskHelpers[11].sMenuItem := MaskHelpers[11].sKeyword + ' ' + rsMulRenMaskVarOnTheFly;
MaskHelpers[12].sMenuItem := MaskHelpers[12].sKeyword + ' ' + rsMulRenMaskYear2Digits;
MaskHelpers[13].sMenuItem := MaskHelpers[13].sKeyword + ' ' + rsMulRenMaskYear4Digits;
MaskHelpers[14].sMenuItem := MaskHelpers[14].sKeyword + ' ' + rsMulRenMaskMonth;
MaskHelpers[15].sMenuItem := MaskHelpers[15].sKeyword + ' ' + rsMulRenMaskMonth2Digits;
MaskHelpers[16].sMenuItem := MaskHelpers[16].sKeyword + ' ' + rsMulRenMaskMonthAbrev;
MaskHelpers[17].sMenuItem := MaskHelpers[17].sKeyword + ' ' + rsMulRenMaskMonthComplete;
MaskHelpers[18].sMenuItem := MaskHelpers[18].sKeyword + ' ' + rsMulRenMaskDay;
MaskHelpers[19].sMenuItem := MaskHelpers[19].sKeyword + ' ' + rsMulRenMaskDay2Digits;
MaskHelpers[20].sMenuItem := MaskHelpers[20].sKeyword + ' ' + rsMulRenMaskDOWAbrev;
MaskHelpers[21].sMenuItem := MaskHelpers[21].sKeyword + ' ' + rsMulRenMaskDOWComplete;
MaskHelpers[22].sMenuItem := MaskHelpers[22].sKeyword + ' ' + rsMulRenMaskCompleteDate;
MaskHelpers[23].sMenuItem := MaskHelpers[23].sKeyword + ' ' + rsMulRenMaskHour;
MaskHelpers[24].sMenuItem := MaskHelpers[24].sKeyword + ' ' + rsMulRenMaskHour2Digits;
MaskHelpers[25].sMenuItem := MaskHelpers[25].sKeyword + ' ' + rsMulRenMaskMin;
MaskHelpers[26].sMenuItem := MaskHelpers[26].sKeyword + ' ' + rsMulRenMaskMin2Digits;
MaskHelpers[27].sMenuItem := MaskHelpers[27].sKeyword + ' ' + rsMulRenMaskSec;
MaskHelpers[28].sMenuItem := MaskHelpers[28].sKeyword + ' ' + rsMulRenMaskSec2Digits;
MaskHelpers[29].sMenuItem := MaskHelpers[29].sKeyword + ' ' + rsMulRenMaskCompleteTime;
end;
end;
{ TfrmMultiRename.PopulateMainMenu }
// This main menu is not essential.
// But it does not occupy a lot of pixels and may benefit to user to help to both discover and remember the keyboard shortcut by visualizing them.
// Also, we populate it run-time to save work to valuable translators so they won't have to re-translate the same strings or to validate copies.
procedure TfrmMultiRename.PopulateMainMenu;
var
miPresets, miMasks, miSubMasks: TMenuItem;
begin
btnAnyNameMask.Action := actAnyNameMask;
btnAnyNameMask.Caption := '...';
btnAnyNameMask.Width := fneRenameLogFileFilename.ButtonWidth;
btnAnyExtMask.Action := actAnyExtMask;
btnAnyExtMask.Caption := '...';
btnAnyExtMask.Width := fneRenameLogFileFilename.ButtonWidth;
btnRelativeRenameLogFile.Action := actInvokeRelativePath;
btnRelativeRenameLogFile.Caption := '';
btnRelativeRenameLogFile.Width := fneRenameLogFileFilename.ButtonWidth;
btnRelativeRenameLogFile.Hint := actInvokeRelativePath.Caption;
btnViewRenameLogFile.Action := actViewRenameLogFile;
btnViewRenameLogFile.Caption := '';
btnViewRenameLogFile.Width := fneRenameLogFileFilename.ButtonWidth;
btnViewRenameLogFile.Hint := actViewRenameLogFile.Caption;
btnPresets.Action := actShowPresetsMenu;
btnPresets.Caption := '';
btnPresets.Hint := actShowPresetsMenu.Caption;
btnPresets.Constraints.MinWidth := fneRenameLogFileFilename.ButtonWidth;
miPresets := TMenuItem.Create(mmMainMenu);
miPresets.Caption := gbPresets.Caption;
mmMainMenu.Items.Add(miPresets);
BuildPresetsMenu(miPresets);
BuildPresetsMenu(pmPresets);
miMasks := TMenuItem.Create(mmMainMenu);
miMasks.Caption := gbMaska.Caption;
mmMainMenu.Items.Add(miMasks);
//We add the sub-menu for the filename masks
miSubMasks := TMenuItem.Create(miMasks);
miSubMasks.Caption := lbName.Caption;
miSubMasks.ImageIndex := GetImageIndexCategoryName(rmtuFilename);
miMasks.Add(miSubMasks);
PopulateFilenameMenu(miSubMasks);
//We add the sub-menu for the filename masks
miSubMasks := TMenuItem.Create(miMasks);
miSubMasks.Caption := lbExt.Caption;
miSubMasks.ImageIndex := GetImageIndexCategoryName(rmtuExtension);
miMasks.Add(miSubMasks);
PopulateExtensionMenu(miSubMasks);
end;
{ TfrmMultiRename.PopulateFilenameMenu }
procedure TfrmMultiRename.PopulateFilenameMenu(AMenuSomething: TComponent);
var
localMenuItem, miSubMenu, miMenuItem: TMenuItem;
begin
if AMenuSomething.ClassType = TPopupMenu then
localMenuItem := TPopupMenu(AMenuSomething).Items
else if AMenuSomething.ClassType = TMenuItem then
begin
localMenuItem := TMenuItem(AMenuSomething);
miMenuItem := TMenuItem.Create(localMenuItem);
miMenuItem.Action := actAnyNameMask;
localMenuItem.Add(miMenuItem);
miMenuItem := TMenuItem.Create(localMenuItem);
miMenuItem.Caption := '-';
localMenuItem.Add(miMenuItem);
end
else
exit;
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuFilename), GetImageIndexCategoryName(rmtuFilename));
BuildMaskMenu(miSubMenu, tfmFilename, rmtuFilename);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuExtension), GetImageIndexCategoryName(rmtuExtension));
BuildMaskMenu(miSubMenu, tfmFilename, rmtuExtension);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuCounter), GetImageIndexCategoryName(rmtuCounter));
BuildMaskMenu(miSubMenu, tfmFilename, rmtuCounter);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuDate), GetImageIndexCategoryName(rmtuDate));
BuildMaskMenu(miSubMenu, tfmFilename, rmtuDate);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuTime), GetImageIndexCategoryName(rmtuTime));
BuildMaskMenu(miSubMenu, tfmFilename, rmtuTime);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuPlugins), GetImageIndexCategoryName(rmtuPlugins));
BuildMaskMenu(miSubMenu, tfmFilename, rmtuPlugins);
AppendSubMenuToThisMenu(localMenuItem, '-', -1);
AppendActionMenuToThisMenu(localMenuItem, actClearNameMask);
AppendActionMenuToThisMenu(localMenuItem, actResetAll);
end;
{ TfrmMultiRename.PopulateExtensionMenu }
procedure TfrmMultiRename.PopulateExtensionMenu(AMenuSomething: TComponent);
var
localMenuItem, miSubMenu, miMenuItem: TMenuItem;
begin
if AMenuSomething.ClassType = TPopupMenu then
localMenuItem := TPopupMenu(AMenuSomething).Items
else if AMenuSomething.ClassType = TMenuItem then
begin
localMenuItem := TMenuItem(AMenuSomething);
miMenuItem := TMenuItem.Create(localMenuItem);
miMenuItem.Action := actAnyExtMask;
localMenuItem.Add(miMenuItem);
miMenuItem := TMenuItem.Create(localMenuItem);
miMenuItem.Caption := '-';
localMenuItem.Add(miMenuItem);
end
else
exit;
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuFilename), GetImageIndexCategoryName(rmtuFilename));
BuildMaskMenu(miSubMenu, tfmExtension, rmtuFilename);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuExtension), GetImageIndexCategoryName(rmtuExtension));
BuildMaskMenu(miSubMenu, tfmExtension, rmtuExtension);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuCounter), GetImageIndexCategoryName(rmtuCounter));
BuildMaskMenu(miSubMenu, tfmExtension, rmtuCounter);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuDate), GetImageIndexCategoryName(rmtuDate));
BuildMaskMenu(miSubMenu, tfmExtension, rmtuDate);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuTime), GetImageIndexCategoryName(rmtuTime));
BuildMaskMenu(miSubMenu, tfmExtension, rmtuTime);
miSubMenu := AppendSubMenuToThisMenu(localMenuItem, GetMaskCategoryName(rmtuPlugins), GetImageIndexCategoryName(rmtuPlugins));
BuildMaskMenu(miSubMenu, tfmExtension, rmtuPlugins);
AppendSubMenuToThisMenu(localMenuItem, '-', -1);
AppendActionMenuToThisMenu(localMenuItem, actClearExtMask);
AppendActionMenuToThisMenu(localMenuItem, actResetAll);
end;
{ TfrmMultiRename.BuildMaskMenu }
procedure TfrmMultiRename.BuildMaskMenu(AMenuSomething: TComponent; iTarget: tTargetForMask; iMenuTypeMask: tRenameMaskToUse);
var
iSeekIndex: integer;
AMenuItem, localMenuItem: TMenuItem;
actCategoryActionToAdd: TAction = nil;
begin
if AMenuSomething.ClassType = TPopupMenu then
localMenuItem := TPopupMenu(AMenuSomething).Items
else if AMenuSomething.ClassType = TMenuItem then
localMenuItem := TMenuItem(AMenuSomething)
else
exit;
localMenuItem.Clear;
if AMenuSomething.ClassType = TMenuItem then
begin
actCategoryActionToAdd := GetCategoryAction(iTarget, iMenuTypeMask);
if actCategoryActionToAdd <> nil then
begin
AMenuItem := TMenuItem.Create(AMenuSomething);
AMenuItem.Action := actCategoryActionToAdd;
localMenuItem.Add(AMenuItem);
AMenuItem := TMenuItem.Create(AMenuSomething);
AMenuItem.Caption := '-';
localMenuItem.Add(AMenuItem);
end;
end;
for iSeekIndex := 0 to pred(NBMAXHELPERS) do
begin
if MaskHelpers[iSeekIndex].iMenuType = iMenuTypeMask then
begin
AMenuItem := TMenuItem.Create(AMenuSomething);
AMenuItem.Caption := MaskHelpers[iSeekIndex].sMenuItem;
AMenuItem.Tag := (iSeekIndex shl 16) or Ord(iTarget);
AMenuItem.Hint := MaskHelpers[iSeekIndex].sKeyword;
AMenuItem.ImageIndex := GetImageIndexCategoryName(MaskHelpers[iSeekIndex].iMenuType);
case MaskHelpers[iSeekIndex].MenuActionStyle of
masStraight: AMenuItem.OnClick := @MenuItemStraightMaskClick;
masXCharacters, masXYCharacters: AMenuItem.OnClick := @MenuItemXCharactersMaskClick;
masAskVariable: AMenuItem.OnClick := @MenuItemVariableMaskClick;
masDirectorySelector: AMenuItem.OnClick := @MenuItemDirectorySelectorMaskClick;
end;
localMenuItem.Add(AMenuItem);
end;
end;
if rmtuPlugins = iMenuTypeMask then
begin
FPluginDispatcher := iTarget;
FillContentFieldMenu(AMenuSomething, @miPluginClick); //No need to clear "pmDynamicMasks" because "FillContentFieldMenu" do it itself.
if AMenuSomething.ClassType = TMenuItem then
begin
//We need to add the mask category menu item at the end since "FillContentFieldMenu" clears our "pmDynamicMasks".
AMenuItem := TMenuItem.Create(AMenuSomething);
AMenuItem.Caption := '-';
localMenuItem.Insert(0, AMenuItem);
AMenuItem := TMenuItem.Create(AMenuSomething);
AMenuItem.Action := actCategoryActionToAdd;
localMenuItem.Insert(0, AMenuItem);
end;
end;
end;
{ TfrmMultiRename.BuildPresetsMenu }
procedure TfrmMultiRename.BuildPresetsMenu(AMenuSomething: TComponent);
var
localMenuItem: TMenuItem;
begin
if AMenuSomething.ClassType = TPopupMenu then
localMenuItem := TPopupMenu(AMenuSomething).Items
else if AMenuSomething.ClassType = TMenuItem then
begin
localMenuItem := TMenuItem(AMenuSomething);
AppendActionMenuToThisMenu(localMenuItem, actShowPresetsMenu);
AppendSubMenuToThisMenu(localMenuItem, '-', -1);
end
else
exit;
AppendActionMenuToThisMenu(localMenuItem, actDropDownPresetList);
AppendSubMenuToThisMenu(localMenuItem, '-', -1);
AppendActionMenuToThisMenu(localMenuItem, actLoadLastPreset);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset1);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset2);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset3);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset4);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset5);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset6);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset7);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset8);
AppendActionMenuToThisMenu(localMenuItem, actLoadPreset9);
AppendSubMenuToThisMenu(localMenuItem, '-', -1);
AppendActionMenuToThisMenu(localMenuItem, actSavePreset);
AppendActionMenuToThisMenu(localMenuItem, actSavePresetAs);
AppendActionMenuToThisMenu(localMenuItem, actRenamePreset);
AppendActionMenuToThisMenu(localMenuItem, actDeletePreset);
AppendActionMenuToThisMenu(localMenuItem, actSortPresets);
end;
{ TfrmMultiRename.BuildMenuAndPopup }
procedure TfrmMultiRename.BuildMenuAndPopup(iTarget: tTargetForMask; iMenuTypeMask: tRenameMaskToUse);
begin
BuildMaskMenu(pmDynamicMasks, iTarget, iMenuTypeMask);
case iTarget of
tfmFilename: PopupDynamicMenuAtThisControl(pmDynamicMasks, cbName);
tfmExtension: PopupDynamicMenuAtThisControl(pmDynamicMasks, cbExt);
end;
end;
{ TfrmMultiRename.GetMaskCategoryName }
function TfrmMultiRename.GetMaskCategoryName(aRenameMaskToUse: tRenameMaskToUse): string;
begin
Result := '';
case aRenameMaskToUse of
rmtuFilename: Result := rsMulRenFilename;
rmtuExtension: Result := rsMulRenExtension;
rmtuCounter: Result := rsMulRenCounter;
rmtuDate: Result := rsMulRenDate;
rmtuTime: Result := rsMulRenTime;
rmtuPlugins: Result := rsMulRenPlugins;
end;
end;
{ TfrmMultiRename.GetImageIndexCategoryName }
function TfrmMultiRename.GetImageIndexCategoryName(aRenameMaskToUse: tRenameMaskToUse): integer;
begin
Result := -1;
case aRenameMaskToUse of
rmtuFilename: Result := 20;
rmtuExtension: Result := 21;
rmtuCounter: Result := 22;
rmtuDate: Result := 23;
rmtuTime: Result := 24;
rmtuPlugins: Result := 25;
end;
end;
{ TfrmMultiRename.GetCategoryAction }
function TfrmMultiRename.GetCategoryAction(TargetForMask: tTargetForMask; aRenameMask: tRenameMaskToUse): TAction;
begin
Result := nil;
case TargetForMask of
tfmFilename:
begin
case aRenameMask of
rmtuFilename: Result := actNameNameMask;
rmtuExtension: Result := actExtNameMask;
rmtuCounter: Result := actCtrNameMask;
rmtuDate: Result := actDateNameMask;
rmtuTime: Result := actTimeNameMask;
rmtuPlugins: Result := actPlgnNameMask;
end;
end;
tfmExtension:
begin
case aRenameMask of
rmtuFilename: Result := actNameExtMask;
rmtuExtension: Result := actExtExtMask;
rmtuCounter: Result := actCtrExtMask;
rmtuDate: Result := actDateExtMask;
rmtuTime: Result := actTimeExtMask;
rmtuPlugins: Result := actPlgnExtMask;
end;
end;
end;
end;
{ TfrmMultiRename.AppendSubMenuToThisMenu }
function TfrmMultiRename.AppendSubMenuToThisMenu(ATargetMenu: TMenuItem; sCaption: string; iImageIndex: integer): TMenuItem;
begin
Result := TMenuItem.Create(ATargetMenu);
Result.ImageIndex := iImageIndex;
if sCaption <> '' then
Result.Caption := sCaption;
ATargetMenu.Add(Result);
end;
{ TfrmMultiRename.AppendActionMenuToThisMenu }
function TfrmMultiRename.AppendActionMenuToThisMenu(ATargetMenu: TMenuItem; paramAction: TAction): TMenuItem;
begin
Result := TMenuItem.Create(ATargetMenu);
Result.Action := paramAction;
ATargetMenu.Add(Result);
end;
{ TfrmMultiRename.MenuItemXCharactersMaskClick }
procedure TfrmMultiRename.MenuItemXCharactersMaskClick(Sender: TObject);
var
sSourceToSelectFromText, sPrefix: string;
sResultingMaskValue: string = '';
iMaskHelperIndex: integer;
begin
iMaskHelperIndex := TMenuItem(Sender).Tag shr 16;
if iMaskHelperIndex < length(MaskHelpers) then
begin
sSourceToSelectFromText := '';
case MaskHelpers[iMaskHelperIndex].iSourceOfInformation of
soiFilename:
begin
sSourceToSelectFromText := FFiles[pred(StringGrid.Row)].NameNoExt;
sPrefix := 'N';
end;
soiExtension:
begin
sSourceToSelectFromText := FFiles[pred(StringGrid.Row)].Extension;
sPrefix := 'E';
end;
soiFullName:
begin
sSourceToSelectFromText := FFiles[pred(StringGrid.Row)].FullPath;
sPrefix := 'A';
end;
end;
if ShowSelectTextRangeDlg(Self, Caption, sSourceToSelectFromText, sPrefix, sResultingMaskValue) then
InsertMask(sResultingMaskValue, tTargetForMask(TMenuItem(Sender).Tag and iTARGETMASK));
end;
end;
{ TfrmMultiRename.MenuItemDirectorySelectorMaskClick }
procedure TfrmMultiRename.MenuItemDirectorySelectorMaskClick(Sender: TObject);
var
sSourceToSelectFromText, sPrefix: string;
sResultingMaskValue: string = '';
iMaskHelperIndex: integer;
begin
iMaskHelperIndex := TMenuItem(Sender).Tag shr 16;
if iMaskHelperIndex < length(MaskHelpers) then
begin
sSourceToSelectFromText := '';
case MaskHelpers[iMaskHelperIndex].iSourceOfInformation of
soiPath:
begin
sSourceToSelectFromText := FFiles[pred(StringGrid.Row)].Path;
sPrefix := 'P';
end;
end;
if ShowSelectPathRangeDlg(Self, Caption, sSourceToSelectFromText, sPrefix, sResultingMaskValue) then
InsertMask(sResultingMaskValue, tTargetForMask(TMenuItem(Sender).Tag and iTARGETMASK));
end;
end;
{ TfrmMultiRename.MenuItemVariableMaskClick }
procedure TfrmMultiRename.MenuItemVariableMaskClick(Sender: TObject);
var
sVariableName: string;
begin
sVariableName := rsSimpleWordVariable;
if InputQuery(rsMulRenDefineVariableName, rsMulRenEnterNameForVar, sVariableName) then
begin
if sVariableName = '' then
sVariableName := rsSimpleWordVariable;
InsertMask('[V:' + sVariableName + ']', tTargetForMask(TMenuItem(Sender).Tag and iTARGETMASK));
end;
end;
{ TfrmMultiRename.MenuItemStraightMaskClick }
procedure TfrmMultiRename.MenuItemStraightMaskClick(Sender: TObject);
var
sMaks: string;
begin
sMaks := TMenuItem(Sender).Hint;
case tTargetForMask(TMenuItem(Sender).Tag and iTARGETMASK) of
tfmFilename:
begin
InsertMask(sMaks, cbName);
cbName.SetFocus;
end;
tfmExtension:
begin
InsertMask(sMaks, cbExt);
cbExt.SetFocus;
end;
end;
end;
{ TfrmMultiRename.PopupDynamicMenuAtThisControl }
procedure TfrmMultiRename.PopupDynamicMenuAtThisControl(APopUpMenu: TPopupMenu; AControl: TControl);
var
PopupPoint: TPoint;
begin
PopupPoint := AControl.Parent.ClientToScreen(Point(AControl.Left + AControl.Width - 5, AControl.Top + AControl.Height - 5));
APopUpMenu.PopUp(PopupPoint.X, PopupPoint.Y);
end;
{ TfrmMultiRename.miPluginClick }
procedure TfrmMultiRename.miPluginClick(Sender: TObject);
var
sMask: string;
MenuItem: TMenuItem absolute Sender;
begin
case MenuItem.Tag of
0:
begin
sMask := '[=DC().' + MenuItem.Hint + '{}]';
end;
1:
begin
sMask := '[=Plugin(' + MenuItem.Parent.Caption + ').' + MenuItem.Hint + '{}]';
end;
2:
begin
sMask := '[=Plugin(' + MenuItem.Parent.Parent.Caption + ').' + MenuItem.Parent.Hint + '{' + MenuItem.Hint + '}]';
end;
3:
begin
sMask := '[=DC().' + MenuItem.Parent.Hint + '{' + MenuItem.Hint + '}]';
end;
end;
case FPluginDispatcher of
tfmFilename:
begin
InsertMask(sMask, cbName);
cbName.SetFocus;
end;
tfmExtension:
begin
InsertMask(sMask, cbExt);
cbExt.SetFocus;
end;
end;
end;
{ TfrmMultiRename.InsertMask }
procedure TfrmMultiRename.InsertMask(const Mask: string; edChoose: TComboBox);
var
sTmp, sInitialString: string;
I: integer;
begin
sInitialString := edChoose.Text;
if edChoose.SelLength > 0 then
edChoose.SelText := Mask // Replace selected text
else
begin
sTmp := edChoose.Text;
I := edChoose.SelStart + 1; // Insert on current position
UTF8Insert(Mask, sTmp, I);
Inc(I, UTF8Length(Mask));
edChoose.Text := sTmp;
edChoose.SelStart := I - 1;
end;
if sInitialString <> edChoose.Text then
cbNameStyleChange(edChoose);
end;
{ TfrmMultiRename.InsertMask }
procedure TfrmMultiRename.InsertMask(const Mask: string; TargetForMask: tTargetForMask);
begin
case TargetForMask of
tfmFilename:
begin
InsertMask(Mask, cbName);
cbName.SetFocus;
end;
tfmExtension:
begin
InsertMask(Mask, cbExt);
cbExt.SetFocus;
end;
end;
end;
{TfrmMultiRename.sReplace }
function TfrmMultiRename.sReplace(sMask: string; ItemNr: integer): string;
var
iStart, iEnd: integer;
begin
Result := '';
while Length(sMask) > 0 do
begin
iStart := Pos('[', sMask);
if iStart > 0 then
begin
iEnd := Pos(']', sMask);
if iEnd > 0 then
begin
Result := Result + Copy(sMask, 1, iStart - 1) +
sHandleFormatString(Copy(sMask, iStart + 1, iEnd - iStart - 1), ItemNr);
Delete(sMask, 1, iEnd);
end
else
Break;
end
else
Break;
end;
Result := Result + sMask;
end;
{ TfrmMultiRename.sReplaceXX }
function TfrmMultiRename.sReplaceXX(const sFormatStr, sOrig: string): string;
var
iFrom, iTo, iDelim: integer;
begin
if Length(sFormatStr) = 1 then
Result := sOrig
else
begin
iDelim := Pos(':', sFormatStr);
if iDelim = 0 then
begin
iDelim := Pos(',', sFormatStr);
// Not found
if iDelim = 0 then
begin
iFrom := StrToIntDef(Copy(sFormatStr, 2, MaxInt), 1);
if iFrom < 0 then
iFrom := sOrig.Length + iFrom + 1;
iTo := iFrom;
end
// Range e.g. N1,3 (from 1, 3 symbols)
else
begin
iFrom := StrToIntDef(Copy(sFormatStr, 2, iDelim - 2), 1);
iDelim := Abs(StrToIntDef(Copy(sFormatStr, iDelim + 1, MaxSmallint), MaxSmallint));
if iFrom >= 0 then
iTo := iDelim + iFrom - 1
else
begin
iTo := sOrig.Length + iFrom + 1;
iFrom := Max(iTo - iDelim + 1, 1);
end;
end;
end
// Range e.g. N1:2 (from 1 to 2)
else
begin
iFrom := StrToIntDef(Copy(sFormatStr, 2, iDelim - 2), 1);
if iFrom < 0 then
iFrom := sOrig.Length + iFrom + 1;
iTo := StrToIntDef(Copy(sFormatStr, iDelim + 1, MaxSmallint), MaxSmallint);
if iTo < 0 then
iTo := sOrig.Length + iTo + 1;
;
if iTo < iFrom then
begin
iDelim := iTo;
iTo := iFrom;
iFrom := iDelim;
end;
end;
Result := UTF8Copy(sOrig, iFrom, iTo - iFrom + 1);
end;
end;
{ TfrmMultiRename.sReplaceVariable }
function TfrmMultiRename.sReplaceVariable(const sFormatStr: string): string;
var
iDelim, iVariableIndex, iVariableSuggestionIndex: integer;
sVariableName: string = '';
sVariableValue: string = '';
begin
Result := '';
iDelim := Pos(':', sFormatStr);
if iDelim <> 0 then
sVariableName := copy(sFormatStr, succ(iDelim), length(sFormatStr) - iDelim)
else
sVariableName := rsSimpleWordVariable;
iVariableIndex := FslVariableNames.IndexOf(sVariableName);
if iVariableIndex = -1 then
begin
iVariableSuggestionIndex := FslVariableSuggestionName.IndexOf(sVariableName);
if iVariableSuggestionIndex <> -1 then
sVariableValue := FslVariableSuggestionValue.Strings[iVariableSuggestionIndex]
else
sVariableValue := sVariableName;
if InputQuery(rsMulRenDefineVariableValue, Format(rsMulRenEnterValueForVar, [sVariableName]), sVariableValue) then
begin
FslVariableNames.Add(sVariableName);
iVariableIndex := FslVariableValues.Add(sVariableValue);
if iVariableSuggestionIndex = -1 then
begin
FslVariableSuggestionName.Add(sVariableName);
FslVariableSuggestionValue.Add(sVariableValue);
end;
end
else
begin
FActuallyRenamingFile := False;
exit;
end;
end;
Result := FslVariableValues.Strings[iVariableIndex];
end;
{ TfrmMultiRename.sReplaceBadChars }//Replace bad path chars in string
function TfrmMultiRename.sReplaceBadChars(const sPath: string): string;
const
{$IFDEF MSWINDOWS}
ForbiddenChars: set of char = ['<', '>', ':', '"', '/', '\', '|', '?', '*'];
{$ELSE}
ForbiddenChars: set of char = ['/'];
{$ENDIF}
var
Index: integer;
begin
Result := '';
for Index := 1 to Length(sPath) do
if not (sPath[Index] in ForbiddenChars) then
Result += sPath[Index]
else
Result += gMulRenInvalidCharReplacement;
end;
{ TfrmMultiRename.IsLetter }
function TfrmMultiRename.IsLetter(AChar: AnsiChar): boolean;
begin
Result := // Ascii letters
((AChar < #128) and
(((AChar >= 'a') and (AChar <= 'z')) or
((AChar >= 'A') and (AChar <= 'Z')))) or
// maybe Ansi or UTF8
(AChar >= #128);
end;
{ TfrmMultiRename.ApplyStyle }
// Applies style (uppercase, lowercase, etc.) to a string.
function TfrmMultiRename.ApplyStyle(InputString: string; Style: integer): string;
begin
case Style of
1: Result := UTF8UpperCase(InputString);
2: Result := UTF8LowerCase(InputString);
3: Result := FirstCharOfFirstWordToUppercaseUTF8(InputString);
4: Result := FirstCharOfEveryWordToUppercaseUTF8(InputString);
else
Result := InputString;
end;
end;
{ TfrmMultiRename.FirstCharToUppercaseUTF8 }
// Changes first char to uppercase and the rest to lowercase
function TfrmMultiRename.FirstCharToUppercaseUTF8(InputString: string): string;
var
FirstChar: string;
begin
if UTF8Length(InputString) > 0 then
begin
Result := UTF8LowerCase(InputString);
FirstChar := UTF8Copy(Result, 1, 1);
UTF8Delete(Result, 1, 1);
Result := UTF8UpperCase(FirstChar) + Result;
end
else
Result := '';
end;
{ TfrmMultiRename.FirstCharOfFirstWordToUppercaseUTF8 }
// Changes first char of first word to uppercase and the rest to lowercase
function TfrmMultiRename.FirstCharOfFirstWordToUppercaseUTF8(InputString: string): string;
var
SeparatorPos: integer;
begin
InputString := UTF8LowerCase(InputString);
Result := '';
// Search for first letter.
for SeparatorPos := 1 to Length(InputString) do
if IsLetter(InputString[SeparatorPos]) then
break;
Result := Copy(InputString, 1, SeparatorPos - 1) + FirstCharToUppercaseUTF8(Copy(InputString, SeparatorPos, Length(InputString) - SeparatorPos + 1));
end;
{ TfrmMultiRename.FirstCharOfEveryWordToUppercaseUTF8 }
// Changes first char of every word to uppercase and the rest to lowercase
function TfrmMultiRename.FirstCharOfEveryWordToUppercaseUTF8(InputString: string): string;
var
SeparatorPos: integer;
begin
InputString := UTF8LowerCase(InputString);
Result := '';
while InputString <> '' do
begin
// Search for first non-letter (word separator).
for SeparatorPos := 1 to Length(InputString) do
if not IsLetter(InputString[SeparatorPos]) then
break;
Result := Result + FirstCharToUppercaseUTF8(Copy(InputString, 1, SeparatorPos));
Delete(InputString, 1, SeparatorPos);
end;
end;
procedure TfrmMultiRename.LoadNamesFromList(const AFileList: TStrings);
begin
if AFileList.Count <> FFiles.Count then
begin
msgError(Format(rsMulRenWrongLinesNumber, [AFileList.Count, FFiles.Count]));
end
else
begin
FNames.Assign(AFileList);
gbMaska.Enabled := False;
gbPresets.Enabled := False;
gbCounter.Enabled := False;
StringGridTopLeftChanged(StringGrid);
end;
end;
{ TfrmMultiRename.LoadNamesFromFile }
procedure TfrmMultiRename.LoadNamesFromFile(const AFileName: string);
var
AFileList: TStringListEx;
begin
AFileList := TStringListEx.Create;
try
AFileList.LoadFromFile(AFileName);
LoadNamesFromList(AFileList);
except
on E: Exception do
msgError(E.Message);
end;
AFileList.Free;
end;
{ TfrmMultiRename.FreshText }
function TfrmMultiRename.FreshText(ItemIndex: integer): string;
var
I: integer;
bError: boolean;
wsText: UnicodeString;
wsReplace: UnicodeString;
Flags: TReplaceFlags = [];
sTmpName, sTmpExt: string;
begin
bError := False;
if FNames.Count > 0 then
Result := FNames[ItemIndex]
else
begin
// Use mask
sTmpName := sReplace(cbName.Text, ItemIndex);
sTmpExt := sReplace(cbExt.Text, ItemIndex);
// Join
Result := sTmpName;
if sTmpExt <> '' then
Result := Result + '.' + sTmpExt;
end;
// Find and replace
if (edFind.Text <> '') then
begin
if cbRegExp.Checked then
try
wsText:= CeUtf8ToUtf16(Result);
wsReplace:= CeUtf8ToUtf16(edReplace.Text);
FRegExp.ModifierI := not cbCaseSens.Checked;
if not cbOnlyFirst.Checked then
begin
Result := CeUtf16ToUtf8(FRegExp.Replace(wsText, wsReplace, cbUseSubs.Checked));
end
else if FRegExp.Exec(wsText) then
begin
Delete(wsText, FRegExp.MatchPos[0], FRegExp.MatchLen[0]);
if cbUseSubs.Checked then
Insert(FRegExp.Substitute(wsReplace), wsText, FRegExp.MatchPos[0])
else begin
Insert(wsReplace, wsText, FRegExp.MatchPos[0]);
end;
Result:= CeUtf16ToUtf8(wsText);
end;
except
Result := rsMsgErrRegExpSyntax;
bError := True;
end
else begin
if not cbOnlyFirst.Checked then
Flags:= [rfReplaceAll];
if not cbCaseSens.Checked then
Flags+= [rfIgnoreCase];
// Many at once, split find and replace by |
if (FReplaceText.Count = 0) then
FReplaceText.Add('');
for I := 0 to FFindText.Count - 1 do
Result := UTF8StringReplace(Result, FFindText[I], FReplaceText[Min(I, FReplaceText.Count - 1)], Flags);
end;
end;
// File name style
sTmpExt := ExtractFileExt(Result);
sTmpName := Copy(Result, 1, Length(Result) - Length(sTmpExt));
sTmpName := ApplyStyle(sTmpName, cbNameMaskStyle.ItemIndex);
sTmpExt := ApplyStyle(sTmpExt, cmbExtensionStyle.ItemIndex);
Result := sTmpName + sTmpExt;
actRename.Enabled := not bError;
if bError then
begin
edFind.Color := clRed;
edFind.Font.Color := clWhite;
end
else
begin
edFind.Color := clWindow;
edFind.Font.Color := clWindowText;
end;
end;
{ TfrmMultiRename.sHandleFormatString }
function TfrmMultiRename.sHandleFormatString(const sFormatStr: string; ItemNr: integer): string;
var
aFile: TFile;
Index: int64;
Counter: int64;
Dirs: TStringArray;
begin
Result := '';
if Length(sFormatStr) > 0 then
begin
aFile := FFiles[ItemNr];
case sFormatStr[1] of
'[', ']':
begin
Result := sFormatStr;
end;
'N':
begin
Result := sReplaceXX(sFormatStr, aFile.NameNoExt);
end;
'E':
begin
Result := sReplaceXX(sFormatStr, aFile.Extension);
end;
'A':
begin
Result := sReplaceBadChars(sReplaceXX(sFormatStr, aFile.FullPath));
end;
'G':
begin
Result := GuidToString(DCGetNewGUID);
end;
'V':
begin
if FActuallyRenamingFile then
Result := sReplaceVariable(sFormatStr)
else
Result := '[' + sFormatStr + ']';
end;
'C':
begin
// Check for start value after C, e.g. C12
if not TryStrToInt64(Copy(sFormatStr, 2, MaxInt), Index) then
Index := StrToInt64Def(edPoc.Text, 1);
Counter := Index + StrToInt64Def(edInterval.Text, 1) * ItemNr;
Result := Format('%.' + cmbxWidth.Items[cmbxWidth.ItemIndex] + 'd', [Counter]);
end;
'P': // sub path index
begin
Index := StrToIntDef(Copy(sFormatStr, 2, MaxInt), 0);
Dirs := (aFile.Path + ' ').Split([PathDelim]);
Dirs[High(Dirs)] := EmptyStr;
if Index < 0 then
Result := Dirs[Max(0, High(Dirs) + Index)]
else
Result := Dirs[Min(Index, High(Dirs))];
end;
'=':
begin
Result := sReplaceBadChars(FormatFileFunction(UTF8Copy(sFormatStr, 2, UTF8Length(sFormatStr) - 1), FFiles.Items[ItemNr], FFileSource, True));
end;
else
begin
// Assume it is date/time formatting string ([h][n][s][Y][M][D]).
with FFiles.Items[ItemNr] do
if fpModificationTime in SupportedProperties then
try
Result := SysToUTF8(FormatDateTime(sFormatStr, ModificationTime));
except
Result := sFormatStr;
end;
end;
end;
end;
end;
{ TfrmMultiRename.SetFilePropertyResult }
procedure TfrmMultiRename.SetFilePropertyResult(Index: integer; aFile: TFile; aTemplate: TFileProperty; Result: TSetFilePropertyResult);
var
sFilenameForLog, S: string;
begin
with TFileNameProperty(aTemplate) do
begin
if cbLog.Checked then
if gMulRenFilenameWithFullPathInLog then
sFilenameForLog := aFile.FullPath
else
sFilenameForLog := aFile.Name;
case Result of
sfprSuccess:
begin
S := 'OK ' + sFilenameForLog + ' -> ' + Value;
if Index < FFiles.Count then
FFiles[Index].Name := Value // Write new name to the file object
else
begin
Index := StrToInt(aFile.Extension);
FFiles[Index].Name := Value; // Write new name to the file object
end;
end;
sfprError: S := 'FAILED ' + sFilenameForLog + ' -> ' + Value;
sfprSkipped: S := 'SKIPPED ' + sFilenameForLog + ' -> ' + Value;
end;
end;
if cbLog.Checked then
FLog.Add(S);
end;
{ TfrmMultiRename.SetOutputGlobalRenameLogFilename }
procedure TfrmMultiRename.SetOutputGlobalRenameLogFilename;
begin
if gMultRenDailyIndividualDirLog then
fneRenameLogFileFilename.FileName := mbExpandFileName(ExtractFilePath(gMulRenLogFilename) + IncludeTrailingPathDelimiter(EnvVarTodaysDate) + ExtractFilename(gMulRenLogFilename))
else
fneRenameLogFileFilename.FileName := gMulRenLogFilename;
end;
{ TfrmMultiRename.cm_ResetAll }
procedure TfrmMultiRename.cm_ResetAll(const Params: array of string);
var
Param: string;
bNeedRefreshActivePresetCommands: boolean = True;
begin
for Param in Params do
GetParamBoolValue(Param, sREFRESHCOMMANDS, bNeedRefreshActivePresetCommands);
cbName.Text := '[N]';
cbName.SelStart := UTF8Length(cbName.Text);
cbExt.Text := '[E]';
cbExt.SelStart := UTF8Length(cbExt.Text);
edFind.Text := '';
edReplace.Text := '';
cbRegExp.Checked := False;
cbUseSubs.Checked := False;
cbCaseSens.Checked := False;
cbOnlyFirst.Checked := False;
cbNameMaskStyle.ItemIndex := 0;
cmbExtensionStyle.ItemIndex := 0;
edPoc.Text := '1';
edInterval.Text := '1';
cmbxWidth.ItemIndex := 0;
case gMulRenSaveRenamingLog of
mrsrlPerPreset:
begin
cbLog.Checked := False;
cbLog.Enabled := True;
cbLogAppend.Checked := False;
fneRenameLogFileFilename.Enabled := cbLog.Checked;
actInvokeRelativePath.Enabled := cbLog.Checked;
actViewRenameLogFile.Enabled := cbLog.Checked;
cbLogAppend.Enabled := cbLog.Checked;
if (FFiles.Count > 0) then
fneRenameLogFileFilename.FileName := FFiles[0].Path + sDEFAULTLOGFILENAME
else
fneRenameLogFileFilename.FileName := sDEFAULTLOGFILENAME;
end;
mrsrlAppendSameLog:
begin
cbLog.Checked := True;
cbLog.Enabled := False;
cbLogAppend.Checked := True;
cbLogAppend.Enabled := False;
fneRenameLogFileFilename.Enabled := False;
SetOutputGlobalRenameLogFilename;
actInvokeRelativePath.Enabled := False;
actViewRenameLogFile.Enabled := cbLog.Checked;
end;
end;
cbPresets.Text := '';
FNames.Clear;
gbMaska.Enabled := True;
gbPresets.Enabled := True;
cbPresets.ItemIndex := 0;
gbCounter.Enabled := True;
StringGridTopLeftChanged(StringGrid);
if bNeedRefreshActivePresetCommands then
RefreshActivePresetCommands;
end;
{ TfrmMultiRename.cm_InvokeEditor }
procedure TfrmMultiRename.cm_InvokeEditor(const {%H-}Params: array of string);
begin
DCPlaceCursorNearControlIfNecessary(btnEditor);
pmEditDirect.PopUp;
end;
{ TfrmMultiRename.cm_LoadNamesFromFile }
procedure TfrmMultiRename.cm_LoadNamesFromFile(const {%H-}Params: array of string);
begin
dmComData.OpenDialog.FileName := EmptyStr;
dmComData.OpenDialog.Filter := AllFilesMask;
if dmComData.OpenDialog.Execute then
LoadNamesFromFile(dmComData.OpenDialog.FileName);
end;
procedure TfrmMultiRename.cm_LoadNamesFromClipboard(
const Params: array of string);
var
AFileList: TStringListEx;
begin
AFileList := TStringListEx.Create;
try
AFileList.Text := Clipboard.AsText;
LoadNamesFromList(AFileList);
except
on E: Exception do
msgError(E.Message);
end;
AFileList.Free;
end;
{ TfrmMultiRename.cm_EditNames }
procedure TfrmMultiRename.cm_EditNames(const {%H-}Params: array of string);
var
I: integer;
AFileName: string;
AFileList: TStringListEx;
begin
AFileList := TStringListEx.Create;
AFileName := GetTempFolderDeletableAtTheEnd;
AFileName := GetTempName(AFileName, 'txt');
if FNames.Count > 0 then
AFileList.Assign(FNames)
else
begin
for I := 0 to FFiles.Count - 1 do
AFileList.Add(FFiles[I].Name);
end;
try
AFileList.SaveToFile(AFileName);
try
if ShowMultiRenameWaitForm(AFileName, Self) then
LoadNamesFromFile(AFileName);
finally
mbDeleteFile(AFileName);
end;
except
on E: Exception do
msgError(E.Message);
end;
AFileList.Free;
end;
{ TfrmMultiRename.cm_EditNewNames }
procedure TfrmMultiRename.cm_EditNewNames(const {%H-}Params: array of string);
var
sFileName: string;
iIndexFile: integer;
AFileList: TStringListEx;
begin
AFileList := TStringListEx.Create;
try
for iIndexFile := 0 to pred(FFiles.Count) do
AFileList.Add(FreshText(iIndexFile));
sFileName := GetTempName(GetTempFolderDeletableAtTheEnd, 'txt');
try
AFileList.SaveToFile(sFileName);
try
if ShowMultiRenameWaitForm(sFileName, Self) then
LoadNamesFromFile(sFileName);
finally
mbDeleteFile(sFileName);
end;
except
on E: Exception do
msgError(E.Message);
end;
finally
AFileList.Free;
end;
end;
{ TfrmMultiRename.cm_Config }
procedure TfrmMultiRename.cm_Config(const {%H-}Params: array of string);
begin
frmMain.Commands.cm_Options(['TfrmOptionsMultiRename']);
end;
{ TfrmMultiRename.cm_Rename }
procedure TfrmMultiRename.cm_Rename(const {%H-}Params: array of string);
var
AFile: TFile;
NewName: string;
I, J, K: integer;
TempFiles: TStringList;
OldFiles, NewFiles: TFiles;
AutoRename: boolean = False;
Operation: TFileSourceOperation;
theNewProperties: TFileProperties;
LogFileStream: TFileStream;
begin
FActuallyRenamingFile := True;
try
if cbLog.Checked then
begin
if fneRenameLogFileFilename.FileName = EmptyStr then
fneRenameLogFileFilename.FileName := FFiles[0].Path + sDEFAULTLOGFILENAME;
mbForceDirectory(ExtractFileDir(mbExpandFileName(fneRenameLogFileFilename.FileName)));
FLog := TStringListEx.Create;
if cbLogAppend.Checked then
FLog.Add(';' + DateTimeToStr(Now) + ' - ' + rsMulRenLogStart);
end;
OldFiles := FFiles.Clone;
TempFiles := TStringList.Create;
NewFiles := TFiles.Create(EmptyStr);
FslVariableNames.Clear;
FslVariableValues.Clear; //We don't clear the "Suggestion" parts because we may re-use them as their original values if we ever re-do rename pass witht he same instance.
// OldNames
FOldNames.Clear;
for I := 0 to OldFiles.Count - 1 do
FOldNames.Add(OldFiles[I].Name, Pointer(PtrInt(I)));
try
FNewNames.Clear;
for I := 0 to FFiles.Count - 1 do
begin
AFile := TFile.Create(EmptyStr);
AFile.Name := FreshText(I);
//In "FreshText", if there was a "Variable on the fly / [V:Hint]" and the user aborted it, the "FActuallyRenamingFile" will be cleared and so we abort the actual renaming process.
if not FActuallyRenamingFile then
Exit;
// Checking duplicates
NewName := FFiles[I].Path + AFile.Name;
J := FNewNames.Find(NewName);
if J < 0 then
FNewNames.Add(NewName)
else
begin
if not AutoRename then
begin
if MessageDlg(rsMulRenWarningDuplicate + LineEnding +
NewName + LineEnding + LineEnding + rsMulRenAutoRename,
mtWarning, [mbYes, mbAbort], 0, mbAbort) <> mrYes then
Exit;
AutoRename := True;
end;
K := 1;
while J >= 0 do
begin
NewName := FFiles[I].Path + AFile.NameNoExt + ' (' + IntToStr(K) + ')';
if AFile.Extension <> '' then
NewName := NewName + ExtensionSeparator + AFile.Extension;
J := FNewNames.Find(NewName);
Inc(K);
end;
FNewNames.Add(NewName);
AFile.Name := ExtractFileName(NewName);
end;
// Avoid collisions with OldNames
J := FOldNames.Find(AFile.Name);
if (J >= 0) and (PtrUInt(FOldNames.List[J]^.Data) <> I) then
begin
NewName := AFile.Name;
// Generate temp file name, save file index as extension
AFile.FullPath := GetTempName(FFiles[I].Path, IntToStr(I));
TempFiles.AddObject(NewName, AFile.Clone);
end;
NewFiles.Add(AFile);
end;
// Rename temp files back
if TempFiles.Count > 0 then
begin
for I := 0 to TempFiles.Count - 1 do
begin
// Temp file name
OldFiles.Add(TFile(TempFiles.Objects[I]));
// Real new file name
AFile := TFile.Create(EmptyStr);
AFile.Name := TempFiles[I];
NewFiles.Add(AFile);
end;
end;
// Rename files
FillChar({%H-}theNewProperties, SizeOf(TFileProperties), 0);
Operation := FFileSource.CreateSetFilePropertyOperation(OldFiles, theNewProperties);
if Assigned(Operation) then
begin
with Operation as TFileSourceSetFilePropertyOperation do
begin
SetTemplateFiles(NewFiles);
OnSetFilePropertyResult := @SetFilePropertyResult;
end;
OperationsManager.AddOperationModal(Operation);
end;
InsertFirstItem(cbExt.Text, cbExt);
InsertFirstItem(cbName.Text, cbName);
finally
if cbLog.Checked then
begin
try
if (cbLogAppend.Checked) and (FileExists(mbExpandFileName(fneRenameLogFileFilename.FileName))) then
begin
LogFileStream := TFileStream.Create(mbExpandFileName(fneRenameLogFileFilename.FileName), fmOpenWrite);
try
LogFileStream.Seek(0, soEnd);
FLog.SaveToStream(LogFileStream);
finally
LogFileStream.Free;
end;
end
else
begin
FLog.SaveToFile(mbExpandFileName(fneRenameLogFileFilename.FileName));
end;
except
on E: Exception do
msgError(E.Message);
end;
FLog.Free;
end;
OldFiles.Free;
NewFiles.Free;
TempFiles.Free;
end;
finally
FActuallyRenamingFile := False;
end;
StringGridTopLeftChanged(StringGrid);
end;
{ TfrmMultiRename.cm_Close }
procedure TfrmMultiRename.cm_Close(const {%H-}Params: array of string);
begin
Close;
end;
{ TfrmMultiRename.cm_ShowPresetsMenu }
procedure TfrmMultiRename.cm_ShowPresetsMenu(const {%H-}Params: array of string);
begin
PopupDynamicMenuAtThisControl(pmPresets, btnPresets);
end;
{ TfrmMultiRename.cm_DropDownPresetList }
procedure TfrmMultiRename.cm_DropDownPresetList(const {%H-}Params: array of string);
begin
if (not cbPresets.CanFocus) and (not cbPresets.Enabled) then
if isOkToLosePresetModification = True then
cbPresets.Enabled := True;
if cbPresets.CanFocus then
begin
cbPresets.SetFocus;
cbPresets.DroppedDown := True;
end;
end;
{ TfrmMultiRename.cm_LoadPreset }
procedure TfrmMultiRename.cm_LoadPreset(const Params: array of string);
var
sPresetName: string;
PresetIndex: integer;
begin
if isOkToLosePresetModification then
begin
//1.Get the preset name from the parameters.
sPresetName := GetPresetNameForCommand(Params);
//2.Make sure we got something.
if sPresetName <> '' then
begin
//3.Make sure it is in our list.
PresetIndex := FMultiRenamePresetList.Find(sPresetName);
if PresetIndex <> -1 then
begin
cbName.Text := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].FileName;
cbName.SelStart := UTF8Length(cbName.Text);
cbExt.Text := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Extension;
cbExt.SelStart := UTF8Length(cbExt.Text);
cbNameMaskStyle.ItemIndex := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].FileNameStyle;
cmbExtensionStyle.ItemIndex := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].ExtensionStyle;
edFind.Text := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Find;
edReplace.Text := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Replace;
cbRegExp.Checked := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].RegExp;
cbUseSubs.Checked := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].UseSubs;
cbCaseSens.Checked := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].CaseSens;
cbOnlyFirst.Checked := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].OnlyFirst;
edPoc.Text := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Counter;
edInterval.Text := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Interval;
cmbxWidth.ItemIndex := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Width;
case gMulRenSaveRenamingLog of
mrsrlPerPreset:
begin
cbLog.Checked := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Log;
cbLogAppend.Checked := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogAppend;
fneRenameLogFileFilename.FileName := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogFile;
end;
mrsrlAppendSameLog:
begin
FbRememberLog := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].Log;
FbRememberAppend := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogAppend;
FsRememberRenameLogFilename := FMultiRenamePresetList.MultiRenamePreset[PresetIndex].LogFile;
SetOutputGlobalRenameLogFilename;
end;
end;
//4.Preserved the last loaded setup.
FLastPreset := sPresetName;
//5.Refresh the whole thing.
edFindChange(edFind);
edReplaceChange(edReplace);
//6.We might come here with parameter "index=x" so make sure we switch also the preset combo box to the same index.
if PresetIndex >= cbPresets.Items.Count then
PresetIndex := 0;
if cbPresets.ItemIndex <> PresetIndex then
cbPresets.ItemIndex := PresetIndex;
//7.Since we've load the setup, activate things so we may change setup if necessary.
SetConfigurationState(CONFIG_SAVED);
//8. If we're from anything else the preset droplist itself, let's go to focus on the name ready to edit it if necessary..
if (ActiveControl <> cbPresets) and (ActiveControl <> cbName) and (cbName.Enabled and gbMaska.Enabled) then
begin
ActiveControl := cbName;
cbName.SelStart := UTF8Length(cbName.Text);
end;
end;
end;
end;
end;
{ TfrmMultiRename.cm_LoadLastPreset }
procedure TfrmMultiRename.cm_LoadLastPreset(const Params: array of string);
begin
cm_LoadPreset(['index=0']);
end;
{ TfrmMultiRename.cm_LoadPreset1 }
procedure TfrmMultiRename.cm_LoadPreset1(const Params: array of string);
begin
cm_LoadPreset(['index=1']);
end;
{ TfrmMultiRename.cm_LoadPreset2 }
procedure TfrmMultiRename.cm_LoadPreset2(const Params: array of string);
begin
cm_LoadPreset(['index=2']);
end;
{ TfrmMultiRename.cm_LoadPreset3 }
procedure TfrmMultiRename.cm_LoadPreset3(const Params: array of string);
begin
cm_LoadPreset(['index=3']);
end;
{ TfrmMultiRename.cm_LoadPreset4 }
procedure TfrmMultiRename.cm_LoadPreset4(const Params: array of string);
begin
cm_LoadPreset(['index=4']);
end;
{ TfrmMultiRename.cm_LoadPreset5 }
procedure TfrmMultiRename.cm_LoadPreset5(const Params: array of string);
begin
cm_LoadPreset(['index=5']);
end;
{ TfrmMultiRename.cm_LoadPreset6 }
procedure TfrmMultiRename.cm_LoadPreset6(const Params: array of string);
begin
cm_LoadPreset(['index=6']);
end;
{ TfrmMultiRename.cm_LoadPreset7 }
procedure TfrmMultiRename.cm_LoadPreset7(const Params: array of string);
begin
cm_LoadPreset(['index=7']);
end;
{ TfrmMultiRename.cm_LoadPreset8 }
procedure TfrmMultiRename.cm_LoadPreset8(const Params: array of string);
begin
cm_LoadPreset(['index=8']);
end;
{ TfrmMultiRename.cm_LoadPreset9 }
procedure TfrmMultiRename.cm_LoadPreset9(const Params: array of string);
begin
cm_LoadPreset(['index=9']);
end;
{ TfrmMultiRename.cm_SavePreset }
procedure TfrmMultiRename.cm_SavePreset(const Params: array of string);
begin
if cbPresets.ItemIndex > 0 then
begin
SavePreset(cbPresets.Items.Strings[cbPresets.ItemIndex]);
SetConfigurationState(CONFIG_SAVED);
end;
end;
{ TfrmMultiRename.cm_SavePresetAs }
procedure TfrmMultiRename.cm_SavePresetAs(const Params: array of string);
var
sNameForPreset: string;
bKeepGoing: boolean;
begin
sNameForPreset := GetPresetNameForCommand(Params);
if sNameForPreset <> '' then
begin
bKeepGoing := True;
end
else
begin
if (FLastPreset = '') or (FLastPreset = sLASTPRESET) then
sNameForPreset := rsMulRenDefaultPresetName
else
sNameForPreset := FLastPreset;
bKeepGoing := InputQuery(Caption, rsMulRenPromptForSavedPresetName, sNameForPreset);
if bKeepGoing then bKeepGoing := (sNameForPreset <> '');
end;
if bKeepGoing and (sNameForPreset <> FLastPreset) then
if FMultiRenamePresetList.Find(sNameForPreset) <> -1 then
if not msgYesNo(Format(rsMsgPresetAlreadyExists, [sNameForPreset]), msmbNo) then
bKeepGoing := False;
if bKeepGoing then
begin
SavePreset(sNameForPreset);
if cbPresets.Items.IndexOf(sNameForPreset) = -1 then
begin
cbPresets.Items.Add(sNameForPreset);
end;
if cbPresets.ItemIndex <> cbPresets.Items.IndexOf(sNameForPreset) then
cbPresets.ItemIndex := cbPresets.Items.IndexOf(sNameForPreset);
SetConfigurationState(CONFIG_SAVED);
RefreshActivePresetCommands;
end;
end;
{ TfrmMultiRename.cm_RenamePreset }
// It also allow the at the same time to rename for changing case like "audio files" to "Audio Files".
procedure TfrmMultiRename.cm_RenamePreset(const Params: array of string);
var
sCurrentName, sNewName: string;
PresetIndex: integer;
bKeepGoing: boolean;
begin
sCurrentName := cbPresets.Items.Strings[cbPresets.ItemIndex];
sNewName := sCurrentName;
bKeepGoing := InputQuery(Caption, rsMulRenPromptNewPresetName, sNewName);
if bKeepGoing and (sNewName <> '') and (sCurrentName <> sNewName) then
begin
PresetIndex := FMultiRenamePresetList.Find(sNewName);
if (PresetIndex = -1) or (SameText(sCurrentName, sNewName)) then
begin
if SameText(FMultiRenamePresetList.MultiRenamePreset[cbPresets.ItemIndex].PresetName, cbPresets.Items.Strings[cbPresets.ItemIndex]) then
begin
FMultiRenamePresetList.MultiRenamePreset[cbPresets.ItemIndex].PresetName := sNewName;
cbPresets.Items.Strings[cbPresets.ItemIndex] := sNewName;
end;
end
else
begin
if msgYesNo(rsMulRenPromptNewNameExists, msmbNo) then
begin
if SameText(FMultiRenamePresetList.MultiRenamePreset[PresetIndex].PresetName, cbPresets.Items.Strings[PresetIndex]) and SameText(FMultiRenamePresetList.MultiRenamePreset[cbPresets.ItemIndex].PresetName, cbPresets.Items.Strings[cbPresets.ItemIndex]) then
begin
FMultiRenamePresetList.MultiRenamePreset[cbPresets.ItemIndex].PresetName := sNewName;
cbPresets.Items.Strings[cbPresets.ItemIndex] := sNewName;
cbPresets.Items.Delete(PresetIndex);
FMultiRenamePresetList.Delete(PresetIndex);
end;
end;
end;
end;
end;
{ TfrmMultiRename.cm_DeletePreset }
procedure TfrmMultiRename.cm_DeletePreset(const Params: array of string);
var
Index: integer;
sPresetName: string;
begin
sPresetName := GetPresetNameForCommand(Params);
if sPresetName = '' then
if cbPresets.ItemIndex > 0 then
sPresetName := cbPresets.Items.Strings[cbPresets.ItemIndex];
if sPresetName <> '' then
begin
if msgYesNo(Format(rsMsgPresetConfigDelete, [sPresetName]), msmbNo) then
begin
DeletePreset(sPresetName);
Index := cbPresets.Items.IndexOf(sPresetName);
if Index = cbPresets.ItemIndex then
cbPresets.ItemIndex := 0;
if Index <> -1 then
cbPresets.Items.Delete(Index);
FillPresetsList;
end;
end;
end;
{ TfrmMultiRename.cm_SortPresets }
procedure TfrmMultiRename.cm_SortPresets(const Params: array of string);
var
slLocalPresets: TStringList;
iSeeker, iPresetIndex: integer;
begin
if isOkToLosePresetModification then
begin
if FMultiRenamePresetList.Count > 1 then
begin
slLocalPresets := TStringList.Create;
try
for iSeeker := 1 to pred(FMultiRenamePresetList.Count) do
slLocalPresets.Add(FMultiRenamePresetList.MultiRenamePreset[iSeeker].PresetName);
if HaveUserSortThisList(Self, rsMulRenSortingPresets, slLocalPresets) = mrOk then
begin
for iSeeker := 0 to pred(slLocalPresets.Count) do
begin
iPresetIndex := FMultiRenamePresetList.Find(slLocalPresets.Strings[iSeeker]);
if succ(iSeeker) <> iPresetIndex then
FMultiRenamePresetList.Move(iPresetIndex, succ(iSeeker));
end;
FillPresetsList(cbPresets.Items.Strings[cbPresets.ItemIndex]);
end;
finally
slLocalPresets.Free;
end;
end;
end;
end;
{ TfrmMultiRename.cm_AnyNameMask }
procedure TfrmMultiRename.cm_AnyNameMask(const {%H-}Params: array of string);
begin
pmFloatingMainMaskMenu.Items.Clear;
PopulateFilenameMenu(pmFloatingMainMaskMenu);
PopupDynamicMenuAtThisControl(pmFloatingMainMaskMenu, btnAnyNameMask);
end;
{ TfrmMultiRename.cm_NameNameMask }
procedure TfrmMultiRename.cm_NameNameMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmFilename, rmtuFilename);
end;
{ TfrmMultiRename.cm_ExtNameMask }
procedure TfrmMultiRename.cm_ExtNameMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmFilename, rmtuExtension);
end;
{ TfrmMultiRename.cm_CtrNameMask }
procedure TfrmMultiRename.cm_CtrNameMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmFilename, rmtuCounter);
end;
{ TfrmMultiRename.cm_DateNameMask }
procedure TfrmMultiRename.cm_DateNameMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmFilename, rmtuDate);
end;
{ TfrmMultiRename.cm_TimeNameMask }
procedure TfrmMultiRename.cm_TimeNameMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmFilename, rmtuTime);
end;
{ TfrmMultiRename.cm_PlgnNameMask }
procedure TfrmMultiRename.cm_PlgnNameMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmFilename, rmtuPlugins);
end;
{ TfrmMultiRename.cm_ClearNameMask }
procedure TfrmMultiRename.cm_ClearNameMask(const {%H-}Params: array of string);
begin
cbName.Text := '';
cbNameStyleChange(cbExt);
if cbName.CanFocus then
cbName.SetFocus;
end;
{ TfrmMultiRename.cm_AnyExtMask }
procedure TfrmMultiRename.cm_AnyExtMask(const {%H-}Params: array of string);
begin
pmFloatingMainMaskMenu.Items.Clear;
PopulateExtensionMenu(pmFloatingMainMaskMenu);
PopupDynamicMenuAtThisControl(pmFloatingMainMaskMenu, btnAnyExtMask);
end;
{ TfrmMultiRename.cm_NameExtMask }
procedure TfrmMultiRename.cm_NameExtMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmExtension, rmtuFilename);
end;
{ TfrmMultiRename.cm_ExtExtMask }
procedure TfrmMultiRename.cm_ExtExtMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmExtension, rmtuExtension);
end;
{ TfrmMultiRename.cm_CtrExtMask }
procedure TfrmMultiRename.cm_CtrExtMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmExtension, rmtuCounter);
end;
{ TfrmMultiRename.cm_DateExtMask }
procedure TfrmMultiRename.cm_DateExtMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmExtension, rmtuDate);
end;
{ TfrmMultiRename.cm_TimeExtMask }
procedure TfrmMultiRename.cm_TimeExtMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmExtension, rmtuTime);
end;
{ TfrmMultiRename.cm_PlgnExtMask }
procedure TfrmMultiRename.cm_PlgnExtMask(const {%H-}Params: array of string);
begin
BuildMenuAndPopup(tfmExtension, rmtuPlugins);
end;
{ TfrmMultiRename.cm_ClearExtMask }
procedure TfrmMultiRename.cm_ClearExtMask(const {%H-}Params: array of string);
begin
cbExt.Text := '';
cbNameStyleChange(cbExt);
if cbExt.CanFocus then cbExt.SetFocus;
end;
{ TfrmMultiRename.cm_ViewRenameLogFile }
procedure TfrmMultiRename.cm_ViewRenameLogFile(const {%H-}Params: array of string);
var
sRenameLogFilename: string;
begin
sRenameLogFilename := mbExpandFileName(fneRenameLogFileFilename.FileName);
if FileExists(sRenameLogFilename) then
ShowViewerByGlob(sRenameLogFilename)
else
MsgError(Format(rsMsgFileNotFound, [sRenameLogFilename]));
end;
{ ShowMultiRenameForm }
// Will be in fact the lone function called externally to launch a MultiRename dialog.
function ShowMultiRenameForm(aFileSource: IFileSource; var aFiles: TFiles; const PresetToLoad: string = ''): boolean;
begin
Result := True;
try
with TfrmMultiRename.Create(Application, aFileSource, aFiles, PresetToLoad) do
begin
Show;
end;
except
Result := False;
end;
end;
initialization
TFormCommands.RegisterCommandsForm(TfrmMultiRename, HotkeysCategoryMultiRename, @rsHotkeyCategoryMultiRename);
end.
|
unit Ils.MySql.EnumPublisher;
interface
uses
TypInfo, SysUtils, SysConst,
Ils.MySQL.Conf, ZDataset, ZConnection;
type
TEnumTextInfo = record
ClassID: Integer;
Name: string;
Comment: string;
Measure: string;
Default: string;
Name2: string;
end;
TEnumPublishField = (efClassID, efComment, efMeasure, efDefault, efName2);
TEnumPublishFieldSet = set of TEnumPublishField;
const
CEnumPublishFieldSetDef = [efComment, efMeasure, efDefault];
// *** пример: ***
//const
// CTestEnumInfo: array[TTestEnum] of TEnumTextInfo = (
// (Name: '1'; Comment: '11'),
// (Name: '2'; Comment: '22'),
// (Name: '3'; Comment: '33')
// );
type
TEnumPublishMySql = class
protected
class var FConnection: TZconnection;
class var FQuery: TZQuery;
class procedure DoIter(AIdx: Integer; AInfo: TEnumTextInfo; AFieldSet: TEnumPublishFieldSet);
class procedure EnumAll(ATypeInfo: PTypeInfo; AInfoArray: array of TEnumTextInfo; AFieldSet: TEnumPublishFieldSet); static;
public
class procedure Publish(ATypeInfo: Pointer; AInfoArray: array of TEnumTextInfo; ATableName: string; AConf: TMySQlDatabaseConfig; AFieldSet: TEnumPublishFieldSet = CEnumPublishFieldSetDef); static;
end;
implementation
{ TEnumPublishMySql }
class procedure TEnumPublishMySql.DoIter(AIdx: Integer; AInfo: TEnumTextInfo; AFieldSet: TEnumPublishFieldSet);
begin
FQuery.ParamByName('ID').AsInteger := AIdx;
FQuery.ParamByName('Name').AsString := AInfo.Name;
if efClassID in AFieldSet then
FQuery.ParamByName('ClassID').AsInteger := AInfo.ClassID;
if efComment in AFieldSet then
FQuery.ParamByName('Comment').AsString := AInfo.Comment;
if efMeasure in AFieldSet then
FQuery.ParamByName('Measure').AsString := AInfo.Measure;
if efDefault in AFieldSet then
FQuery.ParamByName('DefValue').AsString := AInfo.Default;
if efName2 in AFieldSet then
FQuery.ParamByName('Name2').AsString := AInfo.Name2;
FQuery.ExecSQL;
end;
class procedure TEnumPublishMySql.EnumAll(ATypeInfo: PTypeInfo; AInfoArray: array of TEnumTextInfo; AFieldSet: TEnumPublishFieldSet);
var
typeData: PTypeData;
iterValue: Integer;
begin
if ATypeInfo^.Kind <> tkEnumeration then
raise EInvalidCast.CreateRes(@SInvalidCast);
typeData := GetTypeData(ATypeInfo);
for iterValue := typeData.MinValue to typeData.MaxValue do
DoIter(iterValue, AInfoArray[iterValue], AFieldSet);
end;
class procedure TEnumPublishMySql.Publish(
ATypeInfo: Pointer;
AInfoArray: array of TEnumTextInfo; ATableName: string;
AConf: TMySQlDatabaseConfig;
AFieldSet: TEnumPublishFieldSet = CEnumPublishFieldSetDef);
var
f: TEnumPublishField;
s: string;
begin
FConnection := TZConnection.Create(nil);
FConnection.Protocol := 'mysql-5';
FConnection.HostName := AConf.Host;
FConnection.Port := AConf.Port;
FConnection.Catalog := AConf.Database;
FConnection.User := AConf.Login;
FConnection.Password := AConf.Password;
FConnection.Database := AConf.Database;
FConnection.Properties.Text := CMySQLUtf8PropertiesText;
// FConnection.ClientCodepage := 'utf-8';
FQuery := TZQuery.Create(nil);
FQuery.Connection := FConnection;
s := '';
for f in AFieldSet do
case f of
efClassID: s := s + ', ' + 'ClassID = :ClassID';
efComment: s := s + ', ' + 'Comment = :Comment';
efMeasure: s := s + ', ' + 'Measure = :Measure';
efDefault: s := s + ', ' + 'DefaultValue = :DefValue';
efName2: s := s + ', ' + 'Name2 = :Name2';
end;
FQuery.SQL.Text :=
'INSERT IGNORE INTO ' + ATableName +
' SET ID = :ID, Name = :Name ' +
s +
' ON DUPLICATE KEY UPDATE' +
' ID = :ID, Name = :Name ' +
s;
try
EnumAll(ATypeInfo, AInfoArray, AFieldSet);
finally
FQuery.Free;
FConnection.Free;
end;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [PRODUTO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit ProdutoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
UnidadeProdutoVO, ProdutoSubGrupoVO, AlmoxarifadoVO, TributGrupoTributarioVO,
ProdutoMarcaVO, TributIcmsCustomCabVO, ProdutoGrupoVO, FichaTecnicaVO;
type
TProdutoVO = class(TVO)
private
FID: Integer;
FID_TRIBUT_ICMS_CUSTOM_CAB: Integer;
FID_UNIDADE_PRODUTO: Integer;
FID_ALMOXARIFADO: Integer;
FID_GRUPO_TRIBUTARIO: Integer;
FID_MARCA_PRODUTO: Integer;
FID_SUBGRUPO: Integer;
FGTIN: String;
FCODIGO_INTERNO: String;
FNCM: String;
FNOME: String;
FDESCRICAO: String;
FDESCRICAO_PDV: String;
FVALOR_COMPRA: Extended;
FVALOR_VENDA: Extended;
FPRECO_VENDA_MINIMO: Extended;
FPRECO_SUGERIDO: Extended;
FCUSTO_UNITARIO: Extended;
FCUSTO_PRODUCAO: Extended;
FCUSTO_MEDIO_LIQUIDO: Extended;
FPRECO_LUCRO_ZERO: Extended;
FPRECO_LUCRO_MINIMO: Extended;
FPRECO_LUCRO_MAXIMO: Extended;
FMARKUP: Extended;
FQUANTIDADE_ESTOQUE: Extended;
FQUANTIDADE_ESTOQUE_ANTERIOR: Extended;
FESTOQUE_MINIMO: Extended;
FESTOQUE_MAXIMO: Extended;
FESTOQUE_IDEAL: Extended;
FEXCLUIDO: String;
FINATIVO: String;
FDATA_CADASTRO: TDateTime;
FFOTO_PRODUTO: String;
FEX_TIPI: String;
FCODIGO_LST: String;
FCLASSE_ABC: String;
FIAT: String;
FIPPT: String;
FTIPO_ITEM_SPED: String;
FPESO: Extended;
FPORCENTO_COMISSAO: Extended;
FPONTO_PEDIDO: Extended;
FLOTE_ECONOMICO_COMPRA: Extended;
FALIQUOTA_ICMS_PAF: Extended;
FALIQUOTA_ISSQN_PAF: Extended;
FTOTALIZADOR_PARCIAL: String;
FCODIGO_BALANCA: Integer;
FDATA_ALTERACAO: TDateTime;
FTIPO: String;
FSERVICO: String;
FUnidadeProdutoSigla: String;
FAlmoxarifadoNome: String;
FTributIcmsCustomCabDescricao: String;
FTributGrupoTributarioDescricao: String;
FProdutoMarcaNome: String;
FProdutoGrupoNome: String;
FProdutoSubGrupoNome: String;
FImagem: String;
FTipoImagem: String;
FUnidadeProdutoVO: TUnidadeProdutoVO;
FAlmoxarifadoVO: TAlmoxarifadoVO;
FTributIcmsCustomCabVO: TTributIcmsCustomCabVO;
FGrupoTributarioVO: TTributGrupoTributarioVO;
FProdutoMarcaVO: TProdutoMarcaVO;
FProdutoSubGrupoVO: TProdutoSubGrupoVO;
FListaFichaTecnicaVO: TListaFichaTecnicaVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property Gtin: String read FGTIN write FGTIN;
property Nome: String read FNOME write FNOME;
property IdUnidadeProduto: Integer read FID_UNIDADE_PRODUTO write FID_UNIDADE_PRODUTO;
property UnidadeProdutoSigla: String read FUnidadeProdutoSigla write FUnidadeProdutoSigla;
property IdAlmoxarifado: Integer read FID_ALMOXARIFADO write FID_ALMOXARIFADO;
property AlmoxarifadoNome: String read FAlmoxarifadoNome write FAlmoxarifadoNome;
property IdTributIcmsCustomCab: Integer read FID_TRIBUT_ICMS_CUSTOM_CAB write FID_TRIBUT_ICMS_CUSTOM_CAB;
property TributIcmsCustomCabDescricao: String read FTributIcmsCustomCabDescricao write FTributIcmsCustomCabDescricao;
property IdGrupoTributario: Integer read FID_GRUPO_TRIBUTARIO write FID_GRUPO_TRIBUTARIO;
property TributGrupoTributarioDescricao: String read FTributGrupoTributarioDescricao write FTributGrupoTributarioDescricao;
property IdMarcaProduto: Integer read FID_MARCA_PRODUTO write FID_MARCA_PRODUTO;
property ProdutoMarcaNome: String read FProdutoMarcaNome write FProdutoMarcaNome;
property IdSubGrupo: Integer read FID_SUBGRUPO write FID_SUBGRUPO;
property ProdutoGrupoNome: String read FProdutoGrupoNome write FProdutoGrupoNome;
property ProdutoSubGrupoNome: String read FProdutoSubGrupoNome write FProdutoSubGrupoNome;
property CodigoInterno: String read FCODIGO_INTERNO write FCODIGO_INTERNO;
property Ncm: String read FNCM write FNCM;
property Descricao: String read FDESCRICAO write FDESCRICAO;
property DescricaoPdv: String read FDESCRICAO_PDV write FDESCRICAO_PDV;
property ValorCompra: Extended read FVALOR_COMPRA write FVALOR_COMPRA;
property ValorVenda: Extended read FVALOR_VENDA write FVALOR_VENDA;
property PrecoVendaMinimo: Extended read FPRECO_VENDA_MINIMO write FPRECO_VENDA_MINIMO;
property PrecoSugerido: Extended read FPRECO_SUGERIDO write FPRECO_SUGERIDO;
property CustoUnitario: Extended read FCUSTO_UNITARIO write FCUSTO_UNITARIO;
property CustoProducao: Extended read FCUSTO_PRODUCAO write FCUSTO_PRODUCAO;
property CustoMedioLiquido: Extended read FCUSTO_MEDIO_LIQUIDO write FCUSTO_MEDIO_LIQUIDO;
property PrecoLucroZero: Extended read FPRECO_LUCRO_ZERO write FPRECO_LUCRO_ZERO;
property PrecoLucroMinimo: Extended read FPRECO_LUCRO_MINIMO write FPRECO_LUCRO_MINIMO;
property PrecoLucroMaximo: Extended read FPRECO_LUCRO_MAXIMO write FPRECO_LUCRO_MAXIMO;
property Markup: Extended read FMARKUP write FMARKUP;
property QuantidadeEstoque: Extended read FQUANTIDADE_ESTOQUE write FQUANTIDADE_ESTOQUE;
property QuantidadeEstoqueAnterior: Extended read FQUANTIDADE_ESTOQUE_ANTERIOR write FQUANTIDADE_ESTOQUE_ANTERIOR;
property EstoqueMinimo: Extended read FESTOQUE_MINIMO write FESTOQUE_MINIMO;
property EstoqueMaximo: Extended read FESTOQUE_MAXIMO write FESTOQUE_MAXIMO;
property EstoqueIdeal: Extended read FESTOQUE_IDEAL write FESTOQUE_IDEAL;
property Excluido: String read FEXCLUIDO write FEXCLUIDO;
property Inativo: String read FINATIVO write FINATIVO;
property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO;
property FotoProduto: String read FFOTO_PRODUTO write FFOTO_PRODUTO;
property ExTipi: String read FEX_TIPI write FEX_TIPI;
property CodigoLst: String read FCODIGO_LST write FCODIGO_LST;
property ClasseAbc: String read FCLASSE_ABC write FCLASSE_ABC;
property Iat: String read FIAT write FIAT;
property Ippt: String read FIPPT write FIPPT;
property TipoItemSped: String read FTIPO_ITEM_SPED write FTIPO_ITEM_SPED;
property Peso: Extended read FPESO write FPESO;
property PorcentoComissao: Extended read FPORCENTO_COMISSAO write FPORCENTO_COMISSAO;
property PontoPedido: Extended read FPONTO_PEDIDO write FPONTO_PEDIDO;
property LoteEconomicoCompra: Extended read FLOTE_ECONOMICO_COMPRA write FLOTE_ECONOMICO_COMPRA;
property AliquotaIcmsPaf: Extended read FALIQUOTA_ICMS_PAF write FALIQUOTA_ICMS_PAF;
property AliquotaIssqnPaf: Extended read FALIQUOTA_ISSQN_PAF write FALIQUOTA_ISSQN_PAF;
property TotalizadorParcial: String read FTOTALIZADOR_PARCIAL write FTOTALIZADOR_PARCIAL;
property CodigoBalanca: Integer read FCODIGO_BALANCA write FCODIGO_BALANCA;
property DataAlteracao: TDateTime read FDATA_ALTERACAO write FDATA_ALTERACAO;
property Tipo: String read FTIPO write FTIPO;
property Servico: String read FSERVICO write FSERVICO;
property Imagem: String read FImagem write FImagem;
property TipoImagem: String read FTipoImagem write FTipoImagem;
property ProdutoSubGrupoVO: TProdutoSubGrupoVO read FProdutoSubGrupoVO write FProdutoSubGrupoVO;
property UnidadeProdutoVO: TUnidadeProdutoVO read FUnidadeProdutoVO write FUnidadeProdutoVO;
property AlmoxarifadoVO: TAlmoxarifadoVO read FAlmoxarifadoVO write FAlmoxarifadoVO;
property TributIcmsCustomCabVO: TTributIcmsCustomCabVO read FTributIcmsCustomCabVO write FTributIcmsCustomCabVO;
property GrupoTributarioVO: TTributGrupoTributarioVO read FGrupoTributarioVO write FGrupoTributarioVO;
property ProdutoMarcaVO: TProdutoMarcaVO read FProdutoMarcaVO write FProdutoMarcaVO;
property ListaFichaTecnicaVO: TListaFichaTecnicaVO read FListaFichaTecnicaVO write FListaFichaTecnicaVO;
end;
TListaProdutoVO = specialize TFPGObjectList<TProdutoVO>;
implementation
constructor TProdutoVO.Create;
begin
inherited;
FUnidadeProdutoVO := TUnidadeProdutoVO.Create;
FAlmoxarifadoVO := TAlmoxarifadoVO.Create;
FTributIcmsCustomCabVO := TTributIcmsCustomCabVO.Create;
FGrupoTributarioVO := TTributGrupoTributarioVO.Create;
FProdutoMarcaVO := TProdutoMarcaVO.Create;
FProdutoSubGrupoVO := TProdutoSubGrupoVO.Create;
ListaFichaTecnicaVO := TListaFichaTecnicaVO.Create;
end;
destructor TProdutoVO.Destroy;
begin
FreeAndNil(FUnidadeProdutoVO);
FreeAndNil(FAlmoxarifadoVO);
FreeAndNil(FTributIcmsCustomCabVO);
FreeAndNil(FGrupoTributarioVO);
FreeAndNil(FProdutoMarcaVO);
FreeAndNil(FProdutoSubGrupoVO);
FreeAndNil(FListaFichaTecnicaVO);
inherited;
end;
initialization
Classes.RegisterClass(TProdutoVO);
finalization
Classes.UnRegisterClass(TProdutoVO);
end.
|
unit Demo.Form.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.CategoryButtons,
Vcl.ExtCtrls, System.Actions, Vcl.ActnList, System.ImageList, Vcl.ImgList,
System.Rtti, System.JSON,
Neon.Core.Types,
Neon.Core.Persistence,
Neon.Core.Persistence.JSON,
Neon.Core.Persistence.JSON.Schema,
OpenAPI.Model.Classes,
OpenAPI.Model.Schema,
OpenAPI.Neon.Serializers;
type
TPerson = class
private
FAge: Integer;
FName: string;
public
property Age: Integer read FAge write FAge;
property Name: string read FName write FName;
end;
TfrmMain = class(TForm)
memoDocument: TMemo;
catMenu: TCategoryPanelGroup;
panGeneral: TCategoryPanel;
CategoryButtons1: TCategoryButtons;
CategoryPanel1: TCategoryPanel;
CategoryButtons2: TCategoryButtons;
catJSON: TCategoryButtons;
aclCommands: TActionList;
imgCommands: TImageList;
actAddInfo: TAction;
actAddServers: TAction;
actAddPaths: TAction;
actAddSecurity: TAction;
actCompAddSchemas: TAction;
actCompAddResponses: TAction;
actCompAddSecurityDefs: TAction;
actJSONGenerate: TAction;
actJSONReplace: TAction;
actCompAddParameters: TAction;
actCompAddRequestBodies: TAction;
actAddInfoExtensions: TAction;
procedure FormDestroy(Sender: TObject);
procedure actAddInfoExecute(Sender: TObject);
procedure actAddInfoExtensionsExecute(Sender: TObject);
procedure actAddServersExecute(Sender: TObject);
procedure actAddPathsExecute(Sender: TObject);
procedure actCompAddResponsesExecute(Sender: TObject);
procedure actCompAddSchemasExecute(Sender: TObject);
procedure actCompAddSecurityDefsExecute(Sender: TObject);
procedure actAddSecurityExecute(Sender: TObject);
procedure actCompAddParametersExecute(Sender: TObject);
procedure actJSONGenerateExecute(Sender: TObject);
procedure actJSONReplaceExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FDocument: TOpenAPIDocument;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
FDocument.Free;
end;
procedure TfrmMain.actAddInfoExecute(Sender: TObject);
begin
FDocument.Info.Title := 'OpenAPI Demo';
FDocument.Info.Version := '1.0.2';
FDocument.Info.Description := 'OpenAPI Demo Description';
FDocument.Info.Contact.Name := 'Paolo Rossi';
FDocument.Info.Contact.URL := 'https://github.com/paolo-rossi';
FDocument.Info.License.Name := 'Apache-2.0';
FDocument.Info.License.URL := 'http://www.apache.org/licenses/';
end;
procedure TfrmMain.actAddInfoExtensionsExecute(Sender: TObject);
var
LJSON: TJSONObject;
begin
LJSON := TJSONObject.Create;
LJSON.AddPair('url', '/images/wirl.png');
LJSON.AddPair('backgroundColor', '#000000');
LJSON.AddPair('altText', 'WiRL Logo');
FDocument.Info.Extensions.AddPair('x-logo', LJSON);
// Testing the Dictionary serialization for Extensions
//FDocument.Info.Ext.Add('test', 'prova');
//FDocument.Info.Ext.Add('xyz', TStringList.Create.Add('Prova Item 1'));
end;
procedure TfrmMain.actAddServersExecute(Sender: TObject);
begin
FDocument.Servers.Add(TOpenAPIServer.Create('https://api.wirl.com/rest/app/', 'Production Server'));
FDocument.Servers.Add(TOpenAPIServer.Create('https://beta.wirl.com/rest/app/', 'Beta Server API v2'));
FDocument.Servers.Add(TOpenAPIServer.Create('https://test.wirl.com/rest/app/', 'Testing Server'));
end;
procedure TfrmMain.actAddPathsExecute(Sender: TObject);
var
LPath: TOpenAPIPathItem;
LOperation: TOpenAPIOperation;
LParameter: TOpenAPIParameter;
begin
LPath := FDocument.AddPath('/customers');
LPath.Description := 'Customers resource';
LOperation := LPath.AddOperation(TOperationType.Get);
LOperation.Summary := 'Get all customers';
LOperation.OperationId := 'CustomerList';
LParameter := LOperation.AddParameter('id', 'query');
LParameter.Description := 'Customer ID';
LParameter.Schema.Type_ := 'string';
LParameter.Schema.Enum.ValueFrom<TArray<string>>(['enum1', 'enum2']);
LParameter := LOperation.AddParameter('country', 'query');
LParameter.Description := 'Country Code';
LParameter.Schema.Type_ := 'string';
LParameter.Schema.Enum.ValueFrom<TArray<string>>(['it', 'en', 'de', 'ch', 'fr']);
LParameter := LOperation.AddParameter('date', 'query');
LParameter.Description := 'Date';
LParameter.Schema.Type_ := 'string';
LParameter.Schema.Format := 'date-time';
LParameter.Schema.Enum.ValueFrom<TArray<string>>(['it', 'en', 'de', 'ch', 'fr']);
// Uses a JSON schema already existing as a TJSONObject
LParameter := LOperation.AddParameter('person', 'query');
LParameter.Description := 'Person Entity';
LParameter.Schema.SetJSONObject(TNeonSchemaGenerator.ClassToJSONSchema(TPerson));
// Uses #ref
LParameter := LOperation.AddParameter('order', 'query');
LParameter.Description := 'Order Entity';
LParameter.Schema.Reference.Ref := '#comp/deidjed/';
end;
procedure TfrmMain.actCompAddResponsesExecute(Sender: TObject);
var
LResponse: TOpenAPIResponse;
LMediaType: TOpenAPIMediaType;
begin
LResponse := FDocument.Components.AddResponse('200', 'Successful Response');
LMediaType := LResponse.AddMediaType('application/json');
LMediaType.Schema.Reference.Ref := '#components/schemas/country';
end;
procedure TfrmMain.actCompAddSchemasExecute(Sender: TObject);
var
LSchema: TOpenAPISchema;
LProperty: TOpenAPISchema;
begin
LSchema := FDocument.Components.AddSchema('Person');
LSchema.Type_ := 'object';
LProperty := LSchema.AddProperty('id');
LProperty.Title := 'ID Value';
LProperty.Description := 'AutoInc **ID** value';
LProperty.Type_ := 'integer';
LProperty.Format := 'int64';
LProperty := LSchema.AddProperty('firstname');
LProperty.Type_ := 'string';
LProperty := LSchema.AddProperty('lastname');
LProperty.Type_ := 'string';
LProperty := LSchema.AddProperty('birthdate');
LProperty.Title := 'Birth Date';
LProperty.Description := 'Birth Date';
LProperty.Type_ := 'string';
LProperty.Format := 'date-time';
end;
procedure TfrmMain.actCompAddSecurityDefsExecute(Sender: TObject);
begin
FDocument.Components.AddSecurityApiKey('key_auth', 'Key Standard Authentication', 'X-ApiKey', tapikeylocation.Header);
FDocument.Components.AddSecurityHttp('basic_auth', 'Basic Authentication', 'Basic', '');
FDocument.Components.AddSecurityHttp('jwt_auth', 'JWT (Bearer) Authentication', 'Bearer', 'JWT');
end;
procedure TfrmMain.actAddSecurityExecute(Sender: TObject);
begin
FDocument.AddSecurity('basic_auth', []);
FDocument.AddSecurity('jwt_auth', []);
end;
procedure TfrmMain.actCompAddParametersExecute(Sender: TObject);
var
LParameter: TOpenAPIParameter;
begin
LParameter := FDocument.Components.AddParameter('idParam', 'id', 'query');
LParameter.Description := 'Customer ID';
LParameter.Schema.Type_ := 'string';
LParameter.Schema.Enum.ValueFrom<TArray<string>>(['enum1', 'enum2']);
LParameter.Schema.MaxLength := 123;
end;
procedure TfrmMain.actJSONGenerateExecute(Sender: TObject);
begin
memoDocument.Lines.Text :=
TNeon.ObjectToJSONString(FDocument, TOpenAPISerializer.GetNeonConfig);
end;
procedure TfrmMain.actJSONReplaceExecute(Sender: TObject);
begin
memoDocument.Lines.Text :=
StringReplace(memoDocument.Lines.Text, '\/', '/', [rfReplaceAll]);
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
FDocument := TOpenAPIDocument.Create(TOpenAPIVersion.v303);
end;
end.
|
unit Tests.Api;
interface
uses
DUnitX.TestFramework, System.JSON, RESTRequest4D.Request, System.Classes,
Controllers.Api, Horse;
type
[TestFixture]
TApiTest = class(TObject)
private
procedure StartApi;
public
[Test]
procedure TestGet;
[Test]
[TestCase('Test01', 'Teste de requisição POST')]
procedure TestPost(const AValue: string);
[Test]
[TestCase('Test01', 'Teste de requisição PUT')]
procedure TestPut(const AValue: string);
[Test]
[TestCase('Test01', '1')]
procedure TestDelete(const AValue: string);
end;
implementation
{ TApiTest }
procedure TApiTest.StartApi;
begin
if (not THorse.IsRunning) then
begin
TThread.CreateAnonymousThread(
procedure
begin
IsConsole := False;
Controllers.Api.Registry;
THorse.Listen;
THorse.StopListen;
IsConsole := True;
THorse.Listen(9000);
end).Start;
end;
end;
procedure TApiTest.TestGet;
var
LResponse: IResponse;
LContent: TJSONArray;
begin
StartApi;
LResponse := TRequest.New.BaseURL('http://localhost:9000/Api/Test')
.Accept('application/json')
.Get;
LContent := TJSONObject.ParseJSONValue(LResponse.Content) as TJSONArray;
Assert.AreEqual(9000, THorse.Port);
Assert.AreEqual('0.0.0.0', THorse.Host);
Assert.AreEqual(0, THorse.MaxConnections);
Assert.AreEqual(LResponse.StatusCode, 200);
Assert.AreEqual(LContent.Count, 3);
end;
procedure TApiTest.TestPost(const AValue: string);
var
LResponse: IResponse;
LContent: TJSONObject;
begin
StartApi;
LResponse := TRequest.New.BaseURL('http://localhost:9000/Api/Test')
.Accept('application/json')
.AddBody('{"value": "' + AValue + '"}')
.Post;
LContent := TJSONObject.ParseJSONValue(LResponse.Content) as TJSONObject;
Assert.AreEqual(LResponse.StatusCode, 201);
if (not LContent.GetValue('value').Null) then
Assert.AreEqual(AValue, LContent.GetValue('value').Value)
else
Assert.Fail('O retorno não está no formato correto.');
end;
procedure TApiTest.TestPut(const AValue: string);
var
LResponse: IResponse;
LContent: TJSONObject;
begin
StartApi;
LResponse := TRequest.New.BaseURL('http://localhost:9000/Api/Test')
.Accept('application/json')
.AddBody('{"value": "' + AValue + '"}')
.Put;
LContent := TJSONObject.ParseJSONValue(LResponse.Content) as TJSONObject;
Assert.AreEqual(LResponse.StatusCode, 200);
if (not LContent.GetValue('value').Null) then
Assert.AreEqual(AValue, LContent.GetValue('value').Value)
else
Assert.Fail('O retorno não está no formato correto.');
end;
procedure TApiTest.TestDelete(const AValue: string);
var
LResponse: IResponse;
LContent: TJSONObject;
begin
StartApi;
LResponse := TRequest.New.BaseURL('http://localhost:9000/Api/Test/' + AValue)
.Accept('application/json')
.Delete;
LContent := TJSONObject.ParseJSONValue(LResponse.Content) as TJSONObject;
Assert.AreEqual(LResponse.StatusCode, 200);
if (not LContent.GetValue('value').Null) then
Assert.AreEqual(AValue, LContent.GetValue('value').Value)
else
Assert.Fail('O retorno não está no formato correto.');
end;
initialization
TDUnitX.RegisterTestFixture(TApiTest);
end.
|
(* Copyright 2018 B. Zoltán Gorza
*
* This file is part of Math is Fun!, released under the Modified BSD License.
*)
{ Expression class, and its supporting types and functions. }
unit ExpressionClass;
{$mode objfpc}
{$H+}
interface
uses
OperationClass;
type
{ Operation category that is not marked or used in the TOperation class. }
TOperationCategory = (arithmetic, text, tricky);
{ Set of statuses of possible results. }
TResult = (correct, incorrect, unknown);
{ The mighty class that contains every needed data about an expression. }
TExpression = class
private
_a, _b: Integer;
_o: TOperation;
_r: Double;
_uR: Double;
_iC: TResult;
_oC: TOperationCategory;
_idx: Integer;
_text: String;
_outText: String;
procedure validateExpression;
function niceResult: String;
function niceUserResult: String;
public
{ First constant }
property a: Integer read _a;
{ Second constant }
property b: Integer read _b;
{ Operation }
property o: TOperation read _o;
{ Operation category }
property cat: TOperationCategory read _oC;
{ Index (used for outputs about statistics) }
property idx: Integer read _idx;
{ Text for non-arithmetic expressions, this is the text that is shown
instead of a regulas "a R b = x" formula.
@seealso(TOperationCategory)}
property text: String read _text;
{ This is the result of non-arithmetic expressions.
@seealso(TOperationCategory) }
property outText: String read _outText;
{ Formatted result }
property result: String read niceResult;
{ Formatted user's result }
property userResult: String read niceUserResult;
{ The result status. }
property isCorrect: TResult read _iC;
{ Constructor of the class.
@param(ao First constant)
@param(bo Second constant)
@param(oo Operation)
@param(io Index)
@param(oc Operation category)
@param(t Text)
@param(ot Out text or Result text) }
constructor create(const ao: Integer;
const bo: Integer;
const oo: TOperation;
const io: Integer;
const oc: TOperationCategory;
const t: String = '';
const oT: String = '');
{ User input processer procedure. }
procedure getUserInput(uI: Double);
end;
{ Returns a string representation of a @link(TResult result).
@param(r The result to be a string.}
function resultToString(const r: TResult): String;
{ Returns the according Boolean value of a @link(TResult result).
@param(r The result to be a boolean.)
@return(@true if correct, @false otherwise.) }
function resultToBoolean(const r: TResult): Boolean;
{ Return a string representation of an @link(TOperationCategory operation
category).
@param(c The category) }
function categoryToString(const c: TOperationCategory): String;
implementation // --------------------------------------------------------------
uses
Math,
SysUtils;
procedure prepareForDiv(var a: Integer; var b: Integer);
var
tmp: Integer;
begin
if a < b then
begin
tmp := a;
a := b;
b := tmp;
end;
b := b div 2;
if b = 0 then
b := 1;
end;
procedure TExpression.validateExpression;
begin
case _o.op of
dvi, ind, mdu: prepareForDiv(_a, _b);
mul: _b := _b div 7;
//exo: _b := _b mod 5;
end;
end;
constructor TExpression.create(const ao: Integer;
const bo: Integer;
const oo: TOperation;
const io: Integer;
const oc: TOperationCategory;
const t: String = '';
const oT: String = '');
begin
_a := ao;
_b := bo;
_o := oo;
_oC := oc;
_idx := io;
validateExpression;
if _oC <> tricky then
_r := _o.func(_a, _b)
else
_r := 0.0;
_iC := unknown;
_text := t;
_outText := oT;
end;
function TExpression.niceResult: String;
begin
niceResult := formatFloat('0.##', _r);
end;
function TExpression.niceUserResult: String;
begin
niceUserResult := formatFloat('0.##', _uR);
end;
procedure TExpression.getUserInput(uI: Double);
begin
if _iC = unknown then
begin
_uR := uI;
if niceResult = niceUserResult then
_iC := correct
else
_iC := incorrect;
end;
end;
function resultToString(const r: TResult): String;
begin
case r of
correct: resultToString := ':D'; //'Correct :D';
incorrect: resultToString := ':('; //'Incorrect:''(';
unknown: resultToString := ':/'; //'Unknown :/';
end;
end;
function resultToBoolean(const r: TResult): Boolean;
begin
if r = correct then
resultToBoolean := True
else
resultToBoolean := False;
end;
function categoryToString(const c: TOperationCategory): String;
begin
case c of
arithmetic: categoryToString := 'arithmetic';
text: categoryToString := 'text';
tricky: categoryToString := 'tricky';
end;
end;
end.
|
{*****************************************************************}
{* PROTECTION PLUS 4.4.1.0 }
{* }
{* Global constants and declare statements for Delphi 2-5 }
{* Uses KeyLib32.DLL }
{* Last Modified 21 Oct 2007 }
{*****************************************************************}
unit PPP4;
interface
Uses
WinTypes,
WinProcs;
var
lfhandle: LongInt;
compno: LongInt;
semhandle: LongInt;
Type
PBool = ^WordBool;
PBoolean = ^Boolean;
PByte = ^Byte;
PWord = ^Word;
PShortInt = ^ShortInt;
PInteger = ^Integer;
PLongInt = ^LongInt;
PSingle = ^Single;
PDouble = ^Double;
{pp_compno32drivers() flags }
Const CHECK_DRIVER_STATUS = 0; // Check to see if the driver is loaded.
Const INSTALL_DRIVER = 1; // Installs the driver specified.
Const UNINSTALL_DRIVER = 2; // Uninstalls the driver specified.
{pp_compno32drivers() algorithm defines }
Const COMPNO32_BIOS = 1;
Const COMPNO64_BIOS = 2;
{ pp_compno() algorithm defines }
Const COMPNO_BIOS = $0001;
Const COMPNO_HDSERIAL = $0002;
Const COMPNO_HDLOCK = $0004;
Const COMPNO_HDTYPE = $0008;
Const COMPNO_NETNAME = $0010;
Const COMPNO_MACADDR = $0020;
Const COMPNO_FILESTART = $0040;
Const COMPNO_WINPRODID = $0080;
Const COMPNO_IPADDR = $0100;
Const COMPNO_MACADDR_WIN98 = $0200;
Const COMPNO_BIOS16 = $0400;
Const COMPNO_BIOS32 = $0800;
Const COMPNO_MACADDR_WINNB = $1000;
Const COMPNO_BIOS64 = $2000;
Const COMPNO_MACADDR_4200 = $4000;
{ To suppress the MessageBoxes relating to Machnm1.exe }
Const SUPRESS_ERRORS = $8000;
Const COMPNO_ENHANCED = $10000; //use new compid algs
Const COMPNO_SERVER_MACADDR = $20000;
Const COMPNO_NO_WMI = $40000; //used with COMPNO_ENHANCED, COPYCHK_ENHANCED, and COPYADD_ENHANCED to omit WMI initialization for use in a DLL
{ pp_copycheck() action codes }
Const ACTION_MANUAL = 0;
Const ACTION_AUTOADD = 1;
Const COPYCHK_STRICT = 2;
Const COPYCHK_ENHANCED = 4;
{ pp_copyadd() flags }
Const COPYADD_ADDDUPE = 1;
Const COPYADD_ERASEALL = 2;
Const COPYADD_ENHANCED = 4;
{ pp_copydelete() flags }
Const COPYDEL_ALL = -1;
Const COPYDEL_ENHANCED = -2;
{ pp_copyget flags (slot) }
Const COPYGET_ENHANCED = -1;
{ License File type defines }
Const LF_FILE = 1;
Const LF_REGISTRY = 2;
Const LF_CBOX_VERSA = 3;
Const LF_CBOX_560 = 4;
Const LF_INTERNET = 5;
{ License File flag defines }
Const LF_CREATE_NORMAL = 0;
Const LF_CREATE_RDONLY = 1;
Const LF_CREATE_HIDDEN = 2;
Const LF_CREATE_SYSTEM = 4;
Const LF_CREATE_MISSING = 8;
Const LFOPEN_NOLOOP = 16;
Const LFOPEN_NOCACHE = $0020;
Const LFOPEN_OPENALWAYS = $0040; // used in pp_semopen to create file if not there
{ pp_exportfile and import file flag defines }
Const PPP_NOURLENCODE = 1;
Const PPP_EZTRIGPROCESS = 1;
{ pp_lfcreate() flags }
Const LFCREATE_OVERWRITE = 1;
{ pp_semopen flags }
Const SEM_FILE = 0;
Const SEM_TCPIP = 1;
{ pp_update flags }
Const UPDDATE_FORCE = 1;
Const UPDDATE_NOTIME = 2;
{ pp_lfalias() flags }
Const LFALIAS_VERIFY_CHECKSUM = 1;
Const LFALIAS_FIND_RECENT = 2;
Const LFALIAS_OVERWRITE_OLDER = 4;
Const LFALIAS_CREATE_MISSING = 8;
Const LFALIAS_SCATTER = 16;
Const LFALIAS_SCATTER_BACK = $8000000; // high bit
Const LFALIAS_NOCACHE = 32;
{ pp_eztrig1dlg() flags }
Const EZTRIG1DLG_PROCESS = 1;
Const EZTRIG1DLG_DELAYED = 2;
{ return codes for pp_eztrial1() }
Const EZTRIAL1_ERROR = 0;
Const EZTRIAL1_RETAIL = 1;
Const EZTRIAL1_DEMO = 2;
Const EZTRIAL1_BINDING_FAILED = 3;
Const EZTRIAL1_EXPIRED = 4;
Const EZTRIAL1_CLOCKTURNEDBACK = 5;
Const EZTRIAL1_PERIODIC = 6;
Const EZTRIAL1_EXCEEDED_USERS = 7;
{ pp_eztrial1ex() flags }
Const EX_TRIAL1EX_NO_NET = 1;
{ pp_gotourl() flags }
Const GOTOURL_BUYNOW = 1;
{ pp_importactfile flags }
Const PP_EZTRIGPROCESS = 1;
{ pp_netopen() flags }
Const NET_SINGLE = 0;
Const NET_DO_NOT_UPDATE = 1;
Const NET_ALWAYS_CONNECTED = 2;
{ pp_sysinfo() flags }
Const PP_TERMSERV = 1;
Const PP_VMWARE = 2;
Const PP_VIRTUALPC = 4;
Const PP_64BIT = 8;
{ flags for pp_transfer() }
Const PP_TRANSFER_ENHANCED = -1;
{ miscellaneous defines }
Const NO_FLAGS = 0;
Const PP_USE_UTC = 1;
Const TCODE_MAX = 50;
Const PP_MAX_UDEF_STRINGS = 10;
Const PP_MAX_UDEF_NUMBERS = 5;
Const PP_MAX_UDEF_DATES = 5;
{ result and error codes }
Const PP_FAILURE = 0;
Const PP_FALSE = 0;
Const PP_SUCCESS = 1;
Const PP_TRUE = 1;
Const ERR_INVALID_ATTRIBUTES = 2;
Const ERR_CANNOT_CHANGE_ATTRIBS = 3;
Const ERR_HFILE_ERROR = 4;
Const ERR_CANNOT_WRITE_FILE = 5;
Const ERR_CANNOT_CLOSE_FILE = 6;
Const ERR_CANNOT_OPEN_FILE = 7;
Const ERR_CANNOT_READ_FILE = 8;
Const ERR_CANNOT_CREATE_FILE = 9;
Const ERR_CANNOT_DELETE_FILE = 10;
Const ERR_FILE_WAS_CREATED = 11;
Const ERR_INVALID_PASSWORD = 12;
Const ERR_WRONG_PASSWORD = 13;
Const ERR_INCORRECT_PARAMETERS = 14;
Const ERR_FILE_MISSING = 15;
Const ERR_MEMORY_ALLOCATION = 16;
Const ERR_MEMORY_FREE = 17;
Const ERR_MEMORY_LOCK = 18;
Const ERR_SLOT_NUM_INVALID = 19;
Const ERR_SLOT_EMPTY = 20;
Const ERR_SLOTS_FULL = 21;
Const ERR_SLOT_ALREADY_ASSIGNED = 22;
Const ERR_NET_LIC_FULL = 23;
Const ERR_COMPNO_NOT_FOUND = 24;
Const ERR_VAR_NO_INVALID = 25;
Const ERR_SOFT_EXPIRATION = 26;
Const ERR_EXPTYPE_INVALID = 27;
Const ERR_EXP_DATE_EMPTY = 28;
Const ERR_STRING_TOO_LONG = 29;
Const ERR_CURRENT_DATE_OLDER = 30;
Const ERR_CANNOT_LOCK_FILE = 31;
Const ERR_WRONG_LF_VERSION = 32;
Const ERR_CORRUPT_LICENSE_FILE = 33;
Const ERR_SEM_FILE_LOCKED = 34;
Const ERR_CORRUPT_CONTROL_FILE = 35;
Const ERR_WRONG_CF_SERIAL_NUM = 36;
Const ERR_LF_LOCKED = 37;
Const ERR_LF_CHECKSUM_INVALID = 38;
Const ERR_NOT_APPLICABLE = 39;
Const ERR_NOT_IMPLEMENTED_YET = 40;
Const ERR_FILE_EXISTS = 41;
Const ERR_REGISTRY_OPEN = 42;
Const ERR_REGISTRY_QUERY = 43;
Const ERR_REGISTRY_CLOSE = 44;
Const ERR_REGISTRY_READ = 45;
Const ERR_REGISTRY_SET = 46;
Const ERR_CBOX_NOT_PRESENT = 47;
Const ERR_CBOX_WRONG_TYPE = 48;
Const ERR_CBOX_READ_RAM1_ERROR = 49;
Const ERR_CBOX_READ_RAM2_ERROR = 50;
Const ERR_CBOX_WRITE_RAM1_ERROR = 51;
Const ERR_CBOX_WRITE_RAM2_ERROR = 52;
Const ERR_CBOX_ID1_ERROR = 53;
Const ERR_CBOX_ID2_ERROR = 54;
Const ERR_CBOX_ID3_ERROR = 55;
Const ERR_VAR_NOT_AVAILABLE = 56;
Const ERR_DEMO_HAS_EXPIRED = 57;
Const ERR_WINSOCK_STARTUP_ERROR = 58;
Const ERR_WINSOCK_CANNOT_RESOLVE_HOST = 59;
Const ERR_WINSOCK_CANNOT_CREATE_SOCKET = 60;
Const ERR_WINSOCK_CANNOT_CONNECT_TO_SERVER = 61;
Const ERR_WINSOCK_CANNOT_SEND_DATA = 62;
Const ERR_WINSOCK_CANNOT_READ_DATA = 63;
Const ERR_NO_MORE_SOFTWARE_KEYS_AVAILABLE = 64;
Const ERR_INVALID_SERVER_RESPONSE = 65;
Const ERR_CANNOT_ALLOCATE_MEMORY = 66;
Const ERR_WINSOCK_CANNOT_RESOLVE_PROXY = 67;
Const ERR_ALIAS_FILE_DOES_NOT_MATCH = 68;
Const ERR_INVALID_CODE_ENTERED = 69;
Const ERR_INVALID_REGKEY2_ENTERED = 70;
Const ERR_ACCESS_DENIED = 71;
Const ERR_NON_WIN32_OS = 72;
Const ERR_DRIVER_CORRUPT = 73;
Const ERR_MARKED_FOR_DELETE = 74;
// Const ERR_FAKE_FOR_FOXPRO
Const ERR_INVALID_NETHANDLE = 75;
Const ERR_NO_MESSAGES = 76;
Const ERR_ALREADY_OPEN = 77;
Const ERR_INVALID_NETWORK_ADDRESS = 78;
Const ERR_NON_WIN64_OS = 79;
Const ERR_NOT_SUPPORTED_BY_OS = 80;
Const ERR_COULD_NOT_LOAD_DLL = 81;
Const ERR_FUNCTION_NOT_AVAILABLE = 82;
Const ERR_NO_DRIVES_FOUND = 83;
Const ERR_INTERNAL_BROADCAST = 84;
Const ERR_BIND_FAILED = 85;
Const ERR_CANNOT_CREATE_THREAD = 86;
Const ERR_NETWORK_CONNECTIVITY = 87;
Const ERR_COULD_NOT_INSTALL_DRIVER = 88;
Const ERR_NETWORK_RECONNECTED = 89;
Const ERR_NET_MULTI_STARTUP = 90;
Const ERR_COMPNO_ENHANCED = 91;
// Const ERR_SEND_MESSAGE
// Const ERR_READ_MESSAGE
Const ERR_FILE_SIZE_MISMATCH = 100;
Const ERR_FILE_INCORRECT = 101;
{ compno returns for COMPNO_BIOS32 }
Const ERR_ACCESS_DENIED_BIOS32 = -71;
Const ERR_NON_WIN32_OS_BIOS32 = -72;
Const ERR_DRIVER_CORRUPT_BIOS32 = -73;
Const ERR_MARKED_FOR_DELETE_BIOS32 = -74;
{ file attribute defines }
Const PP_NORMAL = 0;
Const PP_RDONLY = 1;
Const PP_HIDDEN = 2;
Const PP_SYSTEM = 4;
{ standard threshhold - used internally only }
Const PP_STD_THRESHOLD = 20;
{ expiration types }
Const EXP_NONE = 'N';
Const EXP_EXE_LIMIT = 'E';
Const EXP_SHAREWARE_VER = 'S';
Const EXP_PAYMENT_LIMIT = 'P';
Const EXP_DEMO_VERSION = 'D';
{ getvar / setvar definitions - character fields }
Const VAR_COMPANY = 1;
Const VAR_NAME = 2;
Const VAR_ADDRESS1 = 3;
Const VAR_ADDRESS2 = 4;
Const VAR_ADDRESS3 = 5;
Const VAR_PHONE1 = 6;
Const VAR_PHONE2 = 7;
Const VAR_SERIAL_TEXT = 8;
Const VAR_EXPIRE_TYPE = 9;
Const VAR_UDEF_CHAR_1 = 10;
Const VAR_UDEF_CHAR_2 = 11;
Const VAR_UDEF_CHAR_3 = 12;
Const VAR_UDEF_CHAR_4 = 13;
Const VAR_UDEF_CHAR_5 = 14;
Const VAR_UDEF_CHAR_6 = 15;
Const VAR_UDEF_CHAR_7 = 16;
Const VAR_UDEF_CHAR_8 = 17;
Const VAR_UDEF_CHAR_9 = 18;
Const VAR_UDEF_CHAR_10 = 19;
Const VAR_EZTRIAL_COMPNO_DRIVE = 20;
Const VAR_EZTRIAL_SYSDIR_FILENAME = 21;
Const VAR_EZTRIG_COMPNO_DRIVE = 22;
Const VAR_EZTRIAL_REG_ALIAS1 = 23;
Const VAR_EZTRIAL_REG_ALIAS2 = 24;
Const VAR_EZTRIG_DLG_LABELS = 25;
Const VAR_AUTOCL_PROXY_ADDR = 26;
Const VAR_AUTOCL_URL_VISIT = 27;
Const VAR_AUTOCL_URL_BUYNOW = 28;
Const VAR_AUTOCL_URL_UNLOCK = 29;
Const VAR_AUTOCL_URL_REGISTER = 30;
Const VAR_EZTRIAL_COMPNO_FILE = 31;
Const VAR_EZTRIG_COMPNO_FILE = 32;
Const VAR_LICENSEPW = 33;
{ getvar / setvar definitions - numeric fields }
Const VAR_SERIAL_NUM = 1;
Const VAR_EXP_COUNT = 2;
Const VAR_EXP_LIMIT = 3;
Const VAR_LAN_COUNT = 4;
Const VAR_LAN_LIMIT = 5;
Const VAR_INSTALL_COUNT = 6;
Const VAR_INSTALL_LIMIT = 7;
Const VAR_AUTHORIZED_COMPS = 8;
Const VAR_UDEF_NUM_1 = 9;
Const VAR_UDEF_NUM_2 = 10;
Const VAR_UDEF_NUM_3 = 11;
Const VAR_UDEF_NUM_4 = 12;
Const VAR_UDEF_NUM_5 = 13;
Const VAR_LF_CHECKSUM = 14;
Const VAR_EZTRIAL_SOFT_BINDING = 15;
Const VAR_EZTRIAL_HARD_BINDING = 16;
Const VAR_EZTRIAL_COMPNO_THRESHOLD = 17;
Const VAR_EZTRIAL_CONVERT_COPIES = 18;
Const VAR_EZTRIAL_UPDATE_LAST_TIME = 19;
Const VAR_EZTRIAL_COMPNO_ALGORITHMS = 20;
Const VAR_EZTRIAL_FILE_VERSION = 21;
Const VAR_EZTRIG_FLAGS = 22;
Const VAR_EZTRIG_COMPNO_ALGORITHMS = 23;
Const VAR_EZTRIG_SEED = 24;
Const VAR_EZTRIG_REGKEY2SEED = 25;
Const VAR_EZTRIAL_DAYS_TO_RUN = 26;
Const VAR_EZTRIAL_TIMES_TO_RUN = 27;
Const VAR_LICENSEID = 28;
Const VAR_CUSTOMERID = 29;
{ getvar / setvar definitions - date fields }
Const VAR_EXP_DATE_SOFT = 1;
Const VAR_EXP_DATE_HARD = 2;
Const VAR_LAST_DATE = 3;
Const VAR_LAST_TIME = 4;
Const VAR_UDEF_DATE_1 = 5;
Const VAR_UDEF_DATE_2 = 6;
Const VAR_UDEF_DATE_3 = 7;
Const VAR_UDEF_DATE_4 = 8;
Const VAR_UDEF_DATE_5 = 9;
{ compatibility with previous versions }
Const VAR_PRODUCT = VAR_UDEF_CHAR_2;
Const VAR_DISTRIBUTOR = VAR_UDEF_CHAR_3;
Const VAR_USER_DEF_1 = VAR_UDEF_CHAR_1;
Const VAR_USER_DEF_2 = VAR_UDEF_NUM_1;
Const VAR_USER_DEF_3 = VAR_UDEF_NUM_2;
Const VAR_USER_DEF_4 = VAR_UDEF_DATE_1;
{ Function prototypes follow }
Procedure pp_adddays (month: PLongInt; day: PLongInt; year: PLongInt; days: LongInt); stdcall;
Function pp_bitclear (bit_field: PLongInt; bit_number: LongInt): LongInt; stdcall;
Function pp_bitset (bit_field: PLongInt; bit_number: LongInt): LongInt; stdcall;
Function pp_bittest (bit_field: LongInt; bit_number: LongInt): LongInt; stdcall;
// Only uncomment this in if you are directed to do so
// Procedure pp_cedate ( enum : LongInt; month : PLongInt; day : PLongInt; year : PLongInt); stdcall;
Function pp_checksum (filename: PChar; checksum: PLongInt): LongInt; stdcall;
Function pp_cenum: LongInt; stdcall;
Function pp_chkvarchar (handle: LongInt; var_no: LongInt): LongInt; stdcall;
Function pp_chkvardate (handle: LongInt; var_no: LongInt): LongInt; stdcall;
Function pp_chkvarnum (handle: LongInt; var_no: LongInt): LongInt; stdcall;
Function pp_compno32drivers( driver : LongInt; flags : LongInt): LongInt; stdcall;
Function pp_compno (cnotype: LongInt; filename: PChar; hard_drive: PChar): LongInt; stdcall;
Function pp_convertv3 (handle: LongInt; v3_cf: PChar; v3_cpf: PChar; v3_sn: LongInt): LongInt; stdcall;
Function pp_copyadd (handle: LongInt; flags: LongInt; comp_num: LongInt): LongInt; stdcall;
Function pp_copycheck (handle: LongInt; action: LongInt; comp_num: LongInt): LongInt; stdcall;
Function pp_copycheckth (handle: LongInt; action: LongInt; comp_num: LongInt; threshold: LongInt): LongInt; stdcall;
Function pp_copydelete (handle: LongInt; comp_num: LongInt): LongInt; stdcall;
Function pp_copyget (handle: LongInt; slot: LongInt; comp_num: PLongInt): LongInt; stdcall;
Function pp_countdec (handle: LongInt; var_no: LongInt): LongInt; stdcall;
Function pp_countinc (handle: LongInt; var_no: LongInt): LongInt; stdcall;
// Only uncomment this in if you are directed to do so
// Function pp_ctcodes (code: LongInt; cenum: LongInt; computer: LongInt; seed: LongInt): LongInt; stdcall;
Function pp_daysleft (handle: LongInt; daysleft: PLongInt): LongInt; stdcall;
Procedure pp_decrypt (iinstr: PChar; pwstr: PChar; ret: PChar); stdcall;
Procedure pp_encrypt (iinstr: PChar; pwstr: PChar; ret: PChar); stdcall;
Procedure pp_errorstr (number: LongInt; buffer: PChar); stdcall;
Function pp_expired (handle: LongInt): LongInt; stdcall;
Function pp_exportactfile( flags : LongInt; lfhandle : LongInt; licensepath : PChar; filepath : PChar;
server : PChar; url : PChar; key : PChar; licenseid : LongInt; password : PChar;
compid : LongInt; version : PChar; productid : LongInt; source : Pchar): LongInt; stdcall;
Function pp_eztrial1 (filename: PChar; password: PChar; errorcode: PLongInt; lfhandle: PLongInt): LongInt; stdcall;
Function pp_eztrial1test (lfhandle: LongInt; errorcode: PLongInt): LongInt; stdcall;
Function pp_eztrial2 ( hwndDlg : LongInt; filename: PChar; password: PChar; flags : LongInt; errorcode : PLongInt; lfhandle: PLongInt): LongInt; stdcall;
Function pp_eztrig1 (hwnd: LongInt; filename: PChar; password: PChar; errorcode: PLongInt): LongInt; stdcall;
Function pp_eztrig1dlg (hwnd: LongInt; handle: LongInt; flags: LongInt; dlg_labels: PChar; usercode1: LongInt;
usercode2: LongInt; tcseed: LongInt; regkey2seed: LongInt; tcvalue: PLongInt; tcdata: PLongInt): LongInt; stdcall;
Function pp_eztrig1ex (handle: LongInt; regkey1: LongInt; regkey2: LongInt; flags: LongInt; usercode1: LongInt;
usercode2: LongInt; tcseed: LongInt; regkey2seed: LongInt; tcvalue: PLongInt; tcdata: PLongInt): LongInt; stdcall;
Function pp_filedelete (filename: PChar): LongInt; stdcall;
Function pp_getcode (hwnd: LongInt; str_title: PChar; str_cenum: PChar; str_comp: PChar; str_code: PChar): LongInt; stdcall;
Procedure pp_getdate (month: PLongInt; day: PLongInt; year: PLongInt; dayofweek: PLongInt); stdcall;
//Procedure pp_getdateex (flags: LongInt; month: PLongInt; day: PLongInt; year: PLongInt; dayofweek: PLongInt); stdcall;
Procedure pp_gettime (hours: PLongInt; minutes: PLongInt; seconds: PLongInt; hseconds: PLongInt); stdcall;
//Procedure pp_gettimeex (flags: LongInt; hours: PLongInt; minutes: PLongInt; seconds: PLongInt; hseconds: PLongInt); stdcall;
Function pp_getvarchar (handle: LongInt; var_no: LongInt; buffer: PChar): LongInt; stdcall;
Function pp_getvardate (handle: LongInt; var_no: LongInt; month_hours: PLongInt; day_minutes: PLongInt;
year_seconds: PLongInt): LongInt; stdcall;
Function pp_getvarnum (handle: LongInt; var_no: LongInt; value: PLongInt): LongInt; stdcall;
Function pp_gotourl (hwnd: LongInt; handle: LongInt; flags: LongInt; url: PChar): LongInt; stdcall;
Function pp_hdserial (drive : PChar): LongInt; stdcall;
Function pp_importactfile( flags : LongInt; lfhandle : LongInt; importtype : LongInt;
compid : LongInt; regkey1 : PLongInt; regkey2 : PLongInt;
session : PLongInt; licenseupd : PChar): LongInt; stdcall;
Procedure pp_lastday (month: LongInt; day: PLongInt; year: LongInt); stdcall;
Function pp_lanactive (handle: LongInt): LongInt; stdcall;
Function pp_lancheck (handle: LongInt): LongInt; stdcall;
Function pp_libtest (testnum: LongInt): LongInt; stdcall;
Procedure pp_libversion(ver1: PLongInt; ver2: PLongInt; ver3: PLongInt; ver4: PLongInt); stdcall;
Function pp_lfalias (handle: LongInt; filename: PChar; lfflags: LongInt; lftype: LongInt; password: PChar;
recenthandle: PLongInt): LongInt; stdcall;
Function pp_lfclose (handle: LongInt): LongInt; stdcall;
Function pp_lfcopy (handle: LongInt; filename: PChar; lftype: LongInt): LongInt; stdcall;
Function pp_lfcreate (filename: PChar; flags: LongInt; lftype: LongInt; password: PChar; attrib: LongInt): LongInt; stdcall;
Function pp_lfdelete (filename: PChar; flags: LongInt; lftype: LongInt; password: PChar): LongInt; stdcall;
Function pp_lflock (mem_handle: LongInt): LongInt; stdcall;
Function pp_lfopen (filename: PChar; lfflags: LongInt; lftype: LongInt; password: PChar; handle: PLongInt): LongInt; stdcall;
Function pp_lfunlock (mem_handle: LongInt): LongInt; stdcall;
Function pp_ndecrypt (number: LongInt; seed: LongInt): LongInt; stdcall;
Function pp_ndecryptx (buffer: PChar; number1: PLongInt; number2: PLongInt; number3: PLongInt; number4: PLongInt;
seed: LongInt): LongInt; stdcall;
Function pp_nencrypt (number: LongInt; seed: LongInt): LongInt; stdcall;
Procedure pp_nencryptx (buffer: PChar; number1: LongInt; number2: LongInt; number3: LongInt; number4: LongInt; seed: LongInt); stdcall;
Function pp_netclose (lNetHandle : LongInt): LongInt; stdcall;
Function pp_netopen (network_password : PChar; flags : LongInt; number1 : LongInt; string1 :
PChar; nethandle : PLongInt; errorcode : PLongInt): LongInt; stdcall;
Function pp_nettest (lNetHandle : LongInt): LongInt; stdcall;
Procedure pp_npdate (month: PLongInt; day: PLongInt; year: PLongInt; dop: LongInt); stdcall;
Function pp_password (buffer: PChar): LongInt; stdcall;
Function pp_redir (drive: PChar): LongInt; stdcall;
Function pp_semclose (handle: LongInt): LongInt; stdcall;
Function pp_semcount (handle: LongInt; semtype: LongInt; prefix_server: PChar; name: PChar; number: PLongInt): LongInt; stdcall;
Function pp_semopen (handle: LongInt; semtype: LongInt; prefix_server: PChar; name: PChar; sem_handle: PLongInt): LongInt; stdcall;
Function pp_semtest (handle: LongInt): LongInt; stdcall;
Function pp_semused (handle: LongInt; semtype: LongInt; prefix_server: PChar; name: PChar; number: PLongInt): LongInt; stdcall;
Function pp_setvarchar (handle: LongInt; var_no: LongInt; buffer: PChar): LongInt; stdcall;
Function pp_setvardate (handle: LongInt; var_no: LongInt; month_hours: LongInt; day_minutes: LongInt;
year_seconds: LongInt): LongInt; stdcall;
Function pp_setvarnum (handle: LongInt; var_no: LongInt; value: LongInt): LongInt; stdcall;
Function pp_sysinfo(flags: LongInt): LongInt; stdcall;
Function pp_tcode (number: LongInt; cenum: LongInt; computer: LongInt; seed: LongInt): LongInt; stdcall;
Function pp_timercheck (timestamp: LongInt; minutes: LongInt): LongInt; stdcall;
Function pp_timerstart: LongInt; stdcall;
Function pp_transfer (handle: LongInt; filename: PChar; password: PChar; comp_num: LongInt): LongInt; stdcall;
Function pp_upddate (handle: LongInt; flag: LongInt): LongInt; stdcall;
Function pp_valdate (handle: LongInt): LongInt; stdcall;
Function pp_get4108mac: LongInt; stdcall;
{ Other Windows API functions used }
Const SW_SHOWNORMAL = 1;
Function ShellExecute (hwnd: LongInt; lpOperation: PChar; lpFile: PChar; lpParameters: PChar;
lpDirectory: PChar; nShowCmd: LongInt): LongInt; stdcall;
Function GetWindowsDirectory (buffer: PChar; length: LongInt): LongInt; stdcall;
Function GetSystemDirectory (buffer: PChar; length: LongInt): LongInt; stdcall;
implementation
Procedure pp_adddays; external 'KeyLib32.dll';
Function pp_bitclear; external 'KeyLib32.dll';
Function pp_bitset; external 'KeyLib32.dll';
Function pp_bittest; external 'KeyLib32.dll';
// Only uncomment this in if you are directed to do so
// Function pp_cedate; external 'KeyLib32.dll';
Function pp_cenum; external 'KeyLib32.dll';
Function pp_checksum; external 'KeyLib32.dll';
Function pp_chkvarchar; external 'KeyLib32.dll';
Function pp_chkvardate; external 'KeyLib32.dll';
Function pp_chkvarnum; external 'KeyLib32.dll';
Function pp_compno32drivers; external 'KeyLib32.dll';
Function pp_compno; external 'KeyLib32.dll';
Function pp_convertv3; external 'KeyLib32.dll';
Function pp_copyadd; external 'KeyLib32.dll';
Function pp_copycheck; external 'KeyLib32.dll';
Function pp_copycheckth; external 'KeyLib32.dll';
Function pp_copydelete; external 'KeyLib32.dll';
Function pp_copyget; external 'KeyLib32.dll';
Function pp_countdec; external 'KeyLib32.dll';
Function pp_countinc; external 'KeyLib32.dll';
// Only uncomment this in if you are directed to do so
// Function pp_ctcodes; external 'KeyLib32.dll';}
Function pp_daysleft; external 'KeyLib32.dll';
Procedure pp_decrypt; external 'KeyLib32.dll';
Procedure pp_encrypt; external 'KeyLib32.dll';
Procedure pp_errorstr; external 'KeyLib32.dll';
Function pp_expired; external 'KeyLib32.dll';
Function pp_exportactfile; external 'KeyLib32.dll';
Function pp_eztrial1; external 'KeyLib32.dll';
Function pp_eztrial1test; external 'KeyLib32.dll';
Function pp_eztrial2; external 'KeyLib32.dll';
Function pp_eztrig1; external 'KeyLib32.dll';
Function pp_eztrig1dlg; external 'KeyLib32.dll';
Function pp_eztrig1ex; external 'KeyLib32.dll';
Function pp_filedelete; external 'KeyLib32.dll';
Function pp_getcode; external 'KeyLib32.dll';
Procedure pp_getdate; external 'KeyLib32.dll';
Procedure pp_gettime; external 'KeyLib32.dll';
Function pp_getvarchar; external 'KeyLib32.dll';
Function pp_getvardate; external 'KeyLib32.dll';
Function pp_getvarnum; external 'KeyLib32.dll';
Function pp_gotourl; external 'KeyLib32.dll';
Function pp_hdserial; external 'KeyLib32.dll';
Function pp_importactfile; external 'KeyLib32.dll';
Procedure pp_initlib; external 'KeyLib32.dll';
Procedure pp_lastday; external 'KeyLib32.dll';
Function pp_lanactive; external 'KeyLib32.dll';
Function pp_lancheck; external 'KeyLib32.dll';
Function pp_libtest; external 'KeyLib32.dll';
Procedure pp_libversion; external 'KeyLib32.dll';
Function pp_lfalias; external 'KeyLib32.dll';
Function pp_lfclose; external 'KeyLib32.dll';
Function pp_lfcopy; external 'KeyLib32.dll';
Function pp_lfcreate; external 'KeyLib32.dll';
Function pp_lfdelete; external 'KeyLib32.dll';
Function pp_lflock; external 'KeyLib32.dll';
Function pp_lfopen; external 'KeyLib32.dll';
Function pp_lfunlock; external 'KeyLib32.dll';
Function pp_ndecrypt; external 'KeyLib32.dll';
Function pp_ndecryptx; external 'KeyLib32.dll';
Function pp_nencrypt; external 'KeyLib32.dll';
Procedure pp_nencryptx; external 'KeyLib32.dll';
Function pp_netclose; external 'KeyLib32.dll';
Function pp_netopen; external 'KeyLib32.dll';
Function pp_nettest; external 'KeyLib32.dll';
Procedure pp_npdate; external 'KeyLib32.dll';
Function pp_password; external 'KeyLib32.dll';
Function pp_redir; external 'KeyLib32.dll';
Function pp_semclose; external 'KeyLib32.dll';
Function pp_semcount; external 'KeyLib32.dll';
Function pp_semopen; external 'KeyLib32.dll';
Function pp_semtest; external 'KeyLib32.dll';
Function pp_semused; external 'KeyLib32.dll';
Function pp_setvarchar; external 'KeyLib32.dll';
Function pp_setvardate; external 'KeyLib32.dll';
Function pp_setvarnum; external 'KeyLib32.dll';
Function pp_sysinfo; external 'KeyLib32.dll';
Function pp_tcode; external 'KeyLib32.dll';
Function pp_timercheck; external 'KeyLib32.dll';
Function pp_timerstart; external 'KeyLib32.dll';
Function pp_transfer; external 'KeyLib32.dll';
Function pp_upddate; external 'KeyLib32.dll';
Function pp_valdate; external 'KeyLib32.dll';
Function pp_get4108mac; external 'KeyLib32.dll';
{ Other Windows API functions used }
Function ShellExecute; external 'shell32.dll' name 'ShellExecuteA';
Function GetWindowsDirectory; external 'kernel32.dll' name 'GetWindowsDirectoryA';
Function GetSystemDirectory; external 'kernel' name 'GetSystemDirectoryA';
end.
|
unit lsdatasettable;
{
Borland TDataSet compatible class
Specify a table name
And access results read/write (if rowid or equivalent available)
}
interface
uses
SysUtils, Classes, Db, lsdatasetbase, passql, passqlite, pasmysql;
type
TlsTable = class(TlsBaseDataSet)
private
FTable: String;
FTables: TStrings;
FPrimaryKeyIndex: Integer;
FEditRow: TResultRow;
FEditRowIndex: Integer;
procedure SetTable(const Value: String);
procedure ClearEditRow;
protected
procedure InternalDelete; override;
procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override;
procedure InternalInsert; override;
procedure InternalPost; override;
procedure InternalEdit; override;
procedure InternalCancel; override;
procedure SetFieldData(Field: TField; Buffer: Pointer); override;
function GetCanModify: Boolean; override;
procedure CheckDBMakeQuery;
public
constructor Create (Owner: TComponent); override;
destructor Destroy; override;
procedure SetDatabase(const Value: TSqlDB); override;
function ListTables: TStrings;
published
property Table: String read FTable write SetTable;
end;
implementation
procedure TlsTable.InternalDelete;
begin
if FPrimaryKeyIndex >= 0 then
begin
//delete from table
if FHelperSet.FormatQuery('delete from %u where %u=%d',
[FTable, FResultSet.FieldName[FPrimaryKeyIndex], FResultSet.Row[FCurrent].Format[FPrimaryKeyIndex].AsInteger]) then
begin
//dirty trick, delete row from resultset without re-querying
//fortunately TResultSet allows this kind of tricks
//Since delete query returned true we assume this gives consistent results.
FResultSet.Row[FCurrent].Free;
FResultSet.FRowList.Delete(FCurrent);
dec (FResultSet.FRowCount);
end;
end;
end;
procedure TlsTable.SetFieldData(Field: TField; Buffer: Pointer);
var sValue: String;
iValue: Integer;
fValue: Double;
bValue: Boolean;
tValue: TDateTime;
row: TResultRow;
begin
row := PRecInfo(ActiveBuffer).Row;
if not Assigned(Row) then
exit;
case Field.DataType of
ftString:
begin
sValue := PChar (Buffer);
row.Strings[FFieldOffset + Field.Index] := sValue;
end;
ftInteger:
begin
Move (Buffer^, iValue, SizeOf(iValue));
Row.Strings[FFieldOffset + Field.Index] := IntToStr(iValue);
end;
ftFloat:
begin
Move (Buffer^, fValue, SizeOf(fValue));
Row.Strings[FFieldOffset + Field.Index] := FloatToStr(fValue);
end;
end;
end;
procedure TlsTable.InternalInsert;
var P: PChar;
i: Integer;
begin
//ActiveRecord should provide us
//access to the buffer
//that was just fetched by the base class
//row is (supposed to be) nil here, we set it to editrow
ClearEditRow;
PRecInfo(ActiveBuffer).Row := FEditRow;
FInserting := True;
end;
procedure TlsTable.InternalEdit;
var i: Integer;
begin
FEditing := True;
//make sure we have empty and corresponding fields
ClearEditRow;
//Copy contents of the row we are editing (dirty workaround - ignores any widestrings)
FEditRow.Assign (PRecInfo(ActiveBuffer).Row);
//D5 don't understand
//FEditRow.FNulls.Assign(PRecInfo(ActiveBuffer).Row.FNulls);
FEditRow.FNulls.Clear;
for i:=0 to PRecInfo(ActiveBuffer).Row.Count - 1 do
FEditRow.FNulls.Add(PRecInfo(ActiveBuffer).Row.FNulls[i]);
//issue here.. what if multiple components want to archieve edit state?
//seems datasource handles this nicely.
//since all dataaware components follow the same cursor
//but multiple writers on same database object
//may have inconsistencies in nested transactions.
// FHelperSet.SQLDB.StartTransaction;
end;
procedure TlsTable.InternalPost;
//Examine the stuff being edited
//build a nice query of the now values
//and update or insert, depending on edit mode
function FormatValue (dt: TSQLDataTypes; c: TResultCell): String;
begin
case dt of
dtString : Result := FDatabase.FormatSql('%s', [c.AsString]);
dtInteger : Result := FDatabase.FormatSql('%d', [c.AsInteger]);
dtFloat : Result := FDatabase.FormatSql('%f', [c.AsFloat]);
//todo: other datatypes
else
Result := 'NULL';
end;
end;
var i: Integer;
row: TResultRow;
q,n,v: String;
fd: TFieldDesc;
begin
row := PRecInfo(ActiveBuffer).Row;
if FEditing then
begin
//update modified fields
q := 'update ' + FTable + ' set ';
v := '';
for i:=FFieldOffset to row.FFields.Count - 1 do
begin
if v<>'' then
v := v + ', ';
v := v + FResultSet.FieldName [i] + '=';
fd := FResultSet.FieldDescriptor[i];
case fd.datatype of
dtString, dtNull : v := v + FDatabase.FormatSql('%s', [row.Format[i].AsString]);
dtInteger : v := v + FDatabase.FormatSql('%d', [row.Format[i].AsInteger]);
dtFloat : v := v + FDatabase.FormatSql('%f', [row.Format[i].AsFloat]);
//todo: other datatypes
else
v := v + 'NULL';
end;
end;
q := q + v + ' where ' + FResultSet.FieldName[FPrimaryKeyIndex] + '=' + IntToStr(FEditRow.Format[FPrimaryKeyIndex].AsInteger);
//q now holds query
if FHelperSet.Query(q) then
//all ok, row is modified
begin
//nothing to do, current row holds info
end
else
begin
//restore contents that were backed up in editrow
row.Assign(FEditRow);
//D5 don't understand
//row.FNulls.Assign(FEditRow.FNulls);
row.FNulls.Clear;
for i := 0 to FEditRow.FNulls.Count - 1 do
begin
row.FNulls.Add(FEditRow.FNulls[i]);
end;
row.FFields := FEditRow.FFields;
end;
end;
if FInserting then
begin
q := 'insert into '+FTable;
n := '';
v := '';
for i := FFieldOffset to row.FFields.Count - 1 do
begin
if i = FPrimaryKeyIndex then
continue;
if n<>'' then
n := n + ', ';
n := n + FResultSet.FieldName [i];
if v<>'' then
v := v + ', ';
fd := FResultSet.FieldDescriptor[i];
case fd.datatype of
dtString : v := v + FDatabase.FormatSql('%s', [row.Format[i].AsString]);
dtInteger : v := v + FDatabase.FormatSql('%d', [row.Format[i].AsInteger]);
dtFloat : v := v + FDatabase.FormatSql('%f', [row.Format[i].AsFloat]);
//todo: other datatypes
else
v := v + 'NULL';
end;
end;
q := q + '(' + n + ') values (' + v + ')';
if FHelperSet.Query(q) then
begin
if FPrimaryKeyIndex >= 0 then
FEditRow.Strings [FPrimaryKeyIndex] := IntToStr (FHelperSet.FLastInsertID);
FResultSet.FRowList.Insert(ActiveRecord {FCurrent}, FEditRow);
//FResultSet.FRowList.Add(FEditRow);
FEditRow := TResultRow.Create;
FEditRow.FFields := FResultSet.FFields;
end
else
begin
//insert failed, do nothing
end;
end;
FEditing := False;
FInserting := False;
// FHelperSet.SQLDB.Commit;
end;
procedure TlsTable.InternalCancel;
var i: Integer;
begin
if FEditing then //not inserting
begin
PRecInfo(ActiveBuffer).Row.Assign (FEditRow );
PRecInfo(ActiveBuffer).Row.FNulls.Clear;
//D5 don't understand
//PRecInfo(ActiveBuffer).Row.FNulls.Assign(FEditRow.FNulls);
for i:=0 to FEditRow.FNulls.Count - 1 do
PRecInfo(ActiveBuffer).Row.FNulls.Add(FEditRow.FNulls[i]);
end;
FEditing := False;
FInserting := False;
// FHelperSet.SQLDB.Rollback;
end;
procedure TlsTable.InternalAddRecord(Buffer: Pointer; Append: Boolean);
begin
// TODO: support adding
end;
function TlsTable.GetCanModify: Boolean;
begin
Result := False; // read-only
//sqlite is editable.. for mysql and odbc i must see how to handle...
if Assigned(FDatabase) and
//(FDatabase is TLiteDB) then
(FPrimaryKeyIndex >= 0)
// and not FEditing?
then
Result := True;
end;
function TlsTable.ListTables: TStrings;
begin
if Assigned(FDatabase) then
begin
FDatabase.UseResultSet(FHelperSet);
FDatabase.ShowTables;
FTables.Free;
FTables := FDatabase.GetColumnAsStrings;
//FTables.Assign(FDatabase.Tables)
end
else
FTables.Clear;
Result := FTables;
end;
procedure TlsTable.SetTable(const Value: String);
begin
FTable := Value;
CheckDBMakeQuery;
{
if FDatabaseOpen then
begin
Active := False;
Active := True;
end;
}
end;
constructor TlsTable.Create(Owner: TComponent);
begin
inherited;
FTables := TStringList.Create;
FEditRow := TResultRow.Create;
FEditRow.FFields := FResultSet.FFields;
end;
destructor TlsTable.Destroy;
begin
FEditRow.Free;
FTables.Free;
inherited;
end;
procedure TlsTable.CheckDBMakeQuery;
var i: Integer;
fd: TFieldDesc;
begin
if Assigned(FDatabase) then
begin
FInternalQuery := 'select * from '+FTable;
FFieldOffset := 0;
FPrimaryKeyIndex := -1;
if FDatabase is TLiteDB then
begin
FInternalQuery := 'select rowid, * from '+FTable;
FFieldOffset := 1;
FPrimaryKeyIndex := 0;
end;
if FDatabase is TMyDB then
begin
for i := 0 to FResultSet.FFields.Count - 1 do
begin
fd := FResultSet.FieldDescriptor [i];
if fd.IsNumeric and
fd.IsAutoIncrement and
fd.IsPrimaryKey then
begin
FPrimaryKeyIndex := i;
break;
end;
end;
end;
end;
end;
procedure TlsTable.SetDatabase(const Value: TSqlDB);
begin
inherited;
CheckDBMakeQuery;
end;
procedure TlsTable.ClearEditRow;
var i: Integer;
begin
FEditRow.Clear;
FEditRow.FFields := FResultSet.FFields;
for i := 0 to FEditRow.FFields.Count do
begin
FEditRow.Add('');
FEditRow.FNulls.Add(nil);
end;
end;
end.
|
unit COW_Design;
interface
uses
Dialogs,SysUtils,Classes,Contnrs,Windows,COW_RunTime,COW_Utils,StrUtils;
type
TGrammar=class;
TNodeGrammarItem=class;
TAndGrammarItem=class;
TOrGrammarItem=class;
TObjectSet=class(TObjectList)
public
function Add(AObject:TObject):Boolean;
function Contains(AObject:TObject):Boolean;
function AddSet(ASet:TObjectSet):Boolean;
end;
PNullItem=^TNullItem;
TNullItem=record
Law:TAndGrammarItem;
LawParent:TOrGrammarItem;
Position:Cardinal;
end;
TNullItemSet=class(TList)
private
function GetItems(Index: Integer): TNullItem;
public
function Add(Law:TAndGrammarItem;Position:Cardinal;Grammar:TGrammar):Boolean;
property Items[Index:Integer]:TNullItem read GetItems;default;
procedure Close;
function Transition(ALaw:TNodeGrammarItem):TNullItemSet;
function IsEqualTo(ASet:TNullItemSet):Boolean;
function IsEmpty:Boolean;
destructor Destroy;override;
end;
TNullItemSetCollection=class(TObjectList)
private
function GetItems(Index: Integer): TNullItemSet;
public
function Add(ASet:TNullItemSet):Boolean;
function IndexOf(ASet:TNullItemSet):Integer;
function Contains(ASet:TNullItemSet):Boolean;
property Items[Index:Integer]:TNullItemSet read GetItems;default;
end;
TTableItemType=(tipAccept,tipError,tipShift,tipReduce,tipGoto);
PTableItem=^TTableItem;
TTableItem=packed record
case ItemType:TTableItemType of
tipAccept:();
tipError:();
tipShift:(Count:Cardinal);
tipReduce:(ID:Cardinal);
tipGoto:(Index:Cardinal);
end;
TAnalyseRow=class(TList)
private
function GetItem(Index: Integer): TTableItem;
procedure SetItem(Index: Integer; const Value: TTableItem);
public
constructor Create(ACount:Integer);
property Item[Index:Integer]:TTableItem read GetItem write SetItem;
destructor Destroy;override;
end;
TAnalyseTable=class
private
FList:TObjectList;
FColCount:Integer;
FCollection:TNullItemSetCollection;
FGrammar:TGrammar;
function GetItem(ARow, ACol: Integer): TTableItem;
function GetRowCount: Integer;
procedure SetItem(ARow, ACol: Integer; const Value: TTableItem);
procedure CheckReduceConflict(ARow,ACol:Integer;Item:TTableItem);
public
constructor Create(ACollection:TNullItemSetCollection;AGrammar:TGrammar);
property Item[ARow,ACol:Integer]:TTableItem read GetItem write SetItem;default;
property RowCount:Integer read GetRowCount;
property ColCount:Integer read FColCount;
destructor Destroy;override;
end;
TAndGrammarItem=class
private
FSubItems:TObjectList;
FUsage:Array of Boolean;
function GetLaw(Index: Integer): TNodeGrammarItem;
function GetLawCount: Integer;
function GetUsedLawItem(Index: Integer): Boolean;
procedure SetUsedLawItem(Index: Integer; const Value: Boolean);
function GetUsageCount: Integer;
protected
FImplementationBlock:string;
public
constructor Create(SubItems:array of TNodeGrammarItem;AImplementationBlock:string='');
procedure InsertSubItem(Index:Integer;Item:TNodeGrammarItem);
property LawCount:Integer read GetLawCount;
property Law[Index:Integer]:TNodeGrammarItem read GetLaw;
property UsedLawItem[Index:Integer]:Boolean read GetUsedLawItem write SetUsedLawItem;
property UsageCount:Integer read GetUsageCount;
destructor Destroy;override;
end;
TNodeGrammarItem=class
private
FGrammar:TGrammar;
FFirst:TObjectSet;
function GetID:Cardinal;
function GetName:string;virtual;abstract;
procedure SetName(const Value: string);virtual;abstract;
function GetUserFriendlyName: string;virtual;abstract;
procedure SetUserFriendlyName(const Value: string);virtual;abstract;
public
constructor Create(AGrammar:TGrammar);
function IsLeaf:Boolean;virtual;abstract;
property Name:string read GetName write SetName;
property UserFriendlyName:string read GetUserFriendlyName write SetUserFriendlyName;
property ID:Cardinal read GetID;
destructor Destroy;override;
end;
TTokenGrammarItem=class(TNodeGrammarItem)
private
FName,FUserFriendlyName:string;
function GetName:string;override;
procedure SetName(const Value: string);override;
function GetUserFriendlyName: string;override;
procedure SetUserFriendlyName(const Value: string);override;
public
constructor Create(AGrammar:TGrammar;AName:string);
function IsLeaf:Boolean;override;
end;
TEOFGrammarItem=class(TNodeGrammarItem)
private
function GetName:string;override;
procedure SetName(const Value: string);override;
function GetUserFriendlyName: string;override;
procedure SetUserFriendlyName(const Value: string);override;
public
function IsLeaf:Boolean;override;
end;
TErrorGrammarItem=class(TNodeGrammarItem)
private
function GetName:string;override;
procedure SetName(const Value: string);override;
function GetUserFriendlyName: string;override;
procedure SetUserFriendlyName(const Value: string);override;
public
function IsLeaf:Boolean;override;
end;
TOrGrammarItem=class(TNodeGrammarItem)
private
FName,FType,FDeclarationBlock:string;
FSubItems:TObjectList;
FNext:TObjectSet;
FUserFriendlyName: string;
FStorable: Boolean;
function GetName:string;override;
procedure SetName(const Value: string);override;
function GetUserFriendlyName: string;override;
procedure SetUserFriendlyName(const Value: string);override;
function GetCount: Integer;
function GetItem(Index: Integer): TAndGrammarItem;
public
constructor Create(AGrammar:TGrammar;SubItems:array of TAndGrammarItem;AName:string;AType:string='';ADeclarationBlock:string='');
function IsLeaf:Boolean;override;
property Count:Integer read GetCount;
property Item[Index:Integer]:TAndGrammarItem read GetItem;default;
procedure InsertItem(Index:Integer;Item:TAndGrammarItem);
property Storable:Boolean read FStorable write FStorable;
destructor Destroy;override;
end;
TGrammar=class
private
FEOF:TEOFGrammarItem;
function GetLawCount: Integer;
function GetLawItem(Name: string): TOrGrammarItem;
function GetTokenItem(Name: string): TTokenGrammarItem;
procedure BuildFirst;
procedure BuildNext;
function GetItem(Name: string): TNodeGrammarItem;
protected
FNodes:TStringList;
FLaws:TObjectList;
FMain:TOrGrammarItem;
public
constructor Create(ATokenList:TStringList);
property LawCount:Integer read GetLawCount;
property LawItem[Name:string]:TOrGrammarItem read GetLawItem;
property TokenItem[Name:string]:TTokenGrammarItem read GetTokenItem;
property Item[Name:string]:TNodeGrammarItem read GetItem;default;
function IndexOfLaw(Law:TAndGrammarItem):Integer;
function BuildAnalyseTable:TAnalyseTable;
destructor Destroy;override;
end;
TCharMap=array[#0..#255] of TNodeGrammarItem;
TLexerItemGrammar=class(TGrammar)
private
FCharMap:TCharMap;
FStored:Boolean;
public
constructor Create(TokenList,LawList:TStringList);
property Stored:Boolean read FStored;
end;
TLexer=class(TGrammar)
private
FRootLexerItems:TStringList;
FBuilt:Boolean;
procedure MakeProper;
procedure BuildSeparateGrammars;
public
constructor Create(ALaws:TStringList);
function BuildLexerDefinition:TLexerDefinition;
function BuildPascalLexerDefinitions(Prefix:string;CRLF:string=#10#13):string;
destructor Destroy;override;
end;
TParser=class(TGrammar)
protected
FPreImplementationBlock,FPostImplementationBlock:string;
FLexer:TLexer;
FError:TErrorGrammarItem;
public
constructor Create(ALexer:TLexer;APreImplementationBlock:string='';APostImplementationBlock:string='');
property Main:TOrGrammarItem read FMain;
function BuildLexerDefinition:TLexerDefinition;
function BuildParserDefinition:TParserDefinition;
function BuildIParser:IParser;
property PreImplementationBlock:string read FPreImplementationBlock;
property PostImplementationBlock:string read FPostImplementationBlock;
function BuildPascalLexerDefinitions(Prefix:string;CRLF:string=#10#13):string;
function BuildPascalParserDefinitions(Prefix:string;CRLF:string=#10#13):string;
function BuildPascalDefinitions(Prefix:string;CRLF:string=#10#13):string;
function BuildPascalClassDeclaration(Prefix:string;CRLF:string=#10#13):string;
function BuildPascalClassImplementation(Prefix:string;CRLF:string=#10#13):string;
end;
//procedure DisplayLaws(Grammar:TGrammar);
procedure DefaultEmitWarning(s:string);
procedure DefaultEmitError(s:string);
procedure DefaultPushProgress;
procedure DefaultUpdateProgress(Position:Single;Caption:string);
procedure DefaultPopProgress;
var
EmitWarning:procedure(s:string)=DefaultEmitWarning;
EmitError:procedure(s:string)=DefaultEmitError;
PushProgress:procedure=DefaultPushProgress;
UpdateProgress:procedure(Position:Single;Caption:string)=DefaultUpdateProgress;
PopProgress:procedure=DefaultPopProgress;
implementation
procedure DefaultEmitWarning(s:string);
begin
ShowMessage('WARNING: '+s);
end;
procedure DefaultEmitError(s:string);
begin
Assert(False,'ERROR: '+s);
end;
procedure DefaultPushProgress;
begin
end;
procedure DefaultUpdateProgress(Position:Single;Caption:string);
begin
end;
procedure DefaultPopProgress;
begin
end;
function CenterString(s:string;l:Integer):string;
var
t:Boolean;
begin
Result:=s;
t:=False;
while Length(Result)<l do begin
if t then
Result:=Result+' '
else
Result:=' '+Result;
t:=not t;
end;
end;
function TableItemToString(Item:TTableItem):string;
begin
case Item.ItemType of
tipAccept:Result:='ACC';
tipError:Result:='';
tipShift:Result:='d'+IntToStr(Item.Count);
tipReduce:Result:='r'+IntToStr(Item.ID);
tipGoto:Result:=IntToStr(Item.Index);
end;
end;
{procedure DisplayLaws(Grammar:TGrammar);
var
a,b,c,d:Integer;
s,t:string;
const
l=10;
begin
Grammar.BuildFirst;
Grammar.BuildNext;
d:=0;
for a:=0 to Grammar.FLaws.Count-1 do
with TOrGrammarItem(Grammar.FLaws[a]) do begin
s:=Name+' -->';
for b:=0 to FSubItems.Count-1 do begin
t:='';
with TAndGrammarItem(FSubItems[b]) do
for c:=0 to FSubItems.Count-1 do
t:=t+' '+TNodeGrammarItem(FSubItems[c]).Name;
Form1.Memo5.Lines.Add('('+IntToStr(d)+') '+s+t);
Inc(d);
end;
end;
Form1.Memo5.Lines.Add('');
for a:=0 to Grammar.FLaws.Count-1 do
with TOrGrammarItem(Grammar.FLaws[a]) do begin
s:=Name+' : [';
t:='';
for b:=0 to FFirst.Count-1 do begin
s:=s+t+TTokenGrammarItem(FFirst[b]).Name;
t:=' , ';
end;
s:=s+'] ; [';
t:='';
for b:=0 to FNext.Count-1 do begin
s:=s+t+TTokenGrammarItem(FNext[b]).Name;
t:=' , ';
end;
Form1.Memo5.Lines.Add(s+']');
end;
Form1.Memo5.Lines.Add('');
s:='|'+CenterString('état',l)+'|';
for a:=0 to Grammar.FNodes.Count-1 do
s:=s+CenterString(Grammar.FNodes[a],l)+'|';
Form1.Memo5.Lines.Add(s);
with Grammar.BuildAnalyseTable do
for a:=0 to RowCount-1 do begin
s:='|'+CenterString(IntToStr(a),l)+'|';
for b:=0 to ColCount-1 do
s:=s+CenterString(TableItemToString(Item[a,b]),l)+'|';
Form1.Memo5.Lines.Add(s);
end;
Form1.Memo5.Lines.Add('');
end;}
{ TObjectSet }
function TObjectSet.Add(AObject: TObject): Boolean;
begin
Result:=not Contains(AObject);
if Result then
inherited Add(AObject);
end;
function TObjectSet.AddSet(ASet: TObjectSet):Boolean;
var
a:Integer;
begin
Result:=False;
for a:=0 to ASet.Count-1 do
Result:=Add(ASet[a]) or Result;
end;
function TObjectSet.Contains(AObject: TObject): Boolean;
begin
Result:=IndexOf(AObject)>-1;
end;
{ TNullItemSet }
function TNullItemSet.Add(Law: TAndGrammarItem; Position: Cardinal; Grammar: TGrammar): Boolean;
var
p:PNullItem;
a:Integer;
begin
Result:=False;
for a:=0 to Count-1 do
if (Items[a].Law=Law) and (Items[a].Position=Position) then
Exit;
New(p);
p^.Law:=Law;
p^.Position:=Position;
p^.LawParent:=nil;
for a:=0 to Grammar.FLaws.Count-1 do
with Grammar.FLaws[a] as TOrGrammarItem do
if FSubItems.IndexOf(Law)>-1 then
p^.LawParent:=Grammar.FLaws[a] as TOrGrammarItem;
Assert(Assigned(p^.LawParent));
inherited Add(p);
Result:=True;
end;
procedure TNullItemSet.Close;
var
a,b:Integer;
t:Boolean;
begin
repeat
t:=False;
for a:=0 to Count-1 do
with Items[a] do
if Position<Cardinal(Law.FSubItems.Count) then
with Law.FSubItems[Position] as TNodeGrammarItem do
if FGrammar.FLaws.IndexOf(Law.FSubItems[Position])>-1 then
with Law.FSubItems[Position] as TOrGrammarItem do
for b:=0 to Count-1 do
t:=Add(Item[b],0,FGrammar) or t;
until not t;
end;
destructor TNullItemSet.Destroy;
begin
while Count>0 do begin
Dispose(inherited Items[0]);
Delete(0);
end;
inherited;
end;
function TNullItemSet.GetItems(Index: Integer): TNullItem;
begin
Result:=PNullItem(inherited Items[Index])^;
end;
function TNullItemSet.IsEmpty: Boolean;
begin
Result:=Count=0;
end;
function TNullItemSet.IsEqualTo(ASet: TNullItemSet): Boolean;
var
a,b:Integer;
begin
Result:=Count=ASet.Count;
if not Result then
Exit;
for a:=0 to Count-1 do begin
Result:=False;
for b:=0 to ASet.Count-1 do
if (Items[a].Law=ASet[b].Law) and (Items[a].Position=ASet[b].Position) then begin
Result:=True;
Break;
end;
if not Result then
Exit;
end;
end;
function TNullItemSet.Transition(ALaw: TNodeGrammarItem): TNullItemSet;
var
a:Integer;
begin
Result:=TNullItemSet.Create;
for a:=0 to Count-1 do
with Items[a] do
if (Position<Cardinal(Law.LawCount)) and (Law.Law[Position]=ALaw) then
Result.Add(Law,Position+1,LawParent.FGrammar);
Result.Close;
end;
{ TNullItemSetCollection }
function TNullItemSetCollection.Add(ASet: TNullItemSet): Boolean;
begin
Result:=not Contains(ASet);
if Result then
inherited Add(ASet);
end;
function TNullItemSetCollection.Contains(ASet: TNullItemSet): Boolean;
var
a:Integer;
begin
Result:=False;
for a:=0 to Count-1 do
Result:=Result or Items[a].IsEqualTo(ASet);
end;
function TNullItemSetCollection.GetItems(Index: Integer): TNullItemSet;
begin
Result:=(inherited Items[Index]) as TNullItemSet;
end;
function TNullItemSetCollection.IndexOf(ASet: TNullItemSet): Integer;
var
a:Integer;
begin
Result:=-1;
for a:=0 to Count-1 do
if Items[a].IsEqualTo(ASet) then begin
Result:=a;
Exit;
end;
end;
{ TAnalyseRow }
constructor TAnalyseRow.Create(ACount: Integer);
var
a:Integer;
p:PTableItem;
begin
inherited Create;
for a:=0 to ACount-1 do begin
New(p);
FillChar(p^,SizeOf(TTableItem),0);
p^.ItemType:=tipError;
Add(p);
end;
end;
destructor TAnalyseRow.Destroy;
begin
while Count>0 do begin
Dispose(inherited Items[0]);
Delete(0);
end;
inherited;
end;
function TAnalyseRow.GetItem(Index: Integer): TTableItem;
begin
Result:=PTableItem(inherited Items[Index])^;
end;
procedure TAnalyseRow.SetItem(Index: Integer; const Value: TTableItem);
begin
PTableItem(inherited Items[Index])^:=Value;
end;
{ TAnalyseTable }
function LawByIndex(AGrammar:TGrammar;Index:Integer):TAndGrammarItem;
var
a:Integer;
begin
Result:=nil;
for a:=0 to AGrammar.FLaws.Count-1 do
with (AGrammar.FLaws[a] as TOrGrammarItem) do
if FSubItems.Count>Index then
Result:=Item[Index]
else
Dec(Index,FSubItems.Count);
end;
function LawToString(AGrammar:TGrammar;Index,LawIndex:Integer):string;
var
l:TOrGrammarItem;
a:Integer;
begin
l:=nil;
for a:=0 to AGrammar.FLaws.Count-1 do
with (AGrammar.FLaws[a] as TOrGrammarItem) do
if Count>Index then begin
l:=AGrammar.FLaws[a] as TOrGrammarItem;
Break;
end else
Dec(Index,Count);
if Assigned(l) then begin
Result:=l.FName+' ->';
with l.FSubItems[Index] as TAndGrammarItem do
for a:=0 to LawCount-1 do
Result:=Result+' '+Law[a].Name;
if LawIndex<AGrammar.FNodes.Count then
with AGrammar.FNodes.Objects[LawIndex] as TNodeGrammarItem do
Result:=Result+' | '+Name;
end else
Result:='Error';
end;
function CompareLaw(u,v:TAndGrammarItem):Boolean;
var
a:Integer;
begin
Result:=Assigned(u) and
Assigned(v) and
(u.LawCount=v.LawCount) and
(u.FImplementationBlock=v.FImplementationBlock);
if Result then
for a:=0 to u.LawCount-1 do
Result:=Result and (u.Law[a]=v.Law[a]);
end;
procedure TAnalyseTable.CheckReduceConflict(ARow, ACol: Integer;
Item: TTableItem);
var
i:TTableItem;
s:string;
begin
i:=Self.Item[ARow,ACol];
case i.ItemType of
tipAccept:EmitWarning('Accept/Reduce conflict');
tipError:;
tipShift:begin
s:='Shift/Reduce conflict'#13;
s:=s+LawToString(FGrammar,Item.ID,ACol)+#13;
EmitWarning(s);
end;
tipReduce:begin
if not CompareLaw(LawByIndex(FGrammar,i.ID),LawByIndex(FGrammar,Item.ID)) then begin
s:='Reduce/Reduce conflict'#13;
s:=s+LawToString(FGrammar,i.ID,ACol)+#13;
s:=s+LawToString(FGrammar,Item.ID,ACol)+#13;
EmitWarning(s);
end;
end;
tipGoto:EmitWarning('Goto/Reduce conflict');
end;
Self.Item[ARow,ACol]:=Item
end;
constructor TAnalyseTable.Create(ACollection: TNullItemSetCollection;
AGrammar: TGrammar);
var
a,b,c,d:Integer;
Item:TNullItemSet;
i:TTableItem;
begin
inherited Create;
FGrammar:=AGrammar;
FColCount:=AGrammar.FNodes.Count-1;
FList:=TObjectList.Create(True);
FCollection:=ACollection;
for a:=0 to FCollection.Count-1 do
FList.Add(TAnalyseRow.Create(FColCount));
PushProgress;
try
for a:=0 to FCollection.Count-1 do begin
UpdateProgress(a/FCollection.Count,'Building row '+IntToStr(a)+'/'+IntToStr(FCollection.Count));
for b:=0 to AGrammar.FNodes.Count-1 do begin
Item:=FCollection[a].Transition(AGrammar.FNodes.Objects[b] as TNodeGrammarItem);
c:=FCollection.IndexOf(Item);
if c>-1 then begin
if (AGrammar.FNodes.Objects[b] as TNodeGrammarItem).IsLeaf then begin
i.ItemType:=tipShift;
i.Count:=c;
end else begin
i.ItemType:=tipGoto;
i.Index:=c;
end;
Self[a,b]:=i;
end;
end;
for b:=0 to FCollection[a].Count-1 do
with FCollection[a].Items[b] do
if Position=Cardinal(Law.LawCount) then
for c:=0 to LawParent.FNext.Count-1 do begin
i.ItemType:=tipReduce;
i.ID:=AGrammar.IndexOfLaw(Law);
d:=AGrammar.FNodes.IndexOfObject(LawParent.FNext[c] as TNodeGrammarItem);
CheckReduceConflict(a,d,i);
end;
end;
finally
PopProgress;
end;
a:=AGrammar.FNodes.IndexOfObject(AGrammar.FMain);
Assert(Self[0,a].ItemType=tipGoto);
b:=AGrammar.FNodes.IndexOf('$');
i.ItemType:=tipAccept;
Self[Self[0,a].Index,b]:=i;
end;
destructor TAnalyseTable.Destroy;
begin
FList.Destroy;
FCollection.Destroy;
inherited;
end;
function TAnalyseTable.GetItem(ARow, ACol: Integer): TTableItem;
begin
Result:=(FList[ARow] as TAnalyseRow).Item[ACol];
end;
function TAnalyseTable.GetRowCount: Integer;
begin
Result:=FList.Count;
end;
procedure TAnalyseTable.SetItem(ARow, ACol: Integer;
const Value: TTableItem);
begin
(FList[ARow] as TAnalyseRow).Item[ACol]:=Value;
end;
{ TAndGrammarItem }
constructor TAndGrammarItem.Create(SubItems: array of TNodeGrammarItem;
AImplementationBlock: string);
var
a:Integer;
begin
inherited Create;
FSubItems:=TObjectList.Create(False);
for a:=Low(SubItems) to High(SubItems) do
FSubItems.Add(SubItems[a]);
FImplementationBlock:=AImplementationBlock;
SetLength(FUsage,0);
end;
destructor TAndGrammarItem.Destroy;
begin
SetLength(FUsage,0);
FSubItems.Destroy;
inherited;
end;
function TAndGrammarItem.GetLaw(Index: Integer): TNodeGrammarItem;
begin
Result:=FSubItems[Index] as TNodeGrammarItem;
end;
function TAndGrammarItem.GetLawCount: Integer;
begin
Result:=FSubItems.Count;
end;
function TAndGrammarItem.GetUsageCount: Integer;
var
a:Integer;
begin
Result:=LawCount-High(FUsage)-1;
for a:=0 to High(FUsage) do
if FUsage[a] then
Inc(Result);
end;
function TAndGrammarItem.GetUsedLawItem(Index: Integer): Boolean;
begin
if Index>High(FUsage) then
Result:=True
else
Result:=FUsage[Index];
end;
procedure TAndGrammarItem.InsertSubItem(Index: Integer;
Item: TNodeGrammarItem);
begin
FSubitems.Insert(Index,Item);
end;
procedure TAndGrammarItem.SetUsedLawItem(Index: Integer;
const Value: Boolean);
var
a,b:Integer;
begin
if (Index>High(FUsage)) and not Value then begin
b:=High(FUsage);
SetLength(FUsage,Index+1);
for a:=b+1 to Index-1 do
FUsage[a]:=True;
end;
if Index<=high(FUsage) then
FUsage[Index]:=Value;
end;
{ TNodeGrammarItem }
constructor TNodeGrammarItem.Create(AGrammar: TGrammar);
begin
inherited Create;
FGrammar:=AGrammar;
FGrammar.FNodes.AddObject(Name,Self);
FFirst:=TObjectSet.Create(False);
end;
destructor TNodeGrammarItem.Destroy;
begin
FFirst.Destroy;
FGrammar.FNodes.Delete(ID);
inherited;
end;
function TNodeGrammarItem.GetID: Cardinal;
begin
Result:=FGrammar.FNodes.IndexOfObject(Self);
end;
{ TTokenGrammarItem }
constructor TTokenGrammarItem.Create(AGrammar: TGrammar; AName: string);
begin
FName:=AName;
inherited Create(AGrammar);
end;
function TTokenGrammarItem.GetName: string;
begin
Result:=FName;
end;
function TTokenGrammarItem.GetUserFriendlyName: string;
begin
if FUserFriendlyName='' then
Result:=Name
else
Result:=FUserFriendlyName;
end;
function TTokenGrammarItem.IsLeaf: Boolean;
begin
Result:=True;
end;
procedure TTokenGrammarItem.SetName(const Value: string);
begin
FName:=Value;
FGrammar.FNodes[ID]:=FName;
end;
procedure TTokenGrammarItem.SetUserFriendlyName(const Value: string);
begin
FUserFriendlyName:=Value;
end;
{ TEOFGrammarItem }
function TEOFGrammarItem.GetName: string;
begin
Result:='$';
end;
function TEOFGrammarItem.GetUserFriendlyName: string;
begin
Result:='end of file';
end;
function TEOFGrammarItem.IsLeaf: Boolean;
begin
Result:=True;
end;
procedure TEOFGrammarItem.SetName(const Value: string);
begin
Assert(False);
end;
procedure TEOFGrammarItem.SetUserFriendlyName(const Value: string);
begin
Assert(False);
end;
{ TErrorGrammarItem }
function TErrorGrammarItem.GetName: string;
begin
Result:='Error';
end;
function TErrorGrammarItem.GetUserFriendlyName: string;
begin
Result:='error';
end;
function TErrorGrammarItem.IsLeaf: Boolean;
begin
Result:=True;
end;
procedure TErrorGrammarItem.SetName(const Value: string);
begin
Assert(False);
end;
procedure TErrorGrammarItem.SetUserFriendlyName(const Value: string);
begin
Assert(False);
end;
{ TOrGrammarItem }
constructor TOrGrammarItem.Create(AGrammar: TGrammar;
SubItems: array of TAndGrammarItem; AName, AType, ADeclarationBlock: string);
var
a:Integer;
begin
if AName='' then
FName:='Item'+IntToStr(AGrammar.FNodes.Count-1)
else
FName:=AName;
inherited Create(AGrammar);
FGrammar.FLaws.Add(Self);
FSubItems:=TObjectList.Create(True);
for a:=Low(SubItems) to High(SubItems) do
FSubItems.Add(SubItems[a]);
FType:=AType;
FDeclarationBlock:=ADeclarationBlock;
FNext:=TObjectSet.Create(False);
if Name='Main' then
FGrammar.FMain:=Self;
end;
destructor TOrGrammarItem.Destroy;
begin
FNext.Destroy;
FSubItems.Destroy;
FGrammar.FLaws.Remove(Self);
inherited;
end;
function TOrGrammarItem.GetCount: Integer;
begin
Result:=FSubItems.Count;
end;
function TOrGrammarItem.GetItem(Index: Integer): TAndGrammarItem;
begin
Result:=FSubItems[Index] as TAndGrammarItem;
end;
function TOrGrammarItem.GetName: string;
begin
Result:=FName;
end;
function TOrGrammarItem.GetUserFriendlyName: string;
begin
if FUserFriendlyName='' then
Result:=Name
else
Result:=FUserFriendlyName;
end;
procedure TOrGrammarItem.InsertItem(Index: Integer; Item: TAndGrammarItem);
begin
FSubItems.Insert(Index,Item);
end;
function TOrGrammarItem.IsLeaf: Boolean;
begin
Result:=False;
end;
procedure TOrGrammarItem.SetName(const Value: string);
begin
FName:=Value;
FGrammar.FNodes[ID]:=FName;
end;
procedure TOrGrammarItem.SetUserFriendlyName(const Value: string);
begin
FUserFriendlyName:=Value;
end;
{ TGrammar }
function TGrammar.BuildAnalyseTable: TAnalyseTable;
var
Collection:TNullItemSetCollection;
Item:TNullItemSet;
NullLaw:TAndGrammarItem;
NullAxiom:TOrGrammarItem;
a,b:Integer;
t:Boolean;
begin
BuildFirst;
BuildNext;
Collection:=TNullItemSetCollection.Create(True);
NullLaw:=TAndGrammarItem.Create([FMain]);
NullAxiom:=TOrGrammarItem.Create(Self,[NullLaw],'NullAxiom');
Item:=TNullItemSet.Create;
Item.Add(NullLaw,0,Self);
Item.Close;
Collection.Add(Item);
PushProgress;
try
repeat
UpdateProgress(0,'Enumerating states ('+IntToStr(Collection.Count)+' found so far)');
t:=False;
for a:=0 to Collection.Count-1 do
for b:=0 to FNodes.Count-1 do begin
Item:=Collection[a].Transition(FNodes.Objects[b] as TNodeGrammarItem);
if Item.IsEmpty then begin
Item.Destroy;
Continue;
end;
if Collection.Add(Item) then
t:=True
else
Item.Destroy;
end;
until not t;
finally
PopProgress;
end;
Result:=TAnalyseTable.Create(Collection,Self);
NullAxiom.Destroy;
end;
procedure TGrammar.BuildFirst;
var
a,b:Integer;
t:Boolean;
begin
for a:=0 to FNodes.Count-1 do
with FNodes.Objects[a] as TNodeGrammarItem do
if IsLeaf then
FFirst.Add(FNodes.Objects[a]);
repeat
t:=False;
for a:=0 to FLaws.Count-1 do
with (FLaws[a] as TOrGrammarItem) do
for b:=0 to Count-1 do
with Item[b] do
t:=FFirst.AddSet((FSubItems[0] as TNodeGrammarItem).FFirst) or t;
until not t;
end;
procedure TGrammar.BuildNext;
var
a,b,c:Integer;
t:Boolean;
// n:TNodeGrammarItem;
begin
Assert(Assigned(FMain));
FMain.FNext.Add(FEOF);
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do
for b:=0 to Count-1 do
with Item[b].FSubItems do
for c:=0 to Count-2 do
with Items[c] as TNodeGrammarItem do
if not IsLeaf then
with Items[c] as TOrGrammarItem do
with Items[c+1] as TNodeGrammarItem do
FNext.AddSet(FFirst);
{ for c:=0 to Count-2 do begin
n:=Items[c] as TNodeGrammarItem;
if not n.IsLeaf then
with n as TOrGrammarItem do
with (FLaws[a] as TOrGrammarItem).FSubItems[c+1] as TNodeGrammarItem do
FNext.AddSet(FFirst);
end;}
repeat
t:=False;
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do
for b:=0 to Count-1 do
with Item[b].FSubItems do
with Items[Count-1] as TNodeGrammarItem do
if not IsLeaf then
with Items[Item[b].FSubItems.Count-1] as TOrGrammarItem do
t:=FNext.AddSet((FLaws[a] as TOrGrammarItem).FNext) or t;
until not t;
end;
constructor TGrammar.Create(ATokenList: TStringList);
var
a:Integer;
begin
inherited Create;
FNodes:=TStringList.Create;
FNodes.CaseSensitive:=True;
FLaws:=TObjectList.Create(False);
for a:=0 to ATokenList.Count-1 do
TTokenGrammarItem.Create(Self,ATokenList[a]);
FEOF:=TEOFGrammarItem.Create(Self);
end;
destructor TGrammar.Destroy;
begin
FLaws.Destroy;
FNodes.Destroy;
inherited;
end;
function TGrammar.GetItem(Name: string): TNodeGrammarItem;
var
a:Integer;
begin
Result:=nil;
a:=FNodes.IndexOf(Name);
if a>-1 then
Result:=FNodes.Objects[a] as TNodeGrammarItem
else
Assert(False,'"'+Name+'" is not defined.');
end;
function TGrammar.GetLawCount: Integer;
begin
Result:=FLaws.Count;
end;
function TGrammar.GetLawItem(Name: string): TOrGrammarItem;
var
a:Integer;
begin
Result:=nil;
a:=FNodes.IndexOf(Name);
if a>-1 then
Result:=TOrGrammarItem(FNodes.Objects[a]);
if Assigned(Result) and not (TObject(Result) is TOrGrammarItem) then
Result:=nil;
Assert(Assigned(Result),'Law "'+Name+'" is not defined.');
end;
function TGrammar.GetTokenItem(Name: string): TTokenGrammarItem;
var
a:Integer;
begin
Result:=nil;
for a:=0 to FNodes.Count-1 do
if (FNodes.Objects[a] is TTokenGrammarItem) and ((FNodes.Objects[a] as TTokenGrammarItem).Name=Name) then begin
Result:=FNodes.Objects[a] as TTokenGrammarItem;
Exit;
end;
Assert(False,'Token "'+Name+'" is not defined.');
end;
function TGrammar.IndexOfLaw(Law: TAndGrammarItem): Integer;
var
a,b,c:Integer;
begin
Result:=-1;
c:=0;
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do
for b:=0 to Count-1 do begin
if Item[b]=Law then begin
Result:=c;
Exit;
end;
Inc(c);
end;
end;
{ TLexerItemGrammar }
function AreTokenEquivalent(t1,t2:TTokenGrammarItem;LawList:TStringList):Boolean;
var
a,b,c,d:Integer;
l:TObjectList;
t:Boolean;
begin
Result:=True;
l:=TObjectList.Create(False);
for a:=0 to LawList.Count-1 do
with LawList.Objects[a] as TOrGrammarItem do
for b:=0 to Count-1 do begin
t:=False;
with Item[b] do
for c:=0 to LawCount-1 do
t:=t or (Law[c]=t1) or (Law[c]=t2);
if not t then
Continue;
l.Clear;
for c:=0 to Count-1 do
if Item[b].LawCount=Item[c].LawCount then
l.Add(Item[c]);
with Item[b] do
for c:=0 to LawCount-1 do
for d:=l.Count-1 downto 0 do
if not ((((l[d] as TAndGrammarItem).Law[c]=Law[c]) and (Law[c]<>t1) and (Law[c]<>t2)) or
(((l[d] as TAndGrammarItem).Law[c]=t1) and (Law[c]=t2)) or
(((l[d] as TAndGrammarItem).Law[c]=t2) and (Law[c]=t1))) then
l.Delete(d);
if l.Count=0 then
Result:=False;
end;
l.Destroy;
end;
constructor TLexerItemGrammar.Create(TokenList, LawList: TStringList);
var
a,b,c,d:Integer;
i:TAndGrammarItem;
j:TTokenGrammarItem;
EquivalentClasses,l:TObjectList;
NewTokens:TStringList;
s:string;
t:Boolean;
function FindTokenClass(i:TTokenGrammarItem):TTokenGrammarItem;
var
a,b:Integer;
begin
Result:=nil;
for a:=0 to EquivalentClasses.Count-1 do
with EquivalentClasses[a] as TObjectList do
for b:=0 to Count-1 do
if Items[b]=i then
Result:=FNodes.Objects[a] as TTokenGrammarItem;
end;
procedure Substitute(FromItem:TOrGrammarItem;ToItem:TNodeGrammarItem);
var
a,b,c:Integer;
begin
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do
for b:=0 to Count-1 do
with Item[b] do
for c:=0 to LawCount-1 do
if Law[c]=FromItem then
FSubItems[c]:=ToItem;
end;
begin
EquivalentClasses:=TObjectList.Create(True);
l:=TObjectList.Create(False);
for a:=0 to TokenList.Count-1 do
l.Add(TokenList.Objects[a]);
EquivalentClasses.Add(l);
repeat
l:=TObjectList.Create(False);
with EquivalentClasses[EquivalentClasses.Count-1] as TObjectList do begin
j:=Items[0] as TTokenGrammarItem;
for b:=Count-1 downto 1 do begin
if not AreTokenEquivalent(j,Items[b] as TTokenGrammarItem,LawList) then begin
l.Add(Items[b]);
Delete(b);
end;
end;
end;
if l.Count>0 then
EquivalentClasses.Add(l);
until l.Count=0;
l.Destroy;
FillChar(FCharMap,SizeOf(FCharMap),0);
NewTokens:=TStringList.Create;
NewTokens.CaseSensitive:=True;
for a:=0 to EquivalentClasses.Count-1 do
with EquivalentClasses[a] as TObjectList do begin
s:='';
for b:=0 to Count-1 do
with Items[b] as TTokenGrammarItem do
if s='' then
s:=Name
else
s:=s+','+Name;
NewTokens.Add('{'+s+'}');
end;
inherited Create(NewTokens);
NewTokens.Destroy;
for a:=0 to EquivalentClasses.Count-1 do
with EquivalentClasses[a] as TObjectList do
for b:=0 to Count-1 do
with Items[b] as TTokenGrammarItem do
FCharMap[Chr(ID)]:=FNodes.Objects[a] as TTokenGrammarItem;
for a:=0 to 255 do
if not Assigned(FCharMap[Chr(a)]) then
FCharMap[Chr(a)]:=FEOF;
for a:=0 to LawList.Count-1 do
TOrGrammarItem.Create(Self,[],LawList[a]);
FMain:=FLaws[0] as TOrGrammarItem;
FStored:=(LawList.Objects[0] as TOrGrammarItem).Storable;
for a:=0 to LawList.Count-1 do
with LawList.Objects[a] as TOrGrammarItem do
for b:=0 to Count-1 do begin
i:=TAndGrammarItem.Create([]);
with Self.Item[Name] as TOrGrammarItem do
InsertItem(Count,i);
with Item[b] do
for c:=0 to LawCount-1 do
with Law[c] do
if IsLeaf then
i.InsertSubItem(i.LawCount,FindTokenClass(Law[c] as TTokenGrammarItem))
else
i.InsertSubItem(i.LawCount,Self.LawItem[Name]);
end;
EquivalentClasses.Destroy;
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do
for b:=0 to Count-1 do
for c:=Count-1 downto b+1 do begin
t:=Item[b].LawCount=Item[c].LawCount;
if t then
for d:=0 to Item[b].LawCount-1 do
t:=t and (Item[b].Law[d]=Item[c].Law[d]);
if t then
FSubItems.Delete(c);
end;
for a:=FLaws.Count-1 downto 0 do
with FLaws[a] as TOrGrammarItem do
if Count=1 then
with Item[0] do
if (LawCount=1) and ((FLaws[a]<>FMain) or not Law[0].IsLeaf) then begin
if FLaws[a]=FMain then begin
FMain:=Law[0] as TOrGrammarItem;
FMain.Name:=(FLaws[a] as TOrGrammarItem).Name;
end;
Substitute(FLaws[a] as TOrGrammarItem,Law[0]);
FLaws[a].Destroy;
end;
end;
{ TLexer }
function TLexer.BuildLexerDefinition: TLexerDefinition;
var
a,b,c:Integer;
d:Word;
t:TAnalyseTable;
u:TLexerTable;
begin
BuildSeparateGrammars;
Result.LexerTablesCount:=FRootLexerItems.Count;
GetMem(Result.LexerTables,FRootLexerItems.Count*SizeOf(TLexerTable));
d:=0;
PushProgress;
try
for a:=0 to FRootLexerItems.Count-1 do begin
UpdateProgress(a/FRootLexerItems.Count,'LEXER: building table '+IntToStr(a)+'/'+IntToStr(FRootLexerItems.Count)+' ('+FRootLexerItems[a]+')');
t:=(FRootLexerItems.Objects[a] as TGrammar).BuildAnalyseTable;
u.Height:=t.RowCount;
u.Width:=t.ColCount;
GetMem(u.TableItems,t.RowCount*t.ColCount*SizeOf(TTableItem));
with FRootLexerItems.Objects[a] as TGrammar do
for b:=0 to FNodes.Count-1 do
with FNodes.Objects[b] as TNodeGrammarItem do
if not IsLeaf then
with FNodes.Objects[b] as TOrGrammarItem do
Assert(Count>0);
for b:=0 to t.RowCount-1 do
for c:=0 to t.ColCount-1 do
case t[b,c].ItemType of
tipAccept:u.TableItems[b*t.ColCount+c].ItemType:=titAccept;
tipError:u.TableItems[b*t.ColCount+c].ItemType:=titError;
tipShift:begin
u.TableItems[b*t.ColCount+c].ItemType:=titShift;
u.TableItems[b*t.ColCount+c].Value:=t[b,c].Count;
end;
tipReduce:begin
u.TableItems[b*t.ColCount+c].ItemType:=titReduce;
u.TableItems[b*t.ColCount+c].Value:=t[b,c].ID+d;
end;
tipGoto:begin
u.TableItems[b*t.ColCount+c].ItemType:=titGoto;
u.TableItems[b*t.ColCount+c].Value:=t[b,c].Index;
end;
end;
with FRootLexerItems.Objects[a] as TLexerItemGrammar do begin
u.EOFId:=FNodes.IndexOfObject(FEOF);
for b:=0 to 255 do
u.CharMap[Chr(b)]:=FCharMap[Chr(b)].ID;
u.Stored:=Stored;
end;
t.Destroy;
with FRootLexerItems.Objects[a] as TGrammar do
for b:=0 to FLaws.Count-1 do
with FLaws[b] as TOrGrammarItem do
Inc(d,Count);
Result.LexerTables[a]:=u;
end;
finally
PopProgress;
end;
Result.LexerEOFId:=FRootLexerItems.Count;
Result.LexerLawsCount:=d;
GetMem(Result.LexerLaws,d*SizeOf(TLexerLaw));
d:=0;
for a:=0 to FRootLexerItems.Count-1 do
with FRootLexerItems.Objects[a] as TGrammar do
for b:=0 to FLaws.Count-1 do
with FLaws[b] as TOrGrammarItem do
for c:=0 to Count-1 do
with Item[c] do begin
Result.LexerLaws[d].ChildsCount:=LawCount;
Result.LexerLaws[d].ID:=FNodes.IndexOfObject(FLaws[b]);
Inc(d);
end;
Result.StaticResource:=False;
end;
function TLexer.BuildPascalLexerDefinitions(Prefix, CRLF: string): string;
begin
Result:=ConvertLexerDefinitionToPascalDeclaration(BuildLexerDefinition,Prefix,'',CRLF);
end;
procedure TLexer.BuildSeparateGrammars;
var
l1,l2:TStringList;
a,b,c,d,e:Integer;
begin
if FBuilt then
Exit;
MakeProper;
l1:=TStringList.Create;
l2:=TStringList.Create;
for a:=0 to FRootLexerItems.Count-1 do begin
l1.Clear;
l2.Clear;
l2.AddObject(FRootLexerItems[a],LawItem[FRootLexerItems[a]]);
repeat
e:=l2.Count;
for b:=l2.Count-1 downto 0 do
with l2.Objects[b] as TOrGrammarItem do
for c:=0 to Count-1 do
with Item[c] do
for d:=0 to LawCount-1 do
with Law[d] do
if IsLeaf then begin
if l1.IndexOf(Name)=-1 then
l1.AddObject(Name,Law[d])
end else begin
if l2.IndexOf(Name)=-1 then
l2.AddObject(Name,Law[d]);
end;
until l2.Count=e;
FRootLexerItems.Objects[a]:=TLexerItemGrammar.Create(l1,l2);
end;
l1.Destroy;
l2.Destroy;
FBuilt:=True;
end;
constructor TLexer.Create(ALaws:TStringList);
var
a:Integer;
l:TStringList;
begin
l:=TStringList.Create;
for a:=0 to 255 do
l.Add('#'+IntToStr(a));
inherited Create(l);
l.Destroy;
FRootLexerItems:=TStringList.Create;
FRootLexerItems.CaseSensitive:=True;
FRootLexerItems.AddStrings(ALaws);
for a:=0 to FRootLexerItems.Count-1 do
TOrGrammarItem.Create(Self,[],FRootLexerItems[a]);
end;
destructor TLexer.Destroy;
begin
FRootLexerItems.Destroy;
inherited;
end;
procedure AddNullSubstitution(o:TOrGrammarItem;a:TAndGrammarItem;Index,Placement:Integer);
var
b,c:Integer;
t:Boolean;
i:TAndGrammarItem;
begin
t:=False;
for b:=0 to o.Count-1 do
if o.Item[b].LawCount=a.LawCount-1 then begin
t:=True;
for c:=0 to a.LawCount-2 do
if c<Index then
t:=t and (o.Item[b].Law[c]=a.Law[c])
else
t:=t and (o.Item[b].Law[c]=a.Law[c+1]);
if t then
Break;
end;
if not t then begin
i:=TAndGrammarItem.Create([]);
for b:=0 to a.LawCount-1 do
if b<>Index then
i.InsertSubItem(i.LawCount,a.Law[b]);
o.InsertItem(Placement,i);
end;
end;
procedure TLexer.MakeProper;
var
a,b,c,d:Integer;
l:TObjectList;
begin
l:=TObjectList.Create(False);
repeat
d:=l.Count;
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do
for b:=Count-1 downto 0 do begin
with Item[b] do
for c:=0 to LawCount-1 do
if l.IndexOf(Law[c])>-1 then
AddNullSubstitution(FLaws[a] as TOrGrammarItem,Item[b],c,b+1);
if Item[b].LawCount=0 then
if l.IndexOf(FLaws[a])=-1 then
l.Add(FLaws[a]);
end;
until l.Count=d;
l.Destroy;
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do begin
for b:=Count-1 downto 0 do
if Item[b].LawCount=0 then
FSubItems.Delete(b);
if Count=0 then
EmitError('Single null production not allowed.');
end;
end;
{ TParser }
function TParser.BuildIParser: IParser;
var
i:ILexer;
begin
i:=TDefaultLexer.Create(FLexer.BuildLexerDefinition);
Result:=TDefaultParser.Create(i,BuildParserDefinition);
end;
function TParser.BuildLexerDefinition: TLexerDefinition;
begin
Result:=FLexer.BuildLexerDefinition;
end;
function TParser.BuildParserDefinition: TParserDefinition;
var
a,b,c,d:Integer;
begin
FLexer.BuildSeparateGrammars;
with BuildAnalyseTable do begin
Result.TableWidth:=ColCount;
Result.TableHeight:=RowCount;
GetMem(Result.ParserTable,ColCount*RowCount*Sizeof(TTableItem));
for a:=0 to RowCount-1 do
for b:=0 to ColCount-1 do
with Item[a,b] do
case ItemType of
tipAccept:Result.ParserTable[a*ColCount+b].ItemType:=titAccept;
tipError:Result.ParserTable[a*ColCount+b].ItemType:=titError;
tipShift:begin
Result.ParserTable[a*ColCount+b].ItemType:=titShift;
Result.ParserTable[a*ColCount+b].Value:=Count;
end;
tipReduce:begin
Result.ParserTable[a*ColCount+b].ItemType:=titReduce;
Result.ParserTable[a*ColCount+b].Value:=ID;
end;
tipGoto:begin
Result.ParserTable[a*ColCount+b].ItemType:=titGoto;
Result.ParserTable[a*ColCount+b].Value:=Index;
end;
end;
b:=0;
for a:=0 to FNodes.Count-1 do
with FNodes.Objects[a] as TNodeGrammarItem do
if not IsLeaf then
with (FNodes.Objects[a] as TOrGrammarItem) do
Inc(b,Count);
Result.ParserLawsCount:=b;
GetMem(Result.ParserLaws,b*SizeOf(TParserLaw));
b:=0;
for a:=0 to FNodes.Count-1 do
with FNodes.Objects[a] as TNodeGrammarItem do
if not IsLeaf then
with (FNodes.Objects[a] as TOrGrammarItem) do begin
for c:=0 to Count-1 do
with Item[c] do begin
Result.ParserLaws[b+c].ChildsCount:=LawCount;
Result.ParserLaws[b+c].ID:=a;
Result.ParserLaws[b+c].UsageCount:=UsageCount;
GetMem(Result.ParserLaws[b+c].Usage,LawCount*SizeOf(Boolean));
for d:=0 to LawCount-1 do
Result.ParserLaws[b+c].Usage[d]:=UsedLawItem[d];
end;
Inc(b,Count)
end;
Result.TokenNamesCount:=FNodes.Count;
GetMem(Result.TokenNames,FNodes.Count*SizeOf(string));
ZeroMemory(Result.TokenNames,FNodes.Count*SizeOf(string));
for a:=0 to FNodes.Count-1 do
with FNodes.Objects[a] as TNodeGrammarItem do
if FLexer.FNodes.IndexOf(Name)>-1 then
Result.TokenNames[a]:=FLexer.Item[Name].UserFriendlyName
else
Result.TokenNames[a]:=UserFriendlyName;
Destroy;
end;
Result.StaticResource:=False;
end;
function TParser.BuildPascalClassDeclaration(Prefix, CRLF: string): string;
var
a:Integer;
begin
Result:='type'+Crlf+Crlf+
' T'+Prefix+'Executer=class(TDefaultExecuter)'+CRLF+
' private'+CRLF;
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do
if FType='' then
Result:=Result+
' procedure ExecuteNode'+IntToStr(a)+'(Node:TParserNode);'+CRLF
else
Result:=Result+
' function ExecuteNode'+IntToStr(a)+'(Node:TParserNode):'+FType+';'+CRLF;
Result:=Result+' protected'+CRLF+
' class function GetParser:IParser;override;'+CRLF+
' public'+CRLF;
if FMain.FType='' then
Result:=Result+
' procedure Execute(Handler:IExecuterExceptionHandler);'+CRLF
else
Result:=Result+
' function Execute(Handler:IExecuterExceptionHandler):'+FMain.FType+';'+CRLF;
Result:=Result+
' end;'+CRLF+CRLF;
end;
function TParser.BuildPascalClassImplementation(Prefix,
CRLF: string): string;
var
a,b,c,d,e:Integer;
s,t,u,v:string;
begin
c:=0;
for a:=0 to FLaws.Count-1 do
with FLaws[a] as TOrGrammarItem do begin
if FType='' then
Result:=Result+
'procedure T'+Prefix+'Executer.ExecuteNode'+IntToStr(a)+'(Node:TParserNode);'+CRLF
else
Result:=Result+
'function T'+Prefix+'Executer.ExecuteNode'+IntToStr(a)+'(Node:TParserNode):'+FType+';'+CRLF;
if FDeclarationBlock<>'' then
Result:=Result+
FDeclarationBlock+CRLF;
Result:=Result+
'begin'+CRLF+
' FErrorOffset:=Node.CharOffset;'+CRLF+
' case Node.ID of'+CRLF;
for b:=0 to Count-1 do
with Item[b] do begin
s:=' '+IntToStr(c)+':begin'+CRLF+
FImplementationBlock+CRLF+
' end;'+CRLF;
s:=AnsiReplaceStr(s,'##','Result');
s:=AnsiReplaceStr(s,'@@','Node.CharOffset');
s:=AnsiReplaceStr(s,'§§','Node.CharLength');
e:=0;
for d:=0 to LawCount-1 do begin
t:='';
if UsedLawItem[d] then begin
if Law[d].IsLeaf and (Law[d]<>FError) then begin
with FLexer.FRootLexerItems.Objects[Law[d].ID] as TLexerItemGrammar do
if Stored then begin
if e=0 then
t:='ExecuteLeaf(Node.SubNodes^)'
else
t:='ExecuteLeaf(ExtractSubParserNode(Node,'+IntToStr(e)+'))';
if e=0 then
u:='Node.SubNodes^.CharOffset'
else
u:='ExtractSubParserNode(Node,'+IntToStr(e)+').CharOffset';
if e=0 then
v:='Node.SubNodes^.CharLength'
else
v:='ExtractSubParserNode(Node,'+IntToStr(e)+').CharLength';
end;
end else begin
if d=0 then
t:='ExecuteNode'+IntToStr(FLaws.IndexOf(Law[d]))+'(Node.SubNodes^)'
else
t:='ExecuteNode'+IntToStr(FLaws.IndexOf(Law[d]))+'(ExtractSubParserNode(Node,'+IntToStr(e)+'))';
if d=0 then
u:='Node.SubNodes^.CharOffset'
else
u:='ExtractSubParserNode(Node,'+IntToStr(e)+').CharOffset';
if d=0 then
v:='Node.SubNodes^.CharLength'
else
v:='ExtractSubParserNode(Node,'+IntToStr(e)+').CharLength';
end;
Inc(e);
end;
if (t='') and (Pos('#'+IntToStr(d+1),s)>0) then
EmitWarning('Parameter #'+IntToStr(d+1)+' is used but not defined in the code section number '+IntToStr(d+1)+' of '+Name+'.');
s:=AnsiReplaceStr(s,'#'+IntToStr(d+1),t);
if (t='') and (Pos('@'+IntToStr(d+1),s)>0) then
EmitWarning('Parameter position @'+IntToStr(d+1)+' is used but not defined in the code section number '+IntToStr(d+1)+' of '+Name+'.');
s:=AnsiReplaceStr(s,'@'+IntToStr(d+1),u);
if (t='') and (Pos('§'+IntToStr(d+1),s)>0) then
EmitWarning('Parameter length §'+IntToStr(d+1)+' is used but not defined in the code section number '+IntToStr(d+1)+' of '+Name+'.');
s:=AnsiReplaceStr(s,'§'+IntToStr(d+1),u);
end;
Result:=Result+s;
Inc(c);
end;
Result:=Result+
' else'+CRLF+
' raise TObject.Create;'+CRLF+
// ' Assert(False,''Fatal parser error'');'+CRLF+
' end;'+CRLF+
'end;'+CRLF+CRLF;
end;
if FMain.FType='' then
Result:=Result+
'procedure T'+Prefix+'Executer.Execute(Handler:IExecuterExceptionHandler);'+CRLF+
'begin'+CRLF+
' FHandler:=Handler;'+CRLF+
' try'+CRLF+
' try'+CRLF+
' ExecuteNode'+IntToStr(FLaws.IndexOf(FMain))+'(FNode);'+CRLF+
' except'+CRLF+
' on e:TObject do'+CRLF+
' if (not Assigned(FHandler)) or (not FHandler.RaiseException(e,FErrorOffset)) then'+CRLF+
' raise;'+CRLF+
' else'+CRLF+
' if (not Assigned(FHandler)) or (not FHandler.RaiseUnknownException(FErrorOffset)) then'+CRLF+
' raise;'+CRLF+
' end;'+CRLF+
' finally'+CRLF+
' FHandler:=nil;'+CRLF+
' end;'+CRLF+
'end;'+CRLF+CRLF
else
Result:=Result+
'function T'+Prefix+'Executer.Execute(Handler:IExecuterExceptionHandler):'+FMain.FType+';'+CRLF+
'begin'+CRLF+
' FHandler:=Handler;'+CRLF+
' try'+CRLF+
' try'+CRLF+
' Result:=ExecuteNode'+IntToStr(FLaws.IndexOf(FMain))+'(FNode);'+CRLF+
' except'+CRLF+
' on e:TObject do'+CRLF+
' if (not Assigned(FHandler)) or (not FHandler.RaiseException(e,FErrorOffset)) then'+CRLF+
' raise;'+CRLF+
' else'+CRLF+
' if (not Assigned(FHandler)) or (not FHandler.RaiseUnknownException(FErrorOffset)) then'+CRLF+
' raise;'+CRLF+
' end;'+CRLF+
' finally'+CRLF+
' FHandler:=nil;'+CRLF+
' end;'+CRLF+
'end;'+CRLF+CRLF;
Result:=Result+
'class function T'+Prefix+'Executer.GetParser:IParser;'+CRLF+
'begin'+CRLF+
' Result:=TDefaultParser.Create(TDefaultLexer.Create('+Prefix+'LexerDefinition),'+Prefix+'ParserDefinition);'+CRLF+
'end;'+CRLF+CRLF
end;
function TParser.BuildPascalDefinitions(Prefix, CRLF: string): string;
begin
Result:=ConvertLexerDefinitionToPascalDeclaration(FLexer.BuildLexerDefinition,Prefix,'',CRLF);
Result:=Result+ConvertParserDefinitionToPascalDeclaration(BuildParserDefinition,Prefix,'',CRLF);
end;
function TParser.BuildPascalLexerDefinitions(Prefix, CRLF: string): string;
begin
Result:=ConvertLexerDefinitionToPascalDeclaration(FLexer.BuildLexerDefinition,Prefix,'',CRLF);
end;
function TParser.BuildPascalParserDefinitions(Prefix,
CRLF: string): string;
begin
Result:=ConvertParserDefinitionToPascalDeclaration(BuildParserDefinition,Prefix,'',CRLF);
end;
constructor TParser.Create(ALexer: TLexer; APreImplementationBlock,
APostImplementationBlock: string);
begin
inherited Create(ALexer.FRootLexerItems);
FError:=TErrorGrammarItem.Create(Self);
FLexer:=ALexer;
FPreImplementationBlock:=APreImplementationBlock;
FPostImplementationBlock:=APostImplementationBlock;
end;
end.
|
unit FreeOTFEExplorerfmeOptions_WebDAV;
interface
uses
Classes, fmeBaseOptions,
Controls, Dialogs, ExtCtrls, Forms,
FreeOTFEExplorerfmeOptions_Base,
ExplorerSettings, Graphics, Messages, SDUFilenameEdit_U, SDUFrames,
SDUStdCtrls, Shredder, Spin64,
StdCtrls, SysUtils, Variants, Windows;
type
TfmeOptions_FreeOTFEExplorerWebDAV = class (TfmeCommonExplorerOptions)
gbWebDAV: TGroupBox;
ckWebDAV: TSDUCheckBox;
cbDrive: TComboBox;
lblDefaultDriveLetter: TLabel;
gbWebDAVAdvanced: TGroupBox;
fedWebDAVLogDebug: TSDUFilenameEdit;
fedWebDAVLogAccess: TSDUFilenameEdit;
edWebDAVShareName: TEdit;
Label6: TLabel;
ckExploreAfterMount: TSDUCheckBox;
ckPromptMountSuccessful: TSDUCheckBox;
ckOverwriteCacheOnDismount: TSDUCheckBox;
ckWebDAVLogAccess: TSDUCheckBox;
ckWebDAVLogDebug: TSDUCheckBox;
procedure ControlChanged(Sender: TObject);
procedure ckWebDAVClick(Sender: TObject);
procedure ckWebDAVLogAccessClick(Sender: TObject);
procedure ckWebDAVLogDebugClick(Sender: TObject);
PRIVATE
FWarnUserChangesRequireRemount: Boolean;
PROTECTED
procedure _ReadSettings(config: TExplorerSettings); OVERRIDE;
procedure _WriteSettings(config: TExplorerSettings); OVERRIDE;
PUBLIC
procedure Initialize(); OVERRIDE;
procedure EnableDisableControls(); OVERRIDE;
end;
implementation
{$R *.dfm}
uses
frmCommonOptions,
CommonSettings,
lcConsts, OTFE_U,
OTFEFreeOTFEBase_U,
lcDialogs,
SDUGeneral,
SDUi18n;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
const
CONTROL_MARGIN_LBL_TO_CONTROL = 5;
resourcestring
USE_DEFAULT = 'Use default';
procedure TfmeOptions_FreeOTFEExplorerWebDAV.ckWebDAVLogAccessClick(Sender: TObject);
begin
inherited;
EnableDisableControls();
end;
procedure TfmeOptions_FreeOTFEExplorerWebDAV.ckWebDAVClick(Sender: TObject);
begin
inherited;
if SDUOSVistaOrLater() then begin
SDUMessageDlg(
RS_DRIVEMAPPING_NOT_SUPPORTED_UNDER_VISTA_AND_7 +
SDUCRLF + SDUParamSubstitute(
_(
'Mounted volumes will only be mapped to drive letters when %1 is run under Windows 2000/Windows XP'),
[Application.Title]),
mtInformation
);
end else
if FWarnUserChangesRequireRemount then begin
SDUMessageDlg(
_('The changes you make here will only take effect when you next mount a container'),
mtInformation
);
FWarnUserChangesRequireRemount := False;
end;
EnableDisableControls();
end;
procedure TfmeOptions_FreeOTFEExplorerWebDAV.ckWebDAVLogDebugClick(Sender: TObject);
begin
inherited;
EnableDisableControls();
end;
procedure TfmeOptions_FreeOTFEExplorerWebDAV.ControlChanged(Sender: TObject);
begin
inherited;
EnableDisableControls();
end;
procedure TfmeOptions_FreeOTFEExplorerWebDAV.EnableDisableControls();
begin
inherited;
SDUEnableControl(ckExploreAfterMount, ckWebDAV.Checked);
SDUEnableControl(ckPromptMountSuccessful, ckWebDAV.Checked);
SDUEnableControl(cbDrive, ckWebDAV.Checked);
SDUEnableControl(gbWebDAVAdvanced, ckWebDAV.Checked);
SDUEnableControl(fedWebDAVLogAccess,
(ckWebDAV.Checked and
ckWebDAVLogAccess.Checked
));
SDUEnableControl(fedWebDAVLogDebug, (ckWebDAV.Checked and
ckWebDAVLogDebug.Checked
));
if not (ckWebDAVLogAccess.Checked) then begin
fedWebDAVLogAccess.Filename := '';
end;
if not (ckWebDAVLogDebug.Checked) then begin
fedWebDAVLogDebug.Filename := '';
end;
end;
procedure TfmeOptions_FreeOTFEExplorerWebDAV.Initialize();
var
driveLetter: Char;
begin
inherited;
FWarnUserChangesRequireRemount := True;
SDUCenterControl(gbWebDAV, ccHorizontal);
SDUCenterControl(gbWebDAV, ccVertical, 25);
cbDrive.Items.Clear();
cbDrive.Items.Add(USE_DEFAULT);
// for driveLetter:='C' to 'Z' do
for driveLetter := 'A' to 'Z' do begin
cbDrive.Items.Add(driveLetter + ':');
end;
end;
procedure TfmeOptions_FreeOTFEExplorerWebDAV._ReadSettings(config: TExplorerSettings);
var
prevWarnUserChangesRequireRemount: Boolean;
begin
// Temporarily set FWarnUserChangesRequireRemount to FALSE - otherwise we'll
// get the warning message as the frame is loaded!
prevWarnUserChangesRequireRemount := FWarnUserChangesRequireRemount;
FWarnUserChangesRequireRemount := False;
ckWebDAV.Checked := config.OptWebDAVEnableServer;
FWarnUserChangesRequireRemount := prevWarnUserChangesRequireRemount;
ckExploreAfterMount.Checked := config.OptExploreAfterMount;
ckPromptMountSuccessful.Checked := config.OptPromptMountSuccessful;
// Default drive letter
if (config.OptDefaultDriveLetter = #0) then begin
cbDrive.ItemIndex := 0;
end else begin
cbDrive.ItemIndex := cbDrive.Items.IndexOf(config.OptDefaultDriveLetter + ':');
end;
ckOverwriteCacheOnDismount.Checked := config.OptOverwriteWebDAVCacheOnDismount;
edWebDAVShareName.Text := config.OptWebDavShareName;
fedWebDAVLogAccess.Filename := config.OptWebDavLogAccess;
fedWebDAVLogDebug.Filename := config.OptWebDavLogDebug;
ckWebDAVLogAccess.Checked := (trim(fedWebDAVLogAccess.Filename) <> '');
ckWebDAVLogDebug.Checked := (trim(fedWebDAVLogDebug.Filename) <> '');
end;
procedure TfmeOptions_FreeOTFEExplorerWebDAV._WriteSettings(config: TExplorerSettings);
begin
config.OptWebDAVEnableServer := ckWebDAV.Checked;
config.OptExploreAfterMount := ckExploreAfterMount.Checked;
config.OptPromptMountSuccessful := ckPromptMountSuccessful.Checked;
// Default drive letter
if (cbDrive.ItemIndex = 0) then begin
config.OptDefaultDriveLetter := #0;
end else begin
config.OptDefaultDriveLetter := DriveLetterChar(cbDrive.Items[cbDrive.ItemIndex][1]);
end;
config.OptOverwriteWebDAVCacheOnDismount := ckOverwriteCacheOnDismount.Checked;
config.OptWebDavShareName := edWebDAVShareName.Text;
config.OptWebDavLogDebug := fedWebDAVLogDebug.Filename;
config.OptWebDavLogAccess := fedWebDAVLogAccess.Filename;
end;
end.
|
{ ******************************************************* }
{ *
{* uMatch.pas
{* Delphi Implementation of the Class Match
{* Generated by Enterprise Architect
{* Created on: 09-févr.-2015 11:44:54
{* Original author: Labelleg
{*
{******************************************************* }
unit xmltvdb.Match;
interface
uses System.Generics.Collections, xmltvdb.MatchAccuracy, xmltvdb.TVDBEpisode,
xmltvdb.TVDBSeries, System.Classes;
type
IMatch = interface
function Getaccuracy: TMatchAccuracy;
function GetmatchingEpisodes: TVDBEpisodeColl;
function Getseries: ITVDBSeries;
// function CompareTo(Value: IMatch): Integer;
end;
TMatch = class (TInterfacedObject,IMatch)
strict private
Faccuracy: TMatchAccuracy;
FmatchingEpisodes: TVDBEpisodeColl;
Fseries: ITVDBSeries;
public
function Getaccuracy: TMatchAccuracy;
function GetmatchingEpisodes: TVDBEpisodeColl;
function Getseries: ITVDBSeries;
function CompareTo(Value: IMatch): Integer;
constructor Create(matchAccuracy: TMatchAccuracy; series: ITVDBSeries; matchingEpisodes: TVDBEpisodeColl);
destructor Destroy; override;
end;
TMatchColl = class(TList<IMatch>)
//// TMatchColl = class(TObjectList<TMatch>)
public
procedure Sort; overload;
constructor Create();
destructor Destroy; override;
// class function Compare(valeur1,valeur2 : IMatch):integer;
end;
implementation
uses
System.SysUtils, System.Generics.Defaults, System.Math;
{ implementation of Match }
function TMatch.CompareTo(Value: IMatch): Integer;
begin
// Result := Self.Faccuracy. .ge return this.accuracy.compareTo(accuracy);
raise Exception.Create('Code no complété');
end;
constructor TMatch.Create(matchAccuracy: TMatchAccuracy; series: ITVDBSeries; matchingEpisodes: TVDBEpisodeColl);
begin
inherited Create;
Self.FmatchingEpisodes := matchingEpisodes;
Self.Faccuracy := matchAccuracy;
Self.Fseries := series;
end;
destructor TMatch.Destroy;
begin
inherited;
end;
function TMatch.Getaccuracy: TMatchAccuracy;
begin
Result:= Faccuracy;
end;
function TMatch.GetmatchingEpisodes: TVDBEpisodeColl;
begin
Result := FmatchingEpisodes;
end;
function TMatch.Getseries: ITVDBSeries;
begin
Result:= Fseries;
end;
{ TMatchColl }
//class function TMatchColl.Compare(valeur1, valeur2: IMatch): integer;
//begin
// raise Exception.Create('Error Message');
//end;
constructor TMatchColl.Create;
begin
inherited Create;
//OwnsObjects := true;
end;
//
destructor TMatchColl.Destroy;
begin
inherited;
end;
procedure TMatchColl.Sort;
begin
Self.Sort( TComparer<IMatch>.Construct(
function(const Item1,Item2:IMatch): Integer
begin
Result := CompareValue( Ord( Item1.Getaccuracy) ,Ord(Item2.Getaccuracy));
end));
end;
end.
|
object fmSpecific: TfmSpecific
Left = 228
Top = 149
BorderStyle = bsDialog
Caption = 'Specific'
ClientHeight = 190
ClientWidth = 205
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
PixelsPerInch = 96
TextHeight = 13
object Panel1: TPanel
Left = 0
Top = 159
Width = 205
Height = 31
Align = alBottom
BevelOuter = bvNone
TabOrder = 1
object Panel2: TPanel
Left = 20
Top = 0
Width = 185
Height = 31
Align = alRight
BevelOuter = bvNone
TabOrder = 0
object btOk: TBitBtn
Left = 23
Top = 2
Width = 75
Height = 25
Caption = 'OK'
Default = True
TabOrder = 0
OnClick = btOkClick
Glyph.Data = {
DE010000424DDE01000000000000760000002800000024000000120000000100
0400000000006801000000000000000000001000000000000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333
3333333333333333333333330000333333333333333333333333F33333333333
00003333344333333333333333388F3333333333000033334224333333333333
338338F3333333330000333422224333333333333833338F3333333300003342
222224333333333383333338F3333333000034222A22224333333338F338F333
8F33333300003222A3A2224333333338F3838F338F33333300003A2A333A2224
33333338F83338F338F33333000033A33333A222433333338333338F338F3333
0000333333333A222433333333333338F338F33300003333333333A222433333
333333338F338F33000033333333333A222433333333333338F338F300003333
33333333A222433333333333338F338F00003333333333333A22433333333333
3338F38F000033333333333333A223333333333333338F830000333333333333
333A333333333333333338330000333333333333333333333333333333333333
0000}
NumGlyphs = 2
end
object BitBtn2: TBitBtn
Left = 104
Top = 2
Width = 75
Height = 25
TabOrder = 1
Kind = bkCancel
end
end
end
object Panel3: TPanel
Left = 0
Top = 0
Width = 205
Height = 159
Align = alClient
BevelOuter = bvNone
BorderWidth = 5
TabOrder = 0
object GroupBox1: TGroupBox
Left = 5
Top = 5
Width = 195
Height = 149
Align = alClient
Caption = 'Columns'
TabOrder = 0
object Label1: TLabel
Left = 10
Top = 55
Width = 30
Height = 13
Caption = 'Value:'
end
object rbNewValue: TRadioButton
Left = 7
Top = 15
Width = 75
Height = 17
Caption = 'NewValue'
Checked = True
TabOrder = 0
TabStop = True
end
object rbOldValue: TRadioButton
Left = 7
Top = 31
Width = 75
Height = 17
Caption = 'OldValue'
TabOrder = 1
end
object rbType: TRadioButton
Left = 82
Top = 16
Width = 52
Height = 17
Caption = 'Type'
TabOrder = 2
end
object rbAddress: TRadioButton
Left = 82
Top = 32
Width = 65
Height = 17
Caption = 'Address'
TabOrder = 3
end
object edValue: TEdit
Left = 47
Top = 51
Width = 139
Height = 21
TabOrder = 5
end
object rbHint: TRadioButton
Left = 141
Top = 16
Width = 47
Height = 17
Caption = 'Hint'
TabOrder = 4
end
object GroupBox2: TGroupBox
Left = 9
Top = 76
Width = 178
Height = 64
Caption = 'Operations'
TabOrder = 6
object rbRemove: TRadioButton
Left = 4
Top = 16
Width = 63
Height = 17
Caption = 'Remove'
Checked = True
TabOrder = 0
TabStop = True
OnClick = rbChangeClick
end
object rbSelect: TRadioButton
Left = 67
Top = 17
Width = 53
Height = 15
Caption = 'Select'
TabOrder = 1
OnClick = rbChangeClick
end
object rbCheck: TRadioButton
Left = 120
Top = 17
Width = 53
Height = 15
Caption = 'Check'
TabOrder = 2
OnClick = rbChangeClick
end
object rbChange: TRadioButton
Left = 4
Top = 38
Width = 63
Height = 17
Caption = 'Change'
TabOrder = 3
OnClick = rbChangeClick
end
object edChange: TEdit
Left = 70
Top = 36
Width = 100
Height = 21
Color = clBtnFace
Enabled = False
TabOrder = 4
end
end
end
end
end
|
unit AsConvertOpTest;
interface
uses
DUnitX.TestFramework,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TAsConvertOpTest = class(TObject)
public
[Test]
procedure AsInteger();
[Test]
procedure AsUInt32();
[Test]
procedure AsInt64();
[Test]
procedure AsUInt64();
end;
implementation
[Test]
procedure TAsConvertOpTest.AsInteger();
var
temp: TIntXLibUInt32Array;
n: Integer;
IntX: TIntX;
un: UInt32;
begin
IntX := TIntX.Create(High(UInt32));
Assert.WillRaise(
procedure
begin
IntX.AsInteger;
end, EOverflowException);
n := 1234567890;
IntX := n;
Assert.AreEqual(n, Integer(IntX));
n := -n;
IntX := n;
Assert.AreEqual(n, Integer(IntX));
n := 0;
IntX := n;
Assert.AreEqual(n, Integer(IntX));
n := 1234567890;
un := UInt32(n);
SetLength(temp, 3);
temp[0] := un;
temp[1] := un;
temp[2] := un;
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(temp, False);
IntX.AsInteger;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(temp, True);
IntX.AsInteger;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(High(Integer)) + 10;
IntX.AsInteger;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(Low(Integer)) - 10;
IntX.AsInteger;
end, EOverflowException);
end;
[Test]
procedure TAsConvertOpTest.AsUInt32();
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
n: UInt32;
begin
n := 1234567890;
IntX := n;
Assert.AreEqual(n, UInt32(IntX));
n := 0;
IntX := n;
Assert.AreEqual(n, UInt32(IntX));
n := 1234567890;
SetLength(temp, 3);
temp[0] := n;
temp[1] := n;
temp[2] := n;
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(temp, False);
IntX.AsUInt32;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(High(UInt32)) + 10;
IntX.AsUInt32;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(Low(UInt32)) - 10;
IntX.AsUInt32;
end, EOverflowException);
end;
[Test]
procedure TAsConvertOpTest.AsInt64();
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
n: Int64;
un: UInt32;
ni: Integer;
begin
n := 1234567890123456789;
IntX := n;
Assert.AreEqual(n, Int64(IntX));
n := -n;
IntX := n;
Assert.AreEqual(n, Int64(IntX));
n := 0;
IntX := n;
Assert.AreEqual(n, Int64(IntX));
un := 1234567890;
SetLength(temp, 5);
temp[0] := un;
temp[1] := un;
temp[2] := un;
temp[3] := un;
temp[4] := un;
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(temp, False);
IntX.AsInt64;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(temp, True);
IntX.AsInt64;
end, EOverflowException);
ni := 1234567890;
n := ni;
IntX := ni;
Assert.AreEqual(n, Int64(IntX));
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(High(Int64)) + 10;
IntX.AsInt64;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(Low(Int64)) - 10;
IntX.AsInt64;
end, EOverflowException);
end;
[Test]
procedure TAsConvertOpTest.AsUInt64();
var
temp: TIntXLibUInt32Array;
IntX: TIntX;
n: UInt64;
un: UInt32;
begin
n := 1234567890123456789;
IntX := n;
Assert.AreEqual(n, UInt64(IntX));
n := 0;
IntX := n;
Assert.AreEqual(n, UInt64(IntX));
un := 1234567890;
SetLength(temp, 5);
temp[0] := un;
temp[1] := un;
temp[2] := un;
temp[3] := un;
temp[4] := un;
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(temp, False);
IntX.AsUInt64;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(High(UInt64)) + 10;
IntX.AsUInt64;
end, EOverflowException);
Assert.WillRaise(
procedure
begin
IntX := TIntX.Create(Low(UInt64)) - 10;
IntX.AsUInt64;
end, EOverflowException);
end;
initialization
TDUnitX.RegisterTestFixture(TAsConvertOpTest);
end.
|
unit Main;
// Description: MouseRNG Test Application
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
MouseRNG, StdCtrls, ComCtrls, SDUDialogs;
const
TARGET_BIT_COUNT = 20000;
type
TfrmMain = class(TForm)
reReport: TRichEdit;
reBytes: TRichEdit;
reBitsCSV: TRichEdit;
Label3: TLabel;
Label2: TLabel;
pbWriteTextFile: TButton;
pbWriteBinaryFile: TButton;
SaveDialog1: TSDUSaveDialog;
Label4: TLabel;
ckEnableRNG: TCheckBox;
RichEdit1: TRichEdit;
MouseRNG1: TMouseRNG;
Label1: TLabel;
lblBitCount: TLabel;
procedure ckEnableRNGClick(Sender: TObject);
procedure pbWriteTextFileClick(Sender: TObject);
procedure pbWriteBinaryFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure MouseRNG1BitGenerated(Sender: TObject; random: Byte);
procedure MouseRNG1ByteGenerated(Sender: TObject; random: Byte);
procedure MouseRNG1DEBUGSampleTakenEvent(Sender: TObject; X,
Y: Integer);
private
sampleCount: integer;
randomBitCount: integer;
randomByteCount: integer;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.DFM}
procedure TfrmMain.ckEnableRNGClick(Sender: TObject);
begin
MouseRNG1.enabled := ckEnableRNG.checked;
end;
procedure TfrmMain.pbWriteTextFileClick(Sender: TObject);
begin
if SaveDialog1.Execute() then
begin
reBytes.Lines.SaveToFile(SaveDialog1.Filename);
end;
end;
procedure TfrmMain.pbWriteBinaryFileClick(Sender: TObject);
var
strAllData: string;
currByte: byte;
dataFile: THandle;
byteWritten: cardinal;
i: integer;
begin
if SaveDialog1.Execute() then
begin
strAllData := reBytes.Text;
dataFile := CreateFile(
PChar(SaveDialog1.Filename),
GENERIC_WRITE,
FILE_SHARE_READ,
nil,
OPEN_ALWAYS,
0,
0
);
if not(dataFile<>INVALID_HANDLE_VALUE) then
begin
showmessage('Unable to open file for writing.');
end
else
begin
for i:=0 to (reBytes.lines.count-1) do
begin
currByte:= strtoint(reBytes.lines[i]);
if not(WriteFile(dataFile, currByte, 1, byteWritten, nil)) then
begin
showmessage('Write failure.');
break;
end;
end;
CloseHandle(dataFile);
end;
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
sampleCount := 0;
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
reReport.PlainText := TRUE;
reBitsCSV.PlainText := TRUE;
reBytes.PlainText := TRUE;
end;
procedure TfrmMain.MouseRNG1BitGenerated(Sender: TObject; random: Byte);
begin
inc(randomBitCount);
if (randomBitCount>1) then
begin
reBitsCSV.Text := reBitsCSV.Text + ',';
end;
reBitsCSV.Text := reBitsCSV.Text + inttostr(random);
lblBitCount.caption := inttostr(randomBitCount);
if (randomBitCount >= TARGET_BIT_COUNT) then
begin
ckEnableRNG.checked := FALSE;
showmessage(inttostr(TARGET_BIT_COUNT)+' random bits generated/');
end;
end;
procedure TfrmMain.MouseRNG1ByteGenerated(Sender: TObject; random: Byte);
begin
inc(randomByteCount);
reBytes.lines.add(inttostr(random));
end;
procedure TfrmMain.MouseRNG1DEBUGSampleTakenEvent(Sender: TObject; X,
Y: Integer);
begin
inc(sampleCount);
reReport.lines.add(inttostr(sampleCount)+' - X='+inttostr(X)+' Y='+inttostr(Y));
end;
END.
|
{: Using materials in a TGLDirectOpenGL OnRender.<p>
This demo shows how to dynamically create materials in a material library
and use them in a TGLDirectOpenGL to render your own stuff.<br>
The render is quite simple: two quads, each with its own texture. The
TGLDirectOpenGL is placed in a small hierarchy with a torus and dummy cube,
and the rotation animation are handled by those two object to show that
the OnRender code uses the hierarchy.
<b>History : </b><font size=-1><ul>
<li>21/04/10 - Yar - Removed direct state changing
</ul></font>
}
unit Unit1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
GLCadencer, GLScene, GLObjects, GLTexture, GLBehaviours,
GLLCLViewer, GLGeomObjects, GLColor, GLCrossPlatform, GLMaterial,
GLCoordinates, GLBaseClasses, GLRenderContextInfo, GLSimpleNavigation;
type
{ TForm1 }
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMaterialLibrary: TGLMaterialLibrary;
GLCamera1: TGLCamera;
DummyCube1: TGLDummyCube;
GLSimpleNavigation1: TGLSimpleNavigation;
Torus1: TGLTorus;
DirectOpenGL1: TGLDirectOpenGL;
GLLightSource1: TGLLightSource;
GLCadencer1: TGLCadencer;
procedure DirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo);
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses OpenGLTokens, GLContext, GLUtils;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
// dynamically create 2 materials and load 2 textures
with GLMaterialLibrary do
begin
with AddTextureMaterial('wood', 'ashwood.jpg') do
begin
Material.FrontProperties.Emission.Color := clrGray50;
Material.FaceCulling := fcNoCull;
end;
with AddTextureMaterial('stone', 'walkway.jpg') do
begin
Material.FrontProperties.Emission.Color := clrGray50;
Material.FaceCulling := fcNoCull;
end;
end;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLSceneViewer1.Invalidate;
end;
procedure TForm1.DirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo);
var
material: TGLLibMaterial;
begin
// 1st quad, textured with 'wood', using standard method
GLMaterialLibrary.ApplyMaterial('wood', rci);
GL.Begin_(GL_QUADS);
GL.TexCoord2f(0, 1);
GL.Vertex3f(0.5, 0.5, -0.5);
GL.TexCoord2f(0, 0);
GL.Vertex3f(-0.5, 0.5, -0.5);
GL.TexCoord2f(1, 0);
GL.Vertex3f(-0.5, 0, 0.5);
GL.TexCoord2f(1, 1);
GL.Vertex3f(0.5, 0, 0.5);
GL.End_;
GLMaterialLibrary.UnApplyMaterial(rci);
// 2nd quad, textured with 'stone'
// we "manually" apply the material, this can be usefull if you want to have
// some dynamic material control
material := GLMaterialLibrary.Materials.GetLibMaterialByName('stone');
material.Material.Apply(rci);
GL.Begin_(GL_QUADS);
GL.TexCoord2f(0, 1);
GL.Vertex3f(0.5, -0.5, -0.5);
GL.TexCoord2f(0, 0);
GL.Vertex3f(0.5, 0, 0.5);
GL.TexCoord2f(1, 0);
GL.Vertex3f(-0.5, 0, 0.5);
GL.TexCoord2f(1, 1);
GL.Vertex3f(-0.5, -0.5, -0.5);
GL.End_;
material.Material.UnApply(rci);
end;
end.
|
unit TopologyAnalyzer;
interface
uses Voxel, VoxelMap;
type
CTopologyAnalyzer = class
private
FMap: TVoxelMap;
// I/O
procedure LoadVoxel(const _Voxel:TVoxelSection);
public
NumVoxels,NumCorrect,Num1Face,Num2Faces,Num3Faces,NumLoneVoxels : longword;
// Constructors and Destructors.
constructor Create(const _Map: TVoxelMap); overload;
constructor Create(const _Voxel: TVoxelSection); overload;
destructor Destroy; override;
procedure Clear;
procedure ResetCounters;
// I/O
procedure Load(const _Voxel:TVoxelSection);
procedure LoadFullVoxel(const _Voxel: TVoxel);
// Execute.
procedure Execute();
// Gets (GUI)
function GetCorrectVoxelsText: string;
function GetNum1FaceText: string;
function GetNum2FacesText: string;
function GetNum3FacesText: string;
function GetLoneVoxelsText: string;
function GetTotalVoxelsText: string;
function GetTopologyScoreText: string;
function GetClassificationText: string;
end;
implementation
uses SysUtils, Normals, BasicMathsTypes, BasicConstants, GLConstants;
// Constructors and Destructors.
constructor CTopologyAnalyzer.Create(const _Map: TVoxelMap);
begin
FMap.Assign(_Map);
ResetCounters;
Execute;
end;
constructor CTopologyAnalyzer.Create(const _Voxel: TVoxelSection);
begin
LoadVoxel(_Voxel);
end;
destructor CTopologyAnalyzer.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure CTopologyAnalyzer.Clear;
begin
FMap.Free;
end;
procedure CTopologyAnalyzer.ResetCounters;
begin
NumVoxels := 0;
NumCorrect := 0;
Num1Face := 0;
Num2Faces := 0;
Num3Faces := 0;
NumLoneVoxels := 0;
end;
// I/O
procedure CTopologyAnalyzer.Load(const _Voxel:TVoxelSection);
begin
Clear;
LoadVoxel(_Voxel);
end;
procedure CTopologyAnalyzer.LoadVoxel(const _Voxel:TVoxelSection);
begin
FMap := TVoxelMap.CreateQuick(_Voxel,1);
FMap.GenerateSurfaceMap;
ResetCounters;
Execute;
end;
procedure CTopologyAnalyzer.LoadFullVoxel(const _Voxel:TVoxel);
var
i : integer;
begin
ResetCounters;
for i := 0 to (_Voxel.Header.NumSections-1) do
begin
Clear;
FMap := TVoxelMap.CreateQuick(_Voxel.Section[i],1);
FMap.GenerateSurfaceMap;
Execute;
end;
end;
// Execute.
procedure CTopologyAnalyzer.Execute();
var
Cube : TNormals;
Direction : TVector3f;
x, y, z, i: longword;
AxisFaces,maxi: byte;
begin
for x := 0 to FMap.GetMaxX do
for y := 0 to FMap.GetMaxY do
for z := 0 to FMap.GetMaxZ do
begin
if FMap.Map[x,y,z] = C_SURFACE then
begin
AxisFaces := 0;
if (FMap.Map[x-1,y,z] >= C_SURFACE) or (FMap.Map[x+1,y,z] >= C_SURFACE) then
begin
inc(AxisFaces);
end;
if (FMap.Map[x,y-1,z] >= C_SURFACE) or (FMap.Map[x,y+1,z] >= C_SURFACE) then
begin
inc(AxisFaces);
end;
if (FMap.Map[x,y,z-1] >= C_SURFACE) or (FMap.Map[x,y,z+1] >= C_SURFACE) then
begin
inc(AxisFaces);
end;
case AxisFaces of
0:
begin
Cube := TNormals.Create(6);
maxi := Cube.GetLastID;
i := 0;
while i <= maxi do
begin
Direction := Cube[i];
if (FMap.Map[x + Round(Direction.X),y + Round(Direction.Y),z + Round(Direction.Z)] >= C_SURFACE) then
begin
inc(Num3Faces);
i := maxi * 2;
end
else
begin
inc(i);
end;
end;
if i < (maxi * 2) then
begin
inc(NumLoneVoxels);
end;
end;
1:
begin
inc(Num2Faces);
end;
2:
begin
inc(Num1Face);
end;
3:
begin
inc(NumCorrect);
end;
end;
inc(NumVoxels);
end;
end;
end;
// Gets
function CTopologyAnalyzer.GetCorrectVoxelsText: string;
begin
Result := IntToStr(NumCorrect) + ' (' + FloatToStrF((100 * NumCorrect) / NumVoxels,ffFixed,12,2) + '%)';
end;
function CTopologyAnalyzer.GetNum1FaceText: string;
begin
Result := IntToStr(Num1Face) + ' (' + FloatToStrF((100 * Num1Face) / NumVoxels,ffFixed,12,2) + '%)';
end;
function CTopologyAnalyzer.GetNum2FacesText: string;
begin
Result := IntToStr(Num2Faces) + ' (' + FloatToStrF((100 * Num2Faces) / NumVoxels,ffFixed,12,2) + '%)';
end;
function CTopologyAnalyzer.GetNum3FacesText: string;
begin
Result := IntToStr(Num3Faces) + ' (' + FloatToStrF((100 * Num3Faces) / NumVoxels,ffFixed,12,2) + '%)';
end;
function CTopologyAnalyzer.GetLoneVoxelsText: string;
begin
Result := IntToStr(NumLoneVoxels) + ' (' + FloatToStrF((100 * NumLoneVoxels) / NumVoxels,ffFixed,12,2) + '%)';
end;
function CTopologyAnalyzer.GetTotalVoxelsText: string;
begin
Result := IntToStr(NumVoxels);
end;
function CTopologyAnalyzer.GetTopologyScoreText: string;
var
Score : single;
begin
if NumLoneVoxels = 0 then
begin
Score := (100 * (NumCorrect - Num2Faces - (2*Num3Faces))) / NumVoxels;
if Score > 0 then
begin
Result := FloatToStrF(Score,ffFixed,12,2) + ' points (out of 100)';
end
else
begin
Result := FloatToStrF(0,ffFixed,12,2) + ' points (out of 100)';
end;
end
else
begin
Result := FloatToStrF(0,ffFixed,12,2) + ' points (out of 100)';
end;
end;
function CTopologyAnalyzer.GetClassificationText: string;
begin
if NumLoneVoxels > 0 then
begin
Result := 'Non-Manifold with Lone Voxels';
end
else if NumCorrect = NumVoxels then
begin
Result := 'Manifold Surface, Unique Normals';
end
else if Num3Faces > 0 then
begin
Result := 'Non-Manifold Volume, Ambiguous Normals';
end
else if Num2Faces > 0 then
begin
Result := 'Manifold Volume, Ambiguous Normals';
end
else
begin
Result := 'Manifold Volume, 2-Sided Normals';
end;
end;
end.
|
unit Stack;
{$POINTERMATH ON}
interface
uses
System.SysUtils;
type
TStack = object
strict protected
FStack: PInteger;
FSize: Integer;
FLength: Integer;
public
property Length: Integer read FLength;
procedure Create(Buffer: Pointer; Size: Integer);
procedure Push<T>(A: T); overload;
function Pop: Integer;
function Get(I: Integer): Integer;
function GetLast: Integer;
end;
implementation
procedure TStack.Create(Buffer: Pointer; Size: Integer);
begin
if (Buffer = nil) or (Size <= 0) then
raise Exception.Create('TStack.Create: Invalid arguments.');
FStack := Buffer;
FSize := Size;
FLength := 0;
end;
function TStack.Get(I: Integer): Integer;
begin
Result := FStack[I];
end;
function TStack.GetLast: Integer;
begin
if FLength <> 0 then
Result := Get(FLength - 1)
else
Result := Get(FLength);
end;
function TStack.Pop: Integer;
begin
if (FStack <> nil) and (FLength > 0) then
begin
Dec(FLength);
Result := PInteger(FStack)[FLength];
end
else
Result := -1;
end;
procedure TStack.Push<T>(A: T);
var
Value: Integer;
begin
if SizeOf(A) > 4 then
raise Exception.Create('TStack.Push: Data with size more than 4 bytes is not supported.')
else
begin
Value := PInteger(@A)^;
case SizeOf(A) of
4: ;
3: Value := Value and $FFFFFF;
2: Value := Value and $FFFF;
1: Value := Value and $FF;
end;
if FStack <> nil then
begin
if FLength = FSize div SizeOf(Integer) then
begin
Move(PInteger(FStack)[1], PInteger(FStack)[0], FLength * SizeOf(Integer) - SizeOf(Integer));
PInteger(FStack)[FLength - 1] := Value;
end
else
begin
PInteger(FStack)[FLength] := Value;
Inc(FLength);
end;
end;
end;
end;
end.
|
{..............................................................................}
{ Summary Common routines to use for the PCB_Scripts project }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Const
Great_Equal = 1;
Less_Equal = 2;
Less_Than = 3;
Great_Than = 4;
{..............................................................................}
{..............................................................................}
Procedure RemoveSpaces(Var Str : AnsiString);
Var
SpacePos : Integer;
Begin
Repeat
SpacePos := Pos(' ', Str);
If SpacePos <> 0 Then
Delete(Str, SpacePos, 1);
Until SpacePos = 0;
End;
{..............................................................................}
{..............................................................................}
Function IsNumber(AChar : Char) : Boolean;
Begin
Result := ('0' <= AChar) And (AChar <= '9');
End;
{..............................................................................}
{..............................................................................}
Function Strip(Var Str : AnsiString) : AnsiString;
Var
t : AnsiString;
LenStr : Integer;
Counter : Integer;
Number : Boolean;
Begin
If Str = '' Then
Result := ''
Else
Begin
LenStr := Length(Str);
Number := IsNumber(Str[1]);
counter := 1;
While (Counter <= LenStr) And (Number = IsNumber(Str[Counter])) Do
Inc(Counter);
t := Copy(Str, 1, Counter - 1);
If Counter <= LenStr Then
Str := Copy(Str, Counter, LenStr - Counter + 1)
Else
Str := '';
If Number Then
t := Copy('00000000' + t, Counter, 8);
Result := t;
End;
End;
{..............................................................................}
{..............................................................................}
Function CompareString(a, b : AnsiString; Comparison : Integer) : Boolean;
Var
a1, b1 : AnsiString;
Begin
Result := False;
RemoveSpaces(a);
RemoveSpaces(b);
Repeat
a1 := Strip(a);
b1 := Strip(b);
Until ((a1 <> b1) Or (a1 = '') And (b1 = ''));
Case Comparison Of
Great_Equal : Result := a1 >= b1;
Less_Equal : Result := a1 <= b1;
Less_Than : Result := a1 < b1;
Great_Than : Result := a1 > b1;
End;
End;
{..............................................................................}
{..............................................................................}
Function LessThan(Const a, b : AnsiString) : Boolean;
Begin
Result := CompareString(a, b, Less_Than);
End;
{..............................................................................}
{..............................................................................}
Function GreatThan(Const a, b : AnsiString) : Boolean;
Begin
Result := CompareString(a, b, Great_Than);
End;
{..............................................................................}
{..............................................................................}
Function SortedListCompare(Const S1, S2 : AnsiString) : Integer;
Begin
If S1 = S2 Then
Result := 0
Else If LessThan(S1, S2) Then
Result := -1
Else If GreatThan(S1, S2) Then
Result := +1
Else
Begin
{Handle the special case N01 and N001 - suffix is numerically same}
{but alphanumerically different}
{So resort to using straight string comparison}
If S1 < S2 Then
Result := -1
Else If S1 > S2 Then
Result := +1
Else
Result := 0;
End;
End;
{..............................................................................}
{..............................................................................}
Function ListSort(List : TStringList; Index1, Index2 : Integer) : integer;
Begin
Result := SortedListCompare(UpperCase(List[Index1]), UpperCase(List[Index2]));
End;
{..............................................................................}
{..............................................................................}
Procedure ExchangeItems(AList : TStringList; L, R : Integer);
Var
tmp : String;
Begin
// note - objects are not exchanged!
tmp := AList[L];
AList[L] := AList[R];
AList[R] := tmp;
End;
{..............................................................................}
{..............................................................................}
Procedure QuickSortStringList(AList : TStringList; L, R : Integer);
Var
I, J, P: Integer;
Begin
If AList.Count = 0 Then Exit;
Repeat
I := L;
J := R;
P := (L + R) shr 1;
Repeat
While ListSort(AList, I, P) < 0 do Inc(I);
While ListSort(AList, J, P) > 0 do Dec(J);
If I <= J Then
Begin
ExchangeItems(AList, I, J);
If P = I Then
P := J
Else if P = J Then
P := I;
Inc(I);
Dec(J);
End;
Until I > J;
If L < J Then
QuickSortStringList(AList, L, J);
L := I;
Until I >= R;
End;
{..............................................................................}
{..............................................................................}
|
unit Amazon.Storage.Service.Intf;
interface
uses System.Classes, Amazon.Storage.Service.API;
type
IAmazonStorageService = interface
['{FDDE1936-EFEB-4EE2-9853-9E56CE020BE2}']
function DownloadFile(const AFileName: string): TMemoryStream;
function ListBuckets: TStrings;
function GetBucket(const ABucketName: string): TAmazonBucketResult;
procedure CreateBucket(const ABucketName: string);
procedure DeleteBucket(const ABucketName: string);
procedure UploadFile(const AFilePath: string); overload;
procedure UploadFile(const AFilePath, AFileName: string); overload;
procedure UploadFile(const AFile: TMemoryStream; AFileName: string); overload;
procedure DeleteFile(const AFileName: string);
end;
implementation
end.
|
unit guiSelectBar;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Imaging.GIFImg, Vcl.StdCtrls, Vcl.Buttons, Vcl.Imaging.pngimage;
type
TFormSelectBar = class(TForm)
pnlHead: TPanel;
imgHG: TImage;
lblSelectedRecipe: TLabel;
btnSelectRecipe: TBitBtn;
lblWs1status: TLabel;
lblWs2status: TLabel;
lblSelectedBar: TLabel;
lblWS1RecipeDscr: TLabel;
imgBG: TImage;
procedure btnSelectRecipeClick(Sender: TObject);
private
procedure BarClick(Sender: TObject);
procedure setBarToPosition(pBarIndex, pPosID: integer);
procedure updateRecipeAndStatus;
function dscrOfWs1Status(iStatus: integer): string;
function dscrOfWs2Status(iStatus: integer): string;
public
procedure selectBar(pvalue: boolean);
procedure setup;
end;
var
FormSelectBar: TFormSelectBar;
implementation uses dOPCDA, uOPCMain, guiMain, dbiMain, guiSelectRecipe;
{$R *.dfm}
{ TFormSelectBar }
const
K_WS1_pos = 25;
K_WS2_pos = 11;
var aBars: array[0 .. 24] of TButton;
_populated: boolean = False;
gBarPosition, gBarEnabled: TdOpcGroup;
kappa, barOnWs1, barOnWs2: integer;
procedure TFormSelectBar.BarClick(Sender: TObject);
var i: integer;
begin
for i := low(aBars) to high(aBars) do begin
if gBarPosition.OPCItems[i].Value = K_WS1_pos then setBarToPosition(i,0); // deseleziono
end;
setBarToPosition((Sender as TButton).tag, K_WS1_pos);
end;
procedure TFormSelectBar.btnSelectRecipeClick(Sender: TObject);
begin
if formSelectRecipe.showModal = mrOK then begin
FormMain.selectedRecipe := formSelectRecipe.selectedRecipe;
lblSelectedRecipe.Caption := Format(' R.: %d %s',
[formSelectRecipe.selectedRecipe, formSelectRecipe.selectedNAME]);
lblWS1RecipeDscr.Caption := Format(' %s',
[formSelectRecipe.selectedDSCR]);
end;
end;
function TFormSelectBar.dscrOfWs1Status(iStatus: integer): string;
begin case iStatus of
0: result := 'no trolley';
2: result := 'trolley in position';
3: result := 'trolley secured';
4: result := 'bar on trolley';
5: result := 'trolley empty';
else result := '>>> ERROR <<<'
end end;
function TFormSelectBar.dscrOfWs2Status(iStatus: integer): string;
begin case iStatus of
0: result := 'no trolley';
2: result := 'trolley in position';
3: result := 'trolley secured';
4: result := 'bar on trolley';
5: result := 'trolley empty';
else result := '>>> ERROR <<<'
end end;
procedure TFormSelectBar.setup;
var i: integer;
begin if _populated then exit;
kappa := ClientWidth div 5;
ClientWidth := kappa * 5;
ClientHeight := kappa * 5 + pnlHead.Height + lblWs2status.Height;
if FileExists('montiEng.png') then imgBG.Picture.LoadFromFile('montiEng.png');
if FileExists('hourGlass.gif') then imgHG.Picture.LoadFromFile('hourGlass.gif');
for i := low(aBars) to high(aBars) do begin
aBars[i] := TButton.Create(Self);
with aBars[i] do begin
Parent := self;
Height := kappa; Width := kappa;
Left := kappa * (i mod 5) - 1;
Top := pnlHead.Height + kappa * (i div 5) - 1;
Caption := IntToStr(i + 1);
Tag := i;
onCLick := BarClick;
end;
end;
lblSelectedBar.Height := kappa;
lblSelectedBar.Width := kappa;
lblSelectedBar.BringToFront;
gBarPosition := MainOPCdlg.getOpcGroupByName('B.Position');
gBarEnabled := MainOPCdlg.getOpcGroupByName('B.Available');
_populated := True;
btnSelectRecipe.Caption := '';
lblSelectedRecipe.Caption := Format(' R.: %d %s',
[FormMain.selectedRecipe, dm.getNameOfRecipe(FormMain.selectedRecipe)]);
lblWS1RecipeDscr.Caption := Format(' %s',
[dm.getDscrOfRecipe(FormMain.selectedRecipe)]);
end;
procedure TFormSelectBar.setBarToPosition(pBarIndex, pPosID: integer);
begin
gBarPosition.OPCItems[pBarIndex].WriteSync(pPosID);
end;
procedure TFormSelectBar.selectBar(pvalue: boolean);
var i, iPosID: integer;
begin
(imgHG.Picture.Graphic as TGIFImage).Animate := not pvalue;
imgHG.Visible := not pvalue;
barOnWs1 := 0; barOnWs2 := 0;
for i := low(aBars) to high(aBars) do begin
iPosID := gBarPosition.OPCItems[i].Value;
if iPosID = K_WS1_pos then begin
barOnWs1 := i + 1;
aBars[i].Visible := False;
end else aBars[i].Visible := pvalue;
aBars[i].Enabled := (iPosID = 0) and gBarEnabled.OPCItems[i].Value;
if iPosID = K_WS2_pos then barOnWs2 := i + 1;
end;
if pvalue and (barOnWs1 > 0) then begin
lblSelectedBar.Caption := IntToStr(barOnWs1);
lblSelectedBar.Left := kappa * ((barOnWs1 - 1) mod 5);
lblSelectedBar.Top := pnlHead.Height + kappa * ((barOnWs1 - 1) div 5);
lblSelectedBar.Visible := True;
end else lblSelectedBar.Visible := False;
updateRecipeAndStatus;
end;
procedure TFormSelectBar.updateRecipeAndStatus;
begin
if FormMain.selectedRecipe <> FormSelectRecipe.selectedRecipe then begin
lblSelectedRecipe.Caption := Format(' R.: %d %s',
[FormMain.selectedRecipe, dm.getNameOfRecipe(FormMain.selectedRecipe)]);
FormSelectRecipe.selectThisRecipe;
lblWS1RecipeDscr.Caption := Format(' %s',
[formSelectRecipe.selectedDSCR]);
end;
lblWs1status.Caption := Format('WS-1 status: %d - %s',
[FormMain.WS1status, dscrOfWs1Status(FormMain.WS1status)]);
if barOnWs1 > 0 then lblWs1status.Caption := Format('%s [%d]',
[lblWs1status.Caption, barOnWs1]);
lblWs2status.Caption := Format('WS-2 status: %d - %s',
[FormMain.WS2status, dscrOfWs2Status(FormMain.WS2status)]);
if barOnWs2 > 0 then lblWs2status.Caption := Format('%s [%d]',
[lblWs2status.Caption, barOnWs2]);
end;
end.
|
unit uIMC;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TFrmIMC = class(TForm)
lblAltura: TLabel;
lblPeso: TLabel;
edtAltura: TEdit;
edtPeso: TEdit;
btnCalcular: TButton;
btnLimpar: TButton;
edtResult: TEdit;
lblResult: TLabel;
procedure btnCalcularClick(Sender: TObject);
procedure btnLimparClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmIMC: TFrmIMC;
implementation
{$R *.dfm}
procedure TFrmIMC.btnCalcularClick(Sender: TObject);
var
altura, peso, res: real;
begin
altura := StrToFloat(edtAltura.Text);
peso := StrToFloat(edtPeso.Text);
res := ((altura * altura) / peso);
if (res < 16) then
begin
edtResult.Text := 'Magresa grave';
end
else
if (res >= 16) and (res <= 17) then
begin
edtResult.Text := 'Magresa moderada';
end
else
if (res > 17) and (res <= 18.5) then
begin
edtResult.Text := 'Magreza leve';
end
else
if (res > 18.5) and (res <= 25) then
begin
edtResult.Text := 'Saudável';
end
else
if (res > 25) and (res <= 30) then
begin
edtResult.Text := 'Sobrepeso';
end
else
if (res > 30) and (res <= 35) then
begin
edtResult.Text := 'Obesidade grau I';
end
else
if (res > 35) and (res <= 40) then
begin
edtResult.Text := 'Obesidade grau II';
end
else
if (res > 40) then
begin
edtResult.Text := 'Obesidade grau III (Mórbida)';
end
end;
procedure TFrmIMC.btnLimparClick(Sender: TObject);
begin
edtAltura.Clear;
edtPeso.Clear;
edtResult.Clear;
end;
procedure TFrmIMC.FormClose(Sender: TObject; var Action: TCloseAction);
begin
action := caFree;
end;
procedure TFrmIMC.FormDestroy(Sender: TObject);
begin
FrmIMC := nil;
end;
end.
|
{
Laz-Model
Copyright (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uLayoutConnector;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Controls, gvector,
uLayoutConcepts, uError;
type
TAnchorPoint = record
Pos: TPoint;
Used: boolean;
Dir: TRelationEnd;
OutPath: TOrthoDir;
end;
TAnchorPoints = Array[apTopLeft..apLeftUpper] of TAnchorPoint;
{
Essentially this class is a mathematical Orthagonal Vector (aka ray).
It is just a point and a direction.
}
TLine = Class
protected
FStartPoint: TPoint;
FDir: TOrthoDir;
function getX: integer;
function getY: integer;
function DebugString: string; virtual;
procedure setX(AValue: integer);
procedure setY(AValue: integer);
procedure Shorten(AValue: integer);
function GetDirectedLength(ALine: TLine): integer; overload;
function GetDirectedLength(APoint: TPoint): integer; overload;
public
constructor Create(StartPoint: TPoint; ADir: TOrthoDir); virtual;
property x: integer read getX write setX;
property y: integer read getY write setY;
property Pos: TPoint read FStartPoint write FStartPoint;
property Dir: TOrthoDir read FDir write FDir;
end;
PTLine = ^TLine;
{
for future rounded corner style connections.
Dir is startpoint tanget for a TArc.
}
TArc = Class(TLine)
private
FRect: TRect;
FRadius: integer;
FAngDir: TAngularRotation;
FSAngle: integer;
FEAngle: integer;
procedure InitialiseArc(EDir: TOrthoDir);
protected
function DebugString: string; override;
public
constructor Create(StartPoint: TPoint; SDir: TOrthoDir; Radius: integer; EDir: TOrthoDir);
procedure Draw(ACanvas: TCanvas);
end;
TPathLines = specialize TVector<TLine>;
{
A path of some description which joins two points.
Being a vector this can be passed to alogritms to be modified before draw.
Adding or removing TLines or its descendents.
}
TPath = class(TPathLines)
private
FEndPoint: TLine;
FRounded: boolean;
FStyle: TPathStyle;
function GetStartPoint: TLine;
public
constructor Create(StartPoint, EndPoint: TLine; Style: TPathStyle);
destructor Destroy; override;
procedure ClearPath;
procedure RoundCorners(Radius: Integer);
procedure Draw(Canvas: TCanvas); virtual;
property StartPoint: TLine read GetStartPoint;
property EndPoint: TLine read FEndPoint write FEndPoint;
property Style: TPathStyle read FStyle write FStyle;
end;
TDecoration = class(TObject)
private
FOrigin: TPoint;
public
constructor Create(AOrigin: TPoint); virtual;
procedure Draw(ACanvas: TCanvas); virtual; abstract;
end;
TStringDecoration = class(TDecoration)
FCaption: string;
public
constructor Create(Caption: string; Origin: TPoint);
procedure Draw(ACanvas: TCanvas); override;
end;
TGraphicDecoration = class(TDecoration)
end;
TOrthoArrowDecoration = class(TGraphicDecoration)
private
FDir: TOrthoDir;
public
procedure Draw(ACanvas: TCanvas; AStyle: TArrowStyle);
constructor Create(AOrigin: TPoint; ADir: TOrthoDir);
end;
TDecs = specialize TVector<TDecoration>;
TDecorations = class(TDecs)
public
procedure Draw(ACanvas: TCanvas; AStyle: TDecorationDisplayStyle);
end;
TDecoratedConnection = class(TPath)
private
FIsDirty: boolean;
FOwner: TControl;
FOwnerEnd: TControl;
FTargetEnd: TControl;
FWantMid: boolean;
FOwnerDecoration: TGraphicDecoration;
FTargetDecoration: TGraphicDecoration;
// temp until associations working
Arrow : TOrthoArrowDecoration;
FArrowStyle: TArrowStyle;
procedure SetOwnerDecoration(AValue: TGraphicDecoration);
procedure SetTargetDecoration(AValue: TGraphicDecoration);
public
Decorations: TDecorations;
constructor Create(AOwner: TControl; AStartPoint, AEndPoint: TLine; AStyle: TPathStyle);
destructor destroy; override;
procedure DrawDecorated(ACanvas: TCanvas; AStyle: TDecorationDisplayStyle = ddsEndpointOnly);
procedure Refresh;
procedure SetEndControls(AOwnerEnd, ATargetEnd: TControl);
property IsDirty: boolean read FIsDirty write FIsDirty;
property WantMid: boolean read FWantMid write FWantMid;
property OwnerEnd: TControl read FOwnerEnd;
property TargetEnd: TControl read FTargetEnd;
property OwnerDecoration: TGraphicDecoration write SetOwnerDecoration;
property TargetDecoration :TGraphicDecoration write SetTargetDecoration;
property ArrowStyle: TArrowStyle read FArrowStyle write FArrowStyle default asEmptyOpen;
end;
implementation
uses essConnectPanel;
{ TDecoration }
constructor TDecoration.Create(AOrigin: TPoint);
begin
inherited Create;
FOrigin := AOrigin;
end;
{ TDecorations }
procedure TDecorations.Draw(ACanvas: TCanvas; AStyle: TDecorationDisplayStyle);
var
it: TVectorEnumerator;
begin
if AStyle > ddsNone then
begin
it := Self.GetEnumerator;
while Assigned(it.Current) do
begin
TDecoration(it.Current).Draw(ACanvas);
end;
it.Free;
end;
end;
{ TArrowDecoration }
constructor TOrthoArrowDecoration.Create(AOrigin: TPoint; ADir: TOrthoDir);
begin
inherited Create(AOrigin);
FDir := ADir;
end;
procedure TOrthoArrowDecoration.Draw(ACanvas: TCanvas; AStyle: TArrowStyle);
var
p1,p2: TPoint;
begin
with ACanvas do
begin
if IsHorizontal[FDir] then
begin
p1.x := FOrigin.x + cArrowLength * oDir[FDir];
p1.y := FOrigin.y + cArrowWidth;
p2.x := FOrigin.x + cArrowLength * oDir[FDir] ;
p2.y := FOrigin.y - cArrowWidth ;
end
else
begin
p1.x := FOrigin.x + cArrowWidth ;
p1.y := FOrigin.y + cArrowLength * oDir[FDir];
p2.x := FOrigin.x - cArrowWidth ;
p2.y := FOrigin.y + cArrowLength * oDir[FDir];
end;
Pen.Width := 1;
Pen.Style := psSolid;
if AStyle = asEmptyClosed then
Polygon([p2,FOrigin, p1])
else
PolyLine([p2,FOrigin,p1]);
end;
end;
{ TDecoratedConnection }
procedure TDecoratedConnection.SetOwnerDecoration(AValue: TGraphicDecoration);
begin
FOwnerDecoration := AValue;
end;
procedure TDecoratedConnection.SetTargetDecoration(AValue: TGraphicDecoration);
begin
FTargetDecoration := AValue;
end;
constructor TDecoratedConnection.Create(AOwner: TControl; AStartPoint,
AEndPoint: TLine; AStyle: TPathStyle);
begin
inherited Create(AStartPoint, AEndPoint, AStyle);
FOwner := AOwner;
//temp
Arrow := TOrthoArrowDecoration.Create(Origin,odLeft);
end;
destructor TDecoratedConnection.destroy;
begin
//temp
Arrow.Free;
inherited destroy;
end;
procedure TDecoratedConnection.DrawDecorated(ACanvas: TCanvas;
AStyle: TDecorationDisplayStyle);
begin
// Call
Self.Draw(ACanvas);
// temp
Arrow.FOrigin := EndPoint.Pos;
Arrow.FDir := EndPoint.FDir ;
Arrow.Draw(ACanvas, FArrowStyle);
// Decorations.Draw(ACanvas, AStyle);
end;
procedure TDecoratedConnection.Refresh;
begin
with TessConnectPanel(FOwner).PathLayout do
begin
RefreshPath(self);
CalculatePath(self);
end;
end;
procedure TDecoratedConnection.SetEndControls(AOwnerEnd, ATargetEnd: TControl);
begin
FOwnerEnd := AOwnerEnd;
FTargetEnd := ATargetEnd;
end;
{ TStringDecoration }
constructor TStringDecoration.Create(Caption: string; Origin: TPoint);
begin
inherited Create(Origin);
FCaption := Caption;
end;
procedure TStringDecoration.Draw(ACanvas: TCanvas);
begin
with ACanvas do
begin
end;
end;
{ TPath }
function TPath.GetStartPoint: TLine;
begin
Result := TLine(Mutable[0]^);
end;
constructor TPath.Create(StartPoint, EndPoint: TLine; Style: TPathStyle);
begin
inherited Create;
FStyle := Style;
FEndPoint := EndPoint;
FRounded := False;
Self.PushBack(StartPoint);
end;
destructor TPath.Destroy;
begin
while not self.IsEmpty do
begin
TLine(Back).Free;
self.PopBack;
end;
FreeAndNil(FEndPoint);
inherited Destroy;
end;
procedure TPath.ClearPath;
begin
while Size > 1 do
begin
TLine(Back).Free;
PopBack;
end;
FRounded := False;
end;
procedure TPath.RoundCorners(Radius: Integer);
var
itp,it,itn: Tline;
len: integer;
fRad: integer; // Forced Radius
dRad: integer; // Drawn Radius
arc: TArc;
i: integer;
p1: TPoint;
Done: boolean;
function WantRad: integer;
begin
if fRad > 0 then
Result := fRad
else
Result := Radius;
end;
begin
if (not FRounded) and (Self.Size > 1) then
begin
i := 1;
itp := Self.Items[i-1];
it := Self.Items[i];
{$IFDEF DEBUG_PATH_ROUNDING}
ErrorHandler.Trace ('New Path Round');
ErrorHandler.Trace ('0p: ' + itp.DebugString);
ErrorHandler.Trace ('0: ' + it.DebugString);
{$ENDIF}
fRad := -1;
// is first line long enough?
len := itp.GetDirectedLength(it);
if len < Radius then
fRad := len div 2;
done := false;
while not Done do
begin
if (i + 1) < Self.Size then
itn := Self.Items[i+1]
else
begin
itn := Self.EndPoint;
done := true;
end;
// Get Line length for it -> itn
len := it.GetDirectedLength(itn);
{$IFDEF DEBUG_PATH_ROUNDING}
ErrorHandler.Trace('Pass: ' + IntToStr(i));
ErrorHandler.Trace ('1p: ' + itp.DebugString);
ErrorHandler.Trace ('1: ' + it.DebugString);
ErrorHandler.Trace ('1n: ' + itn.DebugString);
ErrorHandler.Trace('Len: ' + IntToStr(len));
{$ENDIF}
// Calculate actual radius plus forced next radius
if len > WantRad + Radius then
begin
dRad := WantRad;
fRad := -1;
end
else
if len > fRad * 2 then
begin
dRad := len div 2;
fRad := len div 2;
end
else
begin
dRad := fRad;
fRad := fRad;
end;
// get start point for the arc
p1 := OrthoOffsetPoint(it.Pos, OrthoOpposite[itp.Dir],dRad);
// shorten the next line
it.Shorten(dRad);
// Insert the arc
if (dRad > 2) then
begin
Arc := TArc.Create(p1, itp.Dir, dRad, it.Dir);
Self.Insert(i,arc);
inc(i);
end
else
fRad :=1;
{$IFDEF DEBUG_PATH_ROUNDING}
ErrorHandler.Trace ('Arc: ' + Arc.DebugString);
ErrorHandler.Trace ('Bp: ' + itp.DebugString);
ErrorHandler.Trace ('B: ' + it.DebugString);
ErrorHandler.Trace ('Bn: ' + itn.DebugString);
{$ENDIF}
inc(i);
itp := Self.Items[i-1];
it := Self.Items[i];
end;
FRounded := True;
end;
end;
{
Default to simple drawing of lines with the supplied pathstyle as a default.
For other path resolvers or even here update for rounded. Ortho resolvers
can cope with just this simple algo.
}
procedure TPath.Draw(Canvas: TCanvas);
var
it: TVectorEnumerator;
begin
with Canvas do
begin
Pen.Style := CanvasLineStyle[FStyle];
Pen.Width := CanvasPenWidth[FStyle];
it := Self.GetEnumerator;
// guaranteed to have at least one point from class creation
MoveTo(TLine(it.Current).FStartPoint);
while it.MoveNext do
begin
if (it.Current is TArc) then
begin
LineTo(TLine(it.Current).FStartPoint);
TArc(it.Current).Draw(Canvas);
it.MoveNext;
MoveTo(TLine(it.Current).FStartPoint);
end
else
LineTo(TLine(it.Current).FStartPoint);
end;
LineTo(FEndPoint.FStartPoint);
end;
it.Free;
end;
{ TArc }
procedure TArc.InitialiseArc(EDir: TOrthoDir);
begin
case FDir of
odLeft:
if EDir = odUp then
begin
FSAngle := 270 * 16;
FEAngle := -90 * 16;
FAngDir := adClockwise;
FRect.Left := FStartPoint.x - FRadius;
FRect.Right := FStartPoint.x + FRadius;
FRect.Bottom := FStartPoint.y;
FRect.Top := FStartPoint.y - FRadius - FRadius;
end
else
begin
FSAngle := 90 * 16;
FEAngle := 90 * 16;
FAngDir := adAntiClockwise;
FRect.Left := FStartPoint.x - FRadius;
FRect.Right := FStartPoint.x + FRadius;
FRect.Bottom := FStartPoint.y + FRadius + FRadius;
FRect.Top := FStartPoint.y;
end;
odRight:
if EDir = odUp then
begin
FSAngle := 270 * 16;
FEAngle := 90 * 16 ;
FAngDir := adAntiClockwise;
FRect.Left := FStartPoint.x - FRadius;
FRect.Right := FStartPoint.x + FRadius;
FRect.Bottom := FStartPoint.y;
FRect.Top := FStartPoint.y - FRadius - FRadius;
end
else
begin
FSAngle := 90 * 16;
FEAngle := -90 * 16 ;
FAngDir := adClockwise;
FRect.Left := FStartPoint.x - FRadius;
FRect.Right := FStartPoint.x + FRadius;
FRect.Bottom := FStartPoint.y + FRadius + FRadius;
FRect.Top := FStartPoint.y;
end;
odUp:
if EDir = odLeft then
begin
FSAngle := 0;
FEAngle := 90 * 16;
FAngDir := adAntiClockwise;
FRect.Left := FStartPoint.x - FRadius - FRadius;
FRect.Right := FStartPoint.x;
FRect.Bottom := FStartPoint.y + FRadius;
FRect.Top := FStartPoint.y - FRadius;
end
else
begin
FSAngle := 180 * 16;
FEAngle := -90 * 16;
FAngDir := adClockwise;
FRect.Left := FStartPoint.x;
FRect.Right := FStartPoint.x + FRadius + FRadius;
FRect.Bottom := FStartPoint.y + FRadius;
FRect.Top := FStartPoint.y - FRadius;
end;
odDown:
if EDir = odLeft then
begin
FSAngle := 0 * 16;
FEAngle := -90 * 16;
FAngDir := adClockwise;
FRect.Left := FStartPoint.x - FRadius - FRadius;
FRect.Right := FStartPoint.x;
FRect.Bottom := FStartPoint.y + FRadius;
FRect.Top := FStartPoint.y - FRadius;
end
else
begin
FSAngle := 180 * 16;
FEAngle := 90 * 16;
FAngDir := adAntiClockwise;
FRect.Left := FStartPoint.x;
FRect.Right := FStartPoint.x + FRadius + FRadius;
FRect.Bottom := FStartPoint.y + FRadius;
FRect.Top := FStartPoint.y - FRadius;
end;
end;
end;
function TArc.DebugString: string;
begin
Result := Format('x: %d, y: %d, dir: %d, rad: %d',[x,y,integer(FDir), FRadius]);
end;
constructor TArc.Create(StartPoint: TPoint; SDir: TOrthoDir; Radius: integer;
EDir: TOrthoDir);
begin
inherited Create(StartPoint, SDir);
FRadius := Radius;
InitialiseArc(EDir);
end;
procedure TArc.Draw(ACanvas: TCanvas);
begin
ACanvas.Arc(FRect.Left,FRect.Top,FRect.Right,FRect.Bottom, FSAngle, FEAngle);
end;
{ TLine }
function TLine.getX: integer;
begin
Result := FStartPoint.x;
end;
function TLine.getY: integer;
begin
Result := FStartPoint.y;
end;
function TLine.DebugString: string;
begin
Result := Format('x: %d, y: %d, dir: %d',[x,y,integer(FDir)]);
end;
procedure TLine.setX(AValue: integer);
begin
FStartPoint.x := AValue;
end;
procedure TLine.setY(AValue: integer);
begin
FStartPoint.y := AValue;
end;
procedure TLine.Shorten(AValue: integer);
begin
case FDir of
odLeft: FStartPoint.x := FStartPoint.x - AValue;
odRight: FStartPoint.x := FStartPoint.x + AValue;
odUp: FStartPoint.y := FStartPoint.y - AValue;
odDown: FStartPoint.y := FStartPoint.y + AValue;
end;
end;
function TLine.GetDirectedLength(ALine: TLine): integer;
begin
Result := GetDirectedLength(ALine.Pos);
end;
function TLine.GetDirectedLength(APoint: TPoint): integer;
begin
if IsHorizontal[Self.Dir] then
Result := Abs(FStartPoint.x - APoint.x)
else
Result := Abs(FStartPoint.y - APoint.y);
end;
constructor TLine.Create(StartPoint: TPoint; ADir: TOrthoDir);
begin
inherited create;
FStartPoint := StartPoint;
FDir := ADir;
end;
end.
|
unit uTemplateReceipt13; {увольнение с почасовой работы}
interface
uses SysUtils,
Classes,
Dialogs,
ibase,
DB,
FIBDatabase,
pFIBDatabase,
FIBDataSet,
pFIBDataSet;
function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item : Int64): String; stdcall;
exports GetTemplateString;
implementation
function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item : Int64): String; stdcall;
var szResult,s : String; // Строка для формирования результирующей строки
szTemp : String; // Строка для хранения текстовой строки
cTemp : Char; // Переменная для хранения символа
iTemp : Integer; // Переменная для хранения значения целого типа
iLength : Integer; // Переменная для хранения значения целого типа длины цикла
fTemp : Currency; // Переменная для хранения значения вещественного типа
fdbTemplateReceipt : TpFIBDatabase; // База
ftrTemplateReceipt : TpFIBTransaction; // Транзакция
fdsTemplateReceipt : TpFIBDataSet; // Датасэт
begin
try
fdbTemplateReceipt := TpFIBDatabase.Create(NIL);
ftrTemplateReceipt := TpFIBTransaction.Create(NIL);
fdsTemplateReceipt := TpFIBDataSet.Create(NIL);
fdbTemplateReceipt.SQLDialect := 3;
fdbTemplateReceipt.Handle := hConnection;
ftrTemplateReceipt.DefaultDatabase := fdbTemplateReceipt;
fdbTemplateReceipt.DefaultTransaction := ftrTemplateReceipt;
fdsTemplateReceipt.Database := fdbTemplateReceipt;
fdsTemplateReceipt.Transaction := ftrTemplateReceipt;
ftrTemplateReceipt.StartTransaction;
szResult := '';
fdsTemplateReceipt.SQLs.SelectSQL.Text := 'SELECT * FROM up_dt_order_item_body WHERE id_session = '+IntToStr(id_session)+'';
fdsTemplateReceipt.Open;
// Номер пункта
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_NUM_ITEM_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '.';
// Номер подпункта
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_NUM_SUB_ITEM_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '. ';
// Фамилия
szResult := szResult + '<u>ПІБ:</u> <b>';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_SECOND_NAME_UA_1', []) then
// Заглавными буквами
szResult := szResult + AnsiUpperCase(fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString) + ' ';
// Имя
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_FIRST_NAME_UA_1', []) then
begin
// Заглавными буквами
szTemp := AnsiUpperCase(fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString);
szResult := szResult + szTemp + ' ';
end;
// Отчество
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_LAST_NAME_UA_1', []) then
begin
// Заглавными буквами
szTemp := AnsiUpperCase(fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString);
szResult := szResult + szTemp + ' ';
end;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_TN_1', [])
then szResult := szResult + '(TH ' + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ')';
szResult := szResult + '</b>, ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_EDUC_ZVANIE_AND_ST_1', []) then
if (not fdsTemplateReceipt.FBN('PARAMETR_VALUE').isNull) and (fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '')
then szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ', ';
// Подразделение
szResult := szResult + '<u>підрозділ:</u> ';
// Подразделение
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_NAME_DEPARTMENT_VERH_1', []) then
begin
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ', ';
end;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_NAME_DEPARTMENT_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString+', ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_COUNT_SM_1', []) then
begin
szTemp := '';
iLength := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsInteger;
for iTemp := 1 to iLength do begin
// if iLength >1 then
// if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'PR_SUMMA_SMETA_1_1_' + IntToStr(iTemp), []) then
// szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szTemp := szTemp + ' за рахунок ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_SMETA_TITLE_1_' + IntToStr(iTemp), []) then
szTemp := szTemp + AnsiLowerCase(fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString);
szTemp := szTemp + ' (';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_SMETA_KOD_1_' + IntToStr(iTemp), []) then
szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szTemp := szTemp + ')';
if not (iTemp = iLength) then
begin
szTemp := szTemp + ', ';
end
else begin
szTemp := szTemp + '.';
end;
end;
szResult := szResult + szTemp;
end;
szResult := szResult + '<b> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_DATE_DISMISSION_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szResult := szResult + '</b> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_NAME_DISMISSION_1', []) then
szResult := szResult + '<b> '+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '</b> ';
fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_DES_KZOT_ST_1', []);
szResult := szResult + '<b> ' + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '</b>. ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_NOTE_1', []) then
if (fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '') and (fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> ' ') then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '. ';
szResult := szResult + #13;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BONUS_COUNT_INST_2', []) then
begin
szResult := szResult + '<u>Доплати та надбавки:</u> ';
iLength := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsInteger;
for iTemp := 1 to iLength do
begin
fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BONUS_RAISE_NAME_BONUS_2_' + IntToStr(iTemp), []);
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ' - ';
fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BONUS_PERCENT_2_' + IntToStr(iTemp), []);
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '%';
if (iTemp = iLength)
then szResult := szResult + '.'
else szResult := szResult + ', ';
end;
szResult := szResult + #13;
end;
szResult := szResult + '<u>Підстава:</u> ';
fdsTemplateReceipt.Locate('PARAMETR_NAME', 'DES_POCHAS_REASON_1', []);
szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
s := AnsiLowerCase(Copy(szTemp,1,1));
szResult := szResult + s + Copy(szTemp,2,Length(szTemp));
// szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
// Отсоединение от базы
ftrTemplateReceipt.Rollback;
// Удаление динамически созданных компонент
fdsTemplateReceipt.Free;
ftrTemplateReceipt.Free;
fdbTemplateReceipt.Free;
DecimalSeparator := ',';
except on Error: Exception do begin
MessageDlg('Невозможно сформировать шаблон', mtError, [mbOk], 0);
szResult := '';
end;
end;
Result := szResult;
end;
end.
|
unit HelloUnit;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Objects, FMX.Gestures, FMX.Controls.Presentation;
type
TForm10 = class(TForm)
Label1: TLabel;
CircleOuter: TCircle;
CircleInner: TCircle;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Image1: TImage;
StyleBook1: TStyleBook;
Label5: TLabel;
Timer1: TTimer;
procedure FormShow(Sender: TObject);
procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo;
var Handled: Boolean);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form10: TForm10;
implementation
{$R *.fmx}
{$R *.Moto360.fmx }
{$R *.GearLive.fmx }
{$R *.LGG.fmx }
uses
System.TypInfo, System.Devices, FMX.Platform, System.Rtti;
procedure TForm10.FormGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
case EventInfo.GestureID of
sgiLeft: ShowMessage('Left');
sgiRight: ShowMessage('Right');
sgiUp: ShowMessage('Up');
sgiDown: ShowMessage('Down');
end;
end;
procedure TForm10.FormShow(Sender: TObject);
var
disp: IFMXDeviceMetricsService;
dev: IFMXDeviceService;
devCls: TDeviceInfo.TDeviceClass;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXDeviceMetricsService) then
begin
disp := IFMXDeviceMetricsService(TPlatformServices.Current.GetPlatformService(IFMXDeviceMetricsService));
Label2.Text := Format('Phys: %dx%d',
[disp.GetDisplayMetrics.PhysicalScreenSize.cx, disp.GetDisplayMetrics.PhysicalScreenSize.cy]);
Label3.Text := Format('PPI: %d', [disp.GetDisplayMetrics.PixelsPerInch]);
end;
if TPlatformServices.Current.SupportsPlatformService(IFMXDeviceService) then
begin
dev := IFMXDeviceService(TPlatformServices.Current.GetPlatformService(IFMXDeviceService));
devCls := dev.GetDeviceClass;
Label4.Text := 'Class: ' + GetEnumName(TypeInfo(TDeviceInfo.TDeviceClass), ord(devCls));
end;
Label5.Text := Format('Design: %dx%d', [Self.Width, Self.Height]);
end;
procedure TForm10.Timer1Timer(Sender: TObject);
begin
Label5.Text := Format('Design: %dx%d', [Self.Width, Self.Height]);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Package.Dependency;
interface
uses
DPM.Core.Types,
DPM.Core.Dependency.Version,
DPM.Core.Package.Interfaces;
type
TPackageDependency = class(TInterfacedObject, IPackageDependency)
private
FDependencyVersion : TVersionRange;
FId : string;
FPlatform : TDPMPlatform;
protected
function GeTVersionRange : TVersionRange;
function GetId : string;
function GetPlatform : TDPMPlatform;
procedure SetVersionRange(const value : TVersionRange);
public
constructor Create(const id : string; const version : TVersionRange; const platform : TDPMPlatform);
end;
implementation
{ TPackageDependency }
constructor TPackageDependency.Create(const id : string; const version : TVersionRange; const platform : TDPMPlatform);
begin
FId := id;
FDependencyVersion := version;
FPlatform := platform;
end;
function TPackageDependency.GeTVersionRange : TVersionRange;
begin
result := FDependencyVersion;
end;
procedure TPackageDependency.SetVersionRange(const value : TVersionRange);
begin
FDependencyVersion := value;
end;
function TPackageDependency.GetId : string;
begin
result := FId;
end;
function TPackageDependency.GetPlatform : TDPMPlatform;
begin
result := FPlatform;
end;
end.
|
unit fClient;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
gateway.Proto, gateway_protocol.Client, gateway_protocol.Proto, FMX.Effects,
FMX.Filter.Effects, FMX.Edit, FMX.Layouts, FMX.TreeView;
type
TfrmClient = class(TForm)
Memo1: TMemo;
btnTopology: TButton;
btnCreateWFInstance: TButton;
lblServer: TLabel;
edtServer: TEdit;
edtPort: TEdit;
lblPort: TLabel;
MaskToAlphaEffect1: TMaskToAlphaEffect;
dlgOpenBPMNFile: TOpenDialog;
edtBPMFile: TEdit;
lblBMPFile: TLabel;
edtProcessID: TEdit;
lblProcessID: TLabel;
edtOrderID: TEdit;
lblOrderID: TLabel;
lblAmount: TLabel;
edtAmount: TEdit;
btnCreateJob: TButton;
edtJobName: TEdit;
lblJobName: TLabel;
lblJob2: TLabel;
edtMessage: TEdit;
lblMessage: TLabel;
btnPublishMessage: TButton;
edtKey: TEdit;
lblKey: TLabel;
btnDeploy: TButton;
btnCompleteJob: TButton;
edtJobID: TEdit;
lblJobID: TLabel;
tvWorkFlow: TTreeView;
lblWorkFlow: TLabel;
edtWFInstanceKey: TEdit;
lblWFInstance: TLabel;
trviRoot: TTreeViewItem;
procedure btnTopologyClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnCreateWFInstanceClick(Sender: TObject);
procedure edtPortChange(Sender: TObject);
procedure edtServerChange(Sender: TObject);
procedure edtBPMFileDblClick(Sender: TObject);
procedure edtPortValidate(Sender: TObject; var Text: string);
procedure edtAmountValidate(Sender: TObject; var Text: string);
procedure btnDeployClick(Sender: TObject);
procedure btnCreateJobClick(Sender: TObject);
procedure btnCompleteJobClick(Sender: TObject);
procedure btnPublishMessageClick(Sender: TObject);
private
FServer: String;
FPort: Integer;
FClient: IGateway_Client;
procedure Log(const aText: string);
procedure UpDateJobs(const aResponse: TActivatedJobArray);
procedure CreateClient;
end;
var
frmClient: TfrmClient;
implementation
uses
System.IOUtils, IdURI, System.Net.HttpClient,
JclSysInfo,
SuperObject,
Ultraware.Grpc,
Grijjy.Http, Grijjy.ProtocolBuffers;
{$R *.fmx}
procedure TfrmClient.FormCreate(Sender: TObject);
begin
// FClient := TGateway_Client.Create('localhost',26500);
// Use grpc-dump:
// c:\Users\pmm\gRPC-Tools\grpc-dump --destination 127.0.0.1:26500 --port=58772
FPort := StrToIntDef(edtPort.Text,58772); {58772: test mit grpc-dump}
FServer := edtServer.Text;
CreateClient;
end;
procedure TfrmClient.Log(const aText: string);
begin
TThread.Queue(nil,
procedure
begin
Memo1.Lines.Add(aText);
Application.ProcessMessages;
end);
end;
procedure TfrmClient.UpDateJobs(const aResponse: TActivatedJobArray);
Var
aTvItem: TTreeViewItem;
Begin
TThread.Queue(nil,
procedure
begin
if High(aResponse) > -1
then begin
edtJobID.Text := aResponse[0].Key.ToString;
tvWorkFlow.BeginUpdate;
aTvItem := TTreeViewItem.Create(self);
aTvItem.Text := Format('JOB Item#: %d (WF-Instance#: %d) Worker: %s)',
[aResponse[0].key , aResponse[0].workflowInstanceKey,aResponse[0].worker]);
aTvItem.Parent := tvWorkFlow.Items[0].Items[0];
tvWorkFlow.EndUpdate;
tvWorkFlow.ExpandAll;
end
else edtJobID.Text := '-1';
end);
End;
procedure TfrmClient.CreateClient;
begin
FClient := TGateway_Client.Create(FServer, FPort);
end;
procedure TfrmClient.btnCreateJobClick(Sender: TObject);
(*
TActivateJobsRequest = record
[Serialize(1)] _type: string;
[Serialize(2)] worker: string;
[Serialize(3)] timeout: Int64;
[Serialize(4)] maxJobsToActivate: Integer;
[Serialize(5)] fetchVariable: TStringArray;
[Serialize(6)] requestTimeout: Int64;
end;
TActivateJobsRequestArray = Array of TActivateJobsRequest;
TActivatedJob = record
[Serialize(1)] key: Int64;
[Serialize(2)] _type: string;
[Serialize(3)] workflowInstanceKey: Int64;
[Serialize(4)] bpmnProcessId: string;
[Serialize(5)] workflowDefinitionVersion: Integer;
[Serialize(6)] workflowKey: Int64;
[Serialize(7)] elementId: string;
[Serialize(8)] elementInstanceKey: Int64;
[Serialize(9)] customHeaders: string;
[Serialize(10)] worker: string;
[Serialize(11)] retries: Integer;
[Serialize(12)] deadline: Int64;
[Serialize(13)] variables: string;
end;
TActivatedJobArray = Array of TActivatedJob;
TActivateJobsResponse = record
[Serialize(1)] jobs: TActivatedJobArray;
end;
TProtoCallback<T> = reference to procedure(const aInput: T; const aHasData, aClosed: Boolean);
TActivateJobsCallback = TProtoCallback<TActivatedJobArray>;
procedure ActivateJobs(const aActivateJobsRequest: TActivateJobsRequest; const aActivateJobsCallback: TActivateJobsCallback);
*)
var
aActivateJobsRequest: TActivateJobsRequest;
aFetchVars: string;
aTvItem: TTreeViewItem;
begin
Log('Create Job...');
aActivateJobsRequest._type := edtJobName.Text; { 'initiate-payment' ;}
aActivateJobsRequest.worker := GetLocalComputerName;
aActivateJobsRequest.timeout := 10000;
aActivateJobsRequest.maxJobsToActivate := 1;
aFetchVars := string.format('"orderId": "%s","orderValue": %s',
[edtOrderID.Text, edtAmount.Text]);
aActivateJobsRequest.fetchVariable := [aFetchVars];
aActivateJobsRequest.requestTimeout := 10000;
try
FClient.ActivateJobs(aActivateJobsRequest,
procedure(const aResponse: TActivatedJobArray; const aHasData, aClosed: Boolean)
begin
Log(TSuperRttiContext.Create.AsJson<TActivatedJobArray>(aResponse).AsJSon());
UpDateJobs(aResponse);
end
);
except
on e: Exception do
Log('Error in ActivateJobs: '+E.Message)
end;
Log('Create Job done.');
end;
procedure TfrmClient.btnDeployClick(Sender: TObject);
var
aWFRequest:TWorkflowRequestObject;
aWFs: TWorkflowRequestObjectArray;
aWFResponse: TDeployWorkflowResponse;
aTvItem: TTreeViewItem;
begin
Log('Deploy Workflow...');
try
aWFRequest.name := edtProcessID.Text;
aWFRequest._type := BPMN;
aWFRequest.definition := TFile.ReadAllBytes(edtBPMFile.Text);
aWFs := [aWFRequest];
aWFResponse := FClient.DeployWorkflow(aWFs);
Log(TSuperRttiContext.Create.AsJson<TDeployWorkflowResponse>(aWFResponse).AsJSon());
tvWorkFlow.BeginUpdate;
tvWorkFlow.Clear;
aTvItem := TTreeViewItem.Create(self);
aTvItem.Text := Format('BPMN ID: "%s" - Key: %d',
[aWFResponse.workflows[0].bpmnProcessId,
aWFResponse.workflows[0].workflowKey]);
aTvItem.Parent := tvWorkFlow;
tvWorkFlow.EndUpdate;
tvWorkFlow.ExpandAll;
except
on e: Exception do
Log('Error in Deploy WorkFlow: '+E.Message);
end;
Log('Deploy WF done');
end;
procedure TfrmClient.btnPublishMessageClick(Sender: TObject);
{
TPublishMessageRequest = record
[Serialize(1)] name: string;
[Serialize(2)] correlationKey: string;
[Serialize(3)] timeToLive: Int64;
[Serialize(4)] messageId: string;
[Serialize(5)] variables: string;
end;
}
var aPMRequest: TPublishMessageRequest;
begin
Log('Publishing message...');
try
aPMRequest.name := edtMessage.Text;
aPMRequest.correlationKey := edtOrderID.Text; {'initiate-payment';} //OrderID
aPMRequest.timeToLive := 10000;
aPMRequest.messageId := edtWFInstanceKey.Text; { '2251799813685292';} //WF Instance-Key
aPMRequest.variables := '';
FClient.PublishMessage(aPMRequest);
except
on E: EgoSerializationError do; //passiert, weil Rückgabe-Type ein leerer Record ist.
on E: Exception do
Log('Error in PublishMessage: '+E.Message)
end;
Log('Publishing message done.');
end;
procedure TfrmClient.btnTopologyClick(Sender: TObject);
var aTR: TTopologyResponse;
begin
Log('Get Topology...');
aTR := FClient.Topology();
Log(TSuperRttiContext.Create.AsJson<TTopologyResponse>(aTR).AsJSon());
Log('Topology DONE');
end;
procedure TfrmClient.btnCompleteJobClick(Sender: TObject);
var aJob: TCompleteJobRequest;
begin
Log('Completing JOB...');
try
aJob.jobKey := StrToUInt64(edtJobID.Text);
aJob.variables := string.format('{"orderId": "%s","orderValue": %s}',
[edtOrderID.Text, edtAmount.Text]);
FClient.CompleteJob(aJob);
except
on E: EgoSerializationError do; //passiert, weil Rückgabe-Type ein leerer Record ist.
on e: Exception do
Log('Error in CompleteJob: '+E.Message)
end;
Log('Complete JOB done.');
end;
procedure TfrmClient.btnCreateWFInstanceClick(Sender: TObject);
var
aWFIRequest: TCreateWorkflowInstanceRequest;
aWFIResponse: TCreateWorkflowInstanceResponse;
aTvItem: TTreeViewItem;
begin
Log('Creating Workflow-Instance...');
aWFIRequest.workflowKey := UInt32(-1);
aWFIRequest.bpmnProcessId := edtProcessID.Text; {'order-process'}
aWFIRequest.version := UInt64(-1);
aWFIRequest.variables := Format('{"orderId": "%s", "orderValue": %s}',
[edtOrderID.Text,edtAmount.Text]);
try
aWFIResponse := FClient.CreateWorkflowInstance(aWFIRequest);
Log(TSuperRttiContext.Create.AsJson<TCreateWorkflowInstanceResponse >(aWFIResponse).AsJSon());
tvWorkFlow.BeginUpdate;
aTvItem := TTreeViewItem.Create(self);
aTvItem.Text := Format('WORK FLOW Instance#: %d (WF-Key: %d)',
[aWFIResponse.workflowInstanceKey, aWFIResponse.workflowKey]);
{ aTvItem.Data := aWFIResponse.workflowInstanceKey; }
edtWFInstanceKey.Text := aWFIResponse.workflowInstanceKey.ToString;
aTvItem.Parent := tvWorkFlow.Items[0];
tvWorkFlow.EndUpdate;
except
on e: Exception do
Log('Error in CreateWorkflowInstance: '+E.Message);
end;
end;
procedure TfrmClient.edtAmountValidate(Sender: TObject; var Text: string);
var I: Integer;
begin
if not TryStrToInt(Text,I)
then Text := '99';
end;
procedure TfrmClient.edtBPMFileDblClick(Sender: TObject);
var aStr: string;
I: Integer;
begin
If dlgOpenBPMNFile.Execute
then Begin
edtBPMFile.Text := dlgOpenBPMNFile.FileName;
aStr := ExtractFileName(edtBPMFile.Text);
I := aStr.LastDelimiter('.');
edtProcessID.Text := aStr.SubString(0,I);
End;
end;
procedure TfrmClient.edtPortChange(Sender: TObject);
var I: Integer;
begin
I := StrToIntDef(edtPort.Text,FPort);
if I <> FPort
then begin
FPort := I;
CreateClient;
end;
end;
procedure TfrmClient.edtPortValidate(Sender: TObject; var Text: string);
var I: Integer;
begin
if not TryStrToInt(Text,I)
then Text := IntToStr(FPort);
end;
procedure TfrmClient.edtServerChange(Sender: TObject);
begin
FServer := edtServer.Text;
CreateClient;
end;
end.
|
unit ibSHStatistic;
interface
uses
Classes, SysUtils,
SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHMessages, ibSHValues;
type
TibBTStatistics = class(TSHComponent, IibSHStatistics)
private
FDatabase: IibSHDatabase;
FDRVStatistics: TSHComponent;
FTimeStatistics: IibSHDRVExecTimeStatistics;
protected
{IibSHStatistic}
function GetDatabase: IibSHDatabase;
procedure SetDatabase(const Value: IibSHDatabase);
function GetDRVStatistics: IibSHDRVStatistics;
function GetDRVTimeStatistics: IibSHDRVExecTimeStatistics;
procedure SetDRVTimeStatistics(const Value: IibSHDRVExecTimeStatistics);
function TableStatisticsStr(AIncludeSystemTables: Boolean): string;
function ExecuteTimeStatisticsStr: string;
procedure StartCollection;
procedure CalculateStatistics;
public
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property Statistics: IibSHDRVStatistics read GetDRVStatistics;
end;
implementation
procedure Register;
begin
SHRegisterComponents([TibBTStatistics]);
end;
{ TibBTStatistic }
function TibBTStatistics.GetDatabase: IibSHDatabase;
begin
Result := FDatabase;
end;
procedure TibBTStatistics.SetDatabase(const Value: IibSHDatabase);
var
vComponentClass: TSHComponentClass;
begin
if FDatabase <> Value then
begin
ReferenceInterface(FDatabase, opRemove);
if Assigned(FDRVStatistics) then FDRVStatistics.Free;
FDatabase := Value;
if Assigned(FDatabase) and Assigned(FDatabase.BTCLServer) then
begin
ReferenceInterface(FDatabase, opInsert);
vComponentClass := Designer.GetComponent(FDatabase.BTCLServer.DRVNormalize(IibSHDRVStatistics));
if Assigned(vComponentClass) then
FDRVStatistics := vComponentClass.Create(Self);
Statistics.Database := FDatabase.DRVQuery.Database;
end;
end;
end;
function TibBTStatistics.GetDRVStatistics: IibSHDRVStatistics;
begin
Supports(FDRVStatistics, IibSHDRVStatistics, Result);
end;
function TibBTStatistics.GetDRVTimeStatistics: IibSHDRVExecTimeStatistics;
begin
Result := FTimeStatistics;
end;
procedure TibBTStatistics.SetDRVTimeStatistics(
const Value: IibSHDRVExecTimeStatistics);
begin
if FTimeStatistics <> Value then
begin
ReferenceInterface(FTimeStatistics, opRemove);
FTimeStatistics := Value;
ReferenceInterface(FTimeStatistics, opInsert);
end;
end;
function TibBTStatistics.TableStatisticsStr(
AIncludeSystemTables: Boolean): string;
var
I: Integer;
begin
Result := '';
for I := 0 to Pred(Statistics.TablesCount) do
begin
if (not AIncludeSystemTables) and (Pos('RDB$', Statistics.TableStatistics[I].TableName) = 1) then Continue;
if (Statistics.TableStatistics[I].Inserts > 0) then
Result := Result + Format(SStatisticInserted, [Statistics.TableStatistics[I].TableName, FormatFloat('###,###,###,###', Statistics.TableStatistics[I].Inserts)]) + sLineBreak;
end;
for I := 0 to Pred(Statistics.TablesCount) do
begin
if (not AIncludeSystemTables) and (Pos('RDB$', Statistics.TableStatistics[I].TableName) = 1) then Continue;
if Statistics.TableStatistics[I].Updates > 0 then
Result := Result + Format(SStatisticUpdated, [Statistics.TableStatistics[I].TableName, FormatFloat('###,###,###,###', Statistics.TableStatistics[I].Updates)]) + sLineBreak;
end;
for I := 0 to Pred(Statistics.TablesCount) do
begin
if (not AIncludeSystemTables) and (Pos('RDB$', Statistics.TableStatistics[I].TableName) = 1) then Continue;
if Statistics.TableStatistics[I].Deletes > 0 then
Result := Result + Format(SStatisticDeleted, [Statistics.TableStatistics[I].TableName, FormatFloat('###,###,###,###', Statistics.TableStatistics[I].Deletes)]) + sLineBreak;
end;
{
for I := 0 to Pred(Statistics.TablesCount) do
begin
if (not AIncludeSystemTables) and (Pos('RDB$', Statistics.TableStatistics[I].TableName) = 1) then Continue;
if Statistics.TableStatistics[I].IdxReads > 0 then
Result := Result + Format(SStatisticIndexedRead, [Statistics.TableStatistics[I].TableName, FormatFloat('###,###,###,###', Statistics.TableStatistics[I].IdxReads)]) + sLineBreak;
end;
for I := 0 to Pred(Statistics.TablesCount) do
begin
if (not AIncludeSystemTables) and (Pos('RDB$', Statistics.TableStatistics[I].TableName) = 1) then Continue;
if Statistics.TableStatistics[I].SeqReads > 0 then
Result := Result + Format(SStatisticNonIndexedRead, [Statistics.TableStatistics[I].TableName, FormatFloat('###,###,###,###', Statistics.TableStatistics[I].SeqReads)]) + sLineBreak;
end;
Result := TrimRight(Result);
}
// if Length(Result) > 0 then Result := sLineBreak + Result;
end;
function TibBTStatistics.ExecuteTimeStatisticsStr: string;
begin
Result := '';
if Assigned(FTimeStatistics) then
begin
{
Result := Result + SPrepare + ':' + msToStr(FTimeStatistics.PrepareTime) + sLineBreak;
Result := Result + SExecute + ':' + msToStr(FTimeStatistics.ExecuteTime) + sLineBreak;
Result := Result + SFetch + ':' + msToStr(FTimeStatistics.FetchTime);
}
Result := Result + SPrepare + ':' + msToStr(FTimeStatistics.PrepareTime) + ' ';
Result := Result + SExecute + ':' + msToStr(FTimeStatistics.ExecuteTime) + ' ';
Result := Result + SFetch + ':' + msToStr(FTimeStatistics.FetchTime);
end;
end;
procedure TibBTStatistics.StartCollection;
begin
Statistics.StartCollection;
end;
procedure TibBTStatistics.CalculateStatistics;
begin
Statistics.CalculateStatistics;
end;
procedure TibBTStatistics.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if AComponent.IsImplementorOf(FDatabase) then FDatabase := nil;
if AComponent.IsImplementorOf(FTimeStatistics) then FTimeStatistics := nil;
end;
end;
initialization
Register;
end.
|
unit LuaButton;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, lua, LuaObject, Buttons;
type
{ TLuaButton }
TLuaButton = class(TLuaObject)
private
procedure CommonCreate(LuaState : PLua_State; AParent : TLuaObject = nil); override;
procedure ButtonClickEvent(Sender: TObject);
function GetPropValue(propName : AnsiString): Variant; override;
function SetPropValue(PropName : AnsiString; const AValue: Variant) : Boolean; override;
public
btn : TButton;
destructor Destroy; override;
procedure Click;
end;
procedure RegisterLuaButton(L : Plua_State);
implementation
uses
MainForm;
function Button_Click(l : PLua_State) : Integer; cdecl;
var
btn : TLuaButton;
begin
result := 0;
if (lua_gettop(l) < 1) then
exit;
btn := TLuaButton(LuaToTLuaObject(l, 1));
btn.Click;
end;
function Button_new(L : PLua_State; AParent : TLuaObject=nil):TLuaObject;
begin
result := TLuaButton.Create(L, AParent);
end;
function new_Button(L : PLua_State) : Integer; cdecl;
var
p : TLuaObjectNewCallback;
begin
p := @Button_new;
result := new_LuaObject(L, 'TButton', p);
end;
procedure methods_Button(L : Plua_State; classTable : Integer);
begin
RegisterMethod(L, 'Click', @Button_Click, classTable);
end;
procedure RegisterLuaButton(L: Plua_State);
begin
RegisterTLuaObject(L, 'TButton', @new_Button, @methods_Button);
end;
{ TLuaButton }
procedure TLuaButton.CommonCreate(LuaState: PLua_State; AParent: TLuaObject);
begin
inherited CommonCreate(LuaState, AParent);
btn := TButton.Create(frmMain);
btn.OnClick := @ButtonClickEvent;
btn.Parent := frmMain;
end;
procedure TLuaButton.ButtonClickEvent(Sender: TObject);
begin
CallEvent('OnClick');
end;
function TLuaButton.GetPropValue(propName: AnsiString): Variant;
begin
if CompareText(propName, 'Caption') = 0 then
result := btn.Caption
else if CompareText(propName, 'Width') = 0 then
result := btn.Width
else if CompareText(propName, 'Height') = 0 then
result := btn.Height
else if CompareText(propName, 'Left') = 0 then
result := btn.Left
else if CompareText(propName, 'Top') = 0 then
result := btn.Top
else if CompareText(propName, 'Visible') = 0 then
result := btn.Visible
else if CompareText(propName, 'Enabled') = 0 then
result := btn.Enabled
else
Result:=inherited GetPropValue(propName);
end;
function TLuaButton.SetPropValue(PropName: AnsiString; const AValue: Variant
): Boolean;
begin
result := true;
if CompareText(propName, 'Caption') = 0 then
btn.Caption := AnsiString(AValue)
else if CompareText(propName, 'Width') = 0 then
btn.Width := AValue
else if CompareText(propName, 'Height') = 0 then
btn.Height := AValue
else if CompareText(propName, 'Left') = 0 then
btn.Left := AValue
else if CompareText(propName, 'Top') = 0 then
btn.Top := AValue
else if CompareText(propName, 'Visible') = 0 then
btn.Visible := AValue
else if CompareText(propName, 'Enabled') = 0 then
btn.Enabled := AValue
else
Result:=inherited SetPropValue(propName, AValue);
end;
destructor TLuaButton.Destroy;
begin
inherited Destroy;
end;
procedure TLuaButton.Click;
begin
btn.Click;
end;
end.
|
program expressaoSimples;
uses crt;
const
max=100;
type
TDado = real;
TPilha = array[1..max] of TDado;
procedure push(var p:TPilha; var t:integer; dado:TDado);
begin
if (t < max) then
begin
t := t + 1;
p[t] := dado;
end;
end;
function pop(var p:TPilha; var t:integer):TDado;
begin
pop := 0;
if (t > 0) then
begin
pop := p[t];
t := t - 1;
end;
end;
function calcula(x:real; y:real; operador:char):real;
begin
case operador of
'+' : calcula := x + y;
'*' : calcula := x * y;
'-' : calcula := x - y;
'/' : calcula := x / y;
else calcula := 0;
end;
end;
function charToInteger(c:char):integer;
begin
if (c in ['0'..'1']) then
begin
charToInteger := ord(c) - ord('0');
end
else
begin
charToInteger := 0;
end;
end;
function calculaExpressaoSimples(exp:string):real;
var pilha:TPilha;
i,topo:integer;
n1,n2,resultado:real;
begin
topo := 0;
for i:=1 to length(exp) do
begin
if ((exp[i] >= '0') and (exp[i] <= '9')) then
//if (exp[i] in ['0'..'9']) then
begin
push(pilha,topo,charToInteger(exp[i]));
end
else
begin
n2 := pop(pilha,topo);
n1 := pop(pilha,topo);
push(pilha,topo,calcula(n1,n2,exp[i]));
end;
end;
calculaExpressaoSimples := pop(pilha,topo);
end;
function calculaExpressaoComplexa(exp:string):real;
begin
end;
var expressao:string;
begin
clrscr;
writeln('Entre com uma expressao pos-fixada: ');
readln(expressao);
writeln('Resultado de ',exp,' = ',calculaExpressaoSimples(expressao):8:2);
readkey;
end.
|
unit TestThItemLine;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, BaseTestUnit, FMX.Types, FMX.Forms,
System.UITypes, System.Types, System.SysUtils, FMX.Controls, System.UIConsts;
type
// #19 캔버스에 선을 추가한다.
TestTThLine = class(TThCanvasBaseTestUnit)
published
procedure TestItemFactory;
// #74 마우스 드래그로 시작점과 끝점을 이용해 도형을 그린다.
procedure TestDrawLineTLtoBR;
// #75 끝점이 시작점의 앞에 있어도 그려져야 한다.
procedure TestDrawLineTRtoBL;
procedure TestDrawLineBLtoTR;
procedure TestDrawLineBRtoTL;
{$IFDEF ON_HIGHLIGHT}
// #76 도형에 마우스 오버시 하이라이트 효과가 나타난다.
procedure TestLineMouseOverHighlight;
{$ENDIF}
// #99 선을 넘어서는 일직선 범위를 클릭 시 선이 선택된다.
procedure BugTestLineOutOfRange;
// #98 선이 아닌 다른 지역에 대해 선택이 되지 않아야 한다.
procedure TestLineSelectionRange;
// #97 수직선, 수평선을 그릴 수 있어야 한다.
procedure TestLineHorizon;
procedure TestLineVertical;
// #77 최소 크기를 갖으며 그리거나 크기조정 시 반영된다.
procedure TestLineMinimumSize;
// #43 선의 일정간격 내에서도 마우스로 선택되어야 한다.
procedure TestRangeSelectHorizonOverY; // 수평선
procedure TestRangeSelectVerticalOverX; // 수직선
procedure TestRangeSelectLineTLtoBR;
// #80 SizeSpot을 드래그 하여 크기를 변경 할 수 있다.
procedure TestResizeLine;
procedure TestResizeLineBRtoBottom;
procedure TestResizeLineBottomtoBLOver;
procedure TestResizeLineTLtoBROver;
procedure TestResizeLineTLtoRightOver;
// #100 크기조정 시 최소 크기가 적용되어야 한다.
procedure TestResizeMinimum;
end;
implementation
uses
FMX.TestLib, ThItem, ThShapeItem, ThItemFactory, ThConsts, System.Math, DebugUtils;
{ TestTThShape }
procedure TestTThLine.TestItemFactory;
var
Item: TThItem;
begin
// Not assigned number 0
Item := ItemFactory.Get(0);
try
Check(not Assigned(Item));
finally
if Assigned(Item) then
Item.Free;
end;
Item := ItemFactory.Get(1200);
try
Check(Assigned(Item));
finally
if Assigned(Item) then
Item.Free;
end;
end;
procedure TestTThLine.TestDrawLineTLtoBR;
begin
// TopLeft > BottomRight
DrawLine(10, 10, 100, 100);
Check(TestLib.GetControlPixelColor(FCanvas, 20, 20) = ItemShapeDefaultColor, 'TopLeft > BottomRight - 1');
Check(TestLib.GetControlPixelColor(FCanvas, 90, 90) = ItemShapeDefaultColor, 'TopLeft > BottomRight - 2');
end;
procedure TestTThLine.TestDrawLineTRtoBL;
begin
// TopRight > BottomLeft
DrawLine(100, 10, 10, 100);
Check(TestLib.GetControlPixelColor(FCanvas, 90, 20) = ItemShapeDefaultColor, 'TopRight > BottomLeft - 1');
Check(TestLib.GetControlPixelColor(FCanvas, 20, 90) = ItemShapeDefaultColor, 'TopRight > BottomLeft - 2');
end;
procedure TestTThLine.TestDrawLineBLtoTR;
begin
// BottomLeft > TopRight
DrawLine(10, 100, 100, 10);
Check(TestLib.GetControlPixelColor(FCanvas, 20, 90) = ItemShapeDefaultColor, 'BottomLeft > TopRight - 1');
Check(TestLib.GetControlPixelColor(FCanvas, 90, 20) = ItemShapeDefaultColor, 'BottomLeft > TopRight - 2');
end;
procedure TestTThLine.TestDrawLineBRtoTL;
begin
// BottomRight > TopLeft
DrawLine(100, 100, 10, 10);
Check(TestLib.GetControlPixelColor(FCanvas, 20, 20) = ItemShapeDefaultColor, 'BottomRight > TopLeft - 1');
Check(TestLib.GetControlPixelColor(FCanvas, 90, 90) = ItemShapeDefaultColor, 'BottomRight > TopLeft - 2');
end;
{$IFDEF ON_HIGHLIGHT}
procedure TestTThLine.TestLineMouseOverHighlight;
var
AC: TAlphaColor;
begin
// 추가
DrawLine(10, 10, 100, 100);
// 선택
TestLib.RunMouseClick(50, 50);
FCanvas.BgColor := claPink;
// 선택해제
TestLib.RunMouseClick(150, 150);
AC := TestLib.GetControlPixelColor(FCanvas, 100 + (ItemHighlightSize - 1), 100 + (ItemHighlightSize - 1));
Check(AC <> ItemHighlightColor, 'Color is not highlight color');
MousePath.New
.Add(150, 150)
.Add(50, 50);
// .Add(101, 101);
TestLib.RunMouseMove(MousePath.Path);
// 그림자 확인
AC := TestLib.GetControlPixelColor(FCanvas, 100 + (ItemHighlightSize), 100 + (ItemHighlightSize));
Check(AC = ItemHighlightColor, 'Not matching Color');
// Check(AC = claGray, 'Not matching Color');
end;
{$ENDIF}
procedure TestTThLine.BugTestLineOutOfRange;
begin
// 추가
DrawLine(10, 10, 100, 100);
// 영역외 선택
TestLib.RunMouseClick(150, 150);
Check(not Assigned(FCanvas.SelectedItem), 'Out of range');
// 선택
TestLib.RunMouseClick(50, 50);
// 선택해제
TestLib.RunMouseClick(150, 150);
Check(not Assigned(FCanvas.SelectedItem), 'Unselect');
end;
procedure TestTThLine.TestLineSelectionRange;
begin
// 추가
DrawLine(10, 10, 100, 100);
// 선택 범위 외 선택
TestLib.RunMouseClick(80, 50);
CheckNull(FCanvas.SelectedItem, 'Invalid select area');
// 선택
TestLib.RunMouseClick(50, 50);
// CheckTrue(Assigned(FCanvas.SelectedItem));
CheckNotNull(FCanvas.SelectedItem);
end;
procedure TestTThLine.TestLineHorizon;
begin
DrawLine(10, 200, 20, 200);
FCanvas.ClearSelection;
Check(TestLib.GetControlPixelColor(FCanvas, 10, 197) = ItemShapeDefaultColor, 'Start');
Check(TestLib.GetControlPixelColor(FCanvas, 20, 197) = ItemShapeDefaultColor, 'End');
end;
procedure TestTThLine.TestLineVertical;
begin
DrawLine(10, 10, 10, 20);
FCanvas.ClearSelection;
Check(TestLib.GetControlPixelColor(FCanvas, 7, 10) = ItemShapeDefaultColor, 'Start');
Check(TestLib.GetControlPixelColor(FCanvas, 7, 20) = ItemShapeDefaultColor, 'End');
end;
procedure TestTThLine.TestLineMinimumSize;
begin
DrawLine(10, 10, 20, 10);
TestLib.RunMouseClick(15, 10);
Check(Assigned(FCanvas.SelectedItem));
Check(FCanvas.SelectedItem.Width = 30, Format('W: %f', [FCanvas.SelectedItem.Width]));
TestLib.RunMouseClick(150, 150);
TestLib.RunMouseClick(ItemMinimumSize-1, 10);
Check(Assigned(FCanvas.SelectedItem));
end;
procedure TestTThLine.TestRangeSelectHorizonOverY;
begin
DrawLine(10, 10, 100, 10);
TestLib.RunMouseClick(10, 7);
Check(Assigned(FCanvas.SelectedItem), 'Top');
TestLib.RunMouseClick(100, 100);
TestLib.RunMouseClick(10, 13);
Check(Assigned(FCanvas.SelectedItem), 'Bottom');
TestLib.RunMouseClick(100, 100);
TestLib.RunMouseClick(7, 10);
Check(Assigned(FCanvas.SelectedItem), 'Left');
TestLib.RunMouseClick(100, 100);
TestLib.RunMouseClick(103, 10);
Check(Assigned(FCanvas.SelectedItem), 'Right');
end;
procedure TestTThLine.TestRangeSelectVerticalOverX;
begin
DrawLine(10, 10, 10, 100);
TestLib.RunMouseClick(100, 100);
TestLib.RunMouseClick(10, 7);
Check(Assigned(FCanvas.SelectedItem), 'Top');
TestLib.RunMouseClick(100, 100);
TestLib.RunMouseClick(13, 10);
Check(Assigned(FCanvas.SelectedItem), 'Right');
TestLib.RunMouseClick(100, 100);
TestLib.RunMouseClick(7, 10);
Check(Assigned(FCanvas.SelectedItem), 'Left');
TestLib.RunMouseClick(100, 100);
TestLib.RunMouseClick(10, 103);
Check(Assigned(FCanvas.SelectedItem), 'Bottom');
end;
procedure TestTThLine.TestRangeSelectLineTLtoBR;
var
Rect: TRectF;
P, P2, B, DP: TPointF;
D, R: Single;
begin
Rect := RectF(10, 10,100, 100);
DrawLine(Rect);
D := (ItemLineSelectionThickness - 1) / 2;
P := Rect.CenterPoint;
R := ArcTan(Rect.Height/Rect.Width);
B := PointF(Sin(R) * D, Cos(R) * D);
DP := PointF(B.X, -B.Y);
{
P2 := P.Add(PointF(DP.X, -DP.Y));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('Top D Point(%f, %f)', [P2.X, P2.Y]));
P2 := P.Add(PointF(-DP.X, DP.Y));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('Bottom D Point(%f, %f)', [P2.X, P2.Y]));
}
P2 := P.Add(PointF(0, -D/Cos(R) + 1));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('Center Top(%f, %f)', [P2.X, P2.Y]));
P2 := P.Add(PointF(-D/Sin(R)+1, 0));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('Center Left(%f, %f)', [P2.X, P2.Y]));
P2 := P.Add(PointF(D/Sin(R)-1, 0));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('Center Right(%f, %f)', [P2.X, P2.Y]));
P2 := P.Add(PointF(0, D/Cos(R)-1));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('Center Bottom(%f, %f)', [P2.X, P2.Y]));
P2 := Rect.TopLeft.Add(PointF(-B.X, B.Y));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('TopLeft Left(%f, %f)', [P2.X, P2.Y]));
P2 := Rect.TopLeft.Add(PointF(B.X, - B.Y));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('TopLeft Top(%f, %f)', [P2.X, P2.Y]));
P2 := Rect.TopLeft.Add(PointF(-B.Y, -B.X));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('TopLeft TopLeft(%f, %f)', [P2.X, P2.Y]));
P2 := Rect.BottomRight.Add(PointF(B.X, -B.Y));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('BottomRight Right(%f, %f)', [P2.X, P2.Y]));
P2 := Rect.BottomRight.Add(PointF(-B.X, B.Y));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('BottomRight Bottom(%f, %f)', [P2.X, P2.Y]));
P2 := Rect.BottomRight.Add(PointF(B.Y, B.X));
FCanvas.ClearSelection;
TestLib.RunMouseClick(P2.X, P2.Y);
Check(Assigned(FCanvas.SelectedItem), Format('BottomRight BottomRight(%f, %f)', [P2.X, P2.Y]));
end;
procedure TestTThLine.TestResizeLine;
begin
DrawLine(50, 50, 150, 150);
TestLib.RunMouseClick(100, 100);
MousePath.New
.Add(150, 150)
.Add(180, 180)
.Add(200, 200);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(180, 180);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check(Round(FCanvas.SelectedItem.Width) = 150, Format('Width : %f', [FCanvas.SelectedItem.Width]));
end;
procedure TestTThLine.TestResizeLineBRtoBottom;
begin
DrawLine(50, 50, 150, 150);
MousePath.New
.Add(150, 150)
.Add(50, 150);
TestLib.RunMousePath(MousePath.Path);
FCanvas.ClearSelection;
TestLib.RunMouseClick(50, 120);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check(
(FCanvas.SelectedItem.Width = 1) and (FCanvas.SelectedItem.Height = 100),
Format('W: %f, H: %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height])
);
end;
procedure TestTThLine.TestResizeLineBottomtoBLOver;
begin
DrawLine(250, 50, 250, 150);
TestLib.RunMouseClick(250, 100);
MousePath.New
.Add(250, 150)
.Add(245, 150)
.Add(150, 150);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(200, 100);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check(
(Round(FCanvas.SelectedItem.Width) = 100) and (Round(FCanvas.SelectedItem.Height) = 100),
Format('W: %f, H: %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height])
);
end;
procedure TestTThLine.TestResizeLineTLtoBROver;
begin
DrawLine(50, 50, 150, 150);
TestLib.RunMouseClick(100, 100);
MousePath.New
.Add(50, 50)
.Add(220, 220)
.Add(250, 250);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(180, 180);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check(
(Round(FCanvas.SelectedItem.Width) = 100) and (Round(FCanvas.SelectedItem.Height) = 100),
Format('W: %f, H: %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height])
);
end;
procedure TestTThLine.TestResizeLineTLtoRightOver;
begin
DrawLine(50, 50, 150, 150);
TestLib.RunMouseClick(100, 100);
MousePath.New
.Add(50, 50)
.Add(180, 55)
.Add(250, 50);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(200, 100);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check(
(Round(FCanvas.SelectedItem.Width) = 100) and (Round(FCanvas.SelectedItem.Height) = 100),
Format('W: %f, H: %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height])
);
end;
// S - 100 크기를 20으로 줄였을때 30이 되어야 한다.
procedure TestTThLine.TestResizeMinimum;
var
SizeP: TPointF;
begin
DrawLine(50, 50, 150, 150);
TestLib.RunMouseClick(100, 100);
//크기 조정
MousePath.New
.Add(150, 150)
.Add(180, 180)
.Add(70, 70);
TestLib.RunMousePath(MousePath.Path);
SizeP := DistanceSize(RectF(500, 500, 800, 800), ItemMinimumSize / CanvasZoomScaleDefault);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check(RoundTo(FCanvas.SelectedItem.Width, 3) = RoundTo(SizeP.X, 3), Format('W: %f', [FCanvas.SelectedItem.Width]));
end;
initialization
RegisterTest(TestTThLine.Suite);
end.
|
unit hdf5;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
{$Z+,A+}
Const
DLLname='HDF5DLL';
{Modules convertis: H5public.H
H5Ipublic.H
H5Fpublic.H
}
{************************************************* H5public.H *****************************************}
(* Version numbers *)
Const
H5_VERS_MAJOR=1; (* For major interface/format changes *)
H5_VERS_MINOR=6; (* For minor interface/format changes *)
H5_VERS_RELEASE=5; (* For tweaks, bug-fixes, or development *)
H5_VERS_SUBRELEASE='';(* For pre-releases like snap0 *)
(* Empty string for real releases. *)
H5_VERS_INFO='HDF5 library version: 1.6.5'; (* Full version string *)
(*
* Status return values. Failed integer functions in HDF5 result almost
* always in a negative value (unsigned failing functions sometimes return
* zero for failure) while successfull return is non-negative (often zero).
* The negative failure value is most commonly -1, but don't bet on it. The
* proper way to detect failure is something like:
*
* if ((dset = H5Dopen (file, name))<0) {
* fprintf (stderr, "unable to open the requested dataset\n");
* }
*)
type
herr_t=integer;
(*
* Boolean type. Successful return values are zero (false) or positive
* (true). The typical true value is 1 but don't bet on it. Boolean
* functions cannot fail. Functions that return `htri_t' however return zero
* (false), positive (true), or negative (failure). The proper way to test
* for truth from a htri_t function is:
*
* if ((retval = H5Tcommitted(type))>0) {
* printf("data type is committed\n");
* } else if (!retval) {
* printf("data type is not committed\n");
* } else {
* printf("error determining whether data type is committed\n");
* }
*)
hbool_t=longword;
htri_t=integer;
(* Define the ssize_t type if it not is defined *)
type
ssize_t=integer; { Au pif , essayer int64 }
hsize_t=integer;
hssize_t=integer;
size_t=integer;
(*
* File addresses have there own types.
*)
haddr_t= int64;
(* Functions in H5.c *)
var
H5open: function: herr_t;cdecl;
H5close: function: herr_t;cdecl;
H5dont_atexit: function: herr_t;cdecl;
H5garbage_collect: function: herr_t;cdecl;
H5set_free_list_limits:
function( reg_global_lim,reg_list_lim, arr_global_lim, arr_list_lim, blk_global_lim,
blk_list_lim:integer):herr_t;cdecl;
H5get_libversion: function(var majnum, minnum, relnum: longword):herr_t;cdecl;
H5check_version: function( majnum, minnum, relnum:longword): herr_t;cdecl;
{************************************************* H5Ipublic.h *****************************************}
(*
* Group values allowed. Start with `1' instead of `0' because it makes the
* tracing output look better when hid_t values are large numbers. Change the
* GROUP_BITS in H5I.c if the MAXID gets larger than 32 (an assertion will
* fail otherwise).
*
* When adding groups here, add a section to the 'misc19' test in test/tmisc.c
* to verify that the H5I{inc|dec|get}_ref() routines work correctly with in.
*
*)
type
H5I_type_t= ( H5I_BADID = (-1), (*invalid Group *)
H5I_FILE = 1, (*group ID for File objects *)
H5I_GROUP, (*group ID for Group objects *)
H5I_DATATYPE, (*group ID for Datatype objects *)
H5I_DATASPACE, (*group ID for Dataspace objects *)
H5I_DATASET, (*group ID for Dataset objects *)
H5I_ATTR, (*group ID for Attribute objects *)
H5I_REFERENCE, (*group ID for Reference objects *)
H5I_VFL, (*group ID for virtual file layer *)
H5I_GENPROP_CLS, (*group ID for generic property list classes *)
H5I_GENPROP_LST, (*group ID for generic property lists *)
H5I_NGROUPS (*number of valid groups, MUST BE LAST! *)
);
(* Type of atoms to return to users *)
hid_t=integer;
(* An invalid object ID. This is also negative for error return. *)
Const
H5I_INVALID_HID= -1;
var
(* Public API functions *)
H5Iget_type: function(id:hid_t):H5I_type_t;cdecl;
H5Iget_file_id: function(id:hid_t):hid_t ;cdecl;
H5Iget_name: function(id:hid_t; name:Pchar; size: size_t):ssize_t ;cdecl;
H5Iinc_ref: function(id:hid_t):integer;cdecl;
H5Idec_ref: function(id:hid_t):integer;cdecl;
H5Iget_ref: function(id:hid_t):integer;cdecl;
{************************************************* H5Dpublic.h ***************************************}
(* Values for the H5D_LAYOUT property *)
type
H5D_layout_t =(
H5D_LAYOUT_ERROR = -1,
H5D_COMPACT = 0, (*raw data is very small *)
H5D_CONTIGUOUS = 1, (*the default *)
H5D_CHUNKED = 2, (*slow and fancy *)
H5D_NLAYOUTS = 3 (*this one must be last! *)
);
(* Values for the space allocation time property *)
H5D_alloc_time_t =(
H5D_ALLOC_TIME_ERROR =-1,
H5D_ALLOC_TIME_DEFAULT =0,
H5D_ALLOC_TIME_EARLY =1,
H5D_ALLOC_TIME_LATE =2,
H5D_ALLOC_TIME_INCR =3
);
(* Values for the status of space allocation *)
H5D_space_status_t =(
H5D_SPACE_STATUS_ERROR =-1,
H5D_SPACE_STATUS_NOT_ALLOCATED =0,
H5D_SPACE_STATUS_PART_ALLOCATED =1,
H5D_SPACE_STATUS_ALLOCATED =2
);
(* Values for time of writing fill value property *)
H5D_fill_time_t =(
H5D_FILL_TIME_ERROR =-1,
H5D_FILL_TIME_ALLOC =0,
H5D_FILL_TIME_NEVER =1,
H5D_FILL_TIME_IFSET =2
);
(* Values for fill value status *)
H5D_fill_value_t =(
H5D_FILL_VALUE_ERROR =-1,
H5D_FILL_VALUE_UNDEFINED =0,
H5D_FILL_VALUE_DEFAULT =1,
H5D_FILL_VALUE_USER_DEFINED =2
);
(* Define the operator function pointer for H5Diterate() *)
type
H5D_operator_t=function(elem:pointer; type_id: hid_t; ndim:longword;var point:hsize_t; operator_data:pointer):herr_t;
var
H5Dcreate: function (file_id:hid_t ; name:Pchar; type_id:hid_t ; space_id:hid_t ; plist_id:hid_t ):hid_t;
H5Dopen: function (file_id:hid_t ; name:Pchar):hid_t ;
H5Dclose: function( dset_id: hid_t):herr_t ;
H5Dget_space: function (dset_id: hid_t ):hid_t ;
H5Dget_space_status: function(dset_id:hid_t ; var allocation:H5D_space_status_t):herr_t ;
H5Dget_type: function (dset_id:hid_t ):hid_t ;
H5Dget_create_plist: function ( dset_id:hid_t):hid_t ;
H5Dget_storage_size: function( dset_id:hid_t): hsize_t;
H5Dget_offset: function( dset_id:hid_t): haddr_t;
H5Dread: function (dset_id:hid_t ; mem_type_id:hid_t ; mem_space_id:hid_t ;file_space_id:hid_t ; plist_id:hid_t ; buf:pointer):herr_t ;
H5Dwrite: function (dset_id:hid_t ; mem_type_id:hid_t ; mem_space_id:hid_t ;file_space_id:hid_t ; plist_id:hid_t ; buf:pointer):herr_t ;
H5Dextend: function (dset_id:hid_t ; var size : hsize_t ):herr_t ;
H5Diterate: function(buf:pointer; type_id:hid_t ; space_id:hid_t ;op:H5D_operator_t ; operator_data:pointer):herr_t;
H5Dvlen_reclaim: function(type_id:hid_t ; space_id:hid_t ; plist_id:hid_t ; buf:pointer):herr_t ;
H5Dvlen_get_buf_size: function(dataset_id:hid_t ; type_id:hid_t ; space_id:hid_t ; var size:hsize_t):herr_t ;
H5Dfill: function(fill:pointer; fill_type:hid_t ; buf:pointer;buf_type:hid_t ; space: hid_t):herr_t ;
H5Dset_extent: function (dset_id:hid_t ; var size: hsize_t):herr_t ;
H5Ddebug: function( dset_id : hid_t):herr_t ;
{************************************************* H5Fpublic.H *****************************************}
(*
* These are the bits that can be passed to the `flags' argument of
* H5Fcreate() and H5Fopen(). Use the bit-wise OR operator (|) to combine
* them as needed. As a side effect, they call H5check_version() to make sure
* that the application is compiled with a version of the hdf5 header files
* which are compatible with the library to which the application is linked.
* We're assuming that these constants are used rather early in the hdf5
* session.
*
* NOTE: When adding H5F_ACC_* macros, remember to redefine them in H5Fprivate.h
*
*)
Const
H5F_ACC_RDONLY= $0000; (*absence of rdwr => rd-only *)
H5F_ACC_RDWR = $0001; (*open for read and write *)
H5F_ACC_TRUNC = $0002; (*overwrite existing files *)
H5F_ACC_EXCL = $0004; (*fail if file already exists*)
H5F_ACC_DEBUG = $0008; (*print debug info *)
H5F_ACC_CREAT = $0010; (*create non-existing files *)
(* Flags for H5Fget_obj_count() & H5Fget_obj_ids() calls *)
H5F_OBJ_FILE = $0001; (* File objects *)
H5F_OBJ_DATASET = $0002; (* Dataset objects *)
H5F_OBJ_GROUP = $0004; (* Group objects *)
H5F_OBJ_DATATYPE = $0008; (* Named datatype objects *)
H5F_OBJ_ATTR = $0010; (* Attribute objects *)
H5F_OBJ_ALL = H5F_OBJ_FILE or H5F_OBJ_DATASET or H5F_OBJ_GROUP or H5F_OBJ_DATATYPE or H5F_OBJ_ATTR;
H5F_OBJ_LOCAL = $0020; (* Restrict search to objects opened through current file ID *)
(* (as opposed to objects opened through any file ID accessing this file) *)
(* The difference between a single file and a set of mounted files *)
type
H5F_scope_t = (H5F_SCOPE_LOCAL, (*specified file handle only *)
H5F_SCOPE_GLOBAL, (*entire virtual file *)
H5F_SCOPE_DOWN (*for internal use only *)
);
(* Unlimited file size for H5Pset_external() *)
Const
H5F_UNLIMITED=-1;
(* How does file close behave?
* H5F_CLOSE_DEFAULT - Use the degree pre-defined by underlining VFL
* H5F_CLOSE_WEAK - file closes only after all opened objects are closed
* H5F_CLOSE_SEMI - if no opened objects, file is close; otherwise, file
close fails
* H5F_CLOSE_STRONG - if there are opened objects, close them first, then
close file
*)
type
H5F_close_degree_t=( H5F_CLOSE_DEFAULT = 0,
H5F_CLOSE_WEAK = 1,
H5F_CLOSE_SEMI = 2,
H5F_CLOSE_STRONG = 3
);
(* Functions in H5F.c *)
var
H5Fis_hdf5: function (filename:Pchar):htri_t ;cdecl;
H5Fcreate: function (filename:Pchar;flags:longword;create_plist:hid_t;access_plist:hid_t):hid_t;cdecl;
H5Fopen: function (filename:Pchar;flags:longword;access_plist:hid_t):hid_t;cdecl;
H5Freopen: function(file_id:hid_t):hid_t;cdecl;
H5Fflush: function(object_id:hid_t ;scope:H5F_scope_t ):herr_t ;cdecl;
H5Fclose: function (file_id:hid_t ):herr_t ;cdecl;
H5Fget_create_plist: function (file_id:hid_t ):hid_t ; cdecl;
H5Fget_access_plist: function ( file_id:hid_t):hid_t ; cdecl;
H5Fget_obj_count: function( file_id:hid_t; types:longword):integer;cdecl;
H5Fget_obj_ids: function(file_id:hid_t;types:longword;max_objs:integer; var obj_id_list: hid_t):integer;cdecl;
H5Fget_vfd_handle: function(file_id:hid_t ; fapl:hid_t ; var file_handle:pointer):herr_t ;cdecl;
H5Fmount: function(loc:hid_t;name:Pchar;child: hid_t ; plist:hid_t):herr_t ;cdecl;
H5Funmount: function(loc:hid_t ;name:Pchar):herr_t ;cdecl;
H5Fget_freespace: function( file_id:hid_t):hssize_t ;cdecl;
H5Fget_filesize: function( file_id:hid_t; var size:hsize_t):herr_t;cdecl;
H5Fget_name: function(obj_id:hid_t ; name:Pchar;size: size_t ):ssize_t;cdecl;
{**************************************************** H5FDpublic.H *********************************}
(*
* Types of allocation requests. The values larger than H5FD_MEM_DEFAULT
* should not change other than adding new types to the end. These numbers
* might appear in files.
*)
type
H5FD_mem_t =(
H5FD_MEM_NOLIST = -1, (*must be negative*)
H5FD_MEM_DEFAULT = 0, (*must be zero*)
H5FD_MEM_SUPER = 1,
H5FD_MEM_BTREE = 2,
H5FD_MEM_DRAW = 3,
H5FD_MEM_GHEAP = 4,
H5FD_MEM_LHEAP = 5,
H5FD_MEM_OHDR = 6,
H5FD_MEM_NTYPES (*must be last*)
);
(*
* A free-list map which maps all types of allocation requests to a single
* free list. This is useful for drivers that don't really care about
* keeping different requests segregated in the underlying file and which
* want to make most efficient reuse of freed memory. The use of the
* H5FD_MEM_SUPER free list is arbitrary.
*)
Const
H5FD_FLMAP_SINGLE:array[1..7] of H5FD_mem_t =(
H5FD_MEM_SUPER, (*default*)
H5FD_MEM_SUPER, (*super*)
H5FD_MEM_SUPER, (*btree*)
H5FD_MEM_SUPER, (*draw*)
H5FD_MEM_SUPER, (*gheap*)
H5FD_MEM_SUPER, (*lheap*)
H5FD_MEM_SUPER (*ohdr*)
);
(*
* A free-list map which segregates requests into `raw' or `meta' data
* pools.
*)
H5FD_FLMAP_DICHOTOMY:array[1..7] of H5FD_mem_t =(
H5FD_MEM_SUPER, (*default*)
H5FD_MEM_SUPER, (*super*)
H5FD_MEM_SUPER, (*btree*)
H5FD_MEM_DRAW, (*draw*)
H5FD_MEM_SUPER, (*gheap*)
H5FD_MEM_SUPER, (*lheap*)
H5FD_MEM_SUPER (*ohdr*)
);
(*
* The default free list map which causes each request type to use it's own
* free-list.
*)
H5FD_FLMAP_DEFAULT: array[1..7] of H5FD_mem_t =(
H5FD_MEM_DEFAULT, (*default*)
H5FD_MEM_DEFAULT, (*super*)
H5FD_MEM_DEFAULT, (*btree*)
H5FD_MEM_DEFAULT, (*draw*)
H5FD_MEM_DEFAULT, (*gheap*)
H5FD_MEM_DEFAULT, (*lheap*)
H5FD_MEM_DEFAULT (*ohdr*)
);
(* Define VFL driver features that can be enabled on a per-driver basis *)
(* These are returned with the 'query' function pointer in H5FD_class_t *)
(*
* Defining the H5FD_FEAT_AGGREGATE_METADATA for a VFL driver means that
* the library will attempt to allocate a larger block for metadata and
* then sub-allocate each metadata request from that larger block.
*)
H5FD_FEAT_AGGREGATE_METADATA = $00000001;
(*
* Defining the H5FD_FEAT_ACCUMULATE_METADATA for a VFL driver means that
* the library will attempt to cache metadata as it is written to the file
* and build up a larger block of metadata to eventually pass to the VFL
* 'write' routine.
*
* Distinguish between updating the metadata accumulator on writes and
* reads. This is particularly (perhaps only, even) important for MPI-I/O
* where we guarantee that writes are collective, but reads may not be.
* If we were to allow the metadata accumulator to be written during a
* read operation, the application would hang.
*)
H5FD_FEAT_ACCUMULATE_METADATA_WRITE = $00000002;
H5FD_FEAT_ACCUMULATE_METADATA_READ = $00000004;
H5FD_FEAT_ACCUMULATE_METADATA = H5FD_FEAT_ACCUMULATE_METADATA_WRITE or H5FD_FEAT_ACCUMULATE_METADATA_READ;
(*
* Defining the H5FD_FEAT_DATA_SIEVE for a VFL driver means that
* the library will attempt to cache raw data as it is read from/written to
* a file in a "data seive" buffer. See Rajeev Thakur's papers:
* http://www.mcs.anl.gov/~thakur/papers/romio-coll.ps.gz
* http://www.mcs.anl.gov/~thakur/papers/mpio-high-perf.ps.gz
*)
H5FD_FEAT_DATA_SIEVE = $00000008;
(*
* Defining the H5FD_FEAT_AGGREGATE_SMALLDATA for a VFL driver means that
* the library will attempt to allocate a larger block for "small" raw data
* and then sub-allocate "small" raw data requests from that larger block.
*)
H5FD_FEAT_AGGREGATE_SMALLDATA = $00000010;
(* Forward declaration *)
typedef struct H5FD_t H5FD_t;
(* Class information for each file driver *)
typedef struct H5FD_class_t {
const char *name;
haddr_t maxaddr;
H5F_close_degree_t fc_degree;
hsize_t (*sb_size)(H5FD_t *file);
herr_t (*sb_encode)(H5FD_t *file, char *name(*out*),
unsigned char *p(*out*));
herr_t (*sb_decode)(H5FD_t *f, const char *name, const unsigned char *p);
size_t fapl_size;
void * (*fapl_get)(H5FD_t *file);
void * (*fapl_copy)(const void *fapl);
herr_t (*fapl_free)(void *fapl);
size_t dxpl_size;
void * (*dxpl_copy)(const void *dxpl);
herr_t (*dxpl_free)(void *dxpl);
H5FD_t *(*open)(const char *name, unsigned flags, hid_t fapl,
haddr_t maxaddr);
herr_t (*close)(H5FD_t *file);
int (*cmp)(const H5FD_t *f1, const H5FD_t *f2);
herr_t (*query)(const H5FD_t *f1, unsigned long *flags);
haddr_t (*alloc)(H5FD_t *file, H5FD_mem_t type, hid_t dxpl_id, hsize_t size);
herr_t (*free)(H5FD_t *file, H5FD_mem_t type, hid_t dxpl_id,
haddr_t addr, hsize_t size);
haddr_t (*get_eoa)(H5FD_t *file);
herr_t (*set_eoa)(H5FD_t *file, haddr_t addr);
haddr_t (*get_eof)(H5FD_t *file);
herr_t (*get_handle)(H5FD_t *file, hid_t fapl, void**file_handle);
herr_t (*read)(H5FD_t *file, H5FD_mem_t type, hid_t dxpl,
haddr_t addr, size_t size, void *buffer);
herr_t (*write)(H5FD_t *file, H5FD_mem_t type, hid_t dxpl,
haddr_t addr, size_t size, const void *buffer);
herr_t (*flush)(H5FD_t *file, hid_t dxpl_id, unsigned closing);
herr_t (*lock)(H5FD_t *file, unsigned char *oid, unsigned lock_type, hbool_t last);
herr_t (*unlock)(H5FD_t *file, unsigned char *oid, hbool_t last);
H5FD_mem_t fl_map[H5FD_MEM_NTYPES];
} H5FD_class_t;
(* A free list is a singly-linked list of address/size pairs. *)
typedef struct H5FD_free_t {
haddr_t addr;
hsize_t size;
struct H5FD_free_t *next;
} H5FD_free_t;
(*
* The main datatype for each driver. Public fields common to all drivers
* are declared here and the driver appends private fields in memory.
*)
struct H5FD_t {
hid_t driver_id; (*driver ID for this file *)
const H5FD_class_t *cls; (*constant class info *)
unsigned long fileno[2]; (* File serial number *)
unsigned long feature_flags; (* VFL Driver feature Flags *)
hsize_t threshold; (* Threshold for alignment *)
hsize_t alignment; (* Allocation alignment *)
hsize_t reserved_alloc; (* Space reserved for later alloc calls *)
(* Metadata aggregation fields *)
hsize_t def_meta_block_size; (* Metadata allocation
* block size (if
* aggregating metadata) *)
hsize_t cur_meta_block_size; (* Current size of metadata
* allocation region left *)
haddr_t eoma; (* End of metadata
* allocated region *)
(* "Small data" aggregation fields *)
hsize_t def_sdata_block_size; (* "Small data"
* allocation block size
* (if aggregating "small
* data") *)
hsize_t cur_sdata_block_size; (* Current size of "small
* data" allocation
* region left *)
haddr_t eosda; (* End of "small data"
* allocated region *)
(* Metadata accumulator fields *)
unsigned char *meta_accum; (* Buffer to hold the accumulated metadata *)
haddr_t accum_loc; (* File location (offset) of the
* accumulated metadata *)
size_t accum_size; (* Size of the accumulated
* metadata buffer used (in
* bytes) *)
size_t accum_buf_size; (* Size of the accumulated
* metadata buffer allocated (in
* bytes) *)
unsigned accum_dirty; (* Flag to indicate that the
* accumulated metadata is dirty *)
haddr_t maxaddr; (* For this file, overrides class *)
H5FD_free_t *fl[H5FD_MEM_NTYPES]; (* Freelist per allocation type *)
hsize_t maxsize; (* Largest object on FL, or zero *)
};
#ifdef __cplusplus
extern "C" {
#endif
(* Function prototypes *)
H5_DLL hid_t H5FDregister(const H5FD_class_t *cls);
H5_DLL herr_t H5FDunregister(hid_t driver_id);
H5_DLL H5FD_t *H5FDopen(const char *name, unsigned flags, hid_t fapl_id,
haddr_t maxaddr);
H5_DLL herr_t H5FDclose(H5FD_t *file);
H5_DLL int H5FDcmp(const H5FD_t *f1, const H5FD_t *f2);
H5_DLL int H5FDquery(const H5FD_t *f, unsigned long *flags);
H5_DLL haddr_t H5FDalloc(H5FD_t *file, H5FD_mem_t type, hid_t dxpl_id, hsize_t size);
H5_DLL herr_t H5FDfree(H5FD_t *file, H5FD_mem_t type, hid_t dxpl_id,
haddr_t addr, hsize_t size);
H5_DLL haddr_t H5FDrealloc(H5FD_t *file, H5FD_mem_t type, hid_t dxpl_id,
haddr_t addr, hsize_t old_size, hsize_t new_size);
H5_DLL haddr_t H5FDget_eoa(H5FD_t *file);
H5_DLL herr_t H5FDset_eoa(H5FD_t *file, haddr_t eof);
H5_DLL haddr_t H5FDget_eof(H5FD_t *file);
H5_DLL herr_t H5FDget_vfd_handle(H5FD_t *file, hid_t fapl, void**file_handle);
H5_DLL herr_t H5FDread(H5FD_t *file, H5FD_mem_t type, hid_t dxpl_id,
haddr_t addr, size_t size, void *buf(*out*));
H5_DLL herr_t H5FDwrite(H5FD_t *file, H5FD_mem_t type, hid_t dxpl_id,
haddr_t addr, size_t size, const void *buf);
H5_DLL herr_t H5FDflush(H5FD_t *file, hid_t dxpl_id, unsigned closing);
#ifdef __cplusplus
}
#endif
#endif
{H5Ppublic.H}
(* Default Template for creation, access, etc. templates *)
Const
H5P_DEFAULT=0;
(* Public headers needed by this file *)
(*
#include "H5public.h"
#include "H5Ipublic.h"
#include "H5Dpublic.h"
#include "H5Fpublic.h"
#include "H5FDpublic.h"
#include "H5MMpublic.h"
#include "H5Zpublic.h"
*)
type
off_t=integer;
(* Define property list class callback function pointer types *)
type
H5P_cls_create_func_t= function(prop_id: hid_t;var create_data):herr_t;cdecl;
H5P_cls_copy_func_t = function (new_prop_id:hid_t ; old_prop_id:hid_t; var copy_data):herr_t ;
H5P_cls_close_func_t= function (prop_id:hid_t ; var close_data: pointer):herr_t;
(* Define property list callback function pointer types *)
H5P_prp_cb1_t= function (name: Pchar; size: size_t; var value:pointer):herr_t ;
H5P_prp_cb2_t= function (prop_id:hid_t ; name:Pchar; size:size_t;var value):herr_t;
H5P_prp_create_func_t = H5P_prp_cb1_t;
H5P_prp_set_func_t = H5P_prp_cb2_t;
H5P_prp_get_func_t = H5P_prp_cb2_t;
H5P_prp_delete_func_t = H5P_prp_cb2_t;
H5P_prp_copy_func_t = H5P_prp_cb1_t;
H5P_prp_compare_func_t= function(var value1;var value2; size:size_t):integer;
H5P_prp_close_func_t = H5P_prp_cb1_t;
(* Define property list iteration function type *)
H5P_iterate_t = function( id:hid_t; name:Pchar;var iter_data):herr_t;
(* Public functions *)
var
H5Pcreate_class: function(parent:hid_t ; name:Pchar;
cls_create:H5P_cls_create_func_t ; create_data: pointer;
cls_copy:H5P_cls_copy_func_t ; copy_data:pointer;
cls_close:H5P_cls_close_func_t ; close_data:pointer):hid_t ;
H5Pget_class_name: function(pclass_id:hid_t ):Pchar;
H5Pcreate: function(cls_id:hid_t ):hid_t ;
H5Pregister: function(cls_id:hid_t ; name:Pchar; size:size_t ;
def_value:pointer; prp_create:H5P_prp_create_func_t ;
prp_set:H5P_prp_set_func_t ;prp_get: H5P_prp_get_func_t ;
prp_del:H5P_prp_delete_func_t ;
prp_copy:H5P_prp_copy_func_t ;
prp_close:H5P_prp_close_func_t ):herr_t ;
H5Pinsert: function(plist_id:hid_t ; name:Pchar; size:size_t ;
value:pointer; prp_set:H5P_prp_set_func_t ; prp_get:H5P_prp_get_func_t ;
prp_delete:H5P_prp_delete_func_t ;
prp_copy:H5P_prp_copy_func_t ;
prp_close:H5P_prp_close_func_t ):herr_t ;
H5Pset: function(plist_id: hid_t ; name:Pchar; value:pointer):herr_t ;
H5Pexist: function(plist_id: hid_t ; name: Pchar):htri_t ;
H5Pget_size: function(id: hid_t ; name:Pchar; size: size_t):herr_t ;
H5Pget_nprops: function(id: hid_t ; var nprops:size_t):herr_t ;
H5Pget_class: function( plist_id:hid_t):hid_t ;
H5Pget_class_parent: function(pclass_id:hid_t ):hid_t ;
H5Pget: function(plist_id: hid_t ; name:Pchar; value:pointer):herr_t ;
H5Pequal: function(id1: hid_t ; id2:hid_t):htri_t ;
H5Pisa_class: function(plist_id: hid_t ; pclass_id: hid_t):htri_t ;
H5Piterate: function(id: hid_t ;var idx: integer; iter_func: H5P_iterate_t ;iter_data:pointer):integer ;
H5Pcopy_prop: function(dst_id: hid_t ; src_id: hid_t ; name:Pchar):herr_t ;
H5Premove: function(plist_id: hid_t ; name:Pchar):herr_t ;
H5Punregister: function(pclass_id: hid_t ; name:Pchar):herr_t ;
H5Pclose_class: function( plist_id:hid_t):herr_t ;
H5Pclose: function( plist_id: hid_t):herr_t ;
H5Pcopy: function(plist_id:hid_t ):hid_t ;
H5Pget_version: function(plist_id: hid_t ; var boot,freelist, stab,shhdr: longword):herr_t ;
H5Pset_userblock: function(plist_id: hid_t ; size:hsize_t):herr_t ;
H5Pget_userblock: function( plist_id:hid_t; var size:hsize_t):herr_t ;
H5Pset_alignment: function(fapl_id: hid_t ; threshold: hsize_t ; alignment:hsize_t):herr_t ;
H5Pget_alignment: function(fapl_id: hid_t ; var threshold: hsize_t ;var alignment:hsize_t):herr_t ;
H5Pset_sizes: function(plist_id: hid_t ; sizeof_addr: size_t; sizeof_size: size_t):herr_t ;
H5Pget_sizes: function(plist_id: hid_t ; var sizeof_addr: size_t ; var sizeof_size:size_t):herr_t ;
H5Pset_sym_k: function(plist_id: hid_t ; ik,lk:longword):herr_t ;
H5Pget_sym_k: function(plist_id: hid_t ;var ik, lk: longword):herr_t ;
H5Pset_istore_k: function(plist_id: hid_t ; ik:longword):herr_t ;
H5Pget_istore_k: function(plist_id: hid_t ;var ik:longword):herr_t ;
H5Pset_layout: function(plist_id: hid_t ; layout:H5D_layout_t):herr_t ;
H5Pget_layout: function( plist_id:hid_t):H5D_layout_t ;
H5Pset_chunk: function(plist_id: hid_t ; ndims: integer ; var dim: hsize_t ):herr_t ;
H5Pget_chunk: function(plist_id:hid_t ; max_ndims:integer ; var dim:hsize_t):integer ;
H5Pset_external: function(plist_id:hid_t ; name:Pchar; offset:off_t ;size:hsize_t):herr_t ;
H5Pget_external_count: function(plist_id:hid_t ):integer ;
H5Pget_external: function(plist_id:hid_t ; idx:longword; name_size:size_t ;
name:Pchar;var offset: off_t; var size:hsize_t):herr_t ;
H5Pset_driver: function(plist_id:hid_t ; driver_id:hid_t ;driver_info:pointer):herr_t ;
H5Pget_driver: function(plist_id:hid_t ):hid_t ;
H5Pget_driver_info: function(plist_id:hid_t ):pointer;
H5Pset_family_offset: function(fapl_id:hid_t ; offset:hsize_t):herr_t ;
H5Pget_family_offset: function(fapl_id:hid_t ; var offset:hsize_t):herr_t ;
H5Pset_multi_type: function(fapl_id:hid_t ; tp:H5FD_mem_t ):herr_t ;
H5Pget_multi_type: function(fapl_id:hid_t ; var tp:H5FD_mem_t ):herr_t ;
H5Pset_buffer: function(plist_id:hid_t ; size:size_t ; tconv:pointer;bkg:pointer):herr_t ;
H5Pget_buffer: function(plist_id:hid_t ; var tconv:pointer;var bkg:pointer):size_t ;
H5Pset_preserve: function(plist_id:hid_t ; status:hbool_t):herr_t ;
H5Pget_preserve: function( plist_id:hid_t):int ;
H5Pmodify_filter: function(plist_id:hid_t ; filter:H5Z_filter_t ;flags:longword; cd_nelmts:size_t ;var cd_values:longword):herr_t ;
H5Pset_filter: function(plist_id:hid_t ; filter:H5Z_filter_t ; flags:longword; cd_nelmts:size_t ; var c_values:longword):herr_t ;
H5Pget_nfilters: function( plist_id:hid_t):integer ;
H5Pget_filter: function(plist_id:hid_t ; filter:longword,
var flags:longword,
var cd_nelmts:size_t ;
var cd_values:longword ;
namelen:size_t ; name:Pchar):H5Z_filter_t ;
H5Pget_filter_by_id: function(hid_t plist_id, H5Z_filter_t id,
unsigned int *flags(*out*),
size_t *cd_nelmts(*out*),
unsigned cd_values[](*out*),
size_t namelen, char name[]):H5Z_filter_t ;
H5Pall_filters_avail: function(hid_t plist_id):htri_t ;
H5Pset_deflate: function(hid_t plist_id, unsigned aggression):herr_t ;
H5Pset_szip: function(hid_t plist_id, unsigned options_mask, unsigned pixels_per_block):herr_t ;
H5Pset_shuffle: function(hid_t plist_id):herr_t ;
H5Pset_fletcher32: function(hid_t plist_id):herr_t ;
H5Pset_edc_check: function(hid_t plist_id, H5Z_EDC_t check):herr_t ;
H5Pget_edc_check: function(hid_t plist_id):H5Z_EDC_t ;
H5Pset_filter_callback: function(hid_t plist_id, H5Z_filter_func_t func,void* op_data):herr_t ;
H5Pset_cache: function(hid_t plist_id, int mdc_nelmts, size_t rdcc_nelmts,size_t rdcc_nbytes, double rdcc_w0):herr_t ;
H5Pget_cache: function(hid_t plist_id, int *mdc_nelmts(*out*),
size_t *rdcc_nelmts(*out*),
size_t *rdcc_nbytes(*out*), double *rdcc_w0):herr_t ;
H5Pset_btree_ratios: function(hid_t plist_id, double left, double middle,double right):herr_t ;
H5Pget_btree_ratios: function(hid_t plist_id, double *left(*out*),
double *middle(*out*),
double *right(*out*)):herr_t ;
H5Pset_fill_value: function(hid_t plist_id, hid_t type_id, const void *value):herr_t ;
H5Pget_fill_value: function(hid_t plist_id, hid_t type_id,void *value(*out*)):herr_t ;
H5Pfill_value_defined: function(hid_t plist, H5D_fill_value_t *status):herr_t ;
H5Pset_alloc_time: function(hid_t plist_id, H5D_alloc_time_t alloc_time):herr_t ;
H5Pget_alloc_time: function(hid_t plist_id, H5D_alloc_time_t *alloc_time(*out*)):herr_t ;
H5Pset_fill_time: function(hid_t plist_id, H5D_fill_time_t fill_time):herr_t ;
H5Pget_fill_time: function(hid_t plist_id, H5D_fill_time_t *fill_time(*out*)):herr_t ;
H5Pset_gc_references: function(hid_t fapl_id, unsigned gc_ref):herr_t ;
H5Pget_gc_references: function(hid_t fapl_id, unsigned *gc_ref(*out*)):herr_t ;
H5Pset_fclose_degree: function(hid_t fapl_id, H5F_close_degree_t degree):herr_t ;
H5Pget_fclose_degree: function(hid_t fapl_id, H5F_close_degree_t *degree):herr_t ;
H5Pset_vlen_mem_manager: function(hid_t plist_id,
H5MM_allocate_t alloc_func,
void *alloc_info, H5MM_free_t free_func,
void *free_info):herr_t ;
H5Pget_vlen_mem_manager: function(hid_t plist_id,
H5MM_allocate_t *alloc_func,
void **alloc_info,
H5MM_free_t *free_func,
void **free_info):herr_t ;
H5Pset_meta_block_size: function(hid_t fapl_id, hsize_t size):herr_t ;
H5Pget_meta_block_size: function(hid_t fapl_id, hsize_t *size(*out*)):herr_t ;
H5Pset_sieve_buf_size: function(hid_t fapl_id, size_t size):herr_t ;
H5Pget_sieve_buf_size: function(hid_t fapl_id, size_t *size(*out*)):herr_t ;
H5Pset_hyper_vector_size: function(hid_t fapl_id, size_t size):herr_t ;
H5Pget_hyper_vector_size: function(hid_t fapl_id, size_t *size(*out*)):herr_t ;
H5Pset_small_data_block_size: function(hid_t fapl_id, hsize_t size):herr_t ;
H5Pget_small_data_block_size: function(hid_t fapl_id, hsize_t *size(*out*)):herr_t ;
H5Premove_filter: function(hid_t plist_id, H5Z_filter_t filter):herr_t ;
function InitHDF5:boolean;
procedure freeHDF5;
implementation
uses windows,math,util1,ncdef2;
var
hh:integer;
function getProc(hh:Thandle;st:string):pointer;
begin
result:=GetProcAddress(hh,Pchar(st));
if result=nil then messageCentral(st+'=nil');
{else messageCentral(st+' OK');}
end;
function InitHDF5:boolean;
begin
result:=true;
if hh<>0 then exit;
hh:=GloadLibrary(DLLname);
result:=(hh<>0);
if not result then exit;
H5open:=getProc(hh,'H5open');
H5close:=getProc(hh,'H5close');
H5dont_atexit:=getProc(hh,'H5dont_atexit');
H5garbage_collect:=getProc(hh,'H5garbage_collect');
H5set_free_list_limits:=getProc(hh,'H5set_free_list_limits');
H5get_libversion:=getProc(hh,'H5get_libversion');
H5check_version:=getProc(hh,'H5check_version');
H5Iget_type:=getProc(hh,'H5Iget_type');
H5Iget_file_id:=getProc(hh,'H5Iget_file_id');
H5Iget_name:=getProc(hh,'H5Iget_name');
H5Iinc_ref:=getProc(hh,'H5Iinc_ref');
H5Idec_ref:=getProc(hh,'H5Idec_ref');
H5Iget_ref:=getProc(hh,'H5Iget_ref');
H5Fis_hdf5:=getProc(hh,'H5Fis_hdf5');
H5Fcreate:=getProc(hh,'H5Fcreate');
H5Fopen:=getProc(hh,'H5Fopen');
H5Freopen:=getProc(hh,'H5Freopen');
H5Fflush:=getProc(hh,'H5Fflush');
H5Fclose:=getProc(hh,'H5Fclose');
H5Fget_create_plist:=getProc(hh,'H5Fget_create_plist');
H5Fget_access_plist:=getProc(hh,'H5Fget_access_plist');
H5Fget_obj_count:=getProc(hh,'H5Fget_obj_count');
H5Fget_obj_ids:=getProc(hh,'H5Fget_obj_ids');
H5Fget_vfd_handle:=getProc(hh,'H5Fget_vfd_handle');
H5Fmount:=getProc(hh,'H5Fmount');
H5Funmount:=getProc(hh,'H5Funmount');
H5Fget_freespace:=getProc(hh,'H5Fget_freespace');
H5Fget_filesize:=getProc(hh,'H5Fget_filesize');
H5Fget_name:=getProc(hh,'H5Fget_name');
end;
procedure freeHDF5;
begin
if hh<>0 then freeLibrary(hh);
hh:=0;
end;
procedure HDF5test;
begin
if not initHDF5 then sortieErreur('unable to initialize HDF5 library');
end;
Initialization
AffDebug('Initialization hdf5',0);
finalization
freeHDF5;
end.
|
{------------------------------------------------------------------------------------}
{program p019_000 exercises production #019 }
{subprogram_head -> PROCDURE ID subprogram_parameters ; }
{------------------------------------------------------------------------------------}
{Author: Thomas R. Turner }
{E-Mail: trturner@uco.edu }
{Date: January, 2012 }
{------------------------------------------------------------------------------------}
{Copyright January, 2012 by Thomas R. Turner }
{Do not reproduce without permission from Thomas R. Turner. }
{------------------------------------------------------------------------------------}
program p019_000;
function max(a,b:integer):integer;
begin{max}
if a>b then max:=a else max:=b
end{max};
procedure print(a,b:integer);
begin{print}
writeln('The maximum of ',a,' and ',b,' is ',max(a,b))
end{print};
begin{p019_000}
print(2,3)
end{p019_000}.
|
{ Demo unit : Bezier curves and smothing algorithm
Jean-Yves Queinec : j.y.q@wanadoo.fr
Keywords : Bezier curves
Smoothing algorithm with smooth factor
square to circle transformation
coloured flowers }
unit UB1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, ComCtrls, Buttons;
type
TForm1 = class(TForm)
Panel1: TPanel;
Button1: TButton;
UpDown1: TUpDown;
Edit1: TEdit;
Label1: TLabel;
UpDown2: TUpDown;
Edit2: TEdit;
Label2: TLabel;
Button2: TButton;
Button3: TButton;
Image1: TImage;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
Panel2: TPanel;
RadioGroup1: TRadioGroup;
Panel3: TPanel;
PaintBox1: TPaintBox;
Panelcolo: TPanel;
Panel4: TPanel;
PaintBox2: TPaintBox;
CheckBox3: TCheckBox;
SpeedButton1: TSpeedButton;
Panel5: TPanel;
Memo1: TMemo;
Button4: TButton;
Button5: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure UpDown1Click(Sender: TObject; Button: TUDBtnType);
procedure FormCreate(Sender: TObject);
procedure UpDown2Click(Sender: TObject; Button: TUDBtnType);
procedure FormDestroy(Sender: TObject);
procedure Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CheckBox2Click(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure RadioGroup1Click(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure PaintBox2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBox2Paint(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure PaintBox2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
Bmpfond : Tbitmap; { background bitmap with grid pattern }
Figure : integer; { kingd of shape }
cx, cy : integer; { image centre }
NB1 : longint; { Nunber of points }
AA : array[0..64] of Tpoint; { points }
NB2 : longint; { number of points used for Bezier curve }
BB : array[0..64*3] of Tpoint; { points for Bezier curve}
{ polygon drawing }
Anglepoly : single; { angle regular polygon }
Angles : array[0..64*3] of single; { memorize original angles }
drawing : boolean;
Startp : integer; { current BB point (clic select) }
Startangle : single; { starting angle for current point }
Startx : integer;
Starty : integer;
infoang : array[0..2] of single; { to draw a polygon }
{ colors }
couleur : array[0..127] of Tcolor;
public
Procedure Affichage(lisser : boolean);
procedure Dessin;
procedure Quadrillage;
procedure lissage(acoef: integer);
procedure polygone;
procedure sinusoide;
procedure Lescouleurs;
procedure setpipette(pstyle : boolean);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
crpipette = 2;
{---- The Form ---}
procedure TForm1.FormCreate(Sender: TObject);
begin
Screen.Cursors[crPipette] := LoadCursor(HInstance, 'PCURSEUR');
drawing := false;
lescouleurs;
quadrillage;
figure := 0;
affichage(true);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Bmpfond.free;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
close;
end;
{---- Utility Fonctions ----------}
Function Egalpoints(pt1, pt2 : tpoint): boolean;
begin
IF (pt1.x = pt2.x) AND (pt1.y = Pt2.y) then result := true
else result := false;
end;
Function arctangente(ax, ay : integer) : single;
var
symetrie : boolean;
wx, wy : single;
begin
if ax < 0 then symetrie := true else symetrie := false;
wx := abs(ax);
wy := -ay;
IF wx < 0.001 then { avoid zero divide }
begin
if wy < 0 then result := pi+pi/2 else result := pi/2;
end
else
begin
result := arctan(wy / wx);
IF symetrie then result := pi - result;
end;
end;
procedure Tform1.quadrillage; // bmpfond grid pattern
var
i : integer;
begin
Bmpfond := tbitmap.create;
Bmpfond.width := image1.width;
Bmpfond.height := image1.height;
with Bmpfond.canvas do
begin
brush.color := clwhite;
fillrect(rect(0,0,Image1.width, Image1.height));
cx := Image1.width div 2;
cy := Image1.height div 2;
for i := 1 to Image1.width div 10 do
begin
if i mod 5 = 0 then pen.color := $00B0E0FF else pen.color := $00F0F4FF;
moveto(cx+i*5, 0); lineto(cx+i*5, Image1.height);
moveto(cx-i*5, 0); lineto(cx-i*5, Image1.height);
end;
for i := 1 to Image1.height div 10 do
begin
if i mod 5 = 0 then pen.color := $00B0E0FF else pen.color := $00F0F4FF;
moveto(0,cy+i*5); lineto(Image1.width,cy+i*5);
moveto(0,cy-i*5); lineto(Image1.width,cy-i*5);
end;
pen.color:= $0080B0D0;
moveto(0,cy); lineto(Image1.width,cy);
moveto(cx,0); lineto(cx, Image1.height);
end;
end;
{ Smoothing algorithm
computes Bezier control points
acoef is the smoothing factor
Takes care of points 0 and NB2 when they are at the same
location(closed curve) }
procedure TForm1.lissage(acoef: integer);
var
i, j : integer;
Function sym(a, b : integer): integer; // symmmetry b / a
begin
result := a - ((b-a)*acoef) div 100;
end;
Function mil(a, b : integer): integer; // middle
begin
result := (a+b) div 2;
end;
// computes a control point position based on
// symmetries of 2 adjacents points BB n-1 et BBn+1.
Function ctrlpt(pt, pt1, pt2 : tpoint): tpoint;
begin
result.x := mil(mil(pt.x, pt1.x), mil(sym(pt.x, pt2.x), pt.x));
result.y := mil(mil(pt.y, pt1.y), mil(sym(pt.y, pt2.y), pt.y));
end;
begin
// Computes control points
For j := 1 to NB1-1 do // points of the cource (edges) excluding end points
begin
i := j*3; // range of point in the BB array
BB[i-1] := ctrlpt(BB[i], BB[i-3], BB[i+3]); // prior control point
BB[i+1] := ctrlpt(BB[i], BB[i+3], BB[i-3]); // next control point
end;
IF egalpoints(BB[0], BB[NB2]) then
begin // closed curve
BB[0+1] := ctrlpt(BB[0], BB[3], BB[NB2-3]);
BB[NB2-1] := ctrlpt(BB[NB2], BB[NB2-3], BB[3]);
end
else
begin // open curve
BB[1] := BB[0]; // "right" control point from 0
BB[NB2-1] := BB[NB2]; // "lef" control point from NB2
end;
end;
procedure TForm1.Affichage(lisser : boolean);
var
i : integer;
begin
Image1.canvas.draw(0,0,bmpfond);
case figure of
0 : polygone;
1 : sinusoide;
end;
IF lisser then
begin
// copy the AA array points to BB array
NB2 := NB1*3;
for i := 0 to NB1 do
begin
BB[i*3] := AA[i]; // interval is 3 points
end;
lissage(Updown1.position);
// memorize angular positions in order to keep good precision
// during successive points displacements
IF figure = 0 then for i := 0 to NB2 do
begin
Angles[i] := arctangente(BB[i].x-cx, BB[i].y-cy);
if i < 3 then infoang[i] := Angles[i]; // memorize angles
end;
end;
IF checkbox1.checked then
begin
with image1.canvas do
begin
pen.color := clsilver;
polyline(slice(AA,NB1+1));
pen.color := clblack;
end;
end;
dessin;
end;
// Regular Polygon from number of points NB1
procedure Tform1.Polygone;
var
i : integer;
a1, b : single; // angle and radius
cx, cy : integer; // centre
begin
cx := image1.width div 2;
cy := image1.height div 2;
b := 200.0; // radius
NB1 := updown2.position; // polygone is closed
IF NB1 < 2 then exit;
anglepoly := 2*pi / NB1; // angle increment
a1 := pi / 2; // starting angle
For i := 0 to NB1-1 do
begin
AA[i].x := cx + round(b*cos(a1));
AA[i].y := cy - round(b*sin(a1)); // y inversed
a1 := a1+anglepoly;
end;
AA[NB1] := AA[0]; // close polygon
end;
procedure Tform1.Sinusoide; // aligned points and sine curve
var
i : integer;
a0, a, b : integer;
r : integer;
begin
NB1 := Updown2.position;
a := (Image1.width - 24) div NB1;
a0 := cx - a*(NB1 div 2);
b := Image1.height*3 div 8;
for i := 0 to NB1 do
begin
AA[i].x := a0+a*i;
r := i mod 4;
case r of
0 : AA[i].y := cy;
1 : AA[i].y := cy-b;
2 : AA[i].y := cy;
3 : AA[i].y := cy+b;
end;
end;
IF nb1 mod 2 = 1 then nb1 := nb1 - 1; // even nunber of points
end;
procedure Tform1.Dessin; // draws Bezier curve and points
var
i : integer;
{-----}
procedure unecroix(ax, ay : integer; acolor : tcolor);
begin
with image1.canvas do
begin
pen.color := acolor;
moveto(ax-1, ay); lineto (ax+2, ay);
moveto(ax, ay-1); lineto(ax, ay+2);
end;
end;
{-----}
begin
with image1.canvas do
begin
pen.color := cllime;
if drawing and ((figure = 1) OR (Checkbox1.checked = false)) then
begin
case startp mod 3 of
0 : begin
if startp < NB2 then
begin
moveto(BB[startp].x, BB[startp].y);
lineto(BB[startp+1].x, BB[startp+1].y);
end;
if startp > 0 then
begin
moveto(BB[startp-1].x, BB[startp-1].y);
lineto(BB[startp].x, BB[startp].y);
end;
end;
1 : begin
moveto(BB[startp-1].x, BB[startp-1].y);
lineto(BB[startp].x, BB[startp].y);
end;
2 : begin
moveto(BB[startp].x, BB[startp].y);
lineto(BB[startp+1].x, BB[startp+1].y);
end;
end; // case
end;
// courbe de Bézier
pen.color := clblack;
Windows.polybezier(image1.canvas.handle, BB, NB2+1);
// points
If checkbox2.Checked then
begin
For i := 0 to NB2 do
begin
case i mod 3 of
0 : begin
pen.color := clblack;
ellipse(BB[i].x-2, BB[i].y-2, BB[i].x+2, BB[i].y+2);
end;
1 : unecroix(BB[i].x, BB[i].y, clblue);
2 : unecroix(BB[i].x, BB[i].y, clred);
end;
end;
end
else pixels[0,0] := pixels[0,0];
{ force paintbox to repaint because an API function using the canvas
handle of a timage component doesn't do that }
end;
end;
procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
i : integer;
a, ro, rox, roy : single;
colox, coloy : integer;
begin
// colour drawing
IF speedbutton1.down then
begin
with image1.canvas do
begin
IF Button = MbRight then Panelcolo.color := pixels[x, y]
else
begin
brush.color := Panelcolo.color;
// symmetrical processing
IF checkbox3.checked then
begin
IF figure = 0 then
begin
rox := x-cx;
roy := y-cy;
ro := sqrt(sqr(rox) + sqr(roy));
a := arctangente(x-cx, y-cy);
for i := 0 to Nb1 do
begin
colox := Cx + round(ro*cos(a));
coloy := Cy - round(ro*sin(a));
if Nb1 mod 2 = 0 then
begin
if i mod 2 = 0 then floodfill(colox, coloy, clblack, fsBorder);
end
else floodfill(colox, coloy, clblack, fsBorder);
a := a + anglepoly;
end;
end
else
begin
floodfill(x, y, clblack, fsBorder);
floodfill(cx*2-x, y, clblack, fsborder);
end;
end
else floodfill(x,y, clblack, fsBorder);
brush.color := clwhite;
end;
end;
exit;
end;
For i := 0 to Nb2 do
begin
IF (x > BB[i].x-4) AND (x < BB[i].x+4) AND // clic on a point ?
(y > BB[i].y-4) AND (y < BB[i].y+4) then
begin
startp := i;
startx := BB[startp].x;
starty := BB[startp].y;
startangle := arctangente(startx-cx, starty -cy);
drawing := true;
Image1.Canvas.draw(0,0, bmpfond);
image1.canvas.pen.mode := pmnotxor;
dessin; // uses notxor drawing . Polybezier doesn't do that
break;
end;
end;
end;
procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
i : integer;
m : integer;
rox, roy, ro : single;
a0, a : single;
begin
IF NOT drawing then exit;
dessin; // notxor erase
IF checkbox1.checked then
begin
Case figure of
0: begin
a0 := arctangente(x-cx, y-cy) - startangle;
rox := x-cx;
roy := y-cy;
ro := sqrt(sqr(rox) + sqr(roy)); // same radius for all points
m := startp mod 3; // edge point or conrol point
For i := 0 to NB2 do
begin
if i mod 3 = m then
begin
a := angles[i] + a0 ; // angle variation
BB[i].x := Cx + round(ro*cos(a));
BB[i].y := Cy - round(ro*sin(a));
end;
end;
Case radiogroup1.itemindex of
1 : if m = 0 then // link points 0 et 1 ('right' point)
for i := 0 to NB1 - 1 do BB[i*3+1] := BB[i*3];
2 : if m = 0 then // lier points 0 et 2 ('left' point)
for i := 1 to NB1 do BB[i*3-1] := BB[i*3];
3 : begin // link control points
if m = 1 then for i := 0 to NB1 - 1 do BB[i*3+2] := BB[i*3+1]
else
if m = 2 then for i := 0 to NB1 - 1 do BB[i*3+1] := BB[i*3+2];
end;
4 : begin // opposite control points
if m = 1 then for i := 0 to NB1 - 1 do
begin
BB[i*3+2].x := Cx+Cx - BB[i*3+1].x;
BB[i*3+2].y := Cy+cy - BB[i*3+1].y;
end
else
if m = 2 then for i := 0 to NB1 - 1 do
begin
BB[i*3+1].x := Cx+Cx - BB[i*3+2].x;
BB[i*3+1].y := Cy+cy - BB[i*3+2].y;
end;
end;
5 : For i := 0 to NB2 do // rotation
begin
if i mod 3 <> m then
begin
a := angles[i] + a0 ;
rox := BB[i].x - cx;
roy := BB[i].y - cy;
ro := sqrt(sqr(rox) + sqr(roy));
BB[i].x := Cx + round(ro*cos(a));
BB[i].y := Cy - round(ro*sin(a));
end;
end;
end; // case radiogroup1
end;
1: begin
BB[startp].x := x; // move the point and symmetrical / y axis
BB[startp].y := y;
// symmetrical point from vertical axix (cy)
i := nb2 - startp;
if startp = i then BB[i].x := cx else BB[i].x := cx*2-x;
BB[i].y := y;
end;
end; // case
end // if checkbox
else
begin // no symmetry
BB[startp].x := x;
BB[startp].y := y;
end;
dessin; // notxor
end;
procedure TForm1.Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
i : integer;
begin
IF not drawing then exit;
image1.canvas.pen.mode := pmcopy;
drawing := false;
affichage(false);
IF figure = 0 then
begin // update angles
For i := 0 to Nb2 do Angles[i] := arctangente(BB[i].x-cx, BB[i].y-cy);
{
// display angles and radius for information purpose
With image1.canvas do
begin
textout(8,0,'Total number of points = '+inttostr(NB1+1));
For i := 0 to 2 do
begin
a := (angles[i] - infoang[i])* 180 / pi ; // delta angle in degrees
while a < 0 do a := a + 360; // range 0..360
while a >= 360 do a := a - 360;
rox := BB[i].x-cx;
roy := BB[i].y-cy;
ro := sqrt(sqr(rox) + sqr(roy)); // rayon
Case i of
0 : s := 'Courbe';
1 : s := 'Bz n°1';
2 : s := 'Bz n°2';
end;
Textout(8, 18*(i+1), s+' a = '+ formatfloat('##0', a)+
' ro = '+formatfloat('##0',ro));
end;
end;
}
end;
end;
//--------- section bouttons and updowns
// polygon
procedure TForm1.Button2Click(Sender: TObject);
begin
setpipette(false);
figure := 0;
updown1.position := 75;
affichage(true);
end;
// sine
procedure TForm1.Button3Click(Sender: TObject);
begin
Setpipette(false);
figure := 1;
updown1.position := 55;
affichage(true);
end;
// smooth
procedure TForm1.UpDown1Click(Sender: TObject; Button: TUDBtnType);
begin
Setpipette(false);
Image1.Canvas.draw(0,0, bmpfond);
lissage(updown1.position);
dessin;
end;
// points
procedure TForm1.UpDown2Click(Sender: TObject; Button: TUDBtnType);
begin
Setpipette(false);
IF figure = 0 then
begin
if updown2.position = 4 then updown1.position := 105
else
if updown2.position = 5 then updown1.position := 90
else updown1.position := 75;
end;
IF figure = 1 then updown1.position := 50;
affichage(true);
end;
// Help
procedure TForm1.Button4Click(Sender: TObject);
begin
memo1.visible := true;
button5.visible := true;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
memo1.visible := false;
button5.visible := false;
end;
procedure TForm1.CheckBox2Click(Sender: TObject);
begin
Setpipette(false);
affichage(false);
end;
procedure TForm1.RadioGroup1Click(Sender: TObject);
begin
Setpipette(false);
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
Setpipette(false);
end;
//--------------< section colors >-----------------
procedure Tform1.lescouleurs;
var
i : integer;
rr, bb, gg : integer;
ctr : integer;
Begin
{ creates 128 coulors }
ctr := 0;
for i := 0 to 31 do
begin {Red To Yellow}
rr := 255;
bb := 0;
gg := (255 * i) div 32;
couleur[ctr] := rgb(rr, gg, bb);
inc(ctr);
end;
for i := 0 to 23 do
begin
{ Yellow To Green}
gg := 255;
bb := 0;
rr := 255 - (128*i) div 24;
couleur[ctr] := rgb(rr,gg, bb);
inc(ctr);
end;
For i := 0 to 23 do
begin
{ Green To Cyan}
rr := 0;
gg := 255;
bb := 127+(128 * i) div 24;
couleur[ctr] := rgb(rr,gg, bb);
inc(ctr);
end;
For i := 0 to 15 do
begin
{ Cyan To Blue}
rr := 0;
bb := 255;
gg := 255 - (128 * i) div 16;
couleur[ctr] := rgb(rr,gg, bb);
inc(ctr);
end;
For i := 0 TO 31 do
begin
{ Blue To Magenta}
gg := 0;
bb := 255 - (64*i) div 32;
rr := 127 + (128*i) div 32;
couleur[ctr] := rgb(rr,gg, bb);
inc(ctr);
end;
end;
procedure TForm1.PaintBox1Paint(Sender: TObject);
var
j, i : integer;
function degrad(a, b : integer) : tcolor;
var
c1, c2 : Tcolor;
k : single;
R1, R2, G1, G2, B1, B2 : single;
RN,GN,BN : word;
mano : longint;
begin
C1 := couleur[a];
IF B = 16 then result := c1
else begin
IF B < 16 then
begin
C2 := $00FFFFFF;
k := 15-b;
k := K /15;
end
else
begin
C2 := $00969696;
k := b-15;
k := k/15;
end;
R1 := trunc(GetRvalue(c1)); { colors R V B from c1 }
G1 := trunc(GetGvalue(c1));
B1 := trunc(GetBvalue(c1));
R2 := trunc(GetRvalue(c2)); { coulors R V B from c2 }
G2 := trunc(GetGvalue(c2));
B2 := trunc(GetBvalue(c2));
RN := $00FF AND round(R1+(R2-R1)*k);
GN := $00FF AND round(G1+(G2-G1)*k);
BN := $00FF AND round(B1+(B2-B1)*k);
Mano := RGB(RN,GN,BN);
Result := $02000000 OR Mano;
end
end;
begin
For i:= 0 to 127 do // display colors
For j := 0 to 31 do paintbox1.canvas.pixels[j,i] := degrad(i,j);
end;
procedure TForm1.PaintBox2Paint(Sender: TObject);
var
i: integer;
b : byte;
begin
with paintbox2.canvas do
begin
for i := 0 to 127 do
begin
b := 128+i;
pen.color := rgb(b,b,b);
moveto(0, i); lineto(7,i);
end;
end;
end;
procedure Tform1.setpipette(Pstyle : boolean);
begin
If pstyle = true then
begin
Paintbox1.cursor := crpipette;
Paintbox2.cursor := crpipette;
Image1.cursor := crpipette;
Speedbutton1.cursor := crpipette;
IF speedbutton1.down = false then speedbutton1.down := true;
end
else
begin
Paintbox1.cursor := crdefault;
Paintbox2.cursor := crdefault;
Image1.cursor := crdefault;
Speedbutton1.cursor := crdefault;
IF speedbutton1.down = true then speedbutton1.down := false;
end;
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
IF speedbutton1.down then Setpipette(true) else Setpipette(false);
end;
procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Panelcolo.color := PaintBox1.canvas.pixels[x,y];
Setpipette(true);
end;
procedure TForm1.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
Panel5.color := Paintbox1.canvas.Pixels[x, y];
end;
procedure TForm1.PaintBox2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Panelcolo.color := PaintBox2.canvas.pixels[x,y];
Setpipette(true);
end;
procedure TForm1.PaintBox2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
Panel5.color := Paintbox2.canvas.Pixels[x, y];
end;
end.
|
unit untBot;
interface
uses
Windows,
Winsock,
untFunctions,
untControl,
untAdminSystem;
{$I Settings.ini}
type
TIRCBot = Class(TObject)
Private
mainSocket :TSocket;
mainAddr :TSockAddrIn;
mainWSA :TWSAData;
Procedure ReceiveData;
Procedure ReadCommando(szText: String);
Public
mainNick :String;
mainBuffer :Array[0..2048] Of Char;
mainErr :Integer;
mainData :String;
mainHost :String;
mainIP :String;
mainAdmin :String;
mainChannel :String;
Function SendData(szText: String): Integer;
Procedure Initialize;
End;
var
mainIRC :TIRCBot;
implementation
Procedure TIRCBot.ReadCommando(szText: String);
Var
Parameters :Array [0..4096] Of String;
ParamCount :Integer;
iPos :Integer;
bJoinChannel :Boolean;
szNick :String;
BackUp :String;
ControlSet :TControlSetting;
Begin
BackUp := szText;
FillChar(Parameters, SizeOf(Parameters), #0);
ParamCount := 0;
If (szText = '') Then Exit;
If (szText[Length(szText)] <> #32) Then szText := szText + #32;
bJoinChannel := False;
If (Pos('MOTD', szText) > 0) Or
(Pos('001', szText) > 0) Or
(Pos('005', szText) > 0) Then
bJoinChannel := True;
Repeat
iPos := Pos(#32, szText);
If (iPos > 0) Then
Begin
Parameters[ParamCount] := Copy(szText, 1, iPos-1);
Inc(ParamCount);
Delete(szText, 1, iPos);
End;
Until (iPos <= 0);
If (bJoinChannel) Then
Begin
SendData('JOIN '+server_channel+' '+server_channelkey);
mainChannel := server_channel;
End;
{ping}
If (Parameters[0] = 'PING') Then
Begin
ReplaceStr('PING', 'PONG', Parameters[0]);
SendData(Parameters[0] + #32 + Parameters[1]);
End;
{part}
If (Parameters[1] = 'PART') Then
Begin
szNick := Copy(Parameters[0], 2, Pos('!', Parameters[0])-2 );
If Admin.AdminLoggedIn(szNick) Then
Admin.LogoutAdmin(szNick);
End;
{kick}
If (Parameters[1] = 'KICK') Then
Begin
szNick := Parameters[3];
If Admin.AdminLoggedIn(szNick) Then
Admin.LogoutAdmin(szNick);
End;
{nick exists}
If (Parameters[1] = '433') Then
Begin
mainNick := ReplaceShortcuts(server_nick);
SendData(mainNick);
End;
{userhost}
If (Parameters[1] = '366') Then
Begin
SendData('USERHOST '+Parameters[2]);
End;
{host&ip}
If (Parameters[1] = '302') Then
Begin
mainHost := Parameters[3];
Delete(mainHost, 1, Pos('@', mainHost));
mainIP := fetchIPFromDNS(pChar(mainHost));
End;
{privmsg}
// :nick!ident@host privmsg #channel :text
If (Parameters[1] = 'PRIVMSG') Then
Begin
Delete(Parameters[3], 1, 1);
ControlSet.ControlNick := Copy(Parameters[0], 2, Pos('!', Parameters[0])-2);
ControlSet.ControlIdent := Copy(Parameters[0], Pos('!', Parameters[0])+1, Pos('@', Parameters[0])-2);
ControlSet.ControlHost := Copy(Parameters[0], Pos('@', Parameters[0])+1, Length(Parameters[0]));
ControlSet.ControlChannel := Parameters[2];
If (Parameters[3] = #1'PING'#1) Then
Begin
Parameters[3][3] := 'O';
SendData('NOTICE '+szNick+' '+Parameters[3]+Parameters[4]);
End;
If (Parameters[3] = #1'VERSION'#1) Then
SendData('NOTICE '+szNick+' :'#1'VERSION -unnamed bot beta 0.1');
If (Parameters[3][1] = bot_prefix) Or
(Parameters[3][1] = #1) Then
Begin
Delete(Parameters[3], 1, 1);
TranslateCommando(Parameters[3], Parameters[4], Parameters[5], Parameters[6], Parameters[7], Parameters[8], ControlSet);
End;
End;
End;
Procedure TIRCBot.ReceiveData;
Var
iPos :Integer;
Begin
Repeat
mainErr := Recv(mainSocket, mainBuffer, SizeOf(mainBuffer), 0);
If (mainErr > 0) Then
Begin
SetLength(mainData, mainErr);
Move(mainBuffer[0], mainData[1], mainErr);
Repeat
iPos := 0;
iPos := Pos(#13, mainData);
If (iPos > 0) Then
Begin
ReadCommando(Copy(mainData, 1, iPos-1));
Delete(mainData, 1, iPos+1);
End;
Until iPos <= 0;
End;
Until mainErr <= 0;
End;
Procedure TIRCBot.Initialize;
Begin
If (mainSocket <> INVALID_SOCKET) Then
Begin
SendData('QUIT :Restarting...');
CloseSocket(mainSocket);
WSACleanUP();
End;
WSAStartUP($101, mainWSA);
mainSocket := Socket(AF_INET, SOCK_STREAM, 0);
mainAddr.sin_family := AF_INET;
mainAddr.sin_port := hTons(server_port);
mainAddr.sin_addr.S_addr := inet_addr(pChar(fetchIPfromDNS(server_address)));
If (Connect(mainSocket, mainAddr, SizeOf(mainAddr)) <> 0) Then
Exit;
If (mainNick = '') Then
mainNick := ReplaceShortcuts(server_nick);
SendData('USER '+mainNick+' "'+fetchLocalName+'" "'+fetchOS+'" :'+mainNick);
SendData('NICK '+mainNick);
ReceiveData;
WSACleanUP();
End;
Function TIRCBot.SendData(szText: String): Integer;
Begin
Result := -1;
If (mainSocket = INVALID_SOCKET) Then Exit;
If (szText = '') Then Exit;
If (szText[Length(szText)] <> #10) Then szText := szText + #10;
Result := Send(mainSocket, szText[1], Length(szText), 0);
End;
end.
|
//***********************************************************************
//* Проект "Студгородок" *
//* Добавление льготы *
//***********************************************************************
unit uSp_mesto_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCalendar,
cxCurrencyEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxClasses, cxControls, cxGridCustomView, cxGridDBTableView, cxGrid,
Buttons, cxCheckBox, cxTextEdit, cxLabel, cxContainer, cxGroupBox,
StdCtrls, cxButtons, FIBDataSet, pFIBDataSet, st_ConstUnit,
uSp_mesto_DM, st_common_funcs, iBase,
st_Common_Messages, st_Consts_Messages, st_common_types, cxMaskEdit,
cxDropDownEdit, cxButtonEdit, St_Loader_Unit, st_common_loader, uSp_mesto_serv_AE, KMGetKlass;
type
Tfrm_mesto_AE = class(TForm)
cxGroupBox1: TcxGroupBox;
NameLabel: TcxLabel;
OKButton: TcxButton;
CancelButton: TcxButton;
ButtonEdit_Builds: TcxButtonEdit;
DateEdit_beg: TcxDateEdit;
DateEdit_end: TcxDateEdit;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
ComboBox_type_norma: TcxComboBox;
cxLabel4: TcxLabel;
Button_add_services: TcxButton;
Button_edit_services: TcxButton;
Button_del_services: TcxButton;
cxGroupBox2: TcxGroupBox;
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1DB_name_serv: TcxGridDBColumn;
cxGrid1DB_Summa: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
Cash_Style: TcxStyle;
cxLabel3: TcxLabel;
Serv_button_edit: TcxButtonEdit;
cxLabel5: TcxLabel;
CurrencyEdit_living: TcxCurrencyEdit;
Label_headcound: TcxLabel;
CurrencyEdit_headcount: TcxCurrencyEdit;
ButtonEdit_category_class: TcxButtonEdit;
cxLabel6: TcxLabel;
procedure CancelButtonClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure MedCheckKeyPress(Sender: TObject; var Key: Char);
procedure cxButtonEdit_BuildsPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormShow(Sender: TObject);
procedure Button_del_servicesClick(Sender: TObject);
procedure Button_add_servicesClick(Sender: TObject);
procedure Button_edit_servicesClick(Sender: TObject);
procedure Serv_button_editPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ComboBox_type_normaPropertiesChange(Sender: TObject);
procedure ButtonEdit_category_classPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
private
PLanguageIndex: byte;
procedure FormIniLanguage;
public
aHandle : TISC_DB_HANDLE;
is_admin : Boolean;
id_build : Int64;
id_param_serves : int64;
id_type_norma, id_opt, id_category, kol_live: integer;
DM : Tfrm_mesto_DM;
constructor Create(aOwner : TComponent; aHandle : TISC_DB_HANDLE; id_build : int64);reintroduce;
end;
var
frm_mesto_AE: Tfrm_mesto_AE;
implementation
{$R *.dfm}
procedure Tfrm_mesto_AE.FormIniLanguage();
begin
// индекс языка (1-укр, 2 - рус)
PLanguageIndex:= stLanguageIndex;
//названия кнопок
OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex];
CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex];
end;
procedure Tfrm_mesto_AE.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure Tfrm_mesto_AE.OKButtonClick(Sender: TObject);
begin
if (ButtonEdit_Builds.Text = '') then
Begin
ShowMessage('Необхідно обрати гуртожиток!');
ButtonEdit_Builds.SetFocus;
exit;
end;
if DateEdit_end.EditValue <= DateEdit_beg.EditValue then
Begin
ShowMessage('Дата початку повинна бути менше дати закінчення!');
DateEdit_beg.SetFocus;
exit;
end;
ModalResult := mrOK;
end;
procedure Tfrm_mesto_AE.MedCheckKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then OKButton.SetFocus;
end;
constructor Tfrm_mesto_AE.Create(aOwner: TComponent;
aHandle: TISC_DB_HANDLE; id_build: int64);
begin
inherited Create(aOwner);
self.id_build := id_build;
self.aHandle := aHandle;
DM := Tfrm_mesto_DM.Create(self);
DM.DB.Handle := aHandle;
DM.DB.Connected := True;
DM.Transaction_Read.StartTransaction;
cxGrid1DBTableView1.DataController.DataSource := DM.DataSource_serv;
FormIniLanguage;
DM.MemoryData_mesto.Open;
end;
procedure Tfrm_mesto_AE.cxButtonEdit_BuildsPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ResOpl:Variant;
BuildInfo: TBuildsInfo;
begin
BuildInfo.id_build:= -1;
BuildInfo.N_Room := '';
ResOpl:= Load_st_Builds(self, DM.DB.Handle, true, false, BuildInfo);
if VarArrayDimCount(ResOpl)>0 then
begin
id_build := ResOpl[0];
ButtonEdit_Builds.Text := ResOpl[2];
end;
end;
procedure Tfrm_mesto_AE.FormShow(Sender: TObject);
var
i, liv : Integer;
head: double;
begin
DM.DataSet_read.Close;
DM.DataSet_read.SQLs.SelectSQL.Text := 'select * from st_ini_type_norm where id_type_norma in (1,3,5)';
DM.DataSet_read.Open;
DM.DataSet_read.FetchAll;
DM.DataSet_read.First;
ComboBox_type_norma.Properties.items.Clear;
for i := 0 to DM.DataSet_read.RecordCount - 1 do
Begin
ComboBox_type_norma.Properties.items.Add(DM.DataSet_read['NAME_TYPE_NORMA']);
DM.DataSet_read.Next;
end;
if DM.DataSet_read.RecordCount > 0 then
Begin
if ((id_type_norma = 1) or (id_type_norma=5)) then
begin
if (not(VarIsNull(CurrencyEdit_headcount.EditValue)))
then head := CurrencyEdit_headcount.EditValue;
if (id_type_norma = 1) then
ComboBox_type_norma.ItemIndex := 0 //на семью
else ComboBox_type_norma.ItemIndex := 2; //на семью (посторонние)
CurrencyEdit_headcount.EditValue:=head;
CurrencyEdit_living.Enabled:=False;
ButtonEdit_category_class.Enabled:=False;
CurrencyEdit_living.EditValue:=1;
CurrencyEdit_headcount.Visible:=true;
Label_headcound.Visible:=true;
end;
if (id_type_norma = 3) or (id_type_norma = -1) then
begin
if ((id_type_norma = 3) and (not(VarIsNull(CurrencyEdit_living.EditValue))))
then liv := CurrencyEdit_living.EditValue;
ComboBox_type_norma.ItemIndex := 1; //на человека
CurrencyEdit_headcount.Visible:=False;
Label_headcound.Visible:=False;
CurrencyEdit_headcount.EditValue:=0;
CurrencyEdit_living.Enabled:=true;
ButtonEdit_category_class.Enabled:=true;
if id_type_norma = -1 then CurrencyEdit_living.EditValue:=1;
if id_type_norma = 3 then CurrencyEdit_living.EditValue:=liv;
end;
end;
end;
procedure Tfrm_mesto_AE.Button_del_servicesClick(Sender: TObject);
var
i : Integer;
id_services : Int64;
begin
if DM.MemoryData_mesto.RecordCount = 0 then exit;
If MessageBox(Handle,PChar(st_ConstUnit.st_DeletePromt[PLanguageIndex]),PChar(st_ConstUnit.st_Confirmation_Caption[PLanguageIndex]),MB_YESNO or MB_ICONQUESTION)= mrNo
then exit;
id_services := DM.MemoryData_mesto['MemoryData_id'];
DM.MemoryData_mesto.First;
For i := 0 to DM.MemoryData_mesto.RecordCount - 1 do
Begin
if DM.MemoryData_mesto['MemoryData_id'] = id_services
then DM.MemoryData_mesto.Delete;
DM.MemoryData_mesto.Next;
End;
end;
procedure Tfrm_mesto_AE.Button_add_servicesClick(Sender: TObject);
var
ViewForm : Tfrm_mesto_serv_AE;
begin
ViewForm := Tfrm_mesto_serv_AE.Create(self);
ViewForm.aHandle := DM.DB.Handle;
ViewForm.ShowModal;
if ViewForm.ModalResult = mrOK then
Begin
DM.MemoryData_mesto.Insert;
DM.MemoryData_mesto['MemoryData_id'] := ViewForm.id_serv;
DM.MemoryData_mesto['MemoryData_name'] := ViewForm.ButtonEdit_param.Text;
DM.MemoryData_mesto['MemoryData_summa'] := ViewForm.CurrencyEdit_summ.Value;
DM.MemoryData_mesto.Post;
ViewForm.Free;
end;
end;
procedure Tfrm_mesto_AE.Button_edit_servicesClick(Sender: TObject);
var
ViewForm : Tfrm_mesto_serv_AE;
i : Integer;
id_serv : int64;
begin
If DM.MemoryData_mesto.RecordCount = 0 then Exit;
ViewForm := Tfrm_mesto_serv_AE.Create(self);
ViewForm.aHandle := DM.DB.Handle;
id_serv := DM.MemoryData_mesto['MemoryData_id'];
ViewForm.id_serv := DM.MemoryData_mesto['MemoryData_id'];
ViewForm.ButtonEdit_param.Text:= DM.MemoryData_mesto['MemoryData_name'];
ViewForm.CurrencyEdit_summ.Value := DM.MemoryData_mesto['MemoryData_summa'];
ViewForm.ShowModal;
if ViewForm.ModalResult = mrOK then
Begin
DM.MemoryData_mesto.First;
For i := 0 to DM.MemoryData_mesto.RecordCount - 1 do
Begin
if DM.MemoryData_mesto['MemoryData_id'] = id_serv
then DM.MemoryData_mesto.Delete;
DM.MemoryData_mesto.Next;
End;
DM.MemoryData_mesto.Insert;
DM.MemoryData_mesto['MemoryData_id'] := ViewForm.id_serv;
DM.MemoryData_mesto['MemoryData_name'] := ViewForm.ButtonEdit_param.Text;
DM.MemoryData_mesto['MemoryData_summa'] := ViewForm.CurrencyEdit_summ.Value;
DM.MemoryData_mesto.Post;
end;
ViewForm.Free;
end;
procedure Tfrm_mesto_AE.Serv_button_editPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
aParameter : TstSimpleParams;
res : Variant;
begin
aParameter := TstSimpleParams.Create;
aParameter.Owner := self;
aParameter.Db_Handle := aHandle;
AParameter.Formstyle := fsNormal;
AParameter.WaitPakageOwner := self;
aParameter.is_admin := is_admin;
res := RunFunctionFromPackage(aParameter, 'Studcity\st_services.bpl', 'getServices');
If VarArrayDimCount(res) <> 0 then
begin
id_param_serves := res[0];
Serv_button_edit.Text := res[1];
id_opt := res[3];
end;
aParameter.Free;
end;
procedure Tfrm_mesto_AE.ComboBox_type_normaPropertiesChange(
Sender: TObject);
begin
if ComboBox_type_norma.ItemIndex = 0 then //на семью
begin
CurrencyEdit_living.Enabled:=False;
CurrencyEdit_living.EditValue:=1;
CurrencyEdit_headcount.Visible:=true;
Label_headcound.Visible:=true;
CurrencyEdit_headcount.EditValue:=0.35;
ButtonEdit_category_class.Enabled:=false;
end;
if ComboBox_type_norma.ItemIndex = 1 then //на человека
begin
CurrencyEdit_headcount.Visible:=False;
Label_headcound.Visible:=False;
CurrencyEdit_headcount.EditValue:=0;
CurrencyEdit_living.Enabled:=true;
CurrencyEdit_living.EditValue:=1;
ButtonEdit_category_class.Enabled:=true;
end;
if ComboBox_type_norma.ItemIndex = 2 then //на семью (посторонние)
begin
CurrencyEdit_living.Enabled:=False;
CurrencyEdit_living.EditValue:=1;
CurrencyEdit_headcount.Visible:=true;
Label_headcound.Visible:=true;
CurrencyEdit_headcount.EditValue:=0.3;
ButtonEdit_category_class.Enabled:=false;
end;
end;
procedure Tfrm_mesto_AE.ButtonEdit_category_classPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ViewForm : TfrmKMGetKlass;
begin
ViewForm := TfrmKMGetKlass.Create(Self, DM.DB.Handle, 6, -1);
ViewForm.ShowModal;
if ViewForm.ModalResult = mrOk then
Begin
id_category := ViewForm.id_;
ButtonEdit_category_class.Text := ViewForm.Name;
DM.DataSet_read.Close;
DM.DataSet_read.SQLs.SelectSQL.Text := 'Select * from ST_INI_CATEGORY_CLASS where id_CATEGORY_CLASS = :id_CATEGORY_CLASS';
DM.DataSet_read.ParamByName('id_CATEGORY_CLASS').AsInt64 := id_category;
DM.DataSet_read.Open;
if DM.DataSet_read['PEOPLES'] <> null
then CurrencyEdit_living.EditValue := strtofloat(DM.DataSet_read.FieldByName('PEOPLES').asstring)
else CurrencyEdit_living.EditValue := 0;
{
if DM.DataSet_read['PLACES'] <> null
then CurrencyEdit_living.EditValue := strtofloat(DM.DataSet_read.FieldByName('PLACES').asstring)
else CurrencyEdit_living.EditValue := 0; }
DM.DataSet_read.close;
kol_live := CurrencyEdit_living.EditValue;
//recalc_norm;
end;
ViewForm.Free;
end;
end.
|
unit XLSReadWriteZIP;
{
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
uses SysUtils, Classes, Types, zlib, Contnrs;
const ZIPID_ENDDIR = $06054b50;
const ZIPID_DIR = $02014b50;
const ZIPID_FILE = $04034B50;
type TZipFileHeader = packed record
ReqVersion: word;
Flags: word;
Compression: word;
FileTime: word;
FileDate: word;
CRS32: longword;
CompressedSize: longword;
UncompressedSize: longword;
LenFilename: word;
LenExtraField: word;
end;
type TZipFileDataDescriptor = packed record
Signature: longword;
CRC32: longword;
CompressedSize: longword;
UncompressedSize: longword;
end;
type TZipCentralDir = packed record
Version: word;
ReqVersion: word;
Flags: word;
Compression: word;
Timestamp: longword;
CRC32: longword;
CompressedSize: longword;
UncompressedSize: longword;
FilenameLen: word;
ExtraFieldLen: word;
CommentLen: word;
DiskNumberStart: word;
IntFileAttributes: word;
ExtFileAttributes: longword;
RelOffsetLocalHeader: longword;
end;
type TZipEndCentralDir = packed record
DD1: word; // DD1 - DD3 used by disk(ette) spanning. Not supported anyway.
DD2: word;
DD3: word;
Entries: word;
DirSize: longword;
DirOffset: longword;
CommentLength: word;
end;
type TXLSZipFile = class(TObject)
private
function GetFilenameLC: string;
protected
FDir: TZipCentralDir;
FFilename: string;
FExtraField: string;
FComment: string;
public
procedure Read(Source, Dest: TStream);
property Filename: string read FFilename;
property FilenameLC: string read GetFilenameLC;
end;
type TXLSZipArchive = class(TObjectList)
private
FComment: string;
FEndDir: TZipEndCentralDir;
FStream: TStream;
FOwnsStream: boolean;
function GetItems(Index: integer): TXLSZipFile;
public
procedure Add;
procedure LoadFromFile(Filename: WideString);
procedure LoadFromStream(Stream: TStream);
function Find(Filename: string): integer;
procedure Read(Filename: string; Dest: TStream); overload;
procedure Read(Filename: string; var Dest: string); overload;
procedure Close;
property Items[Index: integer]: TXLSZipFile read GetItems;
property Comment: string read FComment write FComment;
end;
implementation
function ReadStr(Stream: TStream; L: integer): string;
begin
SetLength(Result,L);
Stream.Read(Pointer(Result)^,L);
end;
function GetCRC32(Data: TStream; DataSize: integer): longword;
const
CRCtable: array[0..255] of DWORD = (
$00000000, $77073096, $EE0E612C, $990951BA, $076DC419, $706AF48F, $E963A535,
$9E6495A3, $0EDB8832, $79DCB8A4,
$E0D5E91E, $97D2D988, $09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91, $1DB71064,
$6AB020F2, $F3B97148, $84BE41DE,
$1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7, $136C9856, $646BA8C0, $FD62F97A,
$8A65C9EC, $14015C4F, $63066CD9,
$FA0F3D63, $8D080DF5, $3B6E20C8, $4C69105E, $D56041E4, $A2677172, $3C03E4D1,
$4B04D447, $D20D85FD, $A50AB56B,
$35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF,
$ABD13D59, $26D930AC, $51DE003A,
$C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F, $2802B89E,
$5F058808, $C60CD9B2, $B10BE924,
$2F6F7C87, $58684C11, $C1611DAB, $B6662D3D, $76DC4190, $01DB7106, $98D220BC,
$EFD5102A, $71B18589, $06B6B51F,
$9FBFE4A5, $E8B8D433, $7807C9A2, $0F00F934, $9609A88E, $E10E9818, $7F6A0DBB,
$086D3D2D, $91646C97, $E6635C01,
$6B6B51F4, $1C6C6162, $856530D8, $F262004E, $6C0695ED, $1B01A57B, $8208F4C1,
$F50FC457, $65B0D9C6, $12B7E950,
$8BBEB8EA, $FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65, $4DB26158,
$3AB551CE, $A3BC0074, $D4BB30E2,
$4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB, $4369E96A, $346ED9FC, $AD678846,
$DA60B8D0, $44042D73, $33031DE5,
$AA0A4C5F, $DD0D7CC9, $5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525,
$206F85B3, $B966D409, $CE61E49F,
$5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81, $B7BD5C3B,
$C0BA6CAD, $EDB88320, $9ABFB3B6,
$03B6E20C, $74B1D29A, $EAD54739, $9DD277AF, $04DB2615, $73DC1683, $E3630B12,
$94643B84, $0D6D6A3E, $7A6A5AA8,
$E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1, $F00F9344, $8708A3D2, $1E01F268,
$6906C2FE, $F762575D, $806567CB,
$196C3671, $6E6B06E7, $FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC, $F9B9DF6F,
$8EBEEFF9, $17B7BE43, $60B08ED5,
$D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD,
$48B2364B, $D80D2BDA, $AF0A1B4C,
$36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79, $CB61B38C,
$BC66831A, $256FD2A0, $5268E236,
$CC0C7795, $BB0B4703, $220216B9, $5505262F, $C5BA3BBE, $B2BD0B28, $2BB45A92,
$5CB36A04, $C2D7FFA7, $B5D0CF31,
$2CD99E8B, $5BDEAE1D, $9B64C2B0, $EC63F226, $756AA39C, $026D930A, $9C0906A9,
$EB0E363F, $72076785, $05005713,
$95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7,
$0BDBDF21, $86D3D2D4, $F1D4E242,
$68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777, $88085AE6,
$FF0F6A70, $66063BCA, $11010B5C,
$8F659EFF, $F862AE69, $616BFFD3, $166CCF45, $A00AE278, $D70DD2EE, $4E048354,
$3903B3C2, $A7672661, $D06016F7,
$4969474D, $3E6E77DB, $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53,
$DEBB9EC5, $47B2CF7F, $30B5FFE9,
$BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605, $CDD70693, $54DE5729,
$23D967BF, $B3667A2E, $C4614AB8,
$5D681B02, $2A6F2B94, $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D);
var
i: integer;
B: byte;
begin
Result := $FFFFFFFF;
for i := 0 to DataSize - 1 do begin
Data.Read(B,1);
Result := (Result shr 8) xor (CRCtable[byte(Result) xor B]);
end;
Result := Result xor $FFFFFFFF;
end;
procedure TXLSZipArchive.Close;
begin
if FOwnsStream then begin
FStream.Free;
FStream := Nil;
FOwnsStream := False;
end;
Clear;
end;
function TXLSZipArchive.Find(Filename: string): integer;
begin
Filename := Lowercase(Filename);
for Result := 0 to Count - 1 do begin
if Items[Result].FilenameLC = Filename then
Exit;
end;
Result := -1;
end;
function TXLSZipArchive.GetItems(Index: integer): TXLSZipFile;
begin
Result := TXLSZipFile(inherited Items[Index]);
end;
procedure TXLSZipArchive.LoadFromFile(Filename: WideString);
begin
FStream := TFileStream.Create(Filename,fmOpenRead,fmShareDenyWrite);
FOwnsStream := True;
LoadFromStream(FStream);
end;
procedure TXLSZipArchive.LoadFromStream(Stream: TStream);
var
i,P,Sz: integer;
Signature: longword;
ZFile: TXLSZipFile;
begin
FOwnsStream := Stream = FStream;
if not FOwnsStream then
FStream := Stream;
P := SizeOf(TZipEndCentralDir) + 4;
Sz := Stream.Size;
repeat
Stream.Seek(-P,soFromEnd);
Stream.Read(Signature,4);
Inc(P);
until ((Signature = ZIPID_ENDDIR) or (P >= Sz));
if Signature <> ZIPID_ENDDIR then
raise Exception.Create('ZIP archive error');
Stream.Read(FEndDir,SizeOf(TZipEndCentralDir));
FComment := ReadStr(Stream,FEndDir.CommentLength);
Stream.Seek(FEndDir.DirOffset,soFromBeginning);
for i := 1 to FEndDir.Entries do begin
Stream.Read(Signature,4);
if Signature <> ZIPID_DIR then
raise Exception.Create('ZIP archive error');
ZFile := TXLSZipFile.Create;
Stream.Read(ZFile.FDir,SizeOf(TZipCentralDir));
ZFile.FFilename := ReadStr(Stream,ZFile.FDir.FilenameLen);
ZFile.FExtraField := ReadStr(Stream,ZFile.FDir.ExtraFieldLen);
ZFile.FComment := ReadStr(Stream,ZFile.FDir.CommentLen);
inherited Add(ZFile);
end;
end;
procedure TXLSZipArchive.Read(Filename: string; var Dest: string);
var
StrStream: TStringStream;
begin
StrStream := TStringStream.Create('');
try
Read(Filename,StrStream);
Dest := StrStream.DataString;
finally
StrStream.Free;
end;
end;
procedure TXLSZipArchive.Read(Filename: string; Dest: TStream);
var
i: integer;
begin
i := Find(Filename);
if i < 0 then
raise Exception.CreateFmt('Can not find file %s in ZIP',[Filename]);
Items[i].Read(FStream,Dest);
end;
{ TXLSZipArchive }
procedure TXLSZipArchive.Add;
begin
end;
{ TXLSZipFile }
function TXLSZipFile.GetFilenameLC: string;
begin
Result := Lowercase(FFilename);
end;
procedure TXLSZipFile.Read(Source, Dest: TStream);
var
B: byte;
Header: TZipFileHeader;
Decompressor: TDecompressionStream;
CompStream: TMemoryStream;
Signature: longword;
CRC: longword;
begin
Source.Seek(FDir.RelOffsetLocalHeader,soFromBeginning);
Source.Read(Signature,4);
if Signature <> ZIPID_FILE then
raise Exception.Create('Invalid content in ZIP archive');
Source.Read(Header,SizeOf(TZipFileHeader));
ReadStr(Source,Header.LenFilename);
if FDir.Compression = 0 then begin
Dest.CopyFrom(Source,FDir.UncompressedSize);
end
else begin
CompStream := TMemoryStream.Create;
try
// Create a zlib header.
B := 120;
CompStream.Write(B,1);
B := 156;
CompStream.Write(B,1);
CompStream.CopyFrom(Source,FDir.CompressedSize);
CompStream.Seek(0,soFromBeginning);
Decompressor := TDecompressionStream.Create(CompStream);
try
Dest.CopyFrom(Decompressor,FDir.UncompressedSize);
finally
Decompressor.Free;
end;
finally
CompStream.Free;
end;
end;
Dest.Seek(0,soFromBeginning);
CRC := GetCRC32(Dest,FDir.UncompressedSize);
if CRC <> FDir.CRC32 then
raise Exception.Create('CRC error in ZIP');
end;
end.
|
unit myTypes;
interface
uses sgTypes;
const
//All constants in this section are offset by 1 due to 0-indexing.
//***
MAP_WIDTH = 63; //262144 block space (64*16*16*16)
MAP_HEIGHT = 15;
CHUNK_HEIGHT = 15;
CHUNK_WIDTH = 15;
BLOCK_COUNT = 11; //Amount of types of blocks
//***
ACCELERATION = 0.269;
type
//Each block contains a bitmap and the location in the image file (not the world)
Blocks = Record
image: Bitmap;
x: integer;
y: integer;
end;
BlockArray = Record
block: array [0..BLOCK_COUNT] of Blocks;
end;
//Chunks contain the integer index in the blockArray of what block it is
ChunkArray = Record
Blocks: array [0..CHUNK_WIDTH, 0..CHUNK_HEIGHT] of integer;
end;
//The world contains multiple chunks, allowing for only visible blocks to be rendered without having to iterate through each block to check if its on screen.
WorldArray = Record
Chunks: array [0..MAP_WIDTH, 0..MAP_HEIGHT] of ChunkArray;
end;
PlayerType = Record
x: integer;
y: integer;
jumping: boolean;
vertVelocity: single;
speedVertical: single;
speedHorizontal: single;
leftMovement: boolean;
rightMovement: boolean;
end;
implementation
end. |
unit DSA.Tree.SegmentTree;
interface
uses
System.SysUtils,
System.rtti,
DSA.Interfaces.DataStructure,
DSA.Utils;
type
TSegmentTree<T> = class(TObject)
private
__data: array of T;
__tree: array of T;
__merger: IMerger<T>;
/// <summary> 返回完全二叉树的数组表示中,
/// 一个索引所表示的元素的左孩子节点的索引
/// </summary>
function __leftChild(index: Integer): Integer;
/// <summary> 返回完全二叉树的数组表示中,
/// 一个索引所表示的元素的右孩子节点的索引
/// </summary>
function __rightChild(index: Integer): Integer;
/// <summary> 在treeIndex的位置创建表示区间[l..r]的线段树 </summary>
procedure __buildSegmentTree(treeIndex: Integer; l, r: Integer);
/// <summary> 在以treeIndex为根的线段树中[l..r]的范围里,
/// 搜索区[queryL..queryR]的值
/// </summary>
function __query(treeIndex, l, r, queryL, queryR: Integer): T;
procedure __set(treeIndex, l, r, index: Integer; e: T);
public
constructor Create(arr: array of T; merger: IMerger<T>);
function Get(index: Integer): T;
function GetSize: Integer;
/// <summary> 返回区间[queryL..queryR]的值 </summary>
function Query(queryL, queryR: Integer): T;
/// <summary> 将index位置的值,更新为e </summary>
procedure Set_(index: Integer; e: T);
function ToString(): string; override;
end;
TMerger = class(TInterfacedObject, IMerger<Integer>)
public
function Merge(a, b: Integer): Integer;
end;
procedure Main;
implementation
type
TsegmentTree_int = TSegmentTree<Integer>;
procedure Main;
var
nums: TArray_int;
SegmentTree: TsegmentTree_int;
begin
nums := [-2, 0, 3, -5, 2, -1];
SegmentTree := TsegmentTree_int.Create(nums, TMerger.Create);
Writeln(SegmentTree.ToString);
Writeln(SegmentTree.Query(0, 2));
Writeln(SegmentTree.Query(2, 5));
Writeln(SegmentTree.Query(0, 5));
end;
{ TSegmentTree<T> }
constructor TSegmentTree<T>.Create(arr: array of T; merger: IMerger<T>);
var
i: Integer;
begin
SetLength(__data, Length(arr));
for i := 0 to Length(arr) - 1 do
__data[i] := arr[i];
Self.__merger := merger;
SetLength(__tree, GetSize * 4);
__buildSegmentTree(0, 0, GetSize - 1);
end;
function TSegmentTree<T>.Get(index: Integer): T;
begin
if (index < 0) or (index >= GetSize) then
raise Exception.Create('Index is illegal.');
Result := __data[index];
end;
function TSegmentTree<T>.GetSize: Integer;
begin
Result := Length(__data);
end;
function TSegmentTree<T>.Query(queryL, queryR: Integer): T;
begin
if (queryL < 0) or (queryL >= GetSize) or (queryR < 0) or (queryR >= GetSize)
or (queryL > queryR) then
raise Exception.Create('Index is illegar.');
Result := __query(0, 0, GetSize - 1, queryL, queryR);
end;
procedure TSegmentTree<T>.Set_(index: Integer; e: T);
begin
if (index < 0) or (index >= GetSize) then
raise Exception.Create('Index is illegar.');
__data[index] := e;
__set(0, 0, GetSize - 1, index, e);
end;
function TSegmentTree<T>.ToString: string;
var
res: TStringBuilder;
i: Integer;
value: TValue;
begin
res := TStringBuilder.Create;
try
res.Append('[');
for i := 0 to Length(Self.__tree) - 1 do
begin
TValue.Make(@__tree[i], TypeInfo(T), value);
if value.ToString <> '0' then
res.Append(value.ToString).Append(' ')
else
res.Append('N').Append(' ');
end;
if i >= Length(Self.__tree) - 1 then
res.Append(']').AppendLine;
Result := res.ToString;
finally
res.Free;
end;
end;
procedure TSegmentTree<T>.__buildSegmentTree(treeIndex, l, r: Integer);
var
mid, leftTreeIndex, rightTreeIndex: Integer;
begin
if l = r then
begin
__tree[treeIndex] := __data[l];
Exit;
end;
leftTreeIndex := __leftChild(treeIndex);
rightTreeIndex := __rightChild(treeIndex);
mid := l + (r - l) div 2;
__buildSegmentTree(leftTreeIndex, l, mid);
__buildSegmentTree(rightTreeIndex, mid + 1, r);
__tree[treeIndex] := __merger.Merge(__tree[leftTreeIndex],
__tree[rightTreeIndex]);
end;
function TSegmentTree<T>.__leftChild(index: Integer): Integer;
begin
Result := index * 2 + 1;
end;
function TSegmentTree<T>.__query(treeIndex, l, r, queryL, queryR: Integer): T;
var
mid, leftTreeIndex, rightTreeIndex: Integer;
leftRes, rightRes: T;
begin
if (l = queryL) and (r = queryR) then
begin
Result := __tree[treeIndex];
Exit;
end;
leftTreeIndex := __leftChild(treeIndex);
rightTreeIndex := __rightChild(treeIndex);
mid := l + (r - l) div 2;
if queryL >= mid + 1 then
Result := __query(rightTreeIndex, mid + 1, r, queryL, queryR)
else if queryR <= mid then
Result := __query(leftTreeIndex, l, mid, queryL, queryR)
else
begin
leftRes := __query(leftTreeIndex, l, mid, queryL, mid);
rightRes := __query(rightTreeIndex, mid + 1, r, mid + 1, queryR);
Result := __merger.Merge(leftRes, rightRes);
end;
end;
function TSegmentTree<T>.__rightChild(index: Integer): Integer;
begin
Result := index * 2 + 2;
end;
procedure TSegmentTree<T>.__set(treeIndex, l, r, index: Integer; e: T);
var
mid, leftTreeIndex, rightTreeIndex: Integer;
leftRes, rightRes: T;
begin
if l = r then
begin
__tree[treeIndex] := e;
Exit;
end;
leftTreeIndex := __leftChild(treeIndex);
rightTreeIndex := __rightChild(treeIndex);
mid := l + (r - l) div 2;
if index >= mid + 1 then
__set(rightTreeIndex, mid + 1, r, index, e)
else
__set(leftTreeIndex, l, mid, index, e);
__tree[treeIndex] := __merger.Merge(__tree[leftTreeIndex],
__tree[rightTreeIndex]);
end;
{ TMerger }
function TMerger.Merge(a, b: Integer): Integer;
begin
Result := a + b;
end;
end.
|
unit Geo.Calcs;
//------------------------------------------------------------------------------
// модуль простых операций с гео координатами
//------------------------------------------------------------------------------
// функции с постфиксом Rad принимают аргументы в радианах
// функции с постфиксом Deg принимают аргументы в градусах
// функции без постфиксов принимают любые аргументы
//
// угловые результаты любых функций выражаются ТОЛЬКО в радианах
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, Math,
Geo.Pos;
type
TGeoCalcs = class
public
// Проверка координат на корректность
class function CheckGeoCoordinates(const AGeoPoint: TGeoPos): Boolean;
// Привести координаты пары точек к общему виду (при переходе через линию дат; за основу берётся положительная долгота)
class function CastGeoCoordinates(var AGeoPoint1, AGeoPoint2: TGeoPos): Boolean;
// Привести координаты пары точек к общему виду (при переходе через линию дат; за основу берётся первая точка)
class function CastGeoCoordinates2(var AGeoPoint1, AGeoPoint2: TGeoPos): Boolean;
// Угловое расстояние между точками
class function AngularLengthRadRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double; inline;
class function AngularLengthDegRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double; overload; inline;
class function AngularLengthDegRad(const APos1, APos2: TGeoPos): Double; overload; inline;
// Расстояние между точками, км
class function GeoLengthKmRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double; inline;
class function GeoLengthKmDeg(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double; overload; inline;
class function GeoLengthKmDeg(const APos1, APos2: TGeoPos): Double; overload; inline;
// Расстояние между точками, м
class function GeoLengthRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double; inline;
class function GeoLengthDeg(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double; overload; inline;
class function GeoLengthDeg(const APos1, APos2: TGeoPos): Double; overload; inline;
// Получить радиус круга из трёх точек
class function GetRadius(const APoint1, APoint2, APoint3: TGeoPos): Double;
// Возвращает угол между направлением на север и данным вектором
class function GetAzimuthRad(const AFromPos, AToPos: TGeoPos): Double;
class function GetAzimuthDeg(const AFromPos, AToPos: TGeoPos): Double;
// Возвращает угол между двумя векторами в радианах
class function GetAngleRad(const APos1, APos2, APos3: TGeoPos): Double;
// Физика
class function GetSpeedKmH(const AFromPoint, AToPoint: TGeoTrackPoint): Double;
class function GetSpeedMS(const AFromPoint, AToPoint: TGeoTrackPoint): Double;
class function GetTangentialAcceleration(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
// Угловая скорость, скорость по дуге
class function GetAngularSpeed(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
class function GetArcSpeed(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
// Ускорение
class function GetRadialAcceleration(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
class function GetFullAcceleration(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
// Проверка на правый поворот
class function IsRightTurn(const ALatitude1, ALongitude1, ALatitude2, ALongitude2, ALatitude3, ALongitude3: Double): Boolean; overload;
class function IsRightTurn(const APos1, APos2, APos3: TGeoPos): Boolean; overload;
// Кратчайшее расстояние от точки до отрезка
class function GeoDistancePointToLine(const APoint, APoint1, APoint2: TGeoPos; var APPoint: TGeoPos): Double;
class function GeoDistancePointToLineM(const APoint, APoint1, APoint2: TGeoPos; var APPoint: TGeoPos): Double;
class function GeoDistancePointToLineDeg(const ALatitudePoint, ALongitudePoint, ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
class function GeoDistancePointToLineMDeg(const ALatitudePoint, ALongitudePoint, ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
//
class function GeoDistancePointToZoneMDeg(const ALatitudePoint, ALongitudePoint: Double; const AZone: TGeoPosArray): Double;
class function GeoDistancePointToPolyLineMDeg(const ALatitudePoint, ALongitudePoint: Double; const APolyLine: TGeoPosArray): Double;
// Попадание в зону
class function GeoPointInZone(const ALatitude, ALongitude: Double; const AZone: TGeoPosArray): Boolean;
// Рамки
class function PointBounding(const ACenter: TGeoPos; const ARadius: Double): TGeoSquare;
class function CircleBounding(const ACircle: TGeoCircle): TGeoSquare;
end;
//------------------------------------------------------------------------------
implementation
class function TGeoCalcs.CheckGeoCoordinates(const AGeoPoint: TGeoPos): Boolean;
begin
Result := AGeoPoint.IsValid();
end;
class function TGeoCalcs.CircleBounding(const ACircle: TGeoCircle): TGeoSquare;
begin
Result := PointBounding(ACircle.Pos, ACircle.Radius);
end;
class function TGeoCalcs.CastGeoCoordinates(var AGeoPoint1, AGeoPoint2: TGeoPos): Boolean;
begin
if not (CheckGeoCoordinates(AGeoPoint1) and CheckGeoCoordinates(AGeoPoint2)) then
Exit(False);
if AGeoPoint1.Longitude > AGeoPoint2.Longitude + 180 then
AGeoPoint2.Longitude := AGeoPoint2.Longitude + 360
else if AGeoPoint2.Longitude > AGeoPoint1.Longitude + 180 then
AGeoPoint1.Longitude := AGeoPoint1.Longitude + 360;
Result := True;
end;
class function TGeoCalcs.CastGeoCoordinates2(var AGeoPoint1,
AGeoPoint2: TGeoPos): Boolean;
begin
if not (CheckGeoCoordinates(AGeoPoint1) and CheckGeoCoordinates(AGeoPoint2)) then
Exit(False);
if Abs(AGeoPoint1.Longitude - AGeoPoint2.Longitude) > 180 then
AGeoPoint2.Longitude := IfThen(AGeoPoint1.Longitude > AGeoPoint2.Longitude, AGeoPoint2.Longitude + 360, AGeoPoint2.Longitude - 360);
Result := True;
end;
class function TGeoCalcs.AngularLengthRadRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
begin
if (ALatitude1 = ALatitude2) and (ALongitude1 = ALongitude2) then
Exit(0);
Result:= Sin(ALatitude1) * Sin(ALatitude2) + Cos(ALatitude1) * Cos(ALatitude2) * Cos(ALongitude1 - ALongitude2);
// защита от неточных вычислений
if Abs(Result) <= 1 then
Result := ArcCos(Result)
else if Result > 1 then
Result := 0
else
Result := Pi;
end;
class function TGeoCalcs.AngularLengthDegRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
begin
Result := AngularLengthRadRad(DegToRad(ALatitude1), DegToRad(ALongitude1), DegToRad(ALatitude2), DegToRad(ALongitude2));
end;
class function TGeoCalcs.AngularLengthDegRad(const APos1, APos2: TGeoPos): Double;
begin
Result := AngularLengthRadRad(DegToRad(APos1.Latitude), DegToRad(APos1.Longitude), DegToRad(APos2.Latitude), DegToRad(APos2.Longitude));
end;
class function TGeoCalcs.GeoLengthKmRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
begin
Result := AngularLengthRadRad(ALatitude1, ALongitude1, ALatitude2, ALongitude2) * CEvEarthRadiusKm;
end;
class function TGeoCalcs.GeoLengthKmDeg(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
begin
Result := AngularLengthDegRad(ALatitude1, ALongitude1, ALatitude2, ALongitude2) * CEvEarthRadiusKm;
end;
class function TGeoCalcs.GeoLengthKmDeg(const APos1, APos2: TGeoPos): Double;
begin
Result := AngularLengthDegRad(APos1, APos2) * CEvEarthRadiusKm;
end;
class function TGeoCalcs.GeoLengthRad(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
begin
Result := AngularLengthRadRad(ALatitude1, ALongitude1, ALatitude2, ALongitude2) * CEvEarthRadius;
end;
class function TGeoCalcs.GeoLengthDeg(const ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
begin
Result := AngularLengthDegRad(ALatitude1, ALongitude1, ALatitude2, ALongitude2) * CEvEarthRadius;
end;
class function TGeoCalcs.GeoLengthDeg(const APos1, APos2: TGeoPos): Double;
begin
Result := AngularLengthDegRad(APos1, APos2) * CEvEarthRadius;
end;
class function TGeoCalcs.GetRadius(const APoint1, APoint2, APoint3: TGeoPos): Double;
var
CastGeoPoint1, CastGeoPoint2, CastGeoPoint3: TGeoPos;
Point1, Point2, Point3: TCartesianPos;
S12, S23, S13: Double;
RDenominator: Double;
begin
CastGeoPoint1 := APoint1;
CastGeoPoint2 := APoint2;
CastGeoPoint3 := APoint3;
CastGeoCoordinates(CastGeoPoint1, CastGeoPoint2);
CastGeoCoordinates(CastGeoPoint1, CastGeoPoint3);
Point1 := CastGeoPoint1.ToCartesianPos(APoint2.Longitude);
Point2 := CastGeoPoint2.ToCartesianPos(APoint2.Longitude);
Point3 := CastGeoPoint3.ToCartesianPos(APoint2.Longitude);
S12 := Hypot(Point2.X - Point1.X, Point2.Y - Point1.Y);
S13 := Hypot(Point3.X - Point1.X, Point3.Y - Point1.Y);
S23 := Hypot(Point3.X - Point2.X, Point3.Y - Point2.Y);
RDenominator := (Point2.X - Point1.X) * (Point3.Y - Point2.Y) - (Point2.Y - Point1.Y) * (Point3.X - Point2.X);
if RDenominator = 0 then
Result := Infinity
else
Result := S12 * S23 * S13 / 2 / Abs(RDenominator);
end;
class function TGeoCalcs.GetSpeedKmH(const AFromPoint, AToPoint: TGeoTrackPoint): Double;
var
Point1, Point2: TGeoPos;
begin
Point1 := AFromPoint.Pos.Pos;
Point2 := AToPoint.Pos.Pos;
if not CastGeoCoordinates(Point1, Point2) or (AFromPoint.DateTime = AToPoint.DateTime) then
Exit(0);
Result := GeoLengthKmDeg(Point1, Point2) / ((AToPoint.DateTime - AFromPoint.DateTime) * HoursPerDay);
end;
class function TGeoCalcs.GetSpeedMS(const AFromPoint, AToPoint: TGeoTrackPoint): Double;
var
Point1, Point2: TGeoPos;
begin
Point1 := AFromPoint.Pos.Pos;
Point2 := AToPoint.Pos.Pos;
if not CastGeoCoordinates(Point1, Point2) or (AFromPoint.DateTime = AToPoint.DateTime) then
Exit(0);
Result := GeoLengthDeg(Point1, Point2) / ((AToPoint.DateTime - AFromPoint.DateTime) * SecsPerDay);
end;
class function TGeoCalcs.GetTangentialAcceleration(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
var
S12, S13, t12, t13: Double;
begin
if (AFirstPoint.DateTime >= AMiddlePoint.DateTime)
or (AMiddlePoint.DateTime >= ALastPoint.DateTime) then
Exit(0);
S12 := GeoLengthDeg(AFirstPoint.Pos.Pos.Latitude, AFirstPoint.Pos.Pos.Longitude, AMiddlePoint.Pos.Pos.Latitude, AMiddlePoint.Pos.Pos.Longitude);
S13 := S12 + GeoLengthDeg(AMiddlePoint.Pos.Pos.Latitude, AMiddlePoint.Pos.Pos.Longitude, ALastPoint.Pos.Pos.Latitude, ALastPoint.Pos.Pos.Longitude);
t12 := (AMiddlePoint.DateTime - AFirstPoint.DateTime) * SecsPerDay;
t13 := (ALastPoint.DateTime - AFirstPoint.DateTime) * SecsPerDay;
// формула для ускорения по трём точкам, считая движение равноускоренным
Result := 2 * (S13 * t12 - S12 * t13) / (t12 * t13 * t13 - t13 * t12 * t12);
end;
class function TGeoCalcs.GetRadialAcceleration(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
var
R, w: Double;
begin
if (ALastPoint.DateTime - AMiddlePoint.DateTime) * SecsPerDay < 0.001 then
Exit(0);
w := GetAngularSpeed(AFirstPoint, AMiddlePoint, ALastPoint);
R := GetRadius(AFirstPoint.Pos.Pos, AMiddlePoint.Pos.Pos, ALastPoint.Pos.Pos);
if not IsInfinite(R) then
Result := R * Sqr(w)
else
Result := 0;
end;
class function TGeoCalcs.GetFullAcceleration(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
begin
Result := Hypot(GetTangentialAcceleration(AFirstPoint, AMiddlePoint, ALastPoint), GetRadialAcceleration(AFirstPoint, AMiddlePoint, ALastPoint))
end;
class function TGeoCalcs.GetAzimuthRad(const AFromPos, AToPos: TGeoPos): Double;
begin
if AFromPos.Latitude = 90 then
Exit(0);
Result := GetAngleRad(TGeoPos.Create(90, 0), AFromPos, AToPos);
if ((AToPos.Longitude < AFromPos.Longitude) and (Abs(AToPos.Longitude - AFromPos.Longitude) < 180))
or ((AToPos.Longitude > AFromPos.Longitude) and (Abs(AToPos.Longitude - AFromPos.Longitude) > 180)) then
Result := -Result;
// перевод из формата (-pi; pi] в формат [0; 2*pi)
if Result < 0 then
Result := Result + 2 * Pi;
end;
class function TGeoCalcs.GetAzimuthDeg(const AFromPos, AToPos: TGeoPos): Double;
begin
Result := RadToDeg(GetAzimuthRad(AFromPos, AToPos));
end;
class function TGeoCalcs.GetAngleRad(const APos1, APos2, APos3: TGeoPos): Double;
var
AngLen12, AngLen23, AngLen13: Double;
begin
if not CheckGeoCoordinates(APos1) or not CheckGeoCoordinates(APos2) or not CheckGeoCoordinates(APos3)
or (APos1 = APos2) or (APos2 = APos3) or (APos1 = APos3) then
Exit(0);
AngLen12 := AngularLengthDegRad(APos1, APos2);
AngLen23 := AngularLengthDegRad(APos2, APos3);
AngLen13 := AngularLengthDegRad(APos1, APos3);
if (AngLen12 = 0) or (AngLen23 = 0) then
Exit(0);
Result := (Cos(AngLen13) - Cos(AngLen12) * Cos(AngLen23)) / (Sin(AngLen12) * Sin(AngLen23));
// защита от неточных вычислений
if Abs(Result) <= 1 then
Result := ArcCos(Result)
else if Result > 1 then
Result := 0
else
Result := Pi;
end;
class function TGeoCalcs.GetAngularSpeed(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
var
ArcAngle: Double;
begin
if (AFirstPoint.DateTime >= AMiddlePoint.DateTime) or (AMiddlePoint.DateTime >= ALastPoint.DateTime)
or (AFirstPoint.Pos.Pos = AMiddlePoint.Pos.Pos) or (AMiddlePoint.Pos.Pos = ALastPoint.Pos.Pos) then
Exit(0);
ArcAngle := 2 * (Pi - GetAngleRad(AFirstPoint.Pos.Pos, AMiddlePoint.Pos.Pos, ALastPoint.Pos.Pos));
Result := ArcAngle / ((ALastPoint.DateTime - AFirstPoint.DateTime) * SecsPerDay);
end;
class function TGeoCalcs.GetArcSpeed(const AFirstPoint, AMiddlePoint, ALastPoint: TGeoTrackPoint): Double;
begin
Result := GetAngularSpeed(AFirstPoint, AMiddlePoint, ALastPoint) * GetRadius(AFirstPoint.Pos.Pos, AMiddlePoint.Pos.Pos, ALastPoint.Pos.Pos);
end;
class function TGeoCalcs.IsRightTurn(const ALatitude1, ALongitude1, ALatitude2, ALongitude2, ALatitude3, ALongitude3: Double): Boolean;
begin
Result := (ALatitude1 * ALongitude2 - ALongitude1 * ALatitude2
+ ALatitude2 * ALongitude3 - ALongitude2 * ALatitude3
+ ALatitude3 * ALongitude1 - ALongitude3 * ALatitude1) > 0;
end;
class function TGeoCalcs.IsRightTurn(const APos1, APos2, APos3: TGeoPos): Boolean;
begin
Result := (APos1.Latitude * APos2.Longitude - APos1.Longitude * APos2.Latitude
+ APos2.Latitude * APos3.Longitude - APos2.Longitude * APos3.Latitude
+ APos3.Latitude * APos1.Longitude - APos3.Longitude * APos1.Latitude) > 0;
end;
class function TGeoCalcs.PointBounding(const ACenter: TGeoPos;
const ARadius: Double): TGeoSquare;
begin
if (ACenter.Latitude < -90)
or (ACenter.Latitude > 90)
or (ACenter.Longitude <= -180)
or (ACenter.Longitude > 180)
or (ARadius > 1E6) then
begin
Result.NorthWest := TGeoPos.Create(0, 0);
Result.SouthEast := TGeoPos.Create(0, 0);
Exit;
end;
// Проверка на полюса
if ACenter.Latitude + ARadius / CEvDegLength > 90 then
Result.NorthWest.Latitude := 90
else
Result.NorthWest.Latitude := ACenter.Latitude + ARadius / CEvDegLength;
if ACenter.Latitude - ARadius / CEvDegLength < -90 then
Result.SouthEast.Latitude := -90
else
Result.SouthEast.Latitude := ACenter.Latitude - ARadius / CEvDegLength;
Result.NorthWest.Longitude := ACenter.Longitude - ARadius / CEvDegLength / Cos(DegToRad(ACenter.Longitude));
Result.SouthEast.Longitude := ACenter.Longitude + ARadius / CEvDegLength / Cos(DegToRad(ACenter.Longitude));
if Result.NorthWest.Longitude <= -180 then
Result.NorthWest.Longitude := Result.NorthWest.Longitude + 360;
if Result.SouthEast.Longitude > 180 then
Result.NorthWest.Longitude := Result.NorthWest.Longitude - 360;
end;
class function TGeoCalcs.GeoDistancePointToLine(const APoint, APoint1,
APoint2: TGeoPos; var APPoint: TGeoPos): Double;
var
x1, y1, x2, y2, CorrLon1, CorrLon2, Denominator, t: Double;
begin
// нивелируем эффект прокрутки при пересечении линии дат
if (APoint1.Longitude - APoint.Longitude > 180) then
CorrLon1 := APoint1.Longitude - 360
else if (APoint.Longitude - APoint1.Longitude > 180) then
CorrLon1 := APoint1.Longitude + 360
else
CorrLon1 := APoint1.Longitude;
if (APoint2.Longitude - APoint.Longitude > 180) then
CorrLon2 := APoint2.Longitude - 360
else if (APoint.Longitude - APoint2.Longitude > 180) then
CorrLon2 := APoint2.Longitude + 360
else
CorrLon2 := APoint2.Longitude;
// разворачиваем в декартову систему координат (с единицей "градус широты")
// за начало координат берём точку, для которой ищется расстояние
x1 := (CorrLon1 - APoint.Longitude) * Cos(DegToRad(APoint.Latitude));
y1 := APoint1.Latitude - APoint.Latitude;
x2 := (CorrLon2 - APoint.Longitude) * Cos(DegToRad(APoint.Latitude));
y2 := APoint2.Latitude - APoint.Latitude;
// сам расчёт
if (x1 * (x1 - x2) + y1 * (y1 - y2) <= 0) then // проекция точки оказалась ближе к точке 1 ИЛИ отрезок - это точка
begin
Result := Hypot(x1, y1);
APPoint.Latitude := APoint1.Latitude;
APPoint.Longitude := APoint1.Longitude;
end else
if (x2 * (x2 - x1) + y2 * (y2 - y1) < 0) then // проекция точки оказалась ближе к точке 2
begin
Result := Hypot(x2, y2);
APPoint.Latitude := APoint2.Latitude;
APPoint.Longitude := APoint2.Longitude;
end else // проекция попадает на отрезок
begin
Result := Abs(x2 * y1 - y2 * x1) / Hypot((y2 - y1), (x2 - x1));
Denominator := (CorrLon2 - CorrLon1) * (CorrLon2 - CorrLon1) +
(APoint2.Latitude - APoint1.Latitude) * (APoint2.Latitude - APoint1.Latitude);
if (Denominator = 0) then
begin
APPoint.Latitude := APoint1.Latitude;
APPoint.Longitude := APoint1.Longitude;
Exit;
end;
t := (APoint.Longitude * (CorrLon2 - CorrLon1) -
(CorrLon2 - CorrLon1) * CorrLon1 +
APoint.Latitude * (APoint2.Latitude - APoint1.Latitude) -
(APoint2.Latitude - APoint1.Latitude) * APoint1.Latitude) / Denominator;
APPoint.Longitude := CorrLon1 + (CorrLon2 - CorrLon1) * t;
APPoint.Latitude := APoint1.Latitude + (APoint2.Latitude - APoint1.Latitude) * t;
end;
end;
class function TGeoCalcs.GeoDistancePointToLineDeg(const ALatitudePoint, ALongitudePoint, ALatitude1, ALongitude1, ALatitude2, ALongitude2: Double): Double;
var
x1, y1, x2, y2, CorrLon1, CorrLon2: Double;
begin
// нивелируем эффект прокрутки при пересечении линии дат
if (ALongitude1 - ALongitudePoint > 180) then
CorrLon1 := ALongitude1 - 360
else if (ALongitudePoint - ALongitude1 > 180) then
CorrLon1 := ALongitude1 + 360
else
CorrLon1 := ALongitude1;
if (ALongitude2 - ALongitudePoint > 180) then
CorrLon2 := ALongitude2 - 360
else if (ALongitudePoint - ALongitude2 > 180) then
CorrLon2 := ALongitude2 + 360
else
CorrLon2 := ALongitude2;
// разворачиваем в декартову систему координат (с единицей "градус широты")
// за начало координат берём точку, для которой ищется расстояние
x1 := (CorrLon1 - ALongitudePoint) * Cos(DegToRad(ALatitudePoint));
y1 := ALatitude1 - ALatitudePoint;
x2 := (CorrLon2 - ALongitudePoint) * Cos(DegToRad(ALatitudePoint));
y2 := ALatitude2 - ALatitudePoint;
// сам расчёт
if (x1 * (x1 - x2) + y1 * (y1 - y2) <= 0) then // проекция точки оказалась ближе к точке 1 ИЛИ отрезок - это точка
begin
Result := Hypot(x1, y1);
end else
if (x2 * (x2 - x1) + y2 * (y2 - y1) < 0) then // проекция точки оказалась ближе к точке 2
begin
Result := Hypot(x2, y2);
end else // проекция попадает на отрезок
begin
Result := Abs(x2 * y1 - y2 * x1) / Hypot((y2 - y1), (x2 - x1));
end;
end;
class function TGeoCalcs.GeoDistancePointToLineM(const APoint, APoint1,
APoint2: TGeoPos; var APPoint: TGeoPos): Double;
begin
Result :=
GeoDistancePointToLine(APoint, APoint1, APoint2, APPoint) * CEvDegLength;
end;
class function TGeoCalcs.GeoDistancePointToLineMDeg(const ALatitudePoint,
ALongitudePoint, ALatitude1, ALongitude1, ALatitude2,
ALongitude2: Double): Double;
begin
Result :=
GeoDistancePointToLineDeg(
ALatitudePoint, ALongitudePoint,
ALatitude1, ALongitude1,
ALatitude2, ALongitude2) * CEvDegLength;
end;
class function TGeoCalcs.GeoDistancePointToZoneMDeg(const ALatitudePoint, ALongitudePoint: Double; const AZone: TGeoPosArray): Double;
var
i: Integer;
r: Double;
begin
Result := INFINITE;
i := Length(AZone);
if i >= 2 then
begin
Result := TGeoCalcs.GeoDistancePointToLineMDeg(ALatitudePoint, ALongitudePoint, AZone[0].Latitude, AZone[0].Longitude, AZone[i-1].Latitude, AZone[i-1].Longitude);
for i := 0 to Length(AZone) - 2 do
begin
r := TGeoCalcs.GeoDistancePointToLineMDeg(ALatitudePoint, ALongitudePoint, AZone[i].Latitude, AZone[i].Longitude, AZone[i+1].Latitude, AZone[i+1].Longitude);
if r < Result then
Result := r;
end;
end;
end;
class function TGeoCalcs.GeoDistancePointToPolyLineMDeg(const ALatitudePoint, ALongitudePoint: Double; const APolyLine: TGeoPosArray): Double;
var
i: Integer;
r: Double;
begin
Result := INFINITE;
for i := 0 to Length(APolyLine) - 2 do
begin
r := TGeoCalcs.GeoDistancePointToLineMDeg(ALatitudePoint, ALongitudePoint, APolyLine[i].Latitude, APolyLine[i].Longitude, APolyLine[i+1].Latitude, APolyLine[i+1].Longitude);
if r < Result then
Result := r;
end;
end;
class function TGeoCalcs.GeoPointInZone(const ALatitude, ALongitude: Double; const AZone: TGeoPosArray): Boolean;
var
I, J: Integer;
//------------------------------------------------------------------------------
begin
Result := False;
J := High(AZone);
for I := Low(AZone) to High(AZone) do
begin
if (
(
((AZone[I].Latitude <= ALatitude) and (ALatitude < AZone[J].Latitude))
or
((AZone[J].Latitude <= ALatitude) and (ALatitude < AZone[I].Latitude))
)
and
(
ALongitude
> (AZone[J].Longitude - AZone[I].Longitude)
* (ALatitude - AZone[I].Latitude)
/ (AZone[J].Latitude - AZone[I].Latitude)
+ AZone[I].Longitude
)
) then
Result := not Result;
J := I;
end;
end;
end.
|
unit Win32.MFMediaCapture;
// Checked (and Updated) for SDK 10.0.17763.0 on 2018-12-04
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils,
Win32.MFObjects;
const
IID_IAdvancedMediaCaptureInitializationSettings: TGUID = '{3DE21209-8BA6-4f2a-A577-2819B56FF14D}';
IID_IAdvancedMediaCaptureSettings: TGUID = '{24E0485F-A33E-4aa1-B564-6019B1D14F65}';
IID_IAdvancedMediaCapture: TGUID = '{D0751585-D216-4344-B5BF-463B68F977BB}';
type
IAdvancedMediaCaptureInitializationSettings = interface(IUnknown)
['{3DE21209-8BA6-4f2a-A577-2819B56FF14D}']
function SetDirectxDeviceManager(Value: IMFDXGIDeviceManager): HResult; stdcall;
end;
IAdvancedMediaCaptureSettings = interface(IUnknown)
['{24E0485F-A33E-4aa1-B564-6019B1D14F65}']
function GetDirectxDeviceManager(out Value: IMFDXGIDeviceManager): HResult; stdcall;
end;
IAdvancedMediaCapture = interface(IUnknown)
['{D0751585-D216-4344-B5BF-463B68F977BB}']
function GetAdvancedMediaCaptureSettings(out Value: IAdvancedMediaCaptureSettings): HResult; stdcall;
end;
implementation
end.
|
unit Dialog_EditMemb;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, RzEdit, RzCmboBx, RzTabs,Class_Memb, ComCtrls,
RzDTP,ADODB,Class_DBPool, Grids, BaseGrid, AdvGrid, Menus,Class_Dict,
Class_Context,Class_Menu,Class_MembMenu,Class_Mony, RzButton, RzRadChk,
Class_Smsx,Class_SendSmsx, AdvObj;
type
TDialogEditMemb = class(TForm)
Button1: TButton;
Button2: TButton;
RzPageControl1: TRzPageControl;
TabSheet1: TRzTabSheet;
TabSheet2: TRzTabSheet;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Edit_Name: TRzEdit;
Edit_Cege: TRzEdit;
Edit_Mobi: TRzEdit;
Edit_Card: TRzEdit;
Label5: TLabel;
Edit_Code: TRzEdit;
Label6: TLabel;
Combo_Sex: TRzComboBox;
Label7: TLabel;
TabSheet3: TRzTabSheet;
Edit_Addr: TRzEdit;
Label8: TLabel;
Date_MenbDate: TRzDateTimePicker;
Label9: TLabel;
Edit_Memo: TRzEdit;
AdvGrid: TAdvStringGrid;
BdvGrid: TAdvStringGrid;
PopupMenu1: TPopupMenu;
PopupMenu2: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
Label10: TLabel;
Edit_Levl: TRzEdit;
Btn_1: TButton;
Label11: TLabel;
Edit_Mony: TRzEdit;
Label12: TLabel;
Edit_Gift: TRzEdit;
TabSheet4: TRzTabSheet;
CdvGrid: TAdvStringGrid;
Btn_2: TButton;
ChkBox_BoolSmsx: TRzCheckBox;
lbl1: TLabel;
Edit_Serv: TRzEdit;
lbl2: TLabel;
Date_MembFete: TRzDateTimePicker;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure BdvGridGetAlignment(Sender: TObject; ARow, ACol: Integer;
var HAlign: TAlignment; var VAlign: TVAlignment);
procedure N1Click(Sender: TObject);
procedure Btn_1Click(Sender: TObject);
procedure Edit_CodeExit(Sender: TObject);
procedure CdvGridGetAlignment(Sender: TObject; ARow, ACol: Integer;
var HAlign: TAlignment; var VAlign: TVAlignment);
procedure Btn_2Click(Sender: TObject);
procedure N2Click(Sender: TObject);
private
FEditCode:Integer;
FMemb :TMemb;
protected
procedure SetInitialize;
procedure SetCommParams;
procedure SetGridParams;
procedure SetComboItems;
public
function CheckLicit:Boolean;
procedure DoSaveDB;
procedure InsertDB;
procedure UpdateDB;
//YXC_2010_04_05_01_08_04
procedure RendMemb;
//rend memb menu
procedure RendMenu;
procedure RendMony;
procedure DoViewMenu;
procedure DoViewMony;
procedure DoDeltMony;
procedure FillBdvGrid(AStrs:TStringList);
procedure FillCdvGrid(AStrs:TStringList);
end;
var
DialogEditMemb: TDialogEditMemb;
function FuncEditMemb(AEditCode:Integer;AMemb:TMemb):Integer;
implementation
uses
ConstValue,UtilLib,UtilLib_UiLib,UtilLib_Logic,Dialog_ViewMenu,Dialog_EditMony,
Class_KzUtils;
{$R *.dfm}
function FuncEditMemb(AEditCode:Integer;AMemb:TMemb):Integer;
begin
try
DialogEditMemb:=TDialogEditMemb.Create(nil);
DialogEditMemb.FEditCode:=AEditCode;
DialogEditMemb.FMemb :=AMemb;
Result:=DialogEditMemb.ShowModal;
finally
FreeAndNil(DialogEditMemb);
end;
end;
procedure TDialogEditMemb.FormCreate(Sender: TObject);
begin
UtilLib_UiLib.SetCommonDialogParams(Self);
end;
procedure TDialogEditMemb.SetCommParams;
const
ArrCaption:array[0..1] of string=('新增会员','编辑会员');
begin
Caption:=ArrCaption[FEditCode];
RzPageControl1.ActivePageIndex:=0;
Edit_Mony.Text:='0';
Edit_Gift.Text:='0';
Date_MenbDate.Date:=Now;
RzPageControl1.Pages[1].TabVisible:=False;
end;
procedure TDialogEditMemb.SetInitialize;
begin
SetCommParams;
SetComboItems;
SetGridParams;
if FEditCode=0 then
begin
Label11.Caption:='充值金额';
end else
if FEditCode=1 then
begin
Label11.Caption:='帐户余额';
RendMemb;
RendMenu;
RendMony;
end;
end;
procedure TDialogEditMemb.FormShow(Sender: TObject);
begin
SetInitialize;
end;
procedure TDialogEditMemb.SetComboItems;
begin
Combo_Sex.Items.Clear;
Combo_Sex.Add('女');
Combo_Sex.Add('男');
Combo_Sex.ItemIndex:=0;
end;
procedure TDialogEditMemb.Button1Click(Sender: TObject);
begin
if not CheckLicit then Exit;
case FEditCode of
0:InsertDB;
1:UpdateDB;
end;
end;
function TDialogEditMemb.CheckLicit: Boolean;
begin
Result:=False;
if Trim(Edit_Name.Text)='' then
begin
ShowMessage('请填写姓名');
Exit;
end;
Result:=True;
end;
procedure TDialogEditMemb.InsertDB;
var
ADOCon:TADOConnection;
AMony :TMony;
begin
if (FMemb<>nil) or (FEditCode<>0) then raise Exception.Create('(FMemb<>nil) or (FEditCode<>0)');
if ShowBox('是否确定保存会员基本信息')<>Mrok then Exit;
try
try
ADOCon:=TDBPool.GetConnect(1);
ADOCon.BeginTrans;
FMemb:=TMemb.Create;
FMemb.MembIdex:=FMemb.GetNextCode(ADOCon);
FMemb.MembName:=Trim(Edit_Name.Text);
FMemb.MembSex :=GetSex(Combo_Sex.Text);
FMemb.MembCode:=Trim(Edit_Code.Text);
FMemb.MembCard:=Trim(Edit_Card.Text);
FMemb.MembMobi:=Trim(Edit_Mobi.Text);
FMemb.MembCege:=Trim(Edit_Cege.Text);
FMemb.MembServ:=Trim(Edit_Serv.Text);
FMemb.MembAddr:=Trim(Edit_Addr.Text);
FMemb.MembMemo:=Trim(Edit_Memo.Text);
FMemb.MembFete:=Date_MembFete.DateTime;
FMemb.MembDate:=Date_MenbDate.DateTime;
FMemb.MembMony:=StrToFloat(Trim(Edit_Mony.Text))+StrToFloat(Trim(Edit_Gift.Text));
FMemb.InsertDB(ADOCon);
if FMemb.MembMony<>0 then
begin
AMony:=TMony.Create;
AMony.UnitLink:=FMemb.UnitLink;
AMony.MembIdex:=FMemb.MembIdex;
AMony.MonyIdex:=AMony.GetNextIdex(ADOCon);
AMony.MonyValu:=StrToFloat(Edit_Mony.Text);
AMony.MonyGift:=StrToFloat(Edit_Gift.Text);
AMony.MonyTotl:=FMemb.MembMony;
AMony.MonyDate:=FMemb.MembDate;
AMony.MonyMemo:='';
AMony.UserCode:=Context.LocalUser.UserCode;
AMony.InsertDB(ADOCon);
end;
ADOCon.CommitTrans;
FEditCode:=1;
ShowMessage('保存成功');
//YXC_2010_04_25_21_58_06_{
Label11.Caption:='帐户余额';
RendMemb;
RendMenu;
RendMony;
//YXC_2010_04_25_21_58_10_}
except
ADOCon.RollbackTrans;
end;
finally
FreeAndNil(ADOCon);
end;
end;
procedure TDialogEditMemb.DoSaveDB;
begin
end;
procedure TDialogEditMemb.UpdateDB;
var
ADOCon:TADOConnection;
begin
if ShowBox('是否更新会员基本信息吗?')<>Mrok then Exit;
ADOCon:=TDBPool.GetConnect();
FMemb.MembName:=Trim(Edit_Name.Text);
FMemb.MembSex :=GetSex(Combo_Sex.Text);
FMemb.MembCode:=Trim(Edit_Code.Text);
FMemb.MembCard:=Trim(Edit_Card.Text);
FMemb.MembMobi:=Trim(Edit_Mobi.Text);
FMemb.MembCege:=Trim(Edit_Cege.Text);
FMemb.MembServ:=Trim(Edit_Serv.Text);
FMemb.MembAddr:=Trim(Edit_Addr.Text);
FMemb.MembMemo:=Trim(Edit_Memo.Text);
FMemb.MembFete:=Date_MembFete.DateTime;
FMemb.MembDate:=Date_MenbDate.DateTime;
FMemb.BoolSmsx:=0;
if ChkBox_BoolSmsx.Checked then
begin
FMemb.BoolSmsx:=1;
end;
FMemb.UpdateDB(ADOCon);
ShowMessage('保存成功');
FreeAndNil(ADOCon);
end;
procedure TDialogEditMemb.Button3Click(Sender: TObject);
begin
// Edit_Name.Text:='AAAAA';
// Edit_Cege.Text:='0574-65309965';
// Edit_Mobi.Text:='13857824501';
// Edit_Code.Text:='330226198501017036';
// Edit_Addr.Text:='大在小区27幢';
// Edit_Card.Text:='330226198501017036';
// Edit_Memo.Text:='BBBBBBBBBBB';
end;
procedure TDialogEditMemb.Button2Click(Sender: TObject);
begin
ModalResult:=mrOk;
end;
procedure TDialogEditMemb.RendMemb;
begin
if (FMemb=nil) then raise Exception.Create('FMEMB=NIL');
Edit_Name.Text:=FMemb.MembName;
Edit_Cege.Text:=FMemb.MembCege;
Edit_Mobi.Text:=FMemb.MembMobi;
Edit_Code.Text:=FMemb.MembCode;
Edit_Card.Text:=FMemb.MembCard;
Edit_Serv.Text:=FMemb.MembServ;
Edit_Addr.Text:=FMemb.MembAddr;
Edit_Memo.Text:=FMemb.MembMemo;
Edit_Mony.Text:=FloatToStr(FMemb.MembMony);
Combo_Sex.ItemIndex:=Combo_Sex.IndexOf(GetSex(FMemb.MembSex));
Date_MenbDate.Date :=FMemb.MembDate;
Date_MenbDate.Enabled:=False;
Date_MembFete.Date :=FMemb.MembFete;
Edit_Levl.Text:=FMemb.GetMembLevl;
Edit_Gift.Enabled :=False;
Edit_Mony.ReadOnly:=True;
ChkBox_BoolSmsx.Checked:=FMemb.BoolSmsx=1;
end;
procedure TDialogEditMemb.Button4Click(Sender: TObject);
var
OD:TOpenDialog;
begin
// OD:=TOpenDialog.Create(nil);
//
// if OD.Execute then
// begin
// with AdvGrid do
// begin
// Cells[0,1]:='1';
// Cells[1,1]:=FormatDateTime('YYYY-MM-DD',Now);
// Cells[2,1]:=OD.FileName;
// end;
// end;
// FreeAndNil(OD);
end;
procedure TDialogEditMemb.SetGridParams;
begin
UtilLib_UiLib.SetCommonAdvGridParams(AdvGrid);
UtilLib_UiLib.SetCommonAdvGridParams(BdvGrid);
UtilLib_UiLib.SetCommonAdvGridParams(CdvGrid);
end;
procedure TDialogEditMemb.BdvGridGetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
if ARow=0 then
begin
HAlign:=taCenter;
end else
if (ARow>0) and (ACol in [0,1,2]) then
begin
HAlign:=taCenter;
end;
end;
procedure TDialogEditMemb.N1Click(Sender: TObject);
begin
DoViewMenu;
end;
procedure TDialogEditMemb.DoViewMenu;
var
I:Integer;
DictA:TDict;
DoubA:Double;
TextA:string;
AGift:Boolean;
AStrs:TStringList;
StrsB:TStringList;
TempA:string;
MenuA:TMenu;
SmsxA:TSmsx;
AMembMenu:TMembMenu;
ADOCon:TADOConnection;
begin
StrsB:=nil;
SmsxA:=nil;
AStrs:=nil;
if FMemb=nil then
begin
ShowMessage('会员对象为空,请先保存.');
Exit;
end;
DictA:=Context.GetObjDict(CONST_MENUCATE);
if FuncViewMenu(dvmvmMenu,DictA,AGift,AStrs)=Mrok then
begin
if ShowBox(Format('是否确定办理套餐?'+#13+'%s',[AStrs.Text]))<>Mrok then Exit;
DoubA:=0;
for I:=0 to AStrs.Count-1 do
begin
MenuA:=TMenu(AStrs.Objects[I]);
DoubA:=DoubA+MenuA.MenuCost;
end;
if ShowBox(Format('应收款[%f],请确定收款.',[DoubA]))<>Mrok then Exit;
AMembMenu:=TMembMenu.Create;
try
try
ADOCon:=TDBPool.GetConnect(1);
ADOCon.BeginTrans;
for I:=0 to AStrs.Count-1 do
begin
MenuA:=TMenu(AStrs.Objects[I]);
AMembMenu.UnitLink:=FMemb.UnitLink;
AMembMenu.MembIdex:=FMemb.MembIdex;
AMembMenu.MenuIdex:=MenuA.MenuIdex;
AMembMenu.MembMenu:=AMembMenu.GetNextCode(ADOCon);
AMembMenu.MenuNumb:=MenuA.MenuGift+MenuA.MenuNumb;
AMembMenu.MenuGift:=MenuA.MenuGift;
AMembMenu.MenuTotl:=MenuA.MenuGift+MenuA.MenuNumb;
AMembMenu.ThisDate:=Now;
AMembMenu.MembCost:=MenuA.MenuCost;
//YXC_2012_06_12_12_15_02
if AGift then
begin
AMembMenu.MenuType:=0;
end;
AMembMenu.InsertDB(ADOCon);
end;
ADOCon.CommitTrans;
except
ADOCon.RollbackTrans;
end;
finally
FreeAndNil(AMembMenu);
FreeAndNil(ADOCon);
end;
if (FMemb.BoolSmsx=1) and (Length(FMemb.MembCege)=11) then
begin
if ShowBox('是否发送短信?')=Mrok then
begin
Context.UpdateStrsSmsx;
SmsxA:=nil;
SmsxA:=Context.GetObjxSmsx(CONST_SMSX_TCBL);
if SmsxA=nil then Exit;
if SendSmsx.Initialize then
begin
TextA:=SmsxA.SmsxText;
StrsB:=TStringList.Create;
TempA:='[套餐名称]=%S';
TempA:=Format(TempA,[AStrs.Text]);
StrsB.Add(TempA);
TextA:=FMemb.GetSmsxText(TextA,StrsB);
TempA:='即将往目标[%S]发送短信:'+#13+TextA;
TempA:=Format(TempA,[FMemb.MembCege]);
if ShowBox(TempA)=Mrok then
begin
if SendSmsx.SendTest(FMemb.MembCege,TextA)=1 then
begin
ShowMessage('短信发送成功.');
end;
end;
end;
end;
end;
RendMenu;
end;
if StrsB<>nil then
begin
FreeAndNil(StrsB);
end;
end;
procedure TDialogEditMemb.RendMenu;
var
ASQL:string;
Strs:TStringList;
begin
ASQL:='SELECT A.*,B.MENU_NAME FROM TBL_MEMB_MENU A,TBL_MENU B WHERE A.MENU_IDEX=B.MENU_IDEX AND A.MEMB_IDEX=%D AND A.UNIT_LINK=%S ORDER BY THIS_DATE';
ASQL:=Format(ASQL,[FMemb.MembIdex,QuotedStr(FMemb.UnitLink)]);
Strs:=TMembMenu.StrsDB(ASQL);
FillBdvGrid(Strs);
end;
procedure TDialogEditMemb.FillBdvGrid(AStrs: TStringList);
var
I :Integer;
Idex:Integer;
AObj:TMembMenu;
begin
ClearAdvGrid(BdvGrid,1);
if (AStrs=nil) or (AStrs.Count=0) then Exit;
ClearAdvGrid(BdvGrid,AStrs.Count);
with BdvGrid do
begin
BeginUpdate;
for I:=0 to AStrs.Count-1 do
begin
Idex:=I+1;
AObj:=TMembMenu(AStrs.Objects[I]);
Objects[0,Idex]:=AObj;
Ints[0,Idex] :=Idex;
Cells[1,Idex] :=FormatDateTime('YYYY-MM-DD',AObj.ThisDate);
Ints[2,Idex] :=AObj.MenuNumb;
Cells[3,Idex] :=AObj.GetMenuType;
Alignments[3,Idex]:=taCenter;
Cells[4,Idex] :=AObj.MenuName;
end;
EndUpdate;
end;
end;
procedure TDialogEditMemb.Btn_1Click(Sender: TObject);
begin
DoViewMenu;
end;
procedure TDialogEditMemb.Edit_CodeExit(Sender: TObject);
var
ACode:string;
begin
if FEditCode=1 then Exit;
ACode:=Trim(Edit_Code.Text);
if ACode='' then Exit;
if TMemb.CheckExist(ACode) then
begin
ShowMessageFmt('卡号[%S]己被使用,请重新刷卡',[ACode]);
Edit_Code.Clear;
Edit_Code.SetFocus;
end;
end;
procedure TDialogEditMemb.RendMony;
var
ASQL:string;
Strs:TStringList;
begin
ASQL:='SELECT * FROM TBL_MONY WHERE UNIT_LINK=%S AND MEMB_IDEX=%D';
ASQL:=Format(ASQL,[QuotedStr(FMemb.UnitLink),FMemb.MembIdex]);
Strs:=TMony.StrsDB(ASQL);
FillCdvGrid(Strs);
end;
procedure TDialogEditMemb.FillCdvGrid(AStrs: TStringList);
var
I :Integer;
Idex:Integer;
AObj:TMony;
begin
ClearAdvGrid(CdvGrid,1);
if (AStrs=nil) or (AStrs.Count=0) then Exit;
ClearAdvGrid(CdvGrid,AStrs.Count);
with CdvGrid do
begin
BeginUpdate;
for I:=0 to AStrs.Count-1 do
begin
Idex:=I+1;
AObj:=TMony(AStrs.Objects[I]);
Objects[0,Idex]:=AObj;
Ints[0,Idex] :=Idex;
Cells[1,Idex] :=FormatDateTime('YYYY-MM-DD',AObj.MonyDate);
Cells[2,Idex] :=FloatToStr(AObj.MonyValu);
Cells[3,Idex] :=FloatToStr(AObj.MonyGift);
Cells[4,Idex] :=FloatToStr(AObj.MonyTotl);
Cells[5,Idex] :=AObj.MonyMemo;
end;
EndUpdate;
end;
end;
procedure TDialogEditMemb.CdvGridGetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
if ARow=0 then
begin
HAlign:=taCenter;
end else
if (ARow>0) and (ACol in [0,1]) then
begin
HAlign:=taCenter;
end else
if (ARow>0) and (ACol in [2,3,4]) then
begin
HAlign:=taRightJustify;
end;
end;
procedure TDialogEditMemb.Btn_2Click(Sender: TObject);
begin
DoViewMony;
end;
procedure TDialogEditMemb.DoViewMony;
begin
if FMemb=nil then
begin
ShowMessage('会员对象为空');
Exit;
end;
if FuncEditMony(1,FMemb)=Mrok then
begin
RendMemb;
RendMony;
end;
end;
procedure TDialogEditMemb.N2Click(Sender: TObject);
begin
DoDeltMony;
end;
procedure TDialogEditMemb.DoDeltMony;
var
BoolA:Boolean;
MonyA:TMony;
ADOCon:TADOConnection;
begin
BoolA:=False;
if FMemb=nil then Exit;
if TKzUtils.ErorBox('是否确定删除该充值记录?')<>Mrok then Exit;
with CdvGrid do
begin
MonyA:=nil;
MonyA:=TMony(Objects[0,RealRow]);
if MonyA=nil then Exit;
try
ADOCon:=TDBPool.GetConnect();
TMony.ExecuteSQL(Format('DELETE FROM TBL_MONY WHERE UNIT_LINK=%S AND MEMB_IDEX=%D AND MONY_IDEX=%D',[QuotedStr(MonyA.UnitLink),MonyA.MembIdex,MonyA.MonyIdex]));
FMemb.MembMony:=FMemb.MembMony - MonyA.MonyTotl;
FMemb.UpdateDB(ADOCon);
BoolA:=True;
finally
FreeAndNil(ADOCon);
end;
end;
if BoolA then
begin
SetInitialize;
end;
end;
end.
|
unit KanjiDic;
{ Basic in-memory KanjiDic representation, heavy and slow. If you need anything
fancy, write your own engine and use KanjiDicReader to load data.
Usage:
kd := TKanjidic.Create;
kd.LoadFromFile('kanjidic');
common_ons := kd.FindEntry(char).readings[0].ons.Join(', ');
}
interface
uses SysUtils, Classes, JWBIO, BalancedTree, FastArray, KanjiDicReader;
type
{ Char lookups are indexed. We may add other indexes as the need arises }
TCharItem = class(TBinTreeItem)
protected
FEntry: PKanjiDicEntry;
FChar: UnicodeString; //hopefully shared with the entry
public
constructor Create(AEntry: PKanjiDicEntry; const AChar: UnicodeString);
function CompareData(const a):Integer; override;
function Compare(a:TBinTreeItem):Integer; override;
procedure Copy(ToA:TBinTreeItem); override;
end;
TKanjiDic = class
protected
FEntries: TArray<PKanjiDicEntry>;
FCharTree: TBinTree;
function AllocEntry: PKanjiDicEntry;
procedure RegisterEntry(const AEntry: PKanjiDicEntry);
function GetEntryCount: integer; inline;
function GetEntry(const AIndex: integer): PKanjiDicEntry;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure LoadFromFile(const AFilename: string);
procedure LoadFromStream(const AStream: TStream);
procedure Load(AInput: TStreamDecoder);
function FindEntry(const AChar: UnicodeString): PKanjiDicEntry;
property EntryCount: integer read GetEntryCount;
property Entries[const Index: integer]: PKanjiDicEntry read GetEntry;
end;
implementation
uses WideStrUtils;
constructor TCharItem.Create(AEntry: PKanjiDicEntry; const AChar: UnicodeString);
begin
inherited Create;
Self.FEntry := AEntry;
Self.FChar := AChar;
end;
//Accepts only PWideChar
function TCharItem.CompareData(const a):Integer;
begin
Result := WStrComp(PWideChar(Self.FChar), PWideChar(a));
end;
function TCharItem.Compare(a:TBinTreeItem):Integer;
begin
Result := CompareData(TCharItem(a).FChar);
end;
procedure TCharItem.Copy(ToA:TBinTreeItem);
begin
TCharItem(ToA).FEntry := Self.FEntry;
TCharItem(ToA).FChar := Self.FChar;
end;
constructor TKanjiDic.Create;
begin
inherited;
FCharTree := TBinTree.Create;
end;
destructor TKanjiDic.Destroy;
begin
FreeAndNil(FCharTree);
inherited;
end;
procedure TKanjiDic.Clear;
var i: integer;
ptr: PKanjiDicEntry;
begin
FCharTree.Clear;
for i := FEntries.Length-1 downto 0 do begin
ptr := PKanjiDicEntry(FEntries.GetPointer(i));
Dispose(ptr);
end;
FEntries.Length := 0;
end;
procedure TKanjiDic.LoadFromFile(const AFilename: string);
var inp: TStreamDecoder;
begin
inp := OpenTextFile(AFilename);
try
Load(inp);
finally
FreeAndNil(inp);
end;
end;
procedure TKanjiDic.LoadFromStream(const AStream: TStream);
var inp: TStreamDecoder;
begin
inp := OpenStream(AStream, {owns=}false);
try
Load(inp);
finally
FreeAndNil(inp);
end;
end;
procedure TKanjiDic.Load(AInput: TStreamDecoder);
var ed: PKanjiDicEntry;
ln: string;
begin
Clear;
AInput.Rewind();
while AInput.ReadLn(ln) do begin
ln := Trim(ln);
if ln='' then continue;
if IsKanjidicComment(ln) then
continue;
ed := AllocEntry;
ParseKanjiDicLine(ln, ed);
RegisterEntry(ed);
end;
end;
function TKanjiDic.AllocEntry: PKanjiDicEntry;
begin
New(Result);
FEntries.Add(Result);
end;
procedure TKanjiDic.RegisterEntry(const AEntry: PKanjiDicEntry);
begin
FCharTree.Add(TCharItem.Create(AEntry, AEntry.kanji));
end;
function TKanjiDic.GetEntryCount: integer;
begin
Result := FEntries.Length;
end;
function TKanjiDic.GetEntry(const AIndex: integer): PKanjiDicEntry;
begin
Result := FEntries[AIndex];
end;
{ Searches for a given entry }
function TKanjiDic.FindEntry(const AChar: UnicodeString): PKanjiDicEntry;
var item: TBinTreeItem;
begin
if AChar='' then begin
Result := nil;
exit;
end;
item := FCharTree.SearchData(AChar);
if item=nil then
Result := nil
else
Result := TCharItem(item).FEntry;
end;
end.
|
unit BaseTypes;
interface
uses Dialogs, pFIBDataBase, FIBDataBase;
const
INI_FILENAME = 'app.ini';
DELETE_QUESTION = 'Ви дійсно хочете видалити виділений запис?';
EMPTY_WARNING = 'Необхідно заповнити всі дані';
ST_REMOTE = 0;//Server type
ST_LOCAL = 1;
SYS_DIGITS_AFTER_DOT = 2;
ID_ACTION_ADD = 1;
ID_ACTION_MOD = 2;
ID_ACTION_DEL = 3;
SYSTEM_CODE = 1;
SYSTEM_F = 'SYSTEM_F';
type
TReportFormFunc = function(AppHandle : THandle; DataBase : PCHAR; User : PCHAR; Password : PCHAR; id_report : integer; id_template : integer) : boolean; stdcall;
TReportColumn = packed record
name_column : string;
name_filed : string;
type_filed : string;
visible : boolean;
end;
TReportData = array of TReportColumn;
TIntArray2 = array of integer;
TSpravAction = (saAdd, saMod, saView);
TResultArray = array of variant;
TSpravOptions = packed record
canAdd : boolean;
canEdit : boolean;
canDelete : boolean;
canSelect : boolean;
canSelect2 : boolean;
HideButtons : boolean;
isModal : boolean;
end;
const
DEF_OPTIONS : TSpravOptions = (canAdd: true; canEdit: true; canDelete: true; canSelect: true; canSelect2: false; HideButtons: false; isModal: true);
var
APP_PATH : string;
DB_PATH : string;
DB_USER : string = 'SYSDBA';
DB_PASSWORD : string = 'masterkey';
DB_SERVER_TYPE : integer;// 0 - remote 1 - local
DB_SERVER_NAME : string;
CURRENT_USER : string;
CURRENT_PASSWORD : string;
IMPORT_PATH : string = '';
EXPORT_PATH : string = '';
procedure CheckInteger(var Key : char);
procedure CheckFloat(var Key : char);
function isFloat(const s : string) : boolean;
function isInteger(const s : string) : boolean;
function agCurrToStr(const cur : currency) : string;
function agMessageDlg(const Caption : string; const Msg : string; const DlgType: TMsgDlgType; const Buttons: TMsgDlgButtons) : word;
procedure agShowMessage(const Msg : string);
procedure ReadIniFile;
procedure WriteIniFile;
implementation
uses Forms, StdCtrls, SysUtils, IniFiles;
function agCurrToStr(const cur : currency) : string;
begin
Result := CurrToStrF(cur, ffFixed, SYS_DIGITS_AFTER_DOT);
end;
procedure ReadIniFile;
var
IniFile : TMemIniFile;
begin
if not FileExists(APP_PATH + INI_FILENAME) then exit;
try
IniFile := TMemIniFile.Create(APP_PATH + INI_FILENAME);
DB_PATH := IniFile.ReadString('DB', 'Path', DB_PATH);
// DB_USER := IniFile.ReadString('DB', 'User', DB_USER);
// DB_PASSWORD := IniFile.ReadString('DB', 'Password', DB_PASSWORD);
DB_SERVER_TYPE := IniFile.ReadInteger('DB', 'ServerType', 0);
DB_SERVER_NAME := IniFile.ReadString('DB', 'ServerName', DB_SERVER_NAME);
IMPORT_PATH := IniFile.ReadString('DB', 'Import path', IMPORT_PATH);
EXPORT_PATH := IniFile.ReadString('DB', 'Export path', EXPORT_PATH);
finally
IniFile.Free;
end;
if DB_SERVER_TYPE = ST_REMOTE then DB_PATH := DB_SERVER_NAME + ':' + DB_PATH;
end;
procedure WriteIniFile;
var
IniFile : TIniFile;
begin
try
IniFile := TIniFile.Create(APP_PATH + INI_FILENAME);
IniFile.WriteString('DB', 'Path', DB_PATH);
// IniFile.WriteString('DB', 'User', DB_USER);
// IniFile.WriteString('DB', 'Password', DB_PASSWORD);
IniFile.WriteInteger('DB', 'ServerType', DB_SERVER_TYPE);
IniFile.WriteString('DB', 'ServerName', DB_SERVER_NAME);
finally
IniFile.Free;
end;
end;
procedure CheckInteger(var Key : char);
begin
if not (Key in ['0'..'9',#8, #13]) then Key := #0;
end;
procedure CheckFloat(var Key : char);
begin
if not (Key in ['0'..'9',#8, #13, DecimalSeparator]) then Key := #0;
end;
function agMessageDlg(const Caption : string; const Msg : string; const DlgType: TMsgDlgType; const Buttons: TMsgDlgButtons) : word;
var
form : TForm;
i : integer;
begin
if Buttons = [] then begin
Result := 0;
exit;
end;
form := CreateMessageDialog(Msg, DlgType, Buttons);
form.Caption := Caption;
for i := 0 to form.ComponentCount - 1 do if form.Components[i] is TButton then begin
if UpperCase(TButton(form.Components[i]).Caption) = 'OK' then TButton(form.Components[i]).Caption := 'Прийняти';
if UpperCase(TButton(form.Components[i]).Caption) = 'CANCEL' then TButton(form.Components[i]).Caption := 'Відмінити';
if UpperCase(TButton(form.Components[i]).Caption) = '&YES' then TButton(form.Components[i]).Caption := 'Да';
if UpperCase(TButton(form.Components[i]).Caption) = '&NO' then TButton(form.Components[i]).Caption := 'Ні';
if UpperCase(TButton(form.Components[i]).Caption) = '&ABORT' then TButton(form.Components[i]).Caption := 'Відмінити';
if UpperCase(TButton(form.Components[i]).Caption) = '&RETRY' then TButton(form.Components[i]).Caption := 'Повторити';
if UpperCase(TButton(form.Components[i]).Caption) = '&IGNORE' then TButton(form.Components[i]).Caption := 'Ігнорувати';
if UpperCase(TButton(form.Components[i]).Caption) = '&ALL' then TButton(form.Components[i]).Caption := 'Все';
if UpperCase(TButton(form.Components[i]).Caption) = '&HELP' then TButton(form.Components[i]).Caption := 'Допомога';
if UpperCase(TButton(form.Components[i]).Caption) = 'N&O TO ALL' then TButton(form.Components[i]).Caption := 'Ні для всіх';
if UpperCase(TButton(form.Components[i]).Caption) = 'YES TO &ALL' then TButton(form.Components[i]).Caption := 'Да для всіх';
end;
Result := form.ShowModal;
end;
procedure agShowMessage(const Msg : string);
begin
agMessageDlg('Увага', Msg, mtWarning, [mbOk]);
end;
function isInteger(const s : string) : boolean;
var
i : integer;
k : char;
begin
Result := false;
if s = '' then exit;
for i := 1 to Length(s) do begin
k := s[i];
CheckInteger(k);
if k = #0 then exit;
end;
Result := true;
end;
function isFloat(const s : string) : boolean;
var
i : integer;
k : char;
begin
Result := false;
if s = '' then exit;
for i := 1 to Length(s) do begin
k := s[i];
CheckFloat(k);
if k = #0 then exit;
end;
i := pos(DecimalSeparator, s);
if i <> 0 then if Copy(s, i + 1, Length(s) - i) = '' then exit;
if pos(DecimalSeparator, Copy(s, i + 1, Length(s) - i)) <> 0 then exit;
Result := true;
end;
end.
|
unit PaletteControl;
interface
uses Menus, BasicProgramTypes, Classes;
type
TPaletteControl = class
private
Owner: TComponent;
function IsFileInUse(const _FileName: string): Boolean;
function FindSubMenuItemFromCaption(var _BaseMenuItem: TMenuItem; const _Caption: string):TMenuItem;
procedure ClearSubMenu(var _MenuItem: TMenuItem);
public
PaletteSchemes : TPaletteSchemes;
OnClickEvent: TNotifyEvent;
constructor Create(const _Owner: TComponent; _OnClickEvent: TNotifyEvent);
destructor Destroy; override;
procedure ResetPaletteSchemes;
procedure AddPalettesToSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer); overload;
procedure AddPalettesToSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer; _CreateSubMenu: boolean); overload;
procedure UpdatePalettesAtSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer); overload;
procedure UpdatePalettesAtSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer; _UseBaseItem, _ClearBaseItem: boolean); overload;
end;
implementation
uses BasicFunctions, Windows, SysUtils;
constructor TPaletteControl.Create(const _Owner: TComponent; _OnClickEvent: TNotifyEvent);
begin
Owner := _Owner;
OnClickEvent := _OnClickEvent;
end;
destructor TPaletteControl.Destroy;
begin
ResetPaletteSchemes;
inherited Destroy;
end;
procedure TPaletteControl.ResetPaletteSchemes;
begin
SetLength(PaletteSchemes, 0);
end;
procedure TPaletteControl.ClearSubMenu(var _MenuItem: TMenuItem);
var
i: integer;
item: TMenuItem;
begin
if _MenuItem.Count > 0 then
begin
i := _MenuItem.Count - 1;
while i >= 0 do
begin
item := _MenuItem.Items[i];
if Item.Count > 0 then
begin
ClearSubMenu(Item);
end;
_MenuItem.Delete(i);
dec(i);
end;
end;
end;
function TPaletteControl.FindSubMenuItemFromCaption(var _BaseMenuItem: TMenuItem; const _Caption: string):TMenuItem;
var
i: integer;
begin
i := 0;
while i < _BaseMenuItem.Count do
begin
if CompareText(_BaseMenuItem.Items[i].Caption, _Caption) = 0 then
begin
Result := _BaseMenuItem.Items[i];
exit;
end;
inc(i);
end;
Result := TMenuItem.Create(Owner);
Result.Caption := CopyString(_Caption);
Result.Visible := false;
_BaseMenuItem.Insert(_BaseMenuItem.Count, Result);
end;
// copied from: http://stackoverflow.com/questions/16287983/why-do-i-get-i-o-error-32-even-though-the-file-isnt-open-in-any-other-program
function TPaletteControl.IsFileInUse(const _FileName: string): Boolean;
var
HFileRes: HFILE;
begin
Result := False;
if not FileExists(_FileName) then Exit;
HFileRes := CreateFile(PChar(_FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;
procedure TPaletteControl.AddPalettesToSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer);
begin
AddPalettesToSubMenu(_SubMenu, _Dir, _Counter, _ImageIndex, false);
end;
procedure TPaletteControl.AddPalettesToSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer; _CreateSubMenu: boolean);
var
f: TSearchRec;
FileName, DirName, path: String;
item: TMenuItem;
CurrentSubMenu: TMenuItem;
begin
if not DirectoryExists(_Dir) then
exit;
if _CreateSubMenu then
begin
Item := TMenuItem.Create(Owner);
item.Caption := ExtractFileName(ExcludeTrailingPathDelimiter(_Dir));
// item.OnClick := FrmMain.blank2Click;
_SubMenu.Insert(_SubMenu.Count, Item);
CurrentSubMenu := Item;
end
else
begin
if _SubMenu = nil then
exit;
CurrentSubMenu := _SubMenu;
end;
CurrentSubMenu.Visible := false;
path := Concat(_Dir, '*.pal');
// find files
if FindFirst(path,faAnyFile,f) = 0 then
repeat
Filename := IncludeTrailingPathDelimiter(_Dir) + f.Name;
SetLength(PaletteSchemes, High(PaletteSchemes)+2);
PaletteSchemes[High(PaletteSchemes)].FileName := Filename;
PaletteSchemes[High(PaletteSchemes)].ImageIndex := _ImageIndex;
item := TMenuItem.Create(Owner);
item.AutoHotkeys := maManual;
item.Caption := extractfilename(PaletteSchemes[High(PaletteSchemes)].FileName);
item.Tag := High(PaletteSchemes); // so we know which it is
item.OnClick := OnClickEvent;
CurrentSubMenu.Insert(CurrentSubMenu.Count, item);
until FindNext(f) <> 0;
FindClose(f);
if (High(PaletteSchemes)+1) > _Counter then
begin
CurrentSubMenu.Visible := true;
end;
_Counter := High(PaletteSchemes)+1;
// Find directories.
Path := IncludeTrailingPathDelimiter(_Dir) + '*';
if FindFirst(path,faDirectory,f) = 0 then
begin
repeat
if (CompareStr(f.Name,'.') <> 0) and (CompareStr(f.Name, '..') <> 0) then
begin
DirName := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(_Dir) + f.Name);
if DirectoryExists(DirName) then // It sounds unnecessary, but for some reason, it may catch some weird dirs sometimes.
begin
AddPalettesToSubMenu(CurrentSubMenu, DirName, _Counter, _ImageIndex, true);
end;
end;
until FindNext(f) <> 0;
end;
FindClose(f);
end;
procedure TPaletteControl.UpdatePalettesAtSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer);
begin
UpdatePalettesAtSubMenu(_SubMenu, _Dir, _Counter, _ImageIndex, true, true);
end;
procedure TPaletteControl.UpdatePalettesAtSubMenu(var _SubMenu: TMenuItem; const _Dir: string; var _Counter: integer; const _ImageIndex: integer; _UseBaseItem, _ClearBaseItem: boolean);
var
f: TSearchRec;
FileName, DirName, path: String;
item: TMenuItem;
CurrentSubMenu: TMenuItem;
begin
if not DirectoryExists(_Dir) then
exit;
if not _UseBaseItem then
begin
CurrentSubMenu := FindSubMenuItemFromCaption(_SubMenu, ExtractFileName(ExcludeTrailingPathDelimiter(_Dir)));
end
else
begin
CurrentSubMenu := _SubMenu;
end;
if _ClearBaseItem then
begin
ClearSubMenu(CurrentSubMenu);
end;
path := Concat(_Dir, '*.pal');
// find files
if FindFirst(path,faAnyFile,f) = 0 then
repeat
FileName := _Dir + f.Name;
if FileExists(FileName) and (not IsFileInUse(FileName)) then
begin
SetLength(PaletteSchemes, High(PaletteSchemes)+2);
PaletteSchemes[High(PaletteSchemes)].FileName := Filename;
PaletteSchemes[High(PaletteSchemes)].ImageIndex := _ImageIndex;
item := TMenuItem.Create(Owner);
item.AutoHotkeys := maManual;
item.Caption := extractfilename(PaletteSchemes[High(PaletteSchemes)].FileName);
item.Tag := High(PaletteSchemes); // so we know which it is
item.OnClick := OnClickEvent;
inc(_Counter);
CurrentSubMenu.Insert(CurrentSubMenu.Count, item);
inc(_Counter);
end;
until FindNext(f) <> 0;
FindClose(f);
if (High(PaletteSchemes)+1) > _Counter then
begin
CurrentSubMenu.Visible := true;
end;
// Find directories.
Path := IncludeTrailingPathDelimiter(_Dir) + '*';
if FindFirst(path,faDirectory,f) = 0 then
begin
repeat
if (CompareStr(f.Name,'.') <> 0) and (CompareStr(f.Name, '..') <> 0) then
begin
DirName := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(_Dir) + f.Name);
if DirectoryExists(DirName) then // It sounds unnecessary, but for some reason, it may catch some weird dirs sometimes.
begin
UpdatePalettesAtSubMenu(CurrentSubMenu, DirName, _Counter, _ImageIndex, false, true);
end;
end;
until FindNext(f) <> 0;
end;
FindClose(f);
end;
end.
|
unit MVVM.ViewFactory;
interface
uses
System.Rtti,
System.UITypes,
System.Classes,
System.SysUtils,
Spring.Collections,
MVVM.Interfaces.Architectural;
type
{ A factory for creating views based on their names.
View models can create a view by calling TViewFactory.CreateView. }
TViewFactory = class
{$REGION 'Internal Declarations'}
private
class var FRegisteredViews: IDictionary<String, TRttiInstanceType>;
public
class destructor Destroy;
{$ENDREGION 'Internal Declarations'}
public
class procedure Register(const AViewClass: TRttiInstanceType; const AViewName: String; const APlatform: String = ''); static;
{ Creates a view using a previously registered view class.
Returns:
A newly created view that represents AViewName.
Raises:
EListError if there is no view registered with the given AViewName. }
class function CreateView<TVM: IViewModel>(const APlatform: string; const AViewName: String; const AOwner: TComponent; AViewModel: TVM): IView<TVM>; static;
end;
TViewFactoryClass = class of TViewFactory;
type
{ Internal class used to manage lifetimes of views. }
TViewProxy<TVM: IViewModel> = class(TInterfacedObject, IView, IView<TVM>)
{$REGION 'Internal Declarations'}
private type
TViewFreeListener = class(TComponent)
strict private
FActualView: IView<TVM>;
[unsafe]
FActualViewObject: TComponent;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AView: IView<TVM>); reintroduce;
destructor Destroy; override;
property ActualView: IView<TVM> read FActualView;
end;
private
FViewFreeListener: TViewFreeListener;
protected
function GetViewModel: TVM;
{ IView }
procedure ExecuteModal(const AResultProc: TProc<TModalResult>);
protected
{ IView<TVM> }
procedure InitView(AViewModel: TVM);
{$ENDREGION 'Internal Declarations'}
public
constructor Create(AActualView: IView<TVM>);
destructor Destroy; override;
function GetAsObject: TObject;
procedure SetupView;
property ViewModel: TVM read GetViewModel;
end;
TDummyFormViewProxy<TVM: IViewModel> = class(TInterfacedObject, IView, IView<TVM>, IViewForm<TVM>)
{$REGION 'Internal Declarations'}
private type
TViewFreeListener = class(TComponent)
strict private
FActualView: IView<TVM>;
[unsafe]
FActualViewObject: TComponent;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AView: IView<TVM>); reintroduce;
destructor Destroy; override;
property ActualView: IView<TVM> read FActualView;
end;
private
FViewFreeListener: TViewFreeListener;
protected
function GetViewModel: TVM;
{ IViewForm }
procedure Execute;
procedure ExecuteModal(const AResultProc: TProc<TModalResult>);
protected
{ IView<TVM> }
procedure InitView(AViewModel: TVM);
{$ENDREGION 'Internal Declarations'}
public
constructor Create(AActualView: IView<TVM>);
destructor Destroy; override;
function GetAsObject: TObject;
procedure SetupView;
property ViewModel: TVM read GetViewModel;
end;
TFormViewProxy<TVM: IViewModel> = class(TInterfacedObject, IView, IView<TVM>, IViewForm<TVM>)
{$REGION 'Internal Declarations'}
private type
TViewFreeListener = class(TComponent)
strict private
FActualView: IViewForm<TVM>;
[unsafe]
FActualViewObject: TComponent;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AView: IViewForm<TVM>); reintroduce;
destructor Destroy; override;
property ActualView: IViewForm<TVM> read FActualView;
end;
private
FViewFreeListener: TViewFreeListener;
protected
function GetViewModel: TVM;
{ IViewForm }
procedure Execute;
procedure ExecuteModal(const AResultProc: TProc<TModalResult>);
protected
{ IView<TVM> }
procedure InitView(AViewModel: TVM);
{$ENDREGION 'Internal Declarations'}
public
constructor Create(AActualView: IViewForm<TVM>);
destructor Destroy; override;
function GetAsObject: TObject;
procedure SetupView;
property ViewModel: TVM read GetViewModel;
end;
implementation
uses
System.Generics.Defaults,
MVVM.Core,
MVVM.Rtti,
MVVM.Utils;
{ TViewProxy<TVM> }
constructor TViewProxy<TVM>.Create(AActualView: IView<TVM>);
begin
Assert(Assigned(AActualView));
inherited Create;
{ Executing a view may free it (for example, when the view is a form and its
CloseAction is set to caFree). When that happens, the IView interface
will contain an invalid reference, and you may get an access violation when
it goes out of scope. To avoid this, we use a view proxy. This proxy
subscribes to a free notification of the view, so it can set the IView
interface to nil BEFORE the view is destroyed. }
FViewFreeListener := TViewFreeListener.Create(AActualView);
end;
destructor TViewProxy<TVM>.Destroy;
begin
FViewFreeListener.Free;
inherited;
end;
procedure TViewProxy<TVM>.ExecuteModal(const AResultProc: TProc<TModalResult>);
var
[weak]
LViewForm: IViewForm<TVM>;
begin
if Assigned(FViewFreeListener.ActualView) then
begin
if Supports(FViewFreeListener.ActualView, IViewForm<TVM>, LViewForm) then
LViewForm.ExecuteModal(AResultProc);
end;
end;
function TViewProxy<TVM>.GetAsObject: TObject;
begin
Result := Self
end;
function TViewProxy<TVM>.GetViewModel: TVM;
begin
if Assigned(FViewFreeListener.ActualView) then
Result := FViewFreeListener.ActualView.ViewModel
else
Result := nil;
end;
procedure TViewProxy<TVM>.InitView(AViewModel: TVM);
begin
if Assigned(FViewFreeListener.ActualView) then
FViewFreeListener.ActualView.InitView(AViewModel);
end;
procedure TViewProxy<TVM>.SetupView;
begin
if Assigned(FViewFreeListener.ActualView) then
FViewFreeListener.ActualView.SetupView;
end;
{ TViewProxy<TVM>.TViewFreeListener }
constructor TViewProxy<TVM>.TViewFreeListener.Create(AView: IView<TVM>);
var
Instance: TObject;
begin
inherited Create(nil);
FActualView := AView;
Instance := TObject(AView);
if (Instance is TComponent) then
begin
FActualViewObject := TComponent(Instance);
FActualViewObject.FreeNotification(Self);
end;
end;
destructor TViewProxy<TVM>.TViewFreeListener.Destroy;
begin
if (FActualViewObject <> nil) then
FActualViewObject.RemoveFreeNotification(Self);
inherited;
end;
procedure TViewProxy<TVM>.TViewFreeListener.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (AComponent = FActualViewObject) and (Operation = opRemove) then
begin
FActualView := nil;
FActualViewObject := nil;
end;
end;
{ TViewFactory }
class function TViewFactory.CreateView<TVM>(const APlatform: string; const AViewName: String; const AOwner: TComponent; AViewModel: TVM): IView<TVM>;
var
LViewClass: TRttiInstanceType;
LViewComp: TComponent;
[weak]
LView: IView<TVM>;
[weak]
LViewForm: IViewForm<TVM>;
LName: string;
LParams: array of TValue;
LViewModel: TVM;
LIsForm : Boolean;
begin
//Utils.IdeDebugMsg('<TViewFactory.CreateView<TVM>> ' + AViewName);
LIsForm := False;
LName := APlatform + '.' + AViewName;
try
LViewClass := nil;
if Assigned(FRegisteredViews) then
FRegisteredViews.TryGetValue(LName, LViewClass);
if (LViewClass = nil) then
raise EListError.CreateFmt('Cannot create view. View "%s" is not registered.', [LName]);
SetLength(LParams, 1);
LParams[0] := AOwner;
LViewComp := RttiUtils.CreateComponent_From_RttiInstance(LViewClass, LParams);
if Supports(LViewComp, IViewForm<TVM>, LViewForm) then
begin
LIsForm := True;
Result := TFormViewProxy<TVM>.Create(LViewForm);
end
else
begin
LView := LViewComp as IView<TVM>;
Result := TViewProxy<TVM>.Create(LView);
end;
LViewModel := AViewModel;
if LViewModel = nil then
LViewModel := MVVMCore.IoC.ViewModelProvider<TVM>;
if AOwner <> nil then
begin
AOwner.InsertComponent(Result as TComponent);
MVVMCore.PlatformServices.AssignParent(Result as TComponent, AOwner);
end
else begin
if not LIsform then
begin
MVVMCore.PlatformServices.CreatePlatformEmptyForm
end;
end;
Result.InitView(LViewModel);
except
AViewModel := nil;
raise;
end;
end;
{ TFormViewProxy<TVM> }
constructor TFormViewProxy<TVM>.Create(AActualView: IViewForm<TVM>);
begin
Assert(Assigned(AActualView));
inherited Create;
{ Executing a view may free it (for example, when the view is a form and its
CloseAction is set to caFree). When that happens, the IView interface
will contain an invalid reference, and you may get an access violation when
it goes out of scope. To avoid this, we use a view proxy. This proxy
subscribes to a free notification of the view, so it can set the IView
interface to nil BEFORE the view is destroyed. }
FViewFreeListener := TViewFreeListener.Create(AActualView);
end;
destructor TFormViewProxy<TVM>.Destroy;
begin
FViewFreeListener.Free;
inherited;
end;
procedure TFormViewProxy<TVM>.Execute;
begin
FViewFreeListener.ActualView.Execute;
end;
procedure TFormViewProxy<TVM>.ExecuteModal(const AResultProc: TProc<TModalResult>);
var
[weak]
LViewForm: IViewForm<TVM>;
begin
if Assigned(FViewFreeListener.ActualView) then
begin
if Supports(FViewFreeListener.ActualView, IViewForm<TVM>, LViewForm) then
LViewForm.ExecuteModal(AResultProc);
end;
end;
function TFormViewProxy<TVM>.GetAsObject: TObject;
begin
if Assigned(FViewFreeListener.ActualView) then
Result := FViewFreeListener.ActualView.GetAsObject
else
Result := nil;
end;
function TFormViewProxy<TVM>.GetViewModel: TVM;
begin
if Assigned(FViewFreeListener.ActualView) then
Result := FViewFreeListener.ActualView.ViewModel
else
Result := nil;
end;
procedure TFormViewProxy<TVM>.InitView(AViewModel: TVM);
begin
if Assigned(FViewFreeListener.ActualView) then
FViewFreeListener.ActualView.InitView(AViewModel);
end;
procedure TFormViewProxy<TVM>.SetupView;
begin
if Assigned(FViewFreeListener.ActualView) then
FViewFreeListener.ActualView.SetupView;
end;
{ TFormViewProxy<TVM>.TViewFreeListener }
constructor TFormViewProxy<TVM>.TViewFreeListener.Create(AView: IViewForm<TVM>);
var
Instance: TObject;
begin
inherited Create(nil);
FActualView := AView;
Instance := TObject(AView);
if (Instance is TComponent) then
begin
FActualViewObject := TComponent(Instance);
FActualViewObject.FreeNotification(Self);
end;
end;
destructor TFormViewProxy<TVM>.TViewFreeListener.Destroy;
begin
if (FActualViewObject <> nil) then
FActualViewObject.RemoveFreeNotification(Self);
inherited;
end;
procedure TFormViewProxy<TVM>.TViewFreeListener.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (AComponent = FActualViewObject) and (Operation = opRemove) then
begin
FActualView := nil;
FActualViewObject := nil;
end;
end;
class destructor TViewFactory.Destroy;
begin
FRegisteredViews := nil;
end;
class procedure TViewFactory.Register(const AViewClass: TRttiInstanceType; const AViewName: String; const APlatform: String);
var
LAlias: string;
begin
if (not Supports(AViewClass.MetaclassType, IView)) then
raise EInvalidOperation.CreateFmt('View class %s must implement the IView interface', [AViewClass.MetaclassType.QualifiedClassName]);
if not AViewClass.MetaclassType.InheritsFrom(TComponent) then
raise EInvalidOperation.CreateFmt('View class %s must inherit from TComponent', [AViewClass.MetaclassType.QualifiedClassName]);
if AViewName.IsEmpty then
raise EInvalidOperation.CreateFmt('View class %s must have a ViewName not empty', [AViewClass.MetaclassType.QualifiedClassName]);
if (FRegisteredViews = nil) then
FRegisteredViews := TCollections.CreateDictionary<String, TRttiInstanceType>;
LAlias := Utils.iif<String>(APlatform.IsEmpty, AViewName, APlatform + '.' + AViewName);
FRegisteredViews.AddOrSetValue(LAlias, AViewClass);
end;
{ TDummyFormViewProxy<TVM>.TViewFreeListener }
constructor TDummyFormViewProxy<TVM>.TViewFreeListener.Create(AView: IView<TVM>);
var
Instance: TObject;
begin
inherited Create(nil);
FActualView := AView;
Instance := TObject(AView);
if (Instance is TComponent) then
begin
FActualViewObject := TComponent(Instance);
FActualViewObject.FreeNotification(Self);
end;
end;
destructor TDummyFormViewProxy<TVM>.TViewFreeListener.Destroy;
begin
if (FActualViewObject <> nil) then
FActualViewObject.RemoveFreeNotification(Self);
inherited;
end;
procedure TDummyFormViewProxy<TVM>.TViewFreeListener.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (AComponent = FActualViewObject) and (Operation = opRemove) then
begin
FActualView := nil;
FActualViewObject := nil;
end;
end;
{ TDummyFormViewProxy<TVM> }
constructor TDummyFormViewProxy<TVM>.Create(AActualView: IView<TVM>);
begin
Assert(Assigned(AActualView));
inherited Create;
{ Executing a view may free it (for example, when the view is a form and its
CloseAction is set to caFree). When that happens, the IView interface
will contain an invalid reference, and you may get an access violation when
it goes out of scope. To avoid this, we use a view proxy. This proxy
subscribes to a free notification of the view, so it can set the IView
interface to nil BEFORE the view is destroyed. }
FViewFreeListener := TViewFreeListener.Create(AActualView);
end;
destructor TDummyFormViewProxy<TVM>.Destroy;
begin
FViewFreeListener.Free;
inherited;
end;
procedure TDummyFormViewProxy<TVM>.Execute;
begin
MVVMCore.PlatformServices.ShowFormView(FViewFreeListener.ActualView as TComponent);
end;
procedure TDummyFormViewProxy<TVM>.ExecuteModal(const AResultProc: TProc<TModalResult>);
var
[weak]
LViewForm: IViewForm<TVM>;
begin
if Assigned(FViewFreeListener.ActualView) then
begin
if Supports(FViewFreeListener.ActualView, IViewForm<TVM>, LViewForm) then
LViewForm.ExecuteModal(AResultProc);
end;
end;
function TDummyFormViewProxy<TVM>.GetAsObject: TObject;
begin
if Assigned(FViewFreeListener.ActualView) then
Result := FViewFreeListener.ActualView.GetAsObject
else
Result := nil;
end;
function TDummyFormViewProxy<TVM>.GetViewModel: TVM;
begin
if Assigned(FViewFreeListener.ActualView) then
Result := FViewFreeListener.ActualView.ViewModel
else
Result := nil;
end;
procedure TDummyFormViewProxy<TVM>.InitView(AViewModel: TVM);
begin
if Assigned(FViewFreeListener.ActualView) then
FViewFreeListener.ActualView.InitView(AViewModel);
end;
procedure TDummyFormViewProxy<TVM>.SetupView;
begin
if Assigned(FViewFreeListener.ActualView) then
FViewFreeListener.ActualView.SetupView;
end;
end.
|
{----------------------------------------------------------------
Nome: SrvAnalisesUtils
Descrição: Biblioteca para analisar menssagens vindas do
servidor. Esta biblioteca faz complementação a IRCUtils.
----------------------------------------------------------------}
unit SrvAnalisesUtils;
interface
uses
SysUtils, Classes, StrUtils;
type {Tipos de menssagens do servidor}
TIRCSrvMsg = (ismSimples, ismDesconhecido, ismIndefinido,
ism001, ism002, ism003, ism004,
ism005, ism250, ism251, ism252,
ism254, ism255, ism265, ism266,
ism372, ism375, ism376, ism332,
ism333, ism353, ism366);
{Os tipos [ismDesconhecido, ismIndefinido] são tipos para rastreamento de
de erros e bugs na biblioteca}
{Função principal da unit, analisa a menssagem do servidor e retorna seu
tipo e dados(Organizadamente)}
function AnalisarMsgSrv(Menssagem: string; Dados: string; var Saida: TStringList): TIRCSrvMsg;
implementation
function AnalisarMsgSrv;
var
iID: integer;
Nick, Texto,
Canal, Nicks: string;
Lista: TStrings;
begin
{Define variáveis básicas}
Chomp(Dados); {Retira quebra de linha}
result:=ismIndefinido;
Saida:=TStringList.Create;
iID:=0;
{Verifica se a menssagem é um número identificador}
if (ChecarDigito(Menssagem)) then
iID:=StrToInt(Menssagem);
{Separa os Dados entre Nick e Texto}
Nick:=PegarStr(Dados, 1, Pos(' ', Dados) - 1); {Nick do cliente}
Texto:=Estilete(Dados, Pos(' ', Dados) + 1, deDireita); {Texto recebido}
{Checa qual foi a menssgaem que o servidor enviou, avaliando o identificador}
case iID of
{Menssagens que não são interpretadas}
001,002,003,004,005,250,251,252,
254,255,265,266,372,375,376:
begin
if (Texto[1] = ':') then
Delete(Texto, 1, 1); {Deleta ":", se tiver}
Saida.Add(Texto);
result:=ismSimples;
end;
{__Abaixo todas as menssagens são interpretadas__}
353:
begin {Listagem dos usuários de um canal}
{Nome do canal}
Canal:=PegarStr(Texto, Pos('=', Texto) + 2, Pos(':', Texto) - 2);
Nicks:=Estilete(Texto, Pos(':', Texto) + 1, deDireita);
Saida.Add(Canal);
Lista:=SpArToTStrLst(Split(Nicks, ' '));
{Listagem dos Nicks do canal}
Saida.AddStrings(Lista);
result:=ism353;
end;
end;
end;
end.
|
Vie_algoentre10et20_LV_v1_20/11/17
Algotrithme:Nombre_entre_10_et_20
//But:Demander à un utilisateur un nombre entre 10 et 20 et lui indiquer si jamais le nombre saisie est trop grand ou trop petit
//Principe:On demande à l'utilisateur de saisir un nombre entre 10 et 20 , on test si le nombre est plus grand ou plus petit et on lui indique s'il n'est pas correct
//Entrée:1 nombre entre 10 et 20
//Sortie:L'information sur le nombre plus grand ou plus petit ou dans l'intervalle
VAR
NbS:ENTIER
DEBUT
Répeter
ECRIRE"Saisissez votre nombre"
LIRE NbS
SI NbS < 10 ALORS
ECRIRE "Votre nombre est pas compris entre 10 et 20 , il est trop petit "
FINSI
SI NbS > 20 ALORS
ECRIRE "Votre nombre est pas compris entre 10 et 20 , il est trop grand "
FINSI
Jusqu'à NbS<=20 et NbS >= 10
ECRIRE "Votre nombre est compris entre 10 et 20"
FIN |
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFZipReader;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefZipReaderRef = class(TCefBaseRefCountedRef, ICefZipReader)
protected
function MoveToFirstFile: Boolean;
function MoveToNextFile: Boolean;
function MoveToFile(const fileName: ustring; caseSensitive: Boolean): Boolean;
function Close: Boolean;
function GetFileName: ustring;
function GetFileSize: Int64;
function GetFileLastModified: TCefTime;
function OpenFile(const password: ustring): Boolean;
function CloseFile: Boolean;
function ReadFile(buffer: Pointer; bufferSize: NativeUInt): Integer;
function Tell: Int64;
function Eof: Boolean;
public
class function UnWrap(data: Pointer): ICefZipReader;
class function New(const stream: ICefStreamReader): ICefZipReader;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions;
function TCefZipReaderRef.Close: Boolean;
begin
Result := PCefZipReader(FData).close(FData) <> 0;
end;
function TCefZipReaderRef.CloseFile: Boolean;
begin
Result := PCefZipReader(FData).close_file(FData) <> 0;
end;
class function TCefZipReaderRef.New(const stream: ICefStreamReader): ICefZipReader;
begin
Result := UnWrap(cef_zip_reader_create(CefGetData(stream)));
end;
function TCefZipReaderRef.Eof: Boolean;
begin
Result := PCefZipReader(FData).eof(FData) <> 0;
end;
function TCefZipReaderRef.GetFileLastModified: TCefTime;
begin
Result := PCefZipReader(FData).get_file_last_modified(FData);
end;
function TCefZipReaderRef.GetFileName: ustring;
begin
Result := CefStringFreeAndGet(PCefZipReader(FData).get_file_name(FData));
end;
function TCefZipReaderRef.GetFileSize: Int64;
begin
Result := PCefZipReader(FData).get_file_size(FData);
end;
function TCefZipReaderRef.MoveToFile(const fileName: ustring;
caseSensitive: Boolean): Boolean;
var
f: TCefString;
begin
f := CefString(fileName);
Result := PCefZipReader(FData).move_to_file(FData, @f, Ord(caseSensitive)) <> 0;
end;
function TCefZipReaderRef.MoveToFirstFile: Boolean;
begin
Result := PCefZipReader(FData).move_to_first_file(FData) <> 0;
end;
function TCefZipReaderRef.MoveToNextFile: Boolean;
begin
Result := PCefZipReader(FData).move_to_next_file(FData) <> 0;
end;
function TCefZipReaderRef.OpenFile(const password: ustring): Boolean;
var
p: TCefString;
begin
p := CefString(password);
Result := PCefZipReader(FData).open_file(FData, @p) <> 0;
end;
function TCefZipReaderRef.ReadFile(buffer: Pointer;
bufferSize: NativeUInt): Integer;
begin
Result := PCefZipReader(FData).read_file(FData, buffer, buffersize);
end;
function TCefZipReaderRef.Tell: Int64;
begin
Result := PCefZipReader(FData).tell(FData);
end;
class function TCefZipReaderRef.UnWrap(data: Pointer): ICefZipReader;
begin
if data <> nil then
Result := Create(data) as ICefZipReader else
Result := nil;
end;
end.
|
{..............................................................................}
{ Summary Demonstrate the use of several Schematic Object Interfaces }
{ to fetch details of schematic components on a current schematic. }
{ }
{ Key Schematic Object Interfaces; }
{ ISch_Implementation }
{ ISch_Component }
{ ISch_Iterator }
{ }
{ Copyright (c) 2007 by Altium Limited }
{..............................................................................}
{..............................................................................}
Function BooleanToStr (AValue : Boolean) : TString;
Begin
Result := '';
If AValue = True Then Result := 'True'
Else Result := 'False';
End;
{..............................................................................}
{..............................................................................}
Function RotationToStr (AValue : TRotationBy90) : TString;
Begin
Result := '';
Case AValue Of
eRotate0 : Result := '0 Deg' ;
eRotate90 : Result := '90 Deg' ;
eRotate180 : Result := '180 Deg';
eRotate270 : Result := '270 Deg';
End;
End;
{..............................................................................}
{..............................................................................}
Procedure GetComponentInformation;
Var
CurrentSheet : ISch_Document;
Iterator : ISch_Iterator;
Component : ISch_Component;
ImplIterator : ISch_Iterator;
SchImplementation : ISch_Implementation;
S : TDynamicString;
ReportDocument : IServerDocument;
FootprintString : TDynamicString;
ComponentsList : TStringList;
Begin
If SchServer = Nil Then
Begin
ShowError('Please run the script on a schematic document.');
Exit;
End;
CurrentSheet := SchServer.GetCurrentSchDocument;
If (CurrentSheet = Nil) or (CurrentSheet.ObjectID = eSchLib) Then
Begin
ShowError('Please run the script on a schematic document.');
Exit;
End;
Iterator := CurrentSheet.SchIterator_Create;
Iterator.AddFilter_ObjectSet(MkSet(eSchComponent));
Componentslist := TStringList.Create;
Try
Component := Iterator.FirstSchObject;
While Component <> Nil Do
Begin
FootprintString := '';
ImplIterator := Component.SchIterator_Create;
ImplIterator.AddFilter_ObjectSet(MkSet(eImplementation));
SchImplementation := ImplIterator.FirstSchObject;
While SchImplementation <> Nil Do
Begin
If StringsEqual(SchImplementation.ModelType, 'PCBLIB') And SchImplementation.IsCurrent Then
FootprintString := SchImplementation.ModelName;
SchImplementation := ImplIterator.NextSchObject;
End;
Component.SchIterator_Destroy(ImplIterator);
Componentslist.Add(
'Designator: ' + Component.Designator.Text + ', ' +
'Footprint: ' + FootprintString + ', ' +
'Comment:' + Component.Comment.Text + ', ' +
'UniqueID: ' + Component.UniqueId + ', ' +
'Orientation: ' + RotationToStr(Component.Orientation) + ', ' +
'IsMirrored: ' + BooleanToStr(Component.IsMirrored) + ', ' +
'AreaColor: ' + IntToStr(Component.AreaColor) + ', ' +
'PinColor: ' + IntToStr(Component.PinColor) + ', ' +
'ShowHiddenFields: ' + BooleanToStr(Component.ShowHiddenFIelds) + ', ' +
'LibraryPath: ' + Component.LibraryPath + ', ' +
'Description: ' + Component.ComponentDescription);
Component := Iterator.NextSchObject;
Componentslist.Add('');
End;
Finally
CurrentSheet.SchIterator_Destroy (Iterator);
End;
ComponentsList.Add('Report created on '+ DateToStr(Date) + ' ' + TimeToStr(Time));
ComponentsList.Insert(0,'Schematic Components Report...');
ComponentsList.Insert(1,'==============================');
ComponentsList.Insert(2,'');
ComponentsList.Insert(3,'');
S := 'C:\Report.Txt';
ComponentsList.SaveToFile(S);
ComponentsList.Free;
// Display report in Altium Designer with a list of components and their PCB Footprints.
ReportDocument := Client.OpenDocument('Text', S);
If ReportDocument <> Nil Then
Client.ShowDocument(ReportDocument);
End;
{..............................................................................}
{..............................................................................}
End.
|
unit form_splash;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, form_main, Vcl.StdCtrls;
type
Tfrm_splash = class(TForm)
FTimer: TTimer;
FImage: TImage;
FPanel: TPanel;
FLabel: TLabel;
procedure FTimerTimer(Sender: TObject);
private
FForm: TForm;
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
public
procedure DoSetTitle(const ACaption: string);
end;
var
frm_splash: Tfrm_splash;
implementation
{$R *.dfm}
procedure Tfrm_splash.FormDestroy(Sender: TObject);
begin
FForm := nil;
TThread.Queue(nil,
procedure
begin
DoSetTitle('Завершение');
Close;
end);
end;
procedure Tfrm_splash.FormShow(Sender: TObject);
begin
TThread.Queue(nil,
procedure
begin
DoSetTitle('');
Hide;
end);
end;
procedure Tfrm_splash.DoSetTitle(const ACaption: string);
begin
Caption := Application.Title + ' - ' + ACaption;
FLabel.Caption := ACaption;
Application.ProcessMessages;
end;
procedure Tfrm_splash.FTimerTimer(Sender: TObject);
begin
FTimer.Enabled := false;
if not Assigned(FForm) then
begin
DoSetTitle('Запуск');
FForm := Tfrm_main.Create(Self);
InsertComponent(FForm);
FForm.OnDestroy := FormDestroy;
FForm.OnShow := FormShow;
FForm.Show;
end;
end;
end.
|
{:
GLSL Diffuse Specular Shader Demo<p>
A demo that shows how to use the TGLSLDiffuseSpecularShader component.
Version history:
24/07/09 - DaStr - Added fog support
02/07/07 - DaStr - Removed old Timer leftovers
(GLSimpleNavigation component now does this stuff)
20/03/07 - DaStr - Initial version
}
unit umainform;
interface
uses
// VCL
SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,
// GLScene
GLTexture, GLCadencer, GLViewer, GLScene, GLObjects, GLGraph,
VectorTypes, GLUserShader, GLUtils, GLContext, VectorGeometry, GLGeomObjects,
GLVectorFileObjects, GLSLDiffuseSpecularShader, GLSLShader, GLCustomShader,
GLSimpleNavigation, GLCrossPlatform, GLMaterial, GLCoordinates, BaseClasses,
// FileFormats
GLFileMD2, GLFileMS3D, GLFile3DS;
type
TGLSLTestForm = class(TForm)
Scene: TGLScene;
Viewer: TGLSceneViewer;
Cadencer: TGLCadencer;
Camera: TGLCamera;
Light: TGLLightSource;
LightCube: TGLDummyCube;
GLSphere1: TGLSphere;
GLXYZGrid1: TGLXYZGrid;
GLArrowLine1: TGLArrowLine;
Panel1: TPanel;
LightMovingCheckBox: TCheckBox;
GUICube: TGLDummyCube;
WorldCube: TGLDummyCube;
Fighter: TGLActor;
Teapot: TGLActor;
Sphere_big: TGLActor;
Sphere_little: TGLActor;
MaterialLibrary: TGLMaterialLibrary;
ShaderEnabledCheckBox: TCheckBox;
TurnPitchrollCheckBox: TCheckBox;
RealisticSpecularCheckBox: TCheckBox;
LightCube2: TGLDummyCube;
Light2: TGLLightSource;
GLSphere2: TGLSphere;
MultiLightShaderCheckBox: TCheckBox;
DiffuseSpecularShader: TGLSLDiffuseSpecularShader;
GLSimpleNavigation1: TGLSimpleNavigation;
EnableFogCheckBox: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure CadencerProgress(Sender: TObject; const deltaTime, newTime: double);
procedure LightCubeProgress(Sender: TObject; const deltaTime,
newTime: Double);
procedure ShaderEnabledCheckBoxClick(Sender: TObject);
procedure RealisticSpecularCheckBoxClick(Sender: TObject);
procedure MultiLightShaderCheckBoxClick(Sender: TObject);
procedure EnableFogCheckBoxClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
GLSLTestForm: TGLSLTestForm;
MultiLightShader: TGLSLMLDiffuseSpecularShader;
implementation
{$R *.lfm}
uses
FileUtil;
procedure TGLSLTestForm.FormCreate(Sender: TObject);
var
path: UTF8String;
p: Integer;
I: Integer;
begin
path := ExtractFilePath(ParamStrUTF8(0));
p := Pos('DemosLCL', path);
Delete(path, p+5, Length(path));
path := IncludeTrailingPathDelimiter(path) + 'media';
SetCurrentDirUTF8(path);
// First load models.
Fighter.LoadFromFile('waste.md2'); //Fighter
Fighter.SwitchToAnimation(0, True);
Fighter.AnimationMode := aamLoop;
Fighter.Scale.Scale(3);
Teapot.LoadFromFile('teapot.3ds'); //Teapot (no texture coordinates)
Teapot.Scale.Scale(0.8);
Sphere_big.LoadFromFile('Sphere_big.3ds'); //Sphere_big
Sphere_big.Scale.Scale(70);
Sphere_little.LoadFromFile('Sphere_little.3ds'); //Sphere_little
Sphere_little.Scale.Scale(4);
MaterialLibrary.LibMaterialByName('Earth').Material.Texture.Image.LoadFromFile('Earth.jpg');
MaterialLibrary.LibMaterialByName('Fighter').Material.Texture.Image.LoadFromFile('waste.jpg');
MaterialLibrary.LibMaterialByName('Earth').Shader := DiffuseSpecularShader;
MaterialLibrary.LibMaterialByName('Fighter').Shader := DiffuseSpecularShader;
// This is how a shader is created in runtime.
MultiLightShader := TGLSLMLDiffuseSpecularShader.Create(Self);
MultiLightShader.LightCompensation := 0.7;
MultiLightShader.LightCount := 2;
// Disable fog.
EnableFogCheckBoxClick(nil);
end;
procedure TGLSLTestForm.CadencerProgress(Sender: TObject; const deltaTime, newTime: double);
begin
Viewer.Invalidate;
if TurnPitchrollCheckBox.Checked then
begin
Sphere_big.Pitch(40 * deltaTime);
Fighter.Turn(40 * deltaTime);
Sphere_little.Roll(40 * deltaTime);
Teapot.Roll(-20 * deltaTime);
end;
end;
procedure TGLSLTestForm.LightCubeProgress(Sender: TObject; const deltaTime,
newTime: Double);
begin
if LightMovingCheckBox.Checked then
LightCube.MoveObjectAround(Camera.TargetObject, sin(NewTime) * deltaTime * 10, deltaTime * 20);
end;
procedure TGLSLTestForm.ShaderEnabledCheckBoxClick(Sender: TObject);
begin
DiffuseSpecularShader.Enabled := ShaderEnabledCheckBox.Checked;
MultiLightShader.Enabled := ShaderEnabledCheckBox.Checked;
end;
procedure TGLSLTestForm.RealisticSpecularCheckBoxClick(Sender: TObject);
begin
DiffuseSpecularShader.RealisticSpecular := RealisticSpecularCheckBox.Checked;
MultiLightShader.RealisticSpecular := RealisticSpecularCheckBox.Checked;
if DiffuseSpecularShader.RealisticSpecular then
begin
DiffuseSpecularShader.SpecularPower := 20;
MultiLightShader.SpecularPower := 20;
end
else
begin
DiffuseSpecularShader.SpecularPower := 8;
MultiLightShader.SpecularPower := 8;
end;
end;
procedure TGLSLTestForm.MultiLightShaderCheckBoxClick(Sender: TObject);
begin
if MultiLightShaderCheckBox.Checked then
begin
MaterialLibrary.LibMaterialByName('Earth').Shader := MultiLightShader;
MaterialLibrary.LibMaterialByName('Fighter').Shader := MultiLightShader;
end
else
begin
MaterialLibrary.LibMaterialByName('Earth').Shader := DiffuseSpecularShader;
MaterialLibrary.LibMaterialByName('Fighter').Shader := DiffuseSpecularShader;
end;
Light2.Shining := MultiLightShaderCheckBox.Checked;
LightCube2.Visible := MultiLightShaderCheckBox.Checked;
end;
procedure TGLSLTestForm.EnableFogCheckBoxClick(Sender: TObject);
begin
if EnableFogCheckBox.Checked then
begin
Viewer.Buffer.FogEnable := True;
DiffuseSpecularShader.NotifyChange(Self);
MultiLightShader.NotifyChange(Self);
end
else
begin
Viewer.Buffer.FogEnable := False;
DiffuseSpecularShader.NotifyChange(Self);
MultiLightShader.NotifyChange(Self);
end;
end;
end.
|
unit ibSHDDLFinder;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHTool;
type
IibServerSideSearch= interface
['{E16DE9AB-BE3C-4294-8714-988F1F210476}']
// interface is visible in package Only
function FindOnServerSide(const AClassIID: TGUID; var OutPutList:TStrings):boolean;
procedure SetNeedUTFEncode(Value:boolean);
end;
TibBTLookIn = class;
TibSHDDLFinder = class(TibBTTool, IibSHDDLFinder,IibServerSideSearch, IibSHBranch, IfbSHBranch)
private
FDDLGenerator: TComponent;
FDDLGeneratorIntf: IibSHDDLGenerator;
FLastSource: string;
FActive: Boolean;
FFindString: string;
FCaseSensitive: Boolean;
FWholeWordsOnly: Boolean;
FRegularExpression: Boolean;
FLookIn: TibBTLookIn;
FFindObjects:TStrings;
FNeedUTFEncode:boolean;
function GetActive: Boolean;
procedure SetActive(Value: Boolean);
function GetFindString: string;
procedure SetFindString(Value: string);
function GetCaseSensitive: Boolean;
procedure SetCaseSensitive(Value: Boolean);
function GetWholeWordsOnly: Boolean;
procedure SetWholeWordsOnly(Value: Boolean);
function GetRegularExpression: Boolean;
procedure SetRegularExpression(Value: Boolean);
function GetLookIn: IibSHLookIn;
function Find(const ASource: string): Boolean;
function FindIn(const AClassIID: TGUID; const ACaption: string): Boolean;
function FindOnServerSide(const AClassIID: TGUID; var OutPutList:TStrings):boolean;
procedure SetNeedUTFEncode(Value:boolean);
function LastSource: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property DDLGenerator: IibSHDDLGenerator read FDDLGeneratorIntf;
property Active: Boolean read GetActive write SetActive;
property FindString: string read GetFindString write SetFindString;
published
property CaseSensitive: Boolean read GetCaseSensitive write SetCaseSensitive;
property WholeWordsOnly: Boolean read GetWholeWordsOnly write SetWholeWordsOnly;
property RegularExpression: Boolean read GetRegularExpression write SetRegularExpression;
property LookIn: TibBTLookIn read FLookIn;
end;
TibSHDDLFinderFactory = class(TibBTToolFactory)
end;
TibBTLookIn = class(TSHInterfacedPersistent, IibSHLookIn)
private
FDomains: Boolean;
FTables: Boolean;
FConstraints: Boolean;
FIndices: Boolean;
FViews: Boolean;
FProcedures: Boolean;
FTriggers: Boolean;
FGenerators: Boolean;
FExceptions: Boolean;
FFunctions: Boolean;
FFilters: Boolean;
FRoles: Boolean;
function GetDomains: Boolean;
procedure SetDomains(Value: Boolean);
function GetTables: Boolean;
procedure SetTables(Value: Boolean);
function GetConstraints: Boolean;
procedure SetConstraints(Value: Boolean);
function GetIndices: Boolean;
procedure SetIndices(Value: Boolean);
function GetViews: Boolean;
procedure SetViews(Value: Boolean);
function GetProcedures: Boolean;
procedure SetProcedures(Value: Boolean);
function GetTriggers: Boolean;
procedure SetTriggers(Value: Boolean);
function GetGenerators: Boolean;
procedure SetGenerators(Value: Boolean);
function GetExceptions: Boolean;
procedure SetExceptions(Value: Boolean);
function GetFunctions: Boolean;
procedure SetFunctions(Value: Boolean);
function GetFilters: Boolean;
procedure SetFilters(Value: Boolean);
function GetRoles: Boolean;
procedure SetRoles(Value: Boolean);
published
property Domains: Boolean read GetDomains write SetDomains;
property Tables: Boolean read GetTables write SetTables;
// property Constraints: Boolean read GetConstraints write SetConstraints;
property Indices: Boolean read GetIndices write SetIndices;
property Views: Boolean read GetViews write SetViews;
property Procedures: Boolean read GetProcedures write SetProcedures;
property Triggers: Boolean read GetTriggers write SetTriggers;
property Generators: Boolean read GetGenerators write SetGenerators;
property Exceptions: Boolean read GetExceptions write SetExceptions;
property Functions: Boolean read GetFunctions write SetFunctions;
property Filters: Boolean read GetFilters write SetFilters;
property Roles: Boolean read GetRoles write SetRoles;
end;
procedure Register;
implementation
uses
ibSHConsts, ibSHStrUtil,
ibSHDDLFinderActions,
ibSHDDLFinderEditors;
procedure Register;
begin
SHRegisterImage(GUIDToString(IibSHDDLFinder), 'DDLFinder.bmp');
SHRegisterImage(TibSHDDLFinderPaletteAction.ClassName, 'DDLFinder.bmp');
SHRegisterImage(TibSHDDLFinderFormAction.ClassName, 'Form_Search_Results.bmp');
SHRegisterImage(TibSHDDLFinderToolbarAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibSHDDLFinderToolbarAction_Pause.ClassName, 'Button_Stop.bmp');
SHRegisterImage(TibSHDDLFinderToolbarAction_NextResult.ClassName, 'Button_Arrow_Down.bmp');
SHRegisterImage(TibSHDDLFinderToolbarAction_PrevResult.ClassName, 'Button_Arrow_Top.bmp');
SHRegisterImage(SCallSearchResults, 'Form_Search_Results.bmp');
SHRegisterComponents([
TibSHDDLFinder,
TibSHDDLFinderFactory]);
SHRegisterActions([
// Palette
TibSHDDLFinderPaletteAction,
// Forms
TibSHDDLFinderFormAction,
// Toolbar
TibSHDDLFinderToolbarAction_Run,
TibSHDDLFinderToolbarAction_Pause,
TibSHDDLFinderToolbarAction_NextResult,
TibSHDDLFinderToolbarAction_PrevResult]);
SHRegisterPropertyEditor(IibSHDDLFinder, 'LookIn', TibBTLookInPropEditor);
end;
{ TibSHDDLFinder }
constructor TibSHDDLFinder.Create(AOwner: TComponent);
var
vComponentClass: TSHComponentClass;
begin
inherited Create(AOwner);
FFindObjects:=TStringList.Create;
FLookIn := TibBTLookIn.Create;
FLookIn.Views := True;
FLookIn.Procedures := True;
FLookIn.Triggers := True;
vComponentClass := Designer.GetComponent(IibSHDDLGenerator);
if Assigned(vComponentClass) then
begin
FDDLGenerator := vComponentClass.Create(nil);
Supports(FDDLGenerator, IibSHDDLGenerator, FDDLGeneratorIntf);
end;
end;
destructor TibSHDDLFinder.Destroy;
begin
FFindObjects.Free;
FLookIn.Free;
FDDLGeneratorIntf := nil;
FDDLGenerator.Free;
inherited Destroy;
end;
function TibSHDDLFinder.Find(const ASource: string): Boolean;
var
S1, S2: string;
BegSub, EndSub: TCharSet;
begin
BegSub := ['+', ')', '(', '*', '/', '|', ',', '=', '>', '<', '-', '!', '^', '~', ',', ';', ' ', #13, #10, #9, '"'];
EndSub := ['+', ')', '(', '*', '/', '|', ',', '=', '>', '<', '-', '!', '^', '~', ',', ';', ' ', #13, #10, #9, '"'];
S1 := FindString;
S2 := ASource;
if not CaseSensitive then
begin
S1 := AnsiUpperCase(S1);
S2 := AnsiUpperCase(S2);
end;
if RegularExpression then
begin
Result := Designer.RegExprMatch(S1, S2, CaseSensitive);
Exit;
end;
if WholeWordsOnly then
Result := PosExt(S1, S2, BegSub, EndSub) > 0
else
Result := Pos(S1, S2) > 0;
end;
function TibSHDDLFinder.FindIn(const AClassIID: TGUID; const ACaption: string): Boolean;
var
vComponentClass: TSHComponentClass;
vComponent: TSHComponent;
DBObject: IibSHDBObject;
begin
Result := False;
vComponentClass := Designer.GetComponent(AClassIID);
if Assigned(vComponentClass) then
begin
vComponent := vComponentClass.Create(nil);
try
Supports(vComponent, IibSHDBObject, DBObject);
if Assigned(DBObject) and Assigned(DDLGenerator) then
begin
DBObject.Caption := ACaption;
DBObject.OwnerIID := Self.OwnerIID;
DBObject.State := csSource;
FLastSource := DDLGenerator.GetDDLText(DBObject);
Result := Find(FLastSource);
end;
finally
DBObject := nil;
FreeAndNil(vComponent);
end;
end;
end;
function TibSHDDLFinder.LastSource: string;
begin
Result := FLastSource;
end;
function TibSHDDLFinder.GetActive: Boolean;
begin
Result := FActive;
end;
procedure TibSHDDLFinder.SetActive(Value: Boolean);
begin
FActive := Value;
end;
function TibSHDDLFinder.GetFindString: string;
begin
Result := FFindString;
end;
procedure TibSHDDLFinder.SetFindString(Value: string);
begin
FFindString := Value;
end;
function TibSHDDLFinder.GetCaseSensitive: Boolean;
begin
Result := FCaseSensitive;
end;
procedure TibSHDDLFinder.SetCaseSensitive(Value: Boolean);
begin
FCaseSensitive := Value;
end;
function TibSHDDLFinder.GetWholeWordsOnly: Boolean;
begin
Result := FWholeWordsOnly;
end;
procedure TibSHDDLFinder.SetWholeWordsOnly(Value: Boolean);
begin
FWholeWordsOnly := Value;
end;
function TibSHDDLFinder.GetRegularExpression: Boolean;
begin
Result := FRegularExpression;
end;
procedure TibSHDDLFinder.SetRegularExpression(Value: Boolean);
begin
FRegularExpression := Value;
end;
function TibSHDDLFinder.GetLookIn: IibSHLookIn;
begin
Supports(LookIn, IibSHLookIn, Result);
end;
function TibSHDDLFinder.FindOnServerSide(const AClassIID: TGUID; var OutPutList:TStrings):boolean;
const
cSearchSQL:array[0..7] of string =('SELECT PR.rdb$procedure_name '+
'FROM RDB$PROCEDURES PR '+
'WHERE cast(PR.RDB$PROCEDURE_SOURCE as '+
' blob sub_type text character set NONE) containing :s '+
'or PR.rdb$procedure_name containing :s '+
'UNION '+
'SELECT PAR.rdb$procedure_name '+
'FROM RDB$PROCEDURE_PARAMETERS PAR '+
'WHERE RDB$PARAMETER_NAME containing :s '+
'ORDER BY 1',
' Select distinct r.rdb$relation_name'#$D#$A+
'from rdb$relations R'#$D#$A+
'join rdb$relation_fields f on f.rdb$relation_name=r.rdb$relation_name'#$D#$A+
'Where R.RDB$SYSTEM_FLAG=0 and '#$D#$A+'not r.rdb$view_blr is null and '#$D#$A+
'((cast(r.rdb$view_source as blob sub_type text character set NONE)containing :s) or'#$D#$A+
'(r.rdb$relation_name containing :s)'#$D#$A+
'or f.rdb$field_name containing :S)'#$D#$A+
'order by 1',
'Select t.rdb$trigger_name '#13#10+
'from rdb$triggers t'#13#10+
'where RDB$SYSTEM_FLAG=0 and '#13#10+
'cast(t.rdb$trigger_source as blob sub_type text character set NONE) containing :s'#13#10+
'or t.rdb$trigger_name containing :s' ,
'Select distinct r.rdb$relation_name '#13#10+
'from rdb$relations R '#13#10+
'join rdb$relation_fields f on f.rdb$relation_name=r.rdb$relation_name'#13#10+
'Where R.RDB$SYSTEM_FLAG=0 and r.rdb$view_source is null and'#13#10+
'((r.rdb$relation_name containing :s)'#13#10+
'or f.rdb$field_name containing :S'#13#10+
'or f.rdb$field_source containing :S)'#$D#$A+
'order by 1',
'SELECT RDB$GENERATOR_NAME FROM RDB$GENERATORS'#13#10+
'WHERE RDB$SYSTEM_FLAG IS NULL'#13#10+
'and RDB$GENERATOR_NAME containing :s' ,
'SELECT RDB$EXCEPTION_NAME'#13#10+
'FROM RDB$EXCEPTIONS'#13#10+
'where RDB$SYSTEM_FLAG IS NOT NULL and'#13#10+
'(RDB$EXCEPTION_NAME containing :s or RDB$MESSAGE containing :s )' ,
'SELECT r.rdb$function_name'#13#10+
'FROM rdb$functions r'#13#10+
'where r.rdb$system_flag is null'#13#10+
'and (r.rdb$function_name containing :s or r.rdb$module_name containing :s'#13#10+
' or r.rdb$entrypoint containing :s )' ,
'Select RDB$FIELD_NAME from RDB$FIELDS '#13#10+
'WHERE (rdb$system_flag is null or rdb$system_flag=0) and '#13#10+
'RDB$FIELD_NAME containing :s'
);
var
i:byte;
SearchStr:string;
begin
Result:=not RegularExpression;
if not Result then
Exit;
OutPutList:=FFindObjects;
FFindObjects.Clear;
if IsEqualGUID(AClassIID,IibSHProcedure) then
begin
i:=0;
Result:=True;
end
else
if IsEqualGUID(AClassIID,IibSHView) then
begin
i:=1;
Result:=True;
end
else
if IsEqualGUID(AClassIID,IibSHTrigger) then
begin
i:=2;
Result:=True;
end
else
if IsEqualGUID(AClassIID,IibSHTable) then
begin
i:=3;
Result:=True;
end
else
if IsEqualGUID(AClassIID, IibSHGenerator) then
begin
i:=4;
Result:=True;
end
else
if IsEqualGUID(AClassIID, IibSHException) then
begin
i:=5;
Result:=True;
end
else
if IsEqualGUID(AClassIID, IibSHFunction) then
begin
i:=6;
Result:=True;
end
else
if IsEqualGUID(AClassIID, IibSHDomain) then
begin
i:=7;
Result:=True;
end
else
begin
Result:=False;
Exit
end;
if Result then
begin
if not BTCLDatabase.DRVQuery.Transaction.InTransaction then
BTCLDatabase.DRVQuery.Transaction.StartTransaction;
if FNeedUTFEncode then
SearchStr:=UTF8Encode(FindString)
else
SearchStr:=FindString;
BTCLDatabase.DRVQuery.ExecSQL(cSearchSQL[i],[SearchStr],False);
while not BTCLDatabase.DRVQuery.Eof do
begin
FFindObjects.Add(Trim(BTCLDatabase.DRVQuery.GetFieldValue(0)));
BTCLDatabase.DRVQuery.Next
end;
BTCLDatabase.DRVQuery.Transaction.Commit
end
end;
procedure TibSHDDLFinder.SetNeedUTFEncode(Value: boolean);
begin
FNeedUTFEncode:=Value
end;
{ TibBTLookIn }
function TibBTLookIn.GetDomains: Boolean;
begin
Result := FDomains;
end;
procedure TibBTLookIn.SetDomains(Value: Boolean);
begin
FDomains := Value;
end;
function TibBTLookIn.GetTables: Boolean;
begin
Result := FTables;
end;
procedure TibBTLookIn.SetTables(Value: Boolean);
begin
FTables := Value;
end;
function TibBTLookIn.GetConstraints: Boolean;
begin
Result := FConstraints;
end;
procedure TibBTLookIn.SetConstraints(Value: Boolean);
begin
FConstraints := Value;
end;
function TibBTLookIn.GetIndices: Boolean;
begin
Result := FIndices;
end;
procedure TibBTLookIn.SetIndices(Value: Boolean);
begin
FIndices := Value;
end;
function TibBTLookIn.GetViews: Boolean;
begin
Result := FViews;
end;
procedure TibBTLookIn.SetViews(Value: Boolean);
begin
FViews := Value;
end;
function TibBTLookIn.GetProcedures: Boolean;
begin
Result := FProcedures;
end;
procedure TibBTLookIn.SetProcedures(Value: Boolean);
begin
FProcedures := Value;
end;
function TibBTLookIn.GetTriggers: Boolean;
begin
Result := FTriggers;
end;
procedure TibBTLookIn.SetTriggers(Value: Boolean);
begin
FTriggers := Value;
end;
function TibBTLookIn.GetGenerators: Boolean;
begin
Result := FGenerators;
end;
procedure TibBTLookIn.SetGenerators(Value: Boolean);
begin
FGenerators := Value;
end;
function TibBTLookIn.GetExceptions: Boolean;
begin
Result := FExceptions;
end;
procedure TibBTLookIn.SetExceptions(Value: Boolean);
begin
FExceptions := Value;
end;
function TibBTLookIn.GetFunctions: Boolean;
begin
Result := FFunctions;
end;
procedure TibBTLookIn.SetFunctions(Value: Boolean);
begin
FFunctions := Value;
end;
function TibBTLookIn.GetFilters: Boolean;
begin
Result := FFilters;
end;
procedure TibBTLookIn.SetFilters(Value: Boolean);
begin
FFilters := Value;
end;
function TibBTLookIn.GetRoles: Boolean;
begin
Result := FRoles;
end;
procedure TibBTLookIn.SetRoles(Value: Boolean);
begin
FRoles := Value;
end;
initialization
Register;
end.
|
unit Main;
interface
uses
SysUtils, Forms, Dialogs, StdCtrls, Controls, Classes, ThreadComponent;
type
TMainForm = class(TForm)
ThreadListBox: TListBox;
CreateThreadsBtn: TButton;
GoBtn: TButton;
QuitBtn: TButton;
InfoLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure QuitBtnClick(Sender: TObject);
procedure CreateThreadsBtnClick(Sender: TObject);
procedure GoBtnClick(Sender: TObject);
procedure TimerThreadExecute(Sender: TObject);
procedure ThrdExecute(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
procedure ListThreads; // Procédure pour lister les threads dans la boîte liste
end;
const
ThreadNames: array [0..6] of ShortString = // Tableau des couleurs de l'arc-en-ciel :)
('Rouge', 'Orange', 'Vert', 'Jaune', 'Bleu', 'Violet', 'Indigo');
Priorities: array [0..6] of TThreadPriority = // Tableau de correspondance ordinale des priorités
(tpIdle, tpLowest, tpLower, tpNormal, tpHigher, tpHighest, tpTimeCritical);
var
MainForm: TMainForm; // Notre fiche
ThreadList: TThreadListEx; // La liste de threads
Results: array [0..6] of Cardinal; // Les résultats à la fin du test
TimeOut: Integer; // Le temps restant avant la fin du test
Thrds: array [0..6] of TThreadComponent; // Les threads utilisés pour le test
TimerThrd: TThreadComponent; // Le thread pour décompter le temps
// Un timer aurait fait l'affaire mais bon après tout ...
implementation
{$R *.dfm}
function PriorityToString(Priority: TThreadPriority): String; // Conversion des priorités en chaîne
begin
case Priority of // Rien de bien compliqué !
tpIdle: Result := 'Idle';
tpLowest: Result := 'Lowest';
tpLower: Result := 'Lower';
tpNormal: Result := 'Normal';
tpHigher: Result := 'Higher';
tpHighest: Result := 'Highest';
tpTimeCritical: Result := 'Time Critical';
end;
end;
procedure TMainForm.FormCreate(Sender: TObject); // Création de la fiche
begin
DoubleBuffered := True; // On évite les scintillements
ThreadListBox.DoubleBuffered := True; // Idem
ThreadList := TThreadListEx.Create; // On crée la liste
TimerThrd := TThreadComponent.Create(nil); // On crée le thread pour décompter le temps
TimerThrd.OnExecute := TimerThreadExecute; // On définit son gestionnaire d'évènement OnExecute
end;
procedure TMainForm.QuitBtnClick(Sender: TObject); // Bouton Quitter
begin
ThreadList.Free; // On libère la liste (et tous les threads dedans bien sûr !)
TimerThrd.Free; // On libère le thread pour décompter le temps
Close; // On ferme la fiche principale donc l'application
end;
procedure TMainForm.ListThreads; // Listage des threads
Var
I: Integer; // Variable de contrôle de boucle
S: String; // Chaîne formatée à afficher dans la liste
begin
ThreadListBox.Items.BeginUpdate; // On commence la mise à jour de la boîte liste
ThreadListBox.Clear; // On vide la liste
for I := 0 to ThreadList.Count - 1 do // Pour chaque thread
begin
// On formate la chaîne
S := Format('%s [%s] - %d', [ThreadNames[I], PriorityToString(ThreadList.Threads[I].Priority), Results[I]]);
ThreadListBox.Items.Add(S); // On ajoute la chaîne formatée
end;
ThreadListBox.Items.EndUpdate; // On a terminé la mise à jour
end;
procedure TMainForm.CreateThreadsBtnClick(Sender: TObject); // Bouton "Créer les 7 threads"
Var
I: Integer; // Variable de contrôle de boucle
begin
CreateThreadsBtn.Enabled := False; // On désactive ce bouton
GoBtn.Enabled := True; // On active le bouton pour lancer le test
for I := 0 to 6 do // Pour chaque thread ...
begin
Thrds[I] := TThreadComponent.Create(nil); // On crée ce thread
Thrds[I].Interval := 1; // On lui donne un interval de 1
Thrds[I].Tag := I; // Pour le reconnaître dans le gestionnaire d'évènements
Thrds[I].Priority := Priorities[I]; // On lui donne la priorité convenable
Thrds[I].OnExecute := ThrdExecute; // On lui donne le gestionnaire d'évènement OnExecute
ThreadList.Add(Thrds[I]); // On l'ajoute dans la liste de threads
end;
ListThreads; // On liste les threads
end;
procedure TMainForm.ThrdExecute(Sender: TObject); // Gestionnaire OnExecute
begin
if Sender is TThread then // Vérifie si on a bien affaire à un thread ...
case TThread(Sender).Priority of // Selon la priorité du thread, on augmente le résultat
tpIdle: Inc(Results[0]);
tpLowest: Inc(Results[1]);
tpLower: Inc(Results[2]);
tpNormal: Inc(Results[3]);
tpHigher: Inc(Results[4]);
tpHighest: Inc(Results[5]);
tpTimeCritical: Inc(Results[6]);
end;
end;
procedure TMainForm.GoBtnClick(Sender: TObject); // Bouton "Go"
Var
I: Integer; // Variable de contrôle de boucle
begin
TimeOut := 10; // 10 secondes de test
for I := 0 to 6 do Results[I] := 0; // On initialise les résultats
ListThreads; // On liste les threads
TimerThrd.Active := True; // On active le thread de temps
for I := 0 to 6 do ThreadList.Threads[I].Active := True; // On active tous les autres threads !
end;
procedure TMainForm.TimerThreadExecute(Sender: TObject); // OnExecute du thread de temps
Var
I: Integer; // Variable de contrôle de boucle
begin
Dec(TimeOut); // On descend de 1 le temps (OnExecute de ce thread toutes les secondes)
GoBtn.Caption := 'Fin du test dans ' + IntToStr(TimeOut) + ' seconds.'; // On affiche le temps restant
if TimeOut = 0 then // Si on est à la fin du test ...
begin
for I := 0 to 6 do ThreadList.Threads[I].Active := False; // On désactive chaque thread
TimerThrd.Active := False; // On désactive le thread de temps
ListThreads; // On liste les threads
// On affiche un petit message !
MessageDlg('Normalement, vous devriez observer une certaine logique quant aux resultats obtenus (les threads avec une priorité'
+ ' inférieure auront moins d''executions que les threads avec une priorité supérieure), avec des écarts néanmoins négligeables dans la plupart des cas.', mtInformation, [mbOK], 0);
GoBtn.Caption := 'Lancer le test de performance de 10 secondes';
// On remet le bouton dans son état normal.
end;
end;
end.
|
unit Design;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
LMDDsgClass, LMDDsgDesigner, LMDDsgManager;
type
TDesignForm = class(TForm)
LMDDesigner1: TLMDDesigner;
LMDDesignManager1: TLMDDesignManager;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FOnSelectionChanged: TNotifyEvent;
FOnChange: TNotifyEvent;
function GetActive: Boolean;
function GetSelectedComponent: TComponent;
procedure SetActive(const Value: Boolean);
procedure SetOnSelectionChanged(const Value: TNotifyEvent);
procedure SetSelectedComponent(const Value: TComponent);
public
{ Public declarations }
procedure LoadFromFile(const inFilename: string);
procedure SaveToFile(const inFilename: string);
property Active: Boolean read GetActive write SetActive;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnSelectionChanged: TNotifyEvent read FOnSelectionChanged
write SetOnSelectionChanged;
property SelectedComponent: TComponent read GetSelectedComponent
write SetSelectedComponent;
end;
var
DesignForm: TDesignForm;
implementation
{$R *.dfm}
procedure TDesignForm.FormCreate(Sender: TObject);
begin
LMDDesigner1.DesignControl := Self;
end;
function TDesignForm.GetActive: Boolean;
begin
Result := LMDDesigner1.Active;
end;
procedure TDesignForm.SetActive(const Value: Boolean);
begin
LMDDesigner1.Active := Value;
end;
function TDesignForm.GetSelectedComponent: TComponent;
begin
Result := nil;
end;
procedure TDesignForm.SetSelectedComponent(const Value: TComponent);
begin
//
end;
procedure TDesignForm.SetOnSelectionChanged(const Value: TNotifyEvent);
begin
FOnSelectionChanged := Value;
end;
procedure TDesignForm.LoadFromFile(const inFilename: string);
begin
//
end;
procedure TDesignForm.SaveToFile(const inFilename: string);
begin
//
end;
end.
|
unit oopd2_form;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OOPD2_Datensatz, OOPD2_Adresse, OOPD2_Kunde, StdCtrls, ComCtrls;
type
TFmOOPD2 = class(TForm)
eName: TEdit;
eGeburtstag: TEdit;
eStrasse: TEdit;
ePLZ: TEdit;
eOrt: TEdit;
btnSpeichern: TButton;
lstKunden: TListView;
cbAnrede: TComboBox;
lbl_eName: TLabel;
lbl_eAnrede: TLabel;
lbl_eGeburtstag: TLabel;
lbl_eStrasse: TLabel;
lbl_ePLZ: TLabel;
lbl_eOrt: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSpeichernClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private-Deklarationen }
function EingabeSicher: Boolean;
procedure ListFuellen(datensatz: TDatensatz; adresse: TAdresse);
public
{ Public-Deklarationen }
end;
var
FmOOPD2: TFmOOPD2;
implementation
var
kunden: array of TKunde;
adressen: array of TAdresse;
Anrede: TAnrede;
{$R *.DFM}
// Objekte freigeben
procedure TFmOOPD2.FormClose(Sender: TObject; var Action: TCloseAction);
var
i: Integer;
begin
if length(kunden) > 0 then
begin
SetLength(kunden, length(kunden));
for i:=0 to length(kunden)-1 do
kunden[i].Free;
end;
if length(adressen) > 0 then
begin
SetLength(adressen, length(adressen));
for i:=0 to length(adressen)-1 do
adressen[i].Free;
end;
end;
// Fuellt die Listview mit Objektdaten
procedure TFmOOPD2.ListFuellen(datensatz: TDatensatz; adresse: TAdresse);
var
item: TListItem;
begin
item := lstKunden.Items.Add;
item.Caption := datensatz.getDSN;
if datensatz is TKunde then
begin
item.SubItems.Add((datensatz as TKunde).formatKundenNummer(((datensatz as TKunde).getKundenNummer)));
item.SubItems.Add((datensatz as TKunde).getName);
item.SubItems.Add((datensatz as TKunde).getAnrede);
item.SubItems.Add((datensatz as TKunde).getAlter);
item.SubItems.Add((datensatz as TKunde).getKundeZuAnschrift(adresse));
end;
end;
// Prueft ob die Edit-Felder leer sind
function TFmOOPD2.EingabeSicher: Boolean;
var
bZuweisung: Boolean;
begin
bZuweisung := True;
if (eName.Text = '') or (cbAnrede.Text = '') or (eGeburtstag.Text = '') or (eStrasse.Text = '') or (ePLZ.Text = '') or (eOrt.Text = '') then
bZuweisung := False;
Result := bZuweisung;
end;
// Objekte erzeugen und Aufruf von ListFuellen(object)
procedure TFmOOPD2.btnSpeichernClick(Sender: TObject);
var
i: Integer;
begin
if EingabeSicher then
begin
// Kunden
setlength(kunden, length(kunden)+1);
i := length(kunden)-1;
kunden[i] := TKunde.Create(i+1, eName.Text, kunden[i].setAnrede(Anrede, cbAnrede.ItemIndex), StrToDate(eGeburtstag.Text));
// Adressen
setlength(adressen, length(adressen)+1);
i := length(adressen)-1;
adressen[i] := TAdresse.Create(eStrasse.Text, StrToInt(ePLZ.Text), eOrt.Text);
ListFuellen(kunden[i], adressen[i]);
end
else
MessageDlg('Bitte geben Sie Werte in alle Eingabefelder ein.', mtError, [mbOk], 0);
end;
// Die Combobox manuell auf Read-Only setzen
procedure TFmOOPD2.FormCreate(Sender: TObject);
begin
SendMessage(GetWindow(cbAnrede.Handle,GW_CHILD), EM_SETREADONLY, 1, 0);
end;
end.
|
unit UOptionsButton;
interface
uses
W3System;
type
TOptionsButton = class(TObject)
X : float; //The x position of the button
Y : float; //the y position of the button
Width : float; //the width of the button
Height : float; //the height of the button
Text : string; //the text in the button
TextX : float; //the X of the text in the button
TextY : float; //the Y of the text in the button
constructor create(newX, newY, newWidth, newHeight : float; newText : string; newTextX,newTextY : float);
//If the x and y are in the button, it will return true as it has been clicked
function clicked(clickX, clickY : float) : boolean;
end;
implementation
constructor TOptionsButton.create(newX,newY,newWidth,newHeight : float; newText : string; newTextX,newTextY : float);
begin
X := newX;
Y := newY;
Width := newWidth;
Height := newHeight;
Text := newText;
TextX := newTextX;
TextY := newTextY;
end;
function TOptionsButton.clicked(clickX,clickY : float) : boolean;
begin
if (clickX >= X) and (clickX <= X + Width) then //if the x is in the x range
begin
if (clickY >= Y) and (clickY <= Y + Height) then //if the y is in the y range
begin
Exit(true); //return true if both passed
end;
end;
Exit(false); //otherwise return false
end;
end.
|
unit StockAppPath;
interface
uses
SysUtils, BaseApp, BaseWinApp,
define_datasrc,
define_dealitem,
define_dealstore_file;
type
TStockAppPathData = record
DBPathRoot: string;
DetailDBPath: string;
end;
TStockAppPath = class(TBaseWinAppPath)
protected
fStockAppPathData: TStockAppPathData;
function GetDataBasePath(ADBType: integer; ADataSrc: integer): WideString; override;
function GetInstallPath: WideString; override;
public
constructor Create(App: TBaseApp); override;
function GetRootPath: WideString; override;
function GetFileRelativePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; override;
function GetFilePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; override;
function GetFileName(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; override;
function GetFileExt(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; override;
function GetFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; override;
function CheckOutFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; override;
property DBPathRoot: string read fStockAppPathData.DBPathRoot write fStockAppPathData.DBPathRoot;
end;
implementation
uses
IniFiles;
{ TStockDay163AppPath }
constructor TStockAppPath.Create(App: TBaseApp);
begin
inherited;
FillChar(fStockAppPathData, SizeOf(fStockAppPathData), 0);
fStockAppPathData.DBPathRoot := FilePath_StockData;
end;
function TStockAppPath.GetRootPath: WideString;
begin
Result := GetInstallPath;
end;
function TStockAppPath.GetFileRelativePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString;
var
tmpDataSrcCode: string;
tmpIni: TIniFile;
begin
Result := '';
tmpDataSrcCode := GetDataSrcCode(ADataSrc);
if FilePath_DBType_DayData = ADBType then
Result := fStockAppPathData.DBPathRoot + '\' + FileExt_StockDay + tmpDataSrcCode + '\';
if FilePath_DBType_DayDataWeight = ADBType then
Result := fStockAppPathData.DBPathRoot + '\' + FileExt_StockDayWeight + tmpDataSrcCode + '\';
if FilePath_DBType_InstantData = ADBType then
Result := fStockAppPathData.DBPathRoot + '\' + FileExt_StockInstant + tmpDataSrcCode + '\';
if FilePath_DBType_DetailData = ADBType then
begin
if '' = fStockAppPathData.DetailDBPath then
begin
tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
try
fStockAppPathData.DetailDBPath := tmpIni.ReadString('Path', 'DetailRoot_' + tmpDataSrcCode, '');
if '' = fStockAppPathData.DetailDBPath then
begin
fStockAppPathData.DetailDBPath := fStockAppPathData.DBPathRoot + '\' + FileExt_StockDetail + tmpDataSrcCode + '\';
end;
tmpIni.WriteString('Path', 'DetailRoot_' + tmpDataSrcCode, fStockAppPathData.DetailDBPath);
finally
tmpIni.Free;
end;
end;
Result := fStockAppPathData.DetailDBPath;
end;
if FilePath_DBType_ValueData = ADBType then
Result := fStockAppPathData.DBPathRoot + '\' + FileExt_StockSummaryValue + tmpDataSrcCode + '\';
if FilePath_DBType_ItemDB = ADBType then
Result := fStockAppPathData.DBPathRoot + '\' + 's_dic' + '\';
if '' = Result then
begin
if '' <> tmpDataSrcCode then
Result := fStockAppPathData.DBPathRoot + '\' + 's' + tmpDataSrcCode + '\'
else
Result := fStockAppPathData.DBPathRoot + '\';
end;
end;
function TStockAppPath.GetDataBasePath(ADBType: integer; ADataSrc: integer): WideString;
var
tmpDataSrcCode: string;
tmpIni: TIniFile;
begin
Result := '';
tmpDataSrcCode := GetDataSrcCode(ADataSrc);
if FilePath_DBType_DayData = ADBType then
Result := GetInstallPath + fStockAppPathData.DBPathRoot + '\' + FileExt_StockDay + tmpDataSrcCode + '\';
if FilePath_DBType_DayDataWeight = ADBType then
Result := GetInstallPath + fStockAppPathData.DBPathRoot + '\' + FileExt_StockDayWeight + tmpDataSrcCode + '\';
if FilePath_DBType_InstantData = ADBType then
Result := GetInstallPath + fStockAppPathData.DBPathRoot + '\' + FileExt_StockInstant + tmpDataSrcCode + '\';
if FilePath_DBType_DetailData = ADBType then
begin
if '' = fStockAppPathData.DetailDBPath then
begin
tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
try
fStockAppPathData.DetailDBPath := tmpIni.ReadString('Path', 'DetailRoot_' + tmpDataSrcCode, '');
if '' = fStockAppPathData.DetailDBPath then
begin
fStockAppPathData.DetailDBPath := GetInstallPath + fStockAppPathData.DBPathRoot + '\' + FileExt_StockDetail + tmpDataSrcCode + '\';
end;
tmpIni.WriteString('Path', 'DetailRoot_' + tmpDataSrcCode, fStockAppPathData.DetailDBPath);
finally
tmpIni.Free;
end;
end;
Result := fStockAppPathData.DetailDBPath;
end;
if FilePath_DBType_ValueData = ADBType then
Result := GetInstallPath + fStockAppPathData.DBPathRoot + '\' + FileExt_StockSummaryValue + tmpDataSrcCode + '\';
if FilePath_DBType_ItemDB = ADBType then
Result := GetInstallPath + fStockAppPathData.DBPathRoot + '\' + 's_dic' + '\';
if '' = Result then
begin
if '' <> tmpDataSrcCode then
Result := GetInstallPath + fStockAppPathData.DBPathRoot + '\' + 's' + tmpDataSrcCode + '\'
else
Result := GetInstallPath + fStockAppPathData.DBPathRoot + '\';
end;
if '' <> Result then
begin
Sysutils.ForceDirectories(Result);
end;
end;
function TStockAppPath.GetFilePath(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString;
begin
Result := '';
if FilePath_DBType_DetailData = ADBType then
begin
if nil = AParam then
exit;
Result := DataBasePath[ADBType, ADataSrc] +
Copy(PRT_DealItem(AParam).sCode, 1, 4) + '\' +
PRT_DealItem(AParam).sCode + '\';
if 0 < AParamType then
begin
Result := Result + Copy(FormatDateTime('yyyymmdd', AParamType), 1, 4) + '\';
end;
exit;
end;
if FilePath_DBType_DayData = ADBType then
begin
if nil <> AParam then
begin
Result := DataBasePath[ADBType, ADataSrc];
end;
end;
if FilePath_DBType_DayDataWeight = ADBType then
begin
if nil <> AParam then
begin
Result := DataBasePath[ADBType, ADataSrc];
end;
end;
if FilePath_DBType_InstantData = ADBType then
begin
if nil <> AParam then
begin
Result := DataBasePath[ADBType, ADataSrc];
end;
end;
if FilePath_DBType_ItemDB = ADBType then
begin
Result := DataBasePath[ADBType, 0];
end;
if '' = Result then
begin
Result := DataBasePath[ADBType, ADataSrc];
end;
end;
function TStockAppPath.GetFileName(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString;
begin
Result := '';
if FilePath_DBType_DetailData = ADBType then
begin
Result := PRT_DealItem(AParam).sCode + '_' + FormatDateTime('yyyymmdd', AParamType);
if '' <> AFileExt then
begin
if Pos('.', AFileExt) > 0 then
begin
Result := Result + AFileExt;
end else
begin
Result := Result + '.' + AFileExt;
end;
end else
begin
Result := Result + '.' + GetFileExt(ADBType, ADataSrc, AParamType, AParam);
end;
exit;
end;
if FilePath_DBType_DayData = ADBType then
begin
if nil <> AParam then
begin
Result := PRT_DealItem(AParam).sCode + '.' + GetFileExt(ADBType, ADataSrc, AParamType, AParam);
end;
exit;
end;
if FilePath_DBType_DayDataWeight = ADBType then
begin
if nil <> AParam then
begin
Result := PRT_DealItem(AParam).sCode + '.' + GetFileExt(ADBType, ADataSrc, AParamType, AParam);
end;
exit;
end;
if FilePath_DBType_InstantData = ADBType then
begin
exit;
end;
if FilePath_DBType_ItemDB = ADBType then
begin
Result := 'items.' + GetFileExt(ADBType, ADataSrc, AParamType, AParam);
exit;
end;
end;
function TStockAppPath.GetFileExt(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString;
begin
Result := '';
if FilePath_DBType_DetailData = ADBType then
begin
Result := FileExt_StockDetail + IntToStr(ADataSrc);
exit;
end;
if FilePath_DBType_DayData = ADBType then
begin
Result := FileExt_StockDay + '_' + IntToStr(ADataSrc);
exit;
end;
if FilePath_DBType_DayDataWeight = ADBType then
begin
Result := FileExt_StockDayWeight + '_' + IntToStr(ADataSrc);
exit;
end;
if FilePath_DBType_InstantData = ADBType then
begin
exit;
end;
if FilePath_DBType_ItemDB = ADBType then
begin
Result := 'dic';
exit;
end;
end;
function TStockAppPath.CheckOutFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString;
var
tmpFileName: AnsiString;
tmpFilePath: AnsiString;
begin
Result := '';
tmpFilePath := GetFilePath(ADBType, ADataSrc, AParamType, AParam);
tmpFileName := GetFileName(ADBType, ADataSrc, AParamType, AParam, AFileExt);
if ('' <> tmpFilePath) and ('' <> tmpFileName) then
begin
ForceDirectories(tmpFilePath);
Result := tmpFilePath + tmpFileName;
end;
end;
function TStockAppPath.GetFileUrl(ADBType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString;
var
tmpFileName: AnsiString;
tmpFilePath: AnsiString;
begin
Result := '';
if FilePath_DBType_ItemDB = ADBType then
begin
Result := ChangeFileExt(ParamStr(0), '.dic');
if FileExists(Result) then
begin
exit;
end;
end;
tmpFilePath := GetFilePath(ADBType, ADataSrc, AParamType, AParam);
tmpFileName := GetFileName(ADBType, ADataSrc, AParamType, AParam, AFileExt);
if ('' <> tmpFilePath) and ('' <> tmpFileName) then
begin
Result := tmpFilePath + tmpFileName;
end;
end;
function TStockAppPath.GetInstallPath: WideString;
begin
Result := ExtractFilePath(ParamStr(0));
end;
end.
|
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
zlib bindings (expected zlib version: 1.2.11)
Bindings for statically linked library (object files)
These units provides plain (no wrappers or helpers) bindings for zlib library.
Most comments were copied directly from zlib.h header without any change.
This binding is distributed with all necessary binaries (object files, DLLs)
precompiled. For details please refer to file bin_readme.txt.
©František Milt 2019-03-26
Version 1.1
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting the author by
making a small donation using following link(s):
https://www.paypal.me/FMilt
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
* StrRect - github.com/ncs-sniper/Lib.StrRect
StrRect is required only for dynamically linked part of the binding (unit
ZLibDynamic) and only when compiler for Windows OS.
===============================================================================}
unit ZLibStatic;
{$INCLUDE '.\ZLib_defs.inc'}
{$IF Defined(PurePascal) and Defined(GZIP_Support) and Defined(Windows)}
{$MESSAGE WARN 'Cannot be compiled in PurePascal mode.'}
{$IFEND}
interface
uses
AuxTypes, ZLibCommon;
{===============================================================================
Zlib functions
===============================================================================}
(* basic functions *)
Function zlibVersion: PAnsiChar; cdecl; external;
(* The application can compare zlibVersion and ZLIB_VERSION for consistency.
If the first character differs, the library code actually used is not
compatible with the zlib.h header file used by the application. This check
is automatically made by deflateInit and inflateInit.
*)
Function deflateInit(strm: z_streamp; level: int): int;{$IFDEF CanInline} inline; {$ENDIF}
(*
Initializes the internal stream state for compression. The fields
zalloc, zfree and opaque must be initialized before by the caller. If
zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
allocation functions.
The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
1 gives best speed, 9 gives best compression, 0 gives no compression at all
(the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION
requests a default compromise between speed and compression (currently
equivalent to level 6).
deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if level is not a valid compression level, or
Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
with the version assumed by the caller (ZLIB_VERSION). msg is set to null
if there is no error message. deflateInit does not perform any compression:
this will be done by deflate().
*)
Function deflate(strm: z_streamp; flush: int): int; cdecl; external;
(*
deflate compresses as much data as possible, and stops when the input
buffer becomes empty or the output buffer becomes full. It may introduce
some output latency (reading input without producing any output) except when
forced to flush.
The detailed semantics are as follows. deflate performs one or both of the
following actions:
- Compress more input starting at next_in and update next_in and avail_in
accordingly. If not all input can be processed (because there is not
enough room in the output buffer), next_in and avail_in are updated and
processing will resume at this point for the next call of deflate().
- Generate more output starting at next_out and update next_out and avail_out
accordingly. This action is forced if the parameter flush is non zero.
Forcing flush frequently degrades the compression ratio, so this parameter
should be set only when necessary. Some output may be provided even if
flush is zero.
Before the call of deflate(), the application should ensure that at least
one of the actions is possible, by providing more input and/or consuming more
output, and updating avail_in or avail_out accordingly; avail_out should
never be zero before the call. The application can consume the compressed
output when it wants, for example when the output buffer is full (avail_out
== 0), or after each call of deflate(). If deflate returns Z_OK and with
zero avail_out, it must be called again after making room in the output
buffer because there might be more output pending. See deflatePending(),
which can be used if desired to determine whether or not there is more ouput
in that case.
Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
decide how much data to accumulate before producing output, in order to
maximize compression.
If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
flushed to the output buffer and the output is aligned on a byte boundary, so
that the decompressor can get all input data available so far. (In
particular avail_in is zero after the call if enough output space has been
provided before the call.) Flushing may degrade compression for some
compression algorithms and so it should be used only when necessary. This
completes the current deflate block and follows it with an empty stored block
that is three bits plus filler bits to the next byte, followed by four bytes
(00 00 ff ff).
If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
output buffer, but the output is not aligned to a byte boundary. All of the
input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
This completes the current deflate block and follows it with an empty fixed
codes block that is 10 bits long. This assures that enough bytes are output
in order for the decompressor to finish the block before the empty fixed
codes block.
If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
seven bits of the current block are held to be written as the next byte after
the next deflate block is completed. In this case, the decompressor may not
be provided enough bits at this point in order to complete decompression of
the data provided so far to the compressor. It may need to wait for the next
block to be emitted. This is for advanced applications that need to control
the emission of deflate blocks.
If flush is set to Z_FULL_FLUSH, all output is flushed as with
Z_SYNC_FLUSH, and the compression state is reset so that decompression can
restart from this point if previous compressed data has been damaged or if
random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
compression.
If deflate returns with avail_out == 0, this function must be called again
with the same value of the flush parameter and more output space (updated
avail_out), until the flush is complete (deflate returns with non-zero
avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
avail_out is greater than six to avoid repeated flush markers due to
avail_out == 0 on return.
If the parameter flush is set to Z_FINISH, pending input is processed,
pending output is flushed and deflate returns with Z_STREAM_END if there was
enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this
function must be called again with Z_FINISH and more output space (updated
avail_out) but no more input data, until it returns with Z_STREAM_END or an
error. After deflate has returned Z_STREAM_END, the only possible operations
on the stream are deflateReset or deflateEnd.
Z_FINISH can be used in the first deflate call after deflateInit if all the
compression is to be done in a single step. In order to complete in one
call, avail_out must be at least the value returned by deflateBound (see
below). Then deflate is guaranteed to return Z_STREAM_END. If not enough
output space is provided, deflate will not return Z_STREAM_END, and it must
be called again as described above.
deflate() sets strm->adler to the Adler-32 checksum of all input read
so far (that is, total_in bytes). If a gzip stream is being generated, then
strm->adler will be the CRC-32 checksum of the input read so far. (See
deflateInit2 below.)
deflate() may update strm->data_type if it can make a good guess about
the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is
considered binary. This field is only for information purposes and does not
affect the compression algorithm in any manner.
deflate() returns Z_OK if some progress has been made (more input
processed or more output produced), Z_STREAM_END if all input has been
consumed and all output has been produced (only when flush is set to
Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
if next_in or next_out was Z_NULL or the state was inadvertently written over
by the application), or Z_BUF_ERROR if no progress is possible (for example
avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and
deflate() can be called again with more input and more output space to
continue compressing.
*)
Function deflateEnd(strm: z_streamp): int; cdecl; external;
(*
All dynamically allocated data structures for this stream are freed.
This function discards any unprocessed input and does not flush any pending
output.
deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
stream state was inconsistent, Z_DATA_ERROR if the stream was freed
prematurely (some input or output was discarded). In the error case, msg
may be set but then points to a static string (which must not be
deallocated).
*)
Function inflateInit(strm: z_streamp): int;{$IFDEF CanInline} inline; {$ENDIF}
(*
Initializes the internal stream state for decompression. The fields
next_in, avail_in, zalloc, zfree and opaque must be initialized before by
the caller. In the current version of inflate, the provided input is not
read or consumed. The allocation of a sliding window will be deferred to
the first call of inflate (if the decompression does not complete on the
first call). If zalloc and zfree are set to Z_NULL, inflateInit updates
them to use default allocation functions.
inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
version assumed by the caller, or Z_STREAM_ERROR if the parameters are
invalid, such as a null pointer to the structure. msg is set to null if
there is no error message. inflateInit does not perform any decompression.
Actual decompression will be done by inflate(). So next_in, and avail_in,
next_out, and avail_out are unused and unchanged. The current
implementation of inflateInit() does not process any header information --
that is deferred until inflate() is called.
*)
Function inflate(strm: z_streamp; flush: int): int; cdecl; external;
(*
inflate decompresses as much data as possible, and stops when the input
buffer becomes empty or the output buffer becomes full. It may introduce
some output latency (reading input without producing any output) except when
forced to flush.
The detailed semantics are as follows. inflate performs one or both of the
following actions:
- Decompress more input starting at next_in and update next_in and avail_in
accordingly. If not all input can be processed (because there is not
enough room in the output buffer), then next_in and avail_in are updated
accordingly, and processing will resume at this point for the next call of
inflate().
- Generate more output starting at next_out and update next_out and avail_out
accordingly. inflate() provides as much output as possible, until there is
no more input data or no more space in the output buffer (see below about
the flush parameter).
Before the call of inflate(), the application should ensure that at least
one of the actions is possible, by providing more input and/or consuming more
output, and updating the next_* and avail_* values accordingly. If the
caller of inflate() does not provide both available input and available
output space, it is possible that there will be no progress made. The
application can consume the uncompressed output when it wants, for example
when the output buffer is full (avail_out == 0), or after each call of
inflate(). If inflate returns Z_OK and with zero avail_out, it must be
called again after making room in the output buffer because there might be
more output pending.
The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much
output as possible to the output buffer. Z_BLOCK requests that inflate()
stop if and when it gets to the next deflate block boundary. When decoding
the zlib or gzip format, this will cause inflate() to return immediately
after the header and before the first block. When doing a raw inflate,
inflate() will go ahead and process the first block, and will return when it
gets to the end of that block, or when it runs out of data.
The Z_BLOCK option assists in appending to or combining deflate streams.
To assist in this, on return inflate() always sets strm->data_type to the
number of unused bits in the last byte taken from strm->next_in, plus 64 if
inflate() is currently decoding the last block in the deflate stream, plus
128 if inflate() returned immediately after decoding an end-of-block code or
decoding the complete header up to just before the first byte of the deflate
stream. The end-of-block will not be indicated until all of the uncompressed
data from that block has been written to strm->next_out. The number of
unused bits may in general be greater than seven, except when bit 7 of
data_type is set, in which case the number of unused bits will be less than
eight. data_type is set as noted here every time inflate() returns for all
flush options, and so can be used to determine the amount of currently
consumed input in bits.
The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
end of each deflate block header is reached, before any actual data in that
block is decoded. This allows the caller to determine the length of the
deflate block header for later use in random access within a deflate block.
256 is added to the value of strm->data_type when inflate() returns
immediately after reaching the end of the deflate block header.
inflate() should normally be called until it returns Z_STREAM_END or an
error. However if all decompression is to be performed in a single step (a
single call of inflate), the parameter flush should be set to Z_FINISH. In
this case all pending input is processed and all pending output is flushed;
avail_out must be large enough to hold all of the uncompressed data for the
operation to complete. (The size of the uncompressed data may have been
saved by the compressor for this purpose.) The use of Z_FINISH is not
required to perform an inflation in one step. However it may be used to
inform inflate that a faster approach can be used for the single inflate()
call. Z_FINISH also informs inflate to not maintain a sliding window if the
stream completes, which reduces inflate's memory footprint. If the stream
does not complete, either because not all of the stream is provided or not
enough output space is provided, then a sliding window will be allocated and
inflate() can be called again to continue the operation as if Z_NO_FLUSH had
been used.
In this implementation, inflate() always flushes as much output as
possible to the output buffer, and always uses the faster approach on the
first call. So the effects of the flush parameter in this implementation are
on the return value of inflate() as noted below, when inflate() returns early
when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
memory for a sliding window when Z_FINISH is used.
If a preset dictionary is needed after this call (see inflateSetDictionary
below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
strm->adler to the Adler-32 checksum of all output produced so far (that is,
total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
below. At the end of the stream, inflate() checks that its computed Adler-32
checksum is equal to that saved by the compressor and returns Z_STREAM_END
only if the checksum is correct.
inflate() can decompress and check either zlib-wrapped or gzip-wrapped
deflate data. The header type is detected automatically, if requested when
initializing with inflateInit2(). Any information contained in the gzip
header is not retained unless inflateGetHeader() is used. When processing
gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
produced so far. The CRC-32 is checked against the gzip trailer, as is the
uncompressed length, modulo 2^32.
inflate() returns Z_OK if some progress has been made (more input processed
or more output produced), Z_STREAM_END if the end of the compressed data has
been reached and all uncompressed output has been produced, Z_NEED_DICT if a
preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
corrupted (input stream not conforming to the zlib format or incorrect check
value, in which case strm->msg points to a string with a more specific
error), Z_STREAM_ERROR if the stream structure was inconsistent (for example
next_in or next_out was Z_NULL, or the state was inadvertently written over
by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR
if no progress was possible or if there was not enough room in the output
buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
inflate() can be called again with more input and more output space to
continue decompressing. If Z_DATA_ERROR is returned, the application may
then call inflateSync() to look for a good compression block if a partial
recovery of the data is to be attempted.
*)
Function inflateEnd(strm: z_streamp): int; cdecl; external;
(*
All dynamically allocated data structures for this stream are freed.
This function discards any unprocessed input and does not flush any pending
output.
inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state
was inconsistent.
*)
(* Advanced functions *)
(*
The following functions are needed only in some special applications.
*)
Function deflateInit2(strm: z_streamp; level, method, windowBits, memLevel, strategy: int): int;{$IFDEF CanInline} inline; {$ENDIF}
(*
This is another version of deflateInit with more compression options. The
fields next_in, zalloc, zfree and opaque must be initialized before by the
caller.
The method parameter is the compression method. It must be Z_DEFLATED in
this version of the library.
The windowBits parameter is the base two logarithm of the window size
(the size of the history buffer). It should be in the range 8..15 for this
version of the library. Larger values of this parameter result in better
compression at the expense of memory usage. The default value is 15 if
deflateInit is used instead.
For the current implementation of deflate(), a windowBits value of 8 (a
window size of 256 bytes) is not supported. As a result, a request for 8
will result in 9 (a 512-byte window). In that case, providing 8 to
inflateInit2() will result in an error when the zlib header with 9 is
checked against the initialization of inflate(). The remedy is to not use 8
with deflateInit2() with this initialization, or at least in that case use 9
with inflateInit2().
windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
determines the window size. deflate() will then generate raw deflate data
with no zlib header or trailer, and will not compute a check value.
windowBits can also be greater than 15 for optional gzip encoding. Add
16 to windowBits to write a simple gzip header and trailer around the
compressed data instead of a zlib wrapper. The gzip header will have no
file name, no extra data, no comment, no modification time (set to zero), no
header crc, and the operating system will be set to the appropriate value,
if the operating system was determined at compile time. If a gzip stream is
being written, strm->adler is a CRC-32 instead of an Adler-32.
For raw deflate or gzip encoding, a request for a 256-byte window is
rejected as invalid, since only the zlib header provides a means of
transmitting the window size to the decompressor.
The memLevel parameter specifies how much memory should be allocated
for the internal compression state. memLevel=1 uses minimum memory but is
slow and reduces compression ratio; memLevel=9 uses maximum memory for
optimal speed. The default value is 8. See zconf.h for total memory usage
as a function of windowBits and memLevel.
The strategy parameter is used to tune the compression algorithm. Use the
value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
string match), or Z_RLE to limit match distances to one (run-length
encoding). Filtered data consists mostly of small values with a somewhat
random distribution. In this case, the compression algorithm is tuned to
compress them better. The effect of Z_FILTERED is to force more Huffman
coding and less string matching; it is somewhat intermediate between
Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as
fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The
strategy parameter only affects the compression ratio but not the
correctness of the compressed output even if it is not set appropriately.
Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
decoder for special applications.
deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
incompatible with the version assumed by the caller (ZLIB_VERSION). msg is
set to null if there is no error message. deflateInit2 does not perform any
compression: this will be done by deflate().
*)
Function deflateSetDictionary(strm: z_streamp; dictionary: PByte; dictLength: uInt): int; cdecl; external;
(*
Initializes the compression dictionary from the given byte sequence
without producing any compressed output. When using the zlib format, this
function must be called immediately after deflateInit, deflateInit2 or
deflateReset, and before any call of deflate. When doing raw deflate, this
function must be called either before any call of deflate, or immediately
after the completion of a deflate block, i.e. after all input has been
consumed and all output has been delivered when using any of the flush
options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The
compressor and decompressor must use exactly the same dictionary (see
inflateSetDictionary).
The dictionary should consist of strings (byte sequences) that are likely
to be encountered later in the data to be compressed, with the most commonly
used strings preferably put towards the end of the dictionary. Using a
dictionary is most useful when the data to be compressed is short and can be
predicted with good accuracy; the data can then be compressed better than
with the default empty dictionary.
Depending on the size of the compression data structures selected by
deflateInit or deflateInit2, a part of the dictionary may in effect be
discarded, for example if the dictionary is larger than the window size
provided in deflateInit or deflateInit2. Thus the strings most likely to be
useful should be put at the end of the dictionary, not at the front. In
addition, the current implementation of deflate will use at most the window
size minus 262 bytes of the provided dictionary.
Upon return of this function, strm->adler is set to the Adler-32 value
of the dictionary; the decompressor may later use this value to determine
which dictionary has been used by the compressor. (The Adler-32 value
applies to the whole dictionary even if only a subset of the dictionary is
actually used by the compressor.) If a raw deflate was requested, then the
Adler-32 value is not computed and strm->adler is not set.
deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
inconsistent (for example if deflate has already been called for this stream
or if not at a block boundary for raw deflate). deflateSetDictionary does
not perform any compression: this will be done by deflate().
*)
Function deflateGetDictionary(strm: z_streamp; dictionary: PByte; dictLength: puInt): int; cdecl; external;
(*
Returns the sliding dictionary being maintained by deflate. dictLength is
set to the number of bytes in the dictionary, and that many bytes are copied
to dictionary. dictionary must have enough space, where 32768 bytes is
always enough. If deflateGetDictionary() is called with dictionary equal to
Z_NULL, then only the dictionary length is returned, and nothing is copied.
Similary, if dictLength is Z_NULL, then it is not set.
deflateGetDictionary() may return a length less than the window size, even
when more than the window size in input has been provided. It may return up
to 258 bytes less in that case, due to how zlib's implementation of deflate
manages the sliding window and lookahead for matches, where matches can be
up to 258 bytes long. If the application needs the last window-size bytes of
input, then that would need to be saved by the application outside of zlib.
deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
stream state is inconsistent.
*)
Function deflateCopy(dest, source: z_streamp): int; cdecl; external;
(*
Sets the destination stream as a complete copy of the source stream.
This function can be useful when several compression strategies will be
tried, for example when there are several ways of pre-processing the input
data with a filter. The streams that will be discarded should then be freed
by calling deflateEnd. Note that deflateCopy duplicates the internal
compression state which can be quite large, so this strategy is slow and can
consume lots of memory.
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
(such as zalloc being Z_NULL). msg is left unchanged in both source and
destination.
*)
Function deflateReset(strm: z_streamp): int; cdecl; external;
(*
This function is equivalent to deflateEnd followed by deflateInit, but
does not free and reallocate the internal compression state. The stream
will leave the compression level and any other attributes that may have been
set unchanged.
deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent (such as zalloc or state being Z_NULL).
*)
Function deflateParams(strm: z_streamp; level, strategy: int): int; cdecl; external;
(*
Dynamically update the compression level and compression strategy. The
interpretation of level and strategy is as in deflateInit2(). This can be
used to switch between compression and straight copy of the input data, or
to switch to a different kind of input data requiring a different strategy.
If the compression approach (which is a function of the level) or the
strategy is changed, and if any input has been consumed in a previous
deflate() call, then the input available so far is compressed with the old
level and strategy using deflate(strm, Z_BLOCK). There are three approaches
for the compression levels 0, 1..3, and 4..9 respectively. The new level
and strategy will take effect at the next call of deflate().
If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does
not have enough output space to complete, then the parameter change will not
take effect. In this case, deflateParams() can be called again with the
same parameters and more output space to try again.
In order to assure a change in the parameters on the first try, the
deflate stream should be flushed using deflate() with Z_BLOCK or other flush
request until strm.avail_out is not zero, before calling deflateParams().
Then no more input data should be provided before the deflateParams() call.
If this is done, the old level and strategy will be applied to the data
compressed before deflateParams(), and the new level and strategy will be
applied to the the data compressed after deflateParams().
deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream
state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if
there was not enough output space to complete the compression of the
available input data before a change in the strategy or approach. Note that
in the case of a Z_BUF_ERROR, the parameters are not changed. A return
value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be
retried with more output space.
*)
Function deflateTune(strm: z_streamp; good_length, max_lazy, nice_length, max_chain: int): int; cdecl; external;
(*
Fine tune deflate's internal compression parameters. This should only be
used by someone who understands the algorithm used by zlib's deflate for
searching for the best matching string, and even then only by the most
fanatic optimizer trying to squeeze out the last compressed bit for their
specific input data. Read the deflate.c source code for the meaning of the
max_lazy, good_length, nice_length, and max_chain parameters.
deflateTune() can be called after deflateInit() or deflateInit2(), and
returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
*)
Function deflateBound(strm: z_streamp; sourceLen: uLong): uLong; cdecl; external;
(*
deflateBound() returns an upper bound on the compressed size after
deflation of sourceLen bytes. It must be called after deflateInit() or
deflateInit2(), and after deflateSetHeader(), if used. This would be used
to allocate an output buffer for deflation in a single pass, and so would be
called before deflate(). If that first deflate() call is provided the
sourceLen input bytes, an output buffer allocated to the size returned by
deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
to return Z_STREAM_END. Note that it is possible for the compressed size to
be larger than the value returned by deflateBound() if flush options other
than Z_FINISH or Z_NO_FLUSH are used.
*)
Function deflatePending(strm: z_streamp; pending: punsigned; bits: pint): int; cdecl; external;
(*
deflatePending() returns the number of bytes and bits of output that have
been generated, but not yet provided in the available output. The bytes not
provided would be due to the available output space having being consumed.
The number of bits of output not provided are between 0 and 7, where they
await more bits to join them in order to fill out a full byte. If pending
or bits are Z_NULL, then those values are not set.
deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent.
*)
Function deflatePrime(strm: z_streamp; bits, value: int): int; cdecl; external;
(*
deflatePrime() inserts bits in the deflate output stream. The intent
is that this function is used to start off the deflate output with the bits
leftover from a previous deflate stream when appending to it. As such, this
function can only be used for raw deflate, and must be used before the first
deflate() call after a deflateInit2() or deflateReset(). bits must be less
than or equal to 16, and that many of the least significant bits of value
will be inserted in the output.
deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
source stream state was inconsistent.
*)
Function deflateSetHeader(strm: z_streamp; head: gz_headerp): int; cdecl; external;
(*
deflateSetHeader() provides gzip header information for when a gzip
stream is requested by deflateInit2(). deflateSetHeader() may be called
after deflateInit2() or deflateReset() and before the first call of
deflate(). The text, time, os, extra field, name, and comment information
in the provided gz_header structure are written to the gzip header (xflag is
ignored -- the extra flags are set according to the compression level). The
caller must assure that, if not Z_NULL, name and comment are terminated with
a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
available there. If hcrc is true, a gzip header crc is included. Note that
the current versions of the command-line version of gzip (up through version
1.3.x) do not support header crc's, and will report that it is a "multi-part
gzip file" and give up.
If deflateSetHeader is not used, the default gzip header has text false,
the time set to zero, and os set to 255, with no extra, name, or comment
fields. The gzip header is returned to the default state by deflateReset().
deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent.
*)
Function inflateInit2(strm: z_streamp; windowBits: int): int;{$IFDEF CanInline} inline; {$ENDIF}
(*
This is another version of inflateInit with an extra parameter. The
fields next_in, avail_in, zalloc, zfree and opaque must be initialized
before by the caller.
The windowBits parameter is the base two logarithm of the maximum window
size (the size of the history buffer). It should be in the range 8..15 for
this version of the library. The default value is 15 if inflateInit is used
instead. windowBits must be greater than or equal to the windowBits value
provided to deflateInit2() while compressing, or it must be equal to 15 if
deflateInit2() was not used. If a compressed stream with a larger window
size is given as input, inflate() will return with the error code
Z_DATA_ERROR instead of trying to allocate a larger window.
windowBits can also be zero to request that inflate use the window size in
the zlib header of the compressed stream.
windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
determines the window size. inflate() will then process raw deflate data,
not looking for a zlib or gzip header, not generating a check value, and not
looking for any check values for comparison at the end of the stream. This
is for use with other formats that use the deflate compressed data format
such as zip. Those formats provide their own check values. If a custom
format is developed using the raw deflate format for compressed data, it is
recommended that a check value such as an Adler-32 or a CRC-32 be applied to
the uncompressed data as is done in the zlib, gzip, and zip formats. For
most applications, the zlib format should be used as is. Note that comments
above on the use in deflateInit2() applies to the magnitude of windowBits.
windowBits can also be greater than 15 for optional gzip decoding. Add
32 to windowBits to enable zlib and gzip decoding with automatic header
detection, or add 16 to decode only the gzip format (the zlib format will
return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a
CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see
below), inflate() will not automatically decode concatenated gzip streams.
inflate() will return Z_STREAM_END at the end of the gzip stream. The state
would need to be reset to continue decoding a subsequent gzip stream.
inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
version assumed by the caller, or Z_STREAM_ERROR if the parameters are
invalid, such as a null pointer to the structure. msg is set to null if
there is no error message. inflateInit2 does not perform any decompression
apart from possibly reading the zlib header if present: actual decompression
will be done by inflate(). (So next_in and avail_in may be modified, but
next_out and avail_out are unused and unchanged.) The current implementation
of inflateInit2() does not process any header information -- that is
deferred until inflate() is called.
*)
Function inflateSetDictionary(strm: z_streamp; dictionary: PByte; dictLength: uInt): int; cdecl; external;
(*
Initializes the decompression dictionary from the given uncompressed byte
sequence. This function must be called immediately after a call of inflate,
if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
can be determined from the Adler-32 value returned by that call of inflate.
The compressor and decompressor must use exactly the same dictionary (see
deflateSetDictionary). For raw inflate, this function can be called at any
time to set the dictionary. If the provided dictionary is smaller than the
window and there is already data in the window, then the provided dictionary
will amend what's there. The application must insure that the dictionary
that was used for compression is provided.
inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
expected one (incorrect Adler-32 value). inflateSetDictionary does not
perform any decompression: this will be done by subsequent calls of
inflate().
*)
Function inflateGetDictionary(strm: z_streamp; dictionary: PByte; dictLength: puInt): int; cdecl; external;
(*
Returns the sliding dictionary being maintained by inflate. dictLength is
set to the number of bytes in the dictionary, and that many bytes are copied
to dictionary. dictionary must have enough space, where 32768 bytes is
always enough. If inflateGetDictionary() is called with dictionary equal to
Z_NULL, then only the dictionary length is returned, and nothing is copied.
Similary, if dictLength is Z_NULL, then it is not set.
inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
stream state is inconsistent.
*)
Function inflateSync(strm: z_streamp): int; cdecl; external;
(*
Skips invalid compressed data until a possible full flush point (see above
for the description of deflate with Z_FULL_FLUSH) can be found, or until all
available input is skipped. No output is provided.
inflateSync searches for a 00 00 FF FF pattern in the compressed data.
All full flush points have this pattern, but not all occurrences of this
pattern are full flush points.
inflateSync returns Z_OK if a possible full flush point has been found,
Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
In the success case, the application may save the current current value of
total_in which indicates where valid compressed data was found. In the
error case, the application may repeatedly call inflateSync, providing more
input each time, until success or end of the input data.
*)
Function inflateCopy(dest, source: z_streamp): int; cdecl; external;
(*
Sets the destination stream as a complete copy of the source stream.
This function can be useful when randomly accessing a large stream. The
first pass through the stream can periodically record the inflate state,
allowing restarting inflate at those points when randomly accessing the
stream.
inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
(such as zalloc being Z_NULL). msg is left unchanged in both source and
destination.
*)
Function inflateReset(strm: z_streamp): int; cdecl; external;
(*
This function is equivalent to inflateEnd followed by inflateInit,
but does not free and reallocate the internal decompression state. The
stream will keep attributes that may have been set by inflateInit2.
inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent (such as zalloc or state being Z_NULL).
*)
Function inflateReset2(strm: z_streamp; windowBits: int): int; cdecl; external;
(*
This function is the same as inflateReset, but it also permits changing
the wrap and window size requests. The windowBits parameter is interpreted
the same as it is for inflateInit2. If the window size is changed, then the
memory allocated for the window is freed, and the window will be reallocated
by inflate() if needed.
inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent (such as zalloc or state being Z_NULL), or if
the windowBits parameter is invalid.
*)
Function inflatePrime(strm: z_streamp; bits, value: int): int; cdecl; external;
(*
This function inserts bits in the inflate input stream. The intent is
that this function is used to start inflating at a bit position in the
middle of a byte. The provided bits will be used before any bytes are used
from next_in. This function should only be used with raw inflate, and
should be used before the first inflate() call after inflateInit2() or
inflateReset(). bits must be less than or equal to 16, and that many of the
least significant bits of value will be inserted in the input.
If bits is negative, then the input stream bit buffer is emptied. Then
inflatePrime() can be called again to put bits in the buffer. This is used
to clear out bits leftover after feeding inflate a block description prior
to feeding inflate codes.
inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent.
*)
Function inflateMark(strm: z_streamp): long; cdecl; external;
(*
This function returns two values, one in the lower 16 bits of the return
value, and the other in the remaining upper bits, obtained by shifting the
return value down 16 bits. If the upper value is -1 and the lower value is
zero, then inflate() is currently decoding information outside of a block.
If the upper value is -1 and the lower value is non-zero, then inflate is in
the middle of a stored block, with the lower value equaling the number of
bytes from the input remaining to copy. If the upper value is not -1, then
it is the number of bits back from the current bit position in the input of
the code (literal or length/distance pair) currently being processed. In
that case the lower value is the number of bytes already emitted for that
code.
A code is being processed if inflate is waiting for more input to complete
decoding of the code, or if it has completed decoding but is waiting for
more output space to write the literal or match data.
inflateMark() is used to mark locations in the input data for random
access, which may be at bit positions, and to note those cases where the
output of a code may span boundaries of random access blocks. The current
location in the input stream can be determined from avail_in and data_type
as noted in the description for the Z_BLOCK flush parameter for inflate.
inflateMark returns the value noted above, or -65536 if the provided
source stream state was inconsistent.
*)
Function inflateGetHeader(strm: z_streamp; head: gz_headerp): int; cdecl; external;
(*
inflateGetHeader() requests that gzip header information be stored in the
provided gz_header structure. inflateGetHeader() may be called after
inflateInit2() or inflateReset(), and before the first call of inflate().
As inflate() processes the gzip stream, head->done is zero until the header
is completed, at which time head->done is set to one. If a zlib stream is
being decoded, then head->done is set to -1 to indicate that there will be
no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be
used to force inflate() to return immediately after header processing is
complete and before any actual data is decompressed.
The text, time, xflags, and os fields are filled in with the gzip header
contents. hcrc is set to true if there is a header CRC. (The header CRC
was valid if done is set to one.) If extra is not Z_NULL, then extra_max
contains the maximum number of bytes to write to extra. Once done is true,
extra_len contains the actual extra field length, and extra contains the
extra field, or that field truncated if extra_max is less than extra_len.
If name is not Z_NULL, then up to name_max characters are written there,
terminated with a zero unless the length is greater than name_max. If
comment is not Z_NULL, then up to comm_max characters are written there,
terminated with a zero unless the length is greater than comm_max. When any
of extra, name, or comment are not Z_NULL and the respective field is not
present in the header, then that field is set to Z_NULL to signal its
absence. This allows the use of deflateSetHeader() with the returned
structure to duplicate the header. However if those fields are set to
allocated memory, then the application will need to save those pointers
elsewhere so that they can be eventually freed.
If inflateGetHeader is not used, then the header information is simply
discarded. The header is always checked for validity, including the header
CRC if present. inflateReset() will reset the process to discard the header
information. The application would need to call inflateGetHeader() again to
retrieve the header from the next gzip stream.
inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent.
*)
Function inflateBackInit(strm: z_streamp; windowBits: int; window: PByte): int;{$IFDEF CanInline} inline; {$ENDIF}
(*
Initialize the internal stream state for decompression using inflateBack()
calls. The fields zalloc, zfree and opaque in strm must be initialized
before the call. If zalloc and zfree are Z_NULL, then the default library-
derived memory allocation routines are used. windowBits is the base two
logarithm of the window size, in the range 8..15. window is a caller
supplied buffer of that size. Except for special applications where it is
assured that deflate was used with small window sizes, windowBits must be 15
and a 32K byte window must be supplied to be able to decompress general
deflate streams.
See inflateBack() for the usage of these routines.
inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
the parameters are invalid, Z_MEM_ERROR if the internal state could not be
allocated, or Z_VERSION_ERROR if the version of the library does not match
the version of the header file.
*)
Function inflateBack(strm: z_streamp; in_f: in_func; in_desc: Pointer; out_f: out_func; out_desc: Pointer): int; cdecl; external;
(*
inflateBack() does a raw inflate with a single call using a call-back
interface for input and output. This is potentially more efficient than
inflate() for file i/o applications, in that it avoids copying between the
output and the sliding window by simply making the window itself the output
buffer. inflate() can be faster on modern CPUs when used with large
buffers. inflateBack() trusts the application to not change the output
buffer passed by the output function, at least until inflateBack() returns.
inflateBackInit() must be called first to allocate the internal state
and to initialize the state with the user-provided window buffer.
inflateBack() may then be used multiple times to inflate a complete, raw
deflate stream with each call. inflateBackEnd() is then called to free the
allocated state.
A raw deflate stream is one with no zlib or gzip header or trailer.
This routine would normally be used in a utility that reads zip or gzip
files and writes out uncompressed files. The utility would decode the
header and process the trailer on its own, hence this routine expects only
the raw deflate stream to decompress. This is different from the default
behavior of inflate(), which expects a zlib header and trailer around the
deflate stream.
inflateBack() uses two subroutines supplied by the caller that are then
called by inflateBack() for input and output. inflateBack() calls those
routines until it reads a complete deflate stream and writes out all of the
uncompressed data, or until it encounters an error. The function's
parameters and return types are defined above in the in_func and out_func
typedefs. inflateBack() will call in(in_desc, &buf) which should return the
number of bytes of provided input, and a pointer to that input in buf. If
there is no input available, in() must return zero -- buf is ignored in that
case -- and inflateBack() will return a buffer error. inflateBack() will
call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].
out() should return zero on success, or non-zero on failure. If out()
returns non-zero, inflateBack() will return with an error. Neither in() nor
out() are permitted to change the contents of the window provided to
inflateBackInit(), which is also the buffer that out() uses to write from.
The length written by out() will be at most the window size. Any non-zero
amount of input may be provided by in().
For convenience, inflateBack() can be provided input on the first call by
setting strm->next_in and strm->avail_in. If that input is exhausted, then
in() will be called. Therefore strm->next_in must be initialized before
calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
must also be initialized, and then if strm->avail_in is not zero, input will
initially be taken from strm->next_in[0 .. strm->avail_in - 1].
The in_desc and out_desc parameters of inflateBack() is passed as the
first parameter of in() and out() respectively when they are called. These
descriptors can be optionally used to pass any information that the caller-
supplied in() and out() functions need to do their job.
On return, inflateBack() will set strm->next_in and strm->avail_in to
pass back any unused input that was provided by the last in() call. The
return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
if in() or out() returned an error, Z_DATA_ERROR if there was a format error
in the deflate stream (in which case strm->msg is set to indicate the nature
of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
In the case of Z_BUF_ERROR, an input or output error can be distinguished
using strm->next_in which will be Z_NULL only if in() returned an error. If
strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
non-zero. (in() will always be called before out(), so strm->next_in is
assured to be defined if out() returns non-zero.) Note that inflateBack()
cannot return Z_OK.
*)
Function inflateBackEnd(strm: z_streamp): int; cdecl; external;
(*
All memory allocated by inflateBackInit() is freed.
inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
state was inconsistent.
*)
Function zlibCompileFlags: uLong; cdecl; external;
(* Return flags indicating compile-time options.
Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
1.0: size of uInt
3.2: size of uLong
5.4: size of voidpf (pointer)
7.6: size of z_off_t
Compiler, assembler, and debug options:
8: ZLIB_DEBUG
9: ASMV or ASMINF -- use ASM code
10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
11: 0 (reserved)
One-time table building (smaller code, but not thread-safe if true):
12: BUILDFIXED -- build static block decoding tables when needed
13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
14,15: 0 (reserved)
Library content (indicates missing functionality):
16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
deflate code when not needed)
17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
and decode gzip streams (to avoid linking crc code)
18-19: 0 (reserved)
Operation variations (changes in library functionality):
20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
21: FASTEST -- deflate algorithm with only one, lowest compression level
22,23: 0 (reserved)
The sprintf variant used by gzprintf (zero is best):
24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
26: 0 = returns value, 1 = void -- 1 means inferred string length returned
Remainder:
27-31: 0 (reserved)
*)
(* utility functions *)
(*
The following utility functions are implemented on top of the basic
stream-oriented functions. To simplify the interface, some default options
are assumed (compression level and memory usage, standard memory allocation
functions). The source code of these utility functions can be modified if
you need special options.
*)
Function compress(dest: PByte; destLen: puLong; source: PByte; sourceLen: uLong): int; cdecl; external;
(*
Compresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total size
of the destination buffer, which must be at least the value returned by
compressBound(sourceLen). Upon exit, destLen is the actual size of the
compressed data. compress() is equivalent to compress2() with a level
parameter of Z_DEFAULT_COMPRESSION.
compress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer.
*)
Function compress2(dest: PByte; destLen: puLong; source: PByte; sourceLen: uLong; level: int): int; cdecl; external;
(*
Compresses the source buffer into the destination buffer. The level
parameter has the same meaning as in deflateInit. sourceLen is the byte
length of the source buffer. Upon entry, destLen is the total size of the
destination buffer, which must be at least the value returned by
compressBound(sourceLen). Upon exit, destLen is the actual size of the
compressed data.
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
Z_STREAM_ERROR if the level parameter is invalid.
*)
Function compressBound(sourceLen: uLong): uLong; cdecl; external;
(*
compressBound() returns an upper bound on the compressed size after
compress() or compress2() on sourceLen bytes. It would be used before a
compress() or compress2() call to allocate the destination buffer.
*)
Function uncompress(dest: PByte; destLen: puLong; source: PByte; sourceLen: uLong): int; cdecl; external;
(*
Decompresses the source buffer into the destination buffer. sourceLen is
the byte length of the source buffer. Upon entry, destLen is the total size
of the destination buffer, which must be large enough to hold the entire
uncompressed data. (The size of the uncompressed data must have been saved
previously by the compressor and transmitted to the decompressor by some
mechanism outside the scope of this compression library.) Upon exit, destLen
is the actual size of the uncompressed data.
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_BUF_ERROR if there was not enough room in the output
buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In
the case where there is not enough room, uncompress() will fill the output
buffer with the uncompressed data up to that point.
*)
Function uncompress2(dest: PByte; destLen: puLong; source: PByte; sourceLen: puLong): int; cdecl; external;
(*
Same as uncompress, except that sourceLen is a pointer, where the
length of the source is *sourceLen. On return, *sourceLen is the number of
source bytes consumed.
*)
{$IFDEF GZIP_Support}
(* gzip file access functions *)
(*
This library supports reading and writing files in gzip (.gz) format with
an interface similar to that of stdio, using the functions that start with
"gz". The gzip format is different from the zlib format. gzip is a gzip
wrapper, documented in RFC 1952, wrapped around a deflate stream.
*)
Function gzopen(path: PAnsiChar; mode: PAnsiChar): gzFile; cdecl; external;
(*
Opens a gzip (.gz) file for reading or writing. The mode parameter is as
in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
for fixed code compression as in "wb9F". (See the description of
deflateInit2 for more information about the strategy parameter.) 'T' will
request transparent writing or appending with no compression and not using
the gzip format.
"a" can be used instead of "w" to request that the gzip stream that will
be written be appended to the file. "+" will result in an error, since
reading and writing to the same gzip file is not supported. The addition of
"x" when writing will create the file exclusively, which fails if the file
already exists. On systems that support it, the addition of "e" when
reading or writing will set the flag to close the file on an execve() call.
These functions, as well as gzip, will read and decode a sequence of gzip
streams in a file. The append function of gzopen() can be used to create
such a file. (Also see gzflush() for another way to do this.) When
appending, gzopen does not test whether the file begins with a gzip stream,
nor does it look for the end of the gzip streams to begin appending. gzopen
will simply append a gzip stream to the existing file.
gzopen can be used to read a file which is not in gzip format; in this
case gzread will directly read from the file without decompression. When
reading, this will be detected automatically by looking for the magic two-
byte gzip header.
gzopen returns NULL if the file could not be opened, if there was
insufficient memory to allocate the gzFile state, or if an invalid mode was
specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
errno can be checked to determine if the reason gzopen failed was that the
file could not be opened.
*)
Function gzdopen(fd: int; mode: PAnsiChar): gzFile; cdecl; external;
(*
gzdopen associates a gzFile with the file descriptor fd. File descriptors
are obtained from calls like open, dup, creat, pipe or fileno (if the file
has been previously opened with fopen). The mode parameter is as in gzopen.
The next call of gzclose on the returned gzFile will also close the file
descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
mode);. The duplicated descriptor should be saved to avoid a leak, since
gzdopen does not close fd if it fails. If you are using fileno() to get the
file descriptor from a FILE *, then you will have to use dup() to avoid
double-close()ing the file descriptor. Both gzclose() and fclose() will
close the associated file descriptor, so they need to have different file
descriptors.
gzdopen returns NULL if there was insufficient memory to allocate the
gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
provided, or '+' was provided), or if fd is -1. The file descriptor is not
used until the next gz* read, write, seek, or close operation, so gzdopen
will not detect if fd is invalid (unless fd is -1).
*)
Function gzbuffer(aFile: gzFile; size: unsigned): int; cdecl; external;
(*
Set the internal buffer size used by this library's functions. The
default buffer size is 8192 bytes. This function must be called after
gzopen() or gzdopen(), and before any other calls that read or write the
file. The buffer memory allocation is always deferred to the first read or
write. Three times that size in buffer space is allocated. A larger buffer
size of, for example, 64K or 128K bytes will noticeably increase the speed
of decompression (reading).
The new buffer size also affects the maximum length for gzprintf().
gzbuffer() returns 0 on success, or -1 on failure, such as being called
too late.
*)
Function gzsetparams(aFile: gzFile; level, strategy: int): int; cdecl; external;
(*
Dynamically update the compression level or strategy. See the description
of deflateInit2 for the meaning of these parameters. Previously provided
data is flushed before the parameter change.
gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not
opened for writing, Z_ERRNO if there is an error writing the flushed data,
or Z_MEM_ERROR if there is a memory allocation error.
*)
Function gzread(aFile: gzFile; buf: Pointer; len: unsigned): int; cdecl; external;
(*
Reads the given number of uncompressed bytes from the compressed file. If
the input file is not in gzip format, gzread copies the given number of
bytes into the buffer directly from the file.
After reaching the end of a gzip stream in the input, gzread will continue
to read, looking for another gzip stream. Any number of gzip streams may be
concatenated in the input file, and will all be decompressed by gzread().
If something other than a gzip stream is encountered after a gzip stream,
that remaining trailing garbage is ignored (and no error is returned).
gzread can be used to read a gzip file that is being concurrently written.
Upon reaching the end of the input, gzread will return with the available
data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
gzclearerr can be used to clear the end of file indicator in order to permit
gzread to be tried again. Z_OK indicates that a gzip stream was completed
on the last gzread. Z_BUF_ERROR indicates that the input file ended in the
middle of a gzip stream. Note that gzread does not return -1 in the event
of an incomplete gzip stream. This error is deferred until gzclose(), which
will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
stream. Alternatively, gzerror can be used before gzclose to detect this
case.
gzread returns the number of uncompressed bytes actually read, less than
len for end of file, or -1 for error. If len is too large to fit in an int,
then nothing is read, -1 is returned, and the error state is set to
Z_STREAM_ERROR.
*)
Function gzfread(buf: Pointer; size, nitems: z_size_t; aFile: gzFile): z_size_t; cdecl; external;
(*
Read up to nitems items of size size from file to buf, otherwise operating
as gzread() does. This duplicates the interface of stdio's fread(), with
size_t request and return types. If the library defines size_t, then
z_size_t is identical to size_t. If not, then z_size_t is an unsigned
integer type that can contain a pointer.
gzfread() returns the number of full items read of size size, or zero if
the end of the file was reached and a full item could not be read, or if
there was an error. gzerror() must be consulted if zero is returned in
order to determine if there was an error. If the multiplication of size and
nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
In the event that the end of file is reached and only a partial item is
available at the end, i.e. the remaining uncompressed data length is not a
multiple of size, then the final partial item is nevetheless read into buf
and the end-of-file flag is set. The length of the partial item read is not
provided, but could be inferred from the result of gztell(). This behavior
is the same as the behavior of fread() implementations in common libraries,
but it prevents the direct use of gzfread() to read a concurrently written
file, reseting and retrying on end-of-file, when size is not 1.
*)
Function gzwrite(aFile: gzFile; buf: Pointer; len: unsigned): int; cdecl; external;
(*
Writes the given number of uncompressed bytes into the compressed file.
gzwrite returns the number of uncompressed bytes written or 0 in case of
error.
*)
Function gzfwrite(buf: Pointer; size, nintems: z_size_t; aFile: gzFile): z_size_t; cdecl; external;
(*
gzfwrite() writes nitems items of size size from buf to file, duplicating
the interface of stdio's fwrite(), with size_t request and return types. If
the library defines size_t, then z_size_t is identical to size_t. If not,
then z_size_t is an unsigned integer type that can contain a pointer.
gzfwrite() returns the number of full items written of size size, or zero
if there was an error. If the multiplication of size and nitems overflows,
i.e. the product does not fit in a z_size_t, then nothing is written, zero
is returned, and the error state is set to Z_STREAM_ERROR.
*)
Function gzprintf(aFile: gzFile; format: PAnsiChar): int; cdecl; varargs; external;
(*
Converts, formats, and writes the arguments to the compressed file under
control of the format string, as in fprintf. gzprintf returns the number of
uncompressed bytes actually written, or a negative zlib error code in case
of error. The number of uncompressed bytes written is limited to 8191, or
one less than the buffer size given to gzbuffer(). The caller should assure
that this limit is not exceeded. If it is exceeded, then gzprintf() will
return an error (0) with nothing written. In this case, there may also be a
buffer overflow with unpredictable consequences, which is possible only if
zlib was compiled with the insecure functions sprintf() or vsprintf()
because the secure snprintf() or vsnprintf() functions were not available.
This can be determined using zlibCompileFlags().
*)
Function gzputs(aFile: gzFile; s: PAnsiChar): int; cdecl; external;
(*
Writes the given null-terminated string to the compressed file, excluding
the terminating null character.
gzputs returns the number of characters written, or -1 in case of error.
*)
Function gzgets(aFile: gzFile; buf: PAnsiChar; len: int): PAnsiChar; cdecl; external;
(*
Reads bytes from the compressed file until len-1 characters are read, or a
newline character is read and transferred to buf, or an end-of-file
condition is encountered. If any characters are read or if len == 1, the
string is terminated with a null character. If no characters are read due
to an end-of-file or len < 1, then the buffer is left untouched.
gzgets returns buf which is a null-terminated string, or it returns NULL
for end-of-file or in case of error. If there was an error, the contents at
buf are indeterminate.
*)
Function gzputc(aFile: gzFile; c: int): int; cdecl; external;
(*
Writes c, converted to an unsigned char, into the compressed file. gzputc
returns the value that was written, or -1 in case of error.
*)
Function gzgetc(aFile: gzFile): int; cdecl; external;
(*
Reads one byte from the compressed file. gzgetc returns this byte or -1
in case of end of file or error. This is implemented as a macro for speed.
As such, it does not do all of the checking the other functions do. I.e.
it does not check to see if file is NULL, nor whether the structure file
points to has been clobbered or not.
*)
Function gzungetc(c: int; aFile: gzFile): int; cdecl; external;
(*
Push one character back onto the stream to be read as the first character
on the next read. At least one character of push-back is allowed.
gzungetc() returns the character pushed, or -1 on failure. gzungetc() will
fail if c is -1, and may fail if a character has been pushed but not read
yet. If gzungetc is used immediately after gzopen or gzdopen, at least the
output buffer size of pushed characters is allowed. (See gzbuffer above.)
The pushed character will be discarded if the stream is repositioned with
gzseek() or gzrewind().
*)
Function gzflush(aFile: gzFile; flush: int): int; cdecl; external;
(*
Flushes all pending output into the compressed file. The parameter flush
is as in the deflate() function. The return value is the zlib error number
(see function gzerror below). gzflush is only permitted when writing.
If the flush parameter is Z_FINISH, the remaining data is written and the
gzip stream is completed in the output. If gzwrite() is called again, a new
gzip stream will be started in the output. gzread() is able to read such
concatenated gzip streams.
gzflush should be called only when strictly necessary because it will
degrade compression if called too often.
*)
Function gzseek(aFile: gzFile; offset: z_off_t; whence: int): z_off_t; cdecl; external;
(*
Sets the starting position for the next gzread or gzwrite on the given
compressed file. The offset represents a number of bytes in the
uncompressed data stream. The whence parameter is defined as in lseek(2);
the value SEEK_END is not supported.
If the file is opened for reading, this function is emulated but can be
extremely slow. If the file is opened for writing, only forward seeks are
supported; gzseek then compresses a sequence of zeroes up to the new
starting position.
gzseek returns the resulting offset location as measured in bytes from
the beginning of the uncompressed stream, or -1 in case of error, in
particular if the file is opened for writing and the new starting position
would be before the current position.
*)
Function gzrewind(aFile: gzFile): int; cdecl; external;
(*
Rewinds the given file. This function is supported only for reading.
gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
*)
Function gztell(aFile: gzFile): z_off_t; cdecl; external;
(*
Returns the starting position for the next gzread or gzwrite on the given
compressed file. This position represents a number of bytes in the
uncompressed data stream, and is zero when starting, even if appending or
reading a gzip stream from the middle of a file using gzdopen().
gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
*)
Function gzoffset(aFile: gzFile): z_off_t; cdecl; external;
(*
Returns the current offset in the file being read or written. This offset
includes the count of bytes that precede the gzip stream, for example when
appending or when using gzdopen() for reading. When reading, the offset
does not include as yet unused buffered input. This information can be used
for a progress indicator. On error, gzoffset() returns -1.
*)
Function gzeof(aFile: gzFile): int; cdecl; external;
(*
Returns true (1) if the end-of-file indicator has been set while reading,
false (0) otherwise. Note that the end-of-file indicator is set only if the
read tried to go past the end of the input, but came up short. Therefore,
just like feof(), gzeof() may return false even if there is no more data to
read, in the event that the last read request was for the exact number of
bytes remaining in the input file. This will happen if the input file size
is an exact multiple of the buffer size.
If gzeof() returns true, then the read functions will return no more data,
unless the end-of-file indicator is reset by gzclearerr() and the input file
has grown since the previous end of file was detected.
*)
Function gzdirect(aFile: gzFile): int; cdecl; external;
(*
Returns true (1) if file is being copied directly while reading, or false
(0) if file is a gzip stream being decompressed.
If the input file is empty, gzdirect() will return true, since the input
does not contain a gzip stream.
If gzdirect() is used immediately after gzopen() or gzdopen() it will
cause buffers to be allocated to allow reading the file to determine if it
is a gzip file. Therefore if gzbuffer() is used, it should be called before
gzdirect().
When writing, gzdirect() returns true (1) if transparent writing was
requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note:
gzdirect() is not needed when writing. Transparent writing must be
explicitly requested, so the application already knows the answer. When
linking statically, using gzdirect() will include all of the zlib code for
gzip file reading and decompression, which may not be desired.)
*)
Function gzclose(aFile: gzFile): int; cdecl; external;
(*
Flushes all pending output if necessary, closes the compressed file and
deallocates the (de)compression state. Note that once file is closed, you
cannot call gzerror with file, since its structures have been deallocated.
gzclose must not be called more than once on the same file, just as free
must not be called more than once on the same allocation.
gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
last read ended in the middle of a gzip stream, or Z_OK on success.
*)
Function gzclose_r(aFile: gzFile): int; cdecl; external;
Function gzclose_w(aFile: gzFile): int; cdecl; external;
(*
Same as gzclose(), but gzclose_r() is only for use when reading, and
gzclose_w() is only for use when writing or appending. The advantage to
using these instead of gzclose() is that they avoid linking in zlib
compression or decompression code that is not used when only reading or only
writing respectively. If gzclose() is used, then both compression and
decompression code will be included the application when linking to a static
zlib library.
*)
Function gzerror(aFile: gzFile; errnum: pint): PAnsiChar; cdecl; external;
(*
Returns the error message for the last error which occurred on the given
compressed file. errnum is set to zlib error number. If an error occurred
in the file system and not in the compression library, errnum is set to
Z_ERRNO and the application may consult errno to get the exact error code.
The application must not modify the returned string. Future calls to
this function may invalidate the previously returned string. If file is
closed, then the string previously returned by gzerror will no longer be
available.
gzerror() should be used to distinguish errors from end-of-file for those
functions above that do not distinguish those cases in their return values.
*)
procedure gzclearerr(aFile: gzFile); cdecl; external;
(*
Clears the error and end-of-file flags for file. This is analogous to the
clearerr() function in stdio. This is useful for continuing to read a gzip
file that is being written concurrently.
*)
(* checksum functions *)
(*
These functions are not related to compression but are exported
anyway because they might be useful in applications using the compression
library.
*)
{$ENDIF GZIP_Support}
Function adler32(adler: uLong; buf: PByte; len: uInt): uLong; cdecl; external;
(*
Update a running Adler-32 checksum with the bytes buf[0..len-1] and
return the updated checksum. If buf is Z_NULL, this function returns the
required initial value for the checksum.
An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed
much faster.
Usage example:
uLong adler = adler32(0L, Z_NULL, 0);
while (read_buffer(buffer, length) != EOF) {
adler = adler32(adler, buffer, length);
}
if (adler != original_adler) error();
*)
Function adler32_z(adler: uLong; buf: PByte; len: z_size_t): uLong; cdecl; external;
(*
Same as adler32(), but with a size_t length.
*)
Function adler32_combine(adler1, adler2: uLong; len2: z_off_t): uLong; cdecl; external;
(*
Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note
that the z_off_t type (like off_t) is a signed integer. If len2 is
negative, the result has no meaning or utility.
*)
Function crc32(crc: uLong; buf: PByte; len: uInt): uLong; cdecl; external;
(*
Update a running CRC-32 with the bytes buf[0..len-1] and return the
updated CRC-32. If buf is Z_NULL, this function returns the required
initial value for the crc. Pre- and post-conditioning (one's complement) is
performed within this function so it shouldn't be done by the application.
Usage example:
uLong crc = crc32(0L, Z_NULL, 0);
while (read_buffer(buffer, length) != EOF) {
crc = crc32(crc, buffer, length);
}
if (crc != original_crc) error();
*)
Function crc32_z(crc: uLong; buf: PByte; len: z_size_t): uLong; cdecl; external;
(*
Same as crc32(), but with a size_t length.
*)
Function crc32_combine(crc1, crc2: uLong; len2: z_off_t): uLong; cdecl; external;
(*
Combine two CRC-32 check values into one. For two sequences of bytes,
seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
len2.
*)
(* various hacks, don't look :) *)
(* deflateInit and inflateInit are macros to allow checking the zlib version
* and the compiler's view of z_stream:
*)
Function deflateInit_(strm: z_streamp; level: int; version: PAnsiChar; stream_size: int): int; cdecl; external;
Function inflateInit_(strm: z_streamp; version: PAnsiChar; stream_size: int): int; cdecl; external;
Function deflateInit2_(strm: z_streamp; level, method, windowBits, memLevel, strategy: int; version: PAnsiChar; stream_size: int): int; cdecl; external;
Function inflateInit2_(strm: z_streamp; windowBits: int; version: PAnsiChar; stream_size: int): int; cdecl; external;
Function inflateBackInit_(strm: z_streamp; windowBits: int; window: PByte; version: PAnsiChar; stream_size: int): int; cdecl; external;
{$IFDEF GZIP_Support}
(* gzgetc() macro and its supporting function and exposed data structure. Note
* that the real internal state is much larger than the exposed structure.
* This abbreviated structure exposes just enough for the gzgetc() macro. The
* user should not mess with these exposed elements, since their names or
* behavior could change in the future, perhaps even capriciously. They can
* only be used by the gzgetc() macro. You have been warned.
*)
Function gzgetc_(aFile: gzFile): int; cdecl; external; (* backward compatibility *)
(* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
* change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
* both are true, the application gets the *64 functions, and the regular
* functions are changed to 64 bits) -- in case these are set on systems
* without large file support, _LFS64_LARGEFILE must also be true
*)
Function gzopen64(path: PAnsiChar; mode: PAnsiChar): gzFile; cdecl; external;
Function gzseek64(aFile: gzFile; offset: z_off64_t; whence: int): z_off64_t; cdecl; external;
Function gztell64(aFile: gzFile): z_off64_t; cdecl; external;
Function gzoffset64(aFile: gzFile): z_off64_t; cdecl; external;
{$ENDIF GZIP_Support}
Function adler32_combine64(adler1, adler2: uLong; len2: z_off64_t): uLong; cdecl; external;
Function crc32_combine64(crc1, crc2: uLong; len2: z_off64_t): uLong; cdecl; external;
(* undocumented functions *)
Function zError(errnum: int): PAnsiChar; cdecl; external;
Function inflateSyncPoint(strm: z_streamp): int; cdecl; external;
Function get_crc_table: pz_crc_t; cdecl; external;
Function inflateUndermine(strm: z_streamp; subvert: int): int; cdecl; external;
Function inflateValidate(strm: z_streamp; check: int): int; cdecl; external;
Function inflateCodesUsed(strm: z_streamp): UInt32; cdecl; external;
Function inflateResetKeep(strm: z_streamp): int; cdecl; external;
Function deflateResetKeep(strm: z_streamp): int; cdecl; external;
{$IF Defined(GZIP_Support) and Defined(Windows)}
Function gzopen_w(path: PWideChar; mode: PAnsiChar): gzFile; cdecl; external;
{$IFEND}
implementation
{$IFDEF Linux}
{$LINKLIB libc}
{$IFDEF x86}
{$LINKLIB gcc_s}
{$ENDIF}
{$ENDIF}
{$IFDEF GZIP_Support}
uses
{$IFDEF Windows}Windows,{$ENDIF} SysUtils;
{$ENDIF GZIP_Support}
//== Macro implementation ======================================================
Function deflateInit(strm: z_streamp; level: int): int;
begin
Result := deflateInit_(strm,level,PAnsiChar(ZLIB_VERSION),SizeOf(z_stream_s));
end;
//------------------------------------------------------------------------------
Function inflateInit(strm: z_streamp): int;
begin
Result := inflateInit_(strm,PAnsiChar(ZLIB_VERSION),SizeOf(z_stream_s));
end;
//------------------------------------------------------------------------------
Function deflateInit2(strm: z_streamp; level, method, windowBits, memLevel, strategy: int): int;
begin
Result := deflateInit2_(strm,level,method,windowBits,memLevel,strategy,PAnsiChar(ZLIB_VERSION),SizeOf(z_stream_s));
end;
//------------------------------------------------------------------------------
Function inflateInit2(strm: z_streamp; windowBits: int): int;
begin
Result := inflateInit2_(strm,windowBits,PAnsiChar(ZLIB_VERSION),SizeOf(z_stream_s));
end;
//------------------------------------------------------------------------------
Function inflateBackInit(strm: z_streamp; windowBits: int; window: PByte): int;
begin
Result := inflateBackInit_(strm,windowBits,window,PAnsiChar(ZLIB_VERSION),SizeOf(z_stream_s));
end;
//== Object files linking ======================================================
{$IFDEF Windows}
// windows binaries
{$IFDEF x64}
{$IFDEF GZIP_Support}
{$LINK 'zlib_win64\gzclose.o'}
{$LINK 'zlib_win64\gzwrite.o'}
{$LINK 'zlib_win64\gzread.o'}
{$LINK 'zlib_win64\gzlib.o'}
{$ENDIF GZIP_Support}
{$LINK 'zlib_win64\uncompr.o'}
{$LINK 'zlib_win64\compress.o'}
{$LINK 'zlib_win64\deflate.o'}
{$LINK 'zlib_win64\inflate.o'}
{$LINK 'zlib_win64\infback.o'}
{$LINK 'zlib_win64\inftrees.o'}
{$LINK 'zlib_win64\inffast.o'}
{$LINK 'zlib_win64\trees.o'}
{$LINK 'zlib_win64\crc32.o'}
{$LINK 'zlib_win64\adler32.o'}
{$LINK 'zlib_win64\zutil.o'}
{$ELSE}
{$IFDEF FPC}
{$IFDEF GZIP_Support}
{$LINK 'zlib_win32\gzclose.o'}
{$LINK 'zlib_win32\gzwrite.o'}
{$LINK 'zlib_win32\gzread.o'}
{$LINK 'zlib_win32\gzlib.o'}
{$ENDIF GZIP_Support}
{$LINK 'zlib_win32\uncompr.o'}
{$LINK 'zlib_win32\compress.o'}
{$LINK 'zlib_win32\deflate.o'}
{$LINK 'zlib_win32\inflate.o'}
{$LINK 'zlib_win32\infback.o'}
{$LINK 'zlib_win32\inftrees.o'}
{$LINK 'zlib_win32\inffast.o'}
{$LINK 'zlib_win32\trees.o'}
{$LINK 'zlib_win32\crc32.o'}
{$LINK 'zlib_win32\adler32.o'}
{$LINK 'zlib_win32\zutil.o'}
{$ELSE}
{$IFDEF GZIP_Support}
{$LINK 'zlib_win32\gzclose.obj'}
{$LINK 'zlib_win32\gzwrite.obj'}
{$LINK 'zlib_win32\gzread.obj'}
{$LINK 'zlib_win32\gzlib.obj'}
{$ENDIF GZIP_Support}
{$LINK 'zlib_win32\uncompr.obj'}
{$LINK 'zlib_win32\compress.obj'}
{$LINK 'zlib_win32\deflate.obj'}
{$LINK 'zlib_win32\inflate.obj'}
{$LINK 'zlib_win32\infback.obj'}
{$LINK 'zlib_win32\inftrees.obj'}
{$LINK 'zlib_win32\inffast.obj'}
{$LINK 'zlib_win32\trees.obj'}
{$LINK 'zlib_win32\crc32.obj'}
{$LINK 'zlib_win32\adler32.obj'}
{$LINK 'zlib_win32\zutil.obj'}
{$ENDIF}
{$ENDIF}
{$ELSE}
// linux binaries
{$IFDEF x64}
{$IFDEF GZIP_Support}
{$LINK 'zlib_lin64\gzclose.o'}
{$LINK 'zlib_lin64\gzwrite.o'}
{$LINK 'zlib_lin64\gzread.o'}
{$LINK 'zlib_lin64\gzlib.o'}
{$ENDIF GZIP_Support}
{$LINK 'zlib_lin64\uncompr.o'}
{$LINK 'zlib_lin64\compress.o'}
{$LINK 'zlib_lin64\deflate.o'}
{$LINK 'zlib_lin64\inflate.o'}
{$LINK 'zlib_lin64\infback.o'}
{$LINK 'zlib_lin64\inftrees.o'}
{$LINK 'zlib_lin64\inffast.o'}
{$LINK 'zlib_lin64\trees.o'}
{$LINK 'zlib_lin64\crc32.o'}
{$LINK 'zlib_lin64\adler32.o'}
{$LINK 'zlib_lin64\zutil.o'}
{$ELSE}
{$IFDEF GZIP_Support}
{$LINK 'zlib_lin32\gzclose.o'}
{$LINK 'zlib_lin32\gzwrite.o'}
{$LINK 'zlib_lin32\gzread.o'}
{$LINK 'zlib_lin32\gzlib.o'}
{$ENDIF GZIP_Support}
{$LINK 'zlib_lin32\uncompr.o'}
{$LINK 'zlib_lin32\compress.o'}
{$LINK 'zlib_lin32\deflate.o'}
{$LINK 'zlib_lin32\inflate.o'}
{$LINK 'zlib_lin32\infback.o'}
{$LINK 'zlib_lin32\inftrees.o'}
{$LINK 'zlib_lin32\inffast.o'}
{$LINK 'zlib_lin32\trees.o'}
{$LINK 'zlib_lin32\crc32.o'}
{$LINK 'zlib_lin32\adler32.o'}
{$LINK 'zlib_lin32\zutil.o'}
{$ENDIF}
{$ENDIF}
//== Public functions required by linked object files ==========================
{$IFDEF Windows}
Function memcpy(Dst,Src: Pointer; Count: size_t): Pointer; cdecl;{$IFDEF FPC} public;{$ENDIF}
begin
Move(Src^,Dst^,Count);
Result := Dst;
end;
//------------------------------------------------------------------------------
Function memset(Ptr: Pointer; Value: int; Count: size_t): Pointer; cdecl;{$IFDEF FPC} public;{$ENDIF}
begin
FillChar(Ptr^,Count,Byte(Value));
Result := Ptr;
end;
//------------------------------------------------------------------------------
Function malloc(Size: size_t): Pointer; cdecl;{$IFDEF FPC} public;{$ENDIF}
begin
GetMem(Result,Size);
end;
//------------------------------------------------------------------------------
procedure free(Ptr: Pointer); cdecl;{$IFDEF FPC} public;{$ENDIF}
begin
FreeMem(Ptr);
end;
{$ENDIF Windows}
//------------------------------------------------------------------------------
{$IF not Defined(FPC) and not Defined(x64)} // 32bit Delphi
Function _allrem(a,b: Int64): Int64; cdecl;
begin
Result := a mod b;
end;
{$IFEND}
//== Functions redirected to msvcrt.dll ========================================
{$IF Defined(GZIP_Support) and Defined(Windows)}
var
CRT_LibHandle: THandle = 0;
CRT_libfunc_strlen: Pointer;
CRT_libfunc_open: Pointer;
CRT_libfunc_lseek: Pointer;
CRT_libfunc_wcstombs: Pointer;
CRT_libfunc_wopen: Pointer;
CRT_libfunc_vsnprintf: Pointer;
CRT_libfunc_close: Pointer;
CRT_libfunc_memchr: Pointer;
CRT_libfunc_read: Pointer;
CRT_libfunc_strerror: Pointer;
CRT_libfunc_errno: Pointer;
CRT_libfunc_write: Pointer;
CRT_libfunc_snprintf: Pointer;
//------------------------------------------------------------------------------
procedure CRT_Initialize;
begin
If CRT_LibHandle = 0 then
begin
CRT_LibHandle := LoadLibraryEx(PChar('msvcrt.dll'),0,0);
If CRT_LibHandle <> 0 then
begin
CRT_libfunc_strlen := GetCheckProcAddress(CRT_LibHandle,'strlen');
CRT_libfunc_open := GetCheckProcAddress(CRT_LibHandle,'_open');
CRT_libfunc_lseek := GetCheckProcAddress(CRT_LibHandle,'_lseek');
CRT_libfunc_wcstombs := GetCheckProcAddress(CRT_LibHandle,'wcstombs');
CRT_libfunc_wopen := GetCheckProcAddress(CRT_LibHandle,'_wopen');
CRT_libfunc_vsnprintf := GetCheckProcAddress(CRT_LibHandle,'_vsnprintf');
CRT_libfunc_close := GetCheckProcAddress(CRT_LibHandle,'_close');
CRT_libfunc_memchr := GetCheckProcAddress(CRT_LibHandle,'memchr');
CRT_libfunc_read := GetCheckProcAddress(CRT_LibHandle,'_read');
CRT_libfunc_strerror := GetCheckProcAddress(CRT_LibHandle,'strerror');
CRT_libfunc_errno := GetCheckProcAddress(CRT_LibHandle,'_errno');
CRT_libfunc_write := GetCheckProcAddress(CRT_LibHandle,'_write');
CRT_libfunc_snprintf := GetCheckProcAddress(CRT_LibHandle,'_snprintf');
end
else raise EZLibException.Create('ZLib/Initialize: Unable to load msvcrt.dll');
end;
end;
//------------------------------------------------------------------------------
procedure CRT_Finalize;
begin
If CRT_LibHandle <> 0 then
begin
FreeLibrary(CRT_LibHandle);
CRT_LibHandle := 0;
end;
end;
//==============================================================================
{$STACKFRAMES OFF}
const
{$IFDEF x64}
SymbolPrefix = '';
{$ELSE}
SymbolPrefix = '_';
{$ENDIF}
//------------------------------------------------------------------------------
procedure strlen; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_strlen]
{$ELSE}
JMP CRT_libfunc_strlen
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure open; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_open]
{$ELSE}
JMP CRT_libfunc_open
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure lseek; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_lseek]
{$ELSE}
JMP CRT_libfunc_lseek
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure wcstombs; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_wcstombs]
{$ELSE}
JMP CRT_libfunc_wcstombs
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure _wopen; cdecl;{$IFDEF FPC} public name '__imp_' + SymbolPrefix + '_wopen';{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_wopen]
{$ELSE}
JMP CRT_libfunc_wopen
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure vsnprintf; cdecl;{$IFDEF FPC} public name SymbolPrefix + '__ms_vsnprintf';{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_vsnprintf]
{$ELSE}
JMP CRT_libfunc_vsnprintf
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure close; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_close]
{$ELSE}
JMP CRT_libfunc_close
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure memchr; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_memchr]
{$ELSE}
JMP CRT_libfunc_memchr
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure read; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_read]
{$ELSE}
JMP CRT_libfunc_read
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure strerror; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_strerror]
{$ELSE}
JMP CRT_libfunc_strerror
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure __errno; cdecl;{$IFDEF FPC} public name '__imp_' + SymbolPrefix + '_errno';{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_errno]
{$ELSE}
JMP CRT_libfunc_errno
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure write; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_write]
{$ELSE}
JMP CRT_libfunc_write
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure snprintf; cdecl;{$IFDEF FPC} public;{$ENDIF} assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFDEF x64}
{$IFNDEF FPC}.NOFRAME{$ENDIF}
JMP [RIP + CRT_libfunc_snprintf]
{$ELSE}
JMP CRT_libfunc_snprintf
{$ENDIF}
end;
{$IFEND}
//==============================================================================
initialization
{$IFDEF CheckCompatibility)}
CheckCompatibility(zlibCompileFlags);
{$ENDIF}
{$IF Defined(GZIP_Support) and Defined(Windows)}
CRT_Initialize;
{$IFEND}
finalization
{$IF Defined(GZIP_Support) and Defined(Windows)}
CRT_Finalize;
{$IFEND}
end.
|
unit stmFifoError;
interface
uses classes, sysUtils,
util1, stmDef,
debug0,ErrorForm1;
Const
MaxError=20;
type
TFifoError=class
private
strings: TStringList;
ad: Tlist;
line: Tlist;
stF: TStringList;
FifoIn:integer;
public
constructor create;
destructor destroy;override;
function Put(st:AnsiString;aderror:integer;ErrorLine:integer;stFile:string):integer;
function get(i:integer;var stFile:string; var ErrorLine,AdError: integer): AnsiString;
function getLine(i:integer;var stFile:string; var ErrorLine,AdError: integer): AnsiString;
procedure DisplayHistory;
procedure ClearMessages;
end;
var
FifoError:TFifoError;
GenericExeError:AnsiString;
implementation
constructor TfifoError.create;
begin
strings:=TstringList.Create;
stF:=TstringList.Create;
line:=Tlist.Create;
ad:= Tlist.Create;
end;
destructor TfifoError.destroy;
begin
strings.Free;
stF.Free;
line.Free;
ad.Free;
end;
function TfifoError.Put(st:AnsiString;aderror:integer;ErrorLine:integer;stFile:string):integer;
begin
strings.AddObject(st,pointer(FifoIn));
ad.Add(pointer( adError));
line.Add( pointer(ErrorLine));
stF.Add(stFile);
result:=FifoIn;
inc(FifoIn);
ErrorForm.SetLineCount(Strings.Count);
end;
function TfifoError.getLine(i:integer;var stFile:string; var ErrorLine,AdError: integer ): AnsiString;
begin
if (i<0) or (i>=strings.Count) then
begin
result:='';
stFile:='';
ErrorLine:=0;
AdError:=0;
end
else
begin
result:=strings[i];
AdError:= intG(Ad[i]);
ErrorLine:= intG(line[i]);
stFile:= stF[i];
if not fileExists(stFile) then stFile:= FindFileInPathList(stFile,Pg2SearchPath);
end;
end;
function TfifoError.get(i:integer;var stFile:string; var ErrorLine,AdError: integer ): AnsiString;
begin
i:=strings.IndexOfObject(pointer(i));
result:= getLine(i,stFile, errorLine, AdError);
end;
procedure TFifoError.DisplayHistory;
begin
errorForm.show;
end;
procedure TfifoError.ClearMessages;
begin
strings.Clear;
stF.Clear;
line.Clear;
ad.Clear;
ErrorForm.SetLineCount(Strings.Count);
end;
Initialization
AffDebug('Initialization stmFifoError',0);
FifoError:=TFifoError.create;
finalization
FifoError.free;
end.
|
(*
Category: SWAG Title: TEXT/GRAPHICS COLORS
Original name: 0016.PAS
Description: Setting Text Attr
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:34
*)
{YZ> Does anyone know how to "extract" the foreground and background
YZ> colours from TextAttr?
}
uses crt;
{
Foreground := TextAttr and $0f;
Background := (TextAttr and $f0) shr 4;
}
{A few days ago, I read a message from someone who was trying to extract
foreground and background colors from one Byte Variable. I have since
lost the mail packet, and forgotten the user's name, but here's a
routine that will do that anyways. Hope it gets to the person who was
asking For it......
}
Procedure GetColors(Color : Byte; Var BackGr : Byte; Var ForeGr : Byte);
begin
BackGr := Color shr 4;
ForeGr := Color xor (Backgr shl 4);
end;
var
fc, bc: byte;
begin
textAttr := 30;
WriteLn('Hi!');
fc := TextAttr and $0f;
bc := (TextAttr and $f0) shr 4;
WriteLn('FC=',fc,' BC=',bc);
textcolor(fc);
textbackground(bc);
WriteLn('Hi 2!');
GetColors(TextAttr, bc, fc);
WriteLn('FC=',fc,' BC=',bc);
textcolor(fc);
textbackground(bc);
WriteLn('Hi 3!');
end.
|
unit Win32.AMAudio;
//------------------------------------------------------------------------------
// File: AMAudio.h
// Desc: Audio related definitions and interfaces for ActiveMovie.
// Copyright (c) 1992 - 2001, Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
{$mode delphi}
interface
uses
Windows, Classes, SysUtils,
Win32.DSound;
type
// This is the interface the audio renderer supports to give the application
// access to the direct sound object and buffers it is using, to allow the
// application to use things like the 3D features of Direct Sound for the
// soundtrack of a movie being played with Active Movie
IAMDirectSound = interface(IUnknown)
['{546F4260-D53E-11cf-B3F0-00AA003761C5}']
(* IAMDirectSound methods *)
function GetDirectSoundInterface(out lplpds: PDIRECTSOUND): HResult; stdcall;
function GetPrimaryBufferInterface(out lplpdsb: PDIRECTSOUNDBUFFER): HResult; stdcall;
function GetSecondaryBufferInterface(out lplpdsb: PDIRECTSOUNDBUFFER): HResult; stdcall;
function ReleaseDirectSoundInterface(lpds: PDIRECTSOUND): HResult; stdcall;
function ReleasePrimaryBufferInterface(lpdsb: PDIRECTSOUNDBUFFER): HResult; stdcall;
function ReleaseSecondaryBufferInterface(lpdsb: PDIRECTSOUNDBUFFER): HResult; stdcall;
function SetFocusWindow(hwnd: HWND; bMixingOnOrOff: BOOL): HResult; stdcall;
function GetFocusWindow(out hwnd: HWND; out bMixingOnOrOff: BOOL): HResult; stdcall;
end;
// Validate WAVEFORMATEX block of length cb
function AMValidateAndFixWaveFormatEx(var pwfx:TWAVEFORMATEX; cb:DWORD):HRESULT;
implementation
// Validate WAVEFORMATEX block of length cb
function AMValidateAndFixWaveFormatEx(var pwfx:TWAVEFORMATEX; cb:DWORD):HRESULT; inline;
begin
(* ToDo
if (cb < sizeof(TPCMWAVEFORMAT)) then begin
result:= E_INVALIDARG;
Exit;
end;
if (pwfx.wFormatTag <> WAVE_FORMAT_PCM) then begin
if (cb < sizeof(TWAVEFORMATEX)) then begin
result:= E_INVALIDARG;
Exit;
end;
if (cb < sizeof(TWAVEFORMATEX) + pwfx.cbSize )then begin
pwfx.cbSize = 0;
end;
end;
// Sanity check
if (pwfx.nAvgBytesPerSec > 10000000) or (pwfx.nAvgBytesPerSec = 0) then begin
pwfx.nAvgBytesPerSec := 176400;
end;
if (pwfx.nChannels > 32) then begin
pwfx.nChannels := 1;
end;
*)
result:= S_OK;
end;
end.
|
unit uParamObject;
interface
uses
Classes, SysUtils, Variants, DBClient, superobject;
type
//参数定义
TGParam = record
ParamName: string;
ParamValue: Variant;
IsSystem: Boolean;
end;
//参数数组
TGParams = array of TGParam;
TParamObject = class(TObject)
private
FParams: TGParams;
FCount: Integer;
procedure SetParams(Value: TGParams);
public
constructor Create;
procedure Assign(Source: TObject);
procedure SetValue(AParamName: string; AParamValue: Variant; AddWhenNotExist: Boolean = True);
procedure Add(AParamName: string; AParamValue: Variant; IsSystem: Boolean = False); //先查找,有就修改没有就增加。
procedure Clear; //只清空非系统级的
function AsString(AParamName: string): string;
function AsInteger(AParamName: string): Integer;
function AsBoolean(AParamName: string): Boolean;
function AsFloat(AParamName: string): double;
function AsVariant(AParamName: string): Variant;
property Params: TGParams read FParams write SetParams;
property Count: Integer read FCount write FCount;
destructor Destroy; override;
end;
TParamDataEvent = procedure(ASender: TObject; AList: TParamObject) of object;
function ParamObjectToJson(APB: TParamObject): ISuperObject;
function PackageToJson(AProcName: string; AJson: ISuperObject): ISuperObject;
function ParamObjectToString(APB: TParamObject): string;
procedure ClientDataSetToParamObject(AData: TClientDataSet; AList: TParamObject); //数据转换
implementation
function ParamObjectToString(APB: TParamObject): string;
var
i: Integer;
aToStr: string;
begin
aToStr := '';
for i := 0 to APB.Count - 1 do
begin
if Trim(APB.Params[i].ParamName) = EmptyStr then Continue;
case VarType(APB.Params[i].ParamValue) of
varString: aToStr := aToStr + '[' + APB.Params[i].ParamName + ':''' + APB.Params[i].ParamValue + ''']';
varDouble: aToStr := aToStr + '[' + APB.Params[i].ParamName + ':' + FloatToStr(APB.Params[i].ParamValue) + ']';
varInteger, varShortInt, varByte, varWord, varLongWord, varInt64:
aToStr := aToStr + '[' + APB.Params[i].ParamName + ':' + IntToStr(APB.Params[i].ParamValue) + ']';
else
aToStr := aToStr + '[' + APB.Params[i].ParamName + ':''' + APB.Params[i].ParamValue + ''']';
end;
end;
Result := aToStr;
end;
function ParamObjectToJson(APB: TParamObject): ISuperObject;
var
i: Integer;
aJson: ISuperObject;
begin
aJson := SO();
for i := 0 to APB.Count - 1 do
begin
if Trim(APB.Params[i].ParamName) = EmptyStr then Continue;
case VarType(APB.Params[i].ParamValue) of
varString: aJson.S[APB.Params[i].ParamName] := APB.Params[i].ParamValue;
varDouble: aJson.D[APB.Params[i].ParamName] := APB.Params[i].ParamValue;
varInteger, varShortInt, varByte, varWord, varLongWord, varInt64:
aJson.I[APB.Params[i].ParamName] := APB.Params[i].ParamValue;
else
aJson.S[APB.Params[i].ParamName] := APB.Params[i].ParamValue;
end;
end;
Result := aJson;
end;
function PackageToJson(AProcName: string; AJson: ISuperObject): ISuperObject;
var
aPackageJson: ISuperObject;
begin
aPackageJson := SO();
aPackageJson.S['ProcName'] := AProcName;
aPackageJson.O['Params'] := AJson;
Result := aPackageJson;
end;
{ TParamObject }
procedure TParamObject.Add(AParamName: string; AParamValue: Variant; IsSystem: Boolean = False);
var
I: Integer;
bExists: Boolean;
begin
bExists := False;
for I := Low(FParams) to High(FParams) do
begin
if AnsiCompareStr(LowerCase(AParamName), LowerCase(FParams[I].ParamName)) = 0 then
begin
bExists := True;
Break;
end;
end;
if bExists then
begin
//参数存在,修改参数值
FParams[I].ParamValue := AParamValue;
end
else
begin
//参数不存在,新增参数
bExists := False;
for I := Low(FParams) to High(FParams) do
begin
if AnsiCompareStr('', LowerCase(FParams[I].ParamName)) = 0 then
begin
bExists := True;
Break;
end;
end;
if bExists then
begin
//填补空值
FParams[I].ParamName := AParamName;
FParams[I].ParamValue := AParamValue;
FParams[I].IsSystem := IsSystem;
end
else
begin
Inc(FCount);
SetLength(FParams, FCount);
I := High(FParams);
FParams[I].ParamName := AParamName;
FParams[I].ParamValue := AParamValue;
FParams[I].IsSystem := IsSystem;
end;
end;
end;
function TParamObject.AsBoolean(AParamName: string): Boolean;
var
V: Variant;
begin
V := AsVariant(AParamName);
if VarIsNull(V) then
Result := False
else
Result := V;
end;
function TParamObject.AsFloat(AParamName: string): double;
var
V: Variant;
begin
V := AsVariant(AParamName);
if VarIsNull(V) then
Result := 0.00
else
Result := V;
end;
function TParamObject.AsInteger(AParamName: string): Integer;
var
V: Variant;
begin
V := AsVariant(AParamName);
if VarIsNull(V) then
Result := 0
else
Result := V;
end;
procedure TParamObject.Assign(Source: TObject);
var
i: Integer;
aTGParam: TGParam;
begin
if not (Source is TParamObject) then Exit;
Self.Clear;
for i := 0 to TParamObject(Source).Count - 1 do
begin
aTGParam := TParamObject(Source).Params[i];
Add(aTGParam.ParamName, aTGParam.ParamValue, aTGParam.IsSystem);
end;
end;
function TParamObject.AsString(AParamName: string): string;
var
V: Variant;
begin
V := AsVariant(AParamName);
if VarIsNull(V) then
Result := ''
else
Result := V;
end;
function TParamObject.AsVariant(AParamName: string): Variant;
var
I: Integer;
bExists: Boolean;
begin
Result := null;
bExists := False;
for I := Low(FParams) to High(FParams) do
begin
if AnsiCompareStr(LowerCase(AParamName), LowerCase(FParams[I].ParamName)) = 0 then
begin
bExists := True;
Result := FParams[I].ParamValue;
Break;
end;
end;
end;
procedure TParamObject.Clear;
var
I: Integer;
begin
for I := Low(FParams) to High(FParams) do
begin
if not FParams[I].IsSystem then
begin
FParams[I].ParamName := '';
FParams[I].ParamValue := null;
FParams[I].IsSystem := False;
end;
end;
end;
constructor TParamObject.Create;
begin
inherited;
FParams := nil;
FCount := 0;
end;
destructor TParamObject.Destroy;
begin
SetLength(FParams, 0);
FParams := nil;
FCount := 0;
inherited;
end;
procedure TParamObject.SetParams(Value: TGParams);
var
I: Integer;
begin
if Value = nil then Exit;
if FParams <> Value then
begin
for I := Low(Value) to High(Value) do
begin
Add(Value[I].ParamName, Value[I].ParamValue, Value[I].IsSystem);
end;
end;
end;
procedure TParamObject.SetValue(AParamName: string; AParamValue: Variant; AddWhenNotExist: Boolean);
var I: Integer;
begin
for I := Low(FParams) to High(FParams) do
begin
if AnsiCompareStr(LowerCase(AParamName), LowerCase(FParams[I].ParamName)) = 0 then
begin
FParams[I].ParamValue := AParamValue;
Exit;
end;
end;
if AddWhenNotExist then
Add(AParamName, AParamValue, False);
end;
procedure ClientDataSetToParamObject(AData: TClientDataSet;
AList: TParamObject);
var
aCol: Integer;
aName, aValues: string;
begin
if not Assigned(AList) then Exit;
if not Assigned(AData) then Exit;
if AData.IsEmpty then Exit;
AList.Clear;
AData.First;
for aCol := 0 to AData.FieldCount - 1 do
begin
aName := AData.FieldDefs[aCol].Name;
aValues := AData.FieldList[acol].AsString;
AList.Add(aName, aValues);
end;
end;
end.
|
unit uMain;
interface
uses
{$IF DEFINED(android)}
Androidapi.Helpers,
FMX.Helpers.Android,
{$ENDIF}
FMX.VirtualKeyboard,
FMX.Platform,
FMX.DialogService.Async,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Effects, FMX.Objects, FMX.Controls.Presentation, FMX.TabControl,
FMX.MultiView, FMX.Layouts, FMX.ScrollBox, FMX.Memo, FMX.Ani, FMX.ListBox,
FMX.Colors, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error,
FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool,
FireDAC.Stan.Async, FireDAC.Phys, FireDAC.FMXUI.Wait, Data.DB,
FireDAC.Comp.Client, System.ImageList, FMX.ImgList;
type
TForm2 = class(TForm)
TabControl: TTabControl;
TabHome: TTabItem;
TabCadastro: TTabItem;
ToolBar1: TToolBar;
BarraTitulo: TRectangle;
ShadowEffect1: TShadowEffect;
BotaoMenu: TSpeedButton;
Menu: TMultiView;
Layout1: TLayout;
Memo1: TMemo;
MenuCadastro: TRectangle;
BotaoCadastro: TSpeedButton;
Label1: TLabel;
BotaoClientes: TSpeedButton;
Rectangle2: TRectangle;
MenuScroll: TVertScrollBox;
MenuFundo: TRectangle;
Rectangle3: TRectangle;
Line1: TLine;
Label2: TLabel;
Line2: TLine;
BotaoFornecedores: TSpeedButton;
Rectangle4: TRectangle;
Label3: TLabel;
Line3: TLine;
MenuLiquidar: TRectangle;
BotaoLiquidar: TSpeedButton;
LabelLiquidarContas: TLabel;
Line4: TLine;
BotaoRecebimento: TSpeedButton;
Rectangle6: TRectangle;
BotaoPagamento: TSpeedButton;
Rectangle7: TRectangle;
Label6: TLabel;
Line6: TLine;
BotaoCategoria: TSpeedButton;
Rectangle8: TRectangle;
Label4: TLabel;
Line7: TLine;
MenuLancamento: TRectangle;
BotaoLancamento: TSpeedButton;
Label7: TLabel;
Line8: TLine;
BotaoReceita: TSpeedButton;
Rectangle10: TRectangle;
Label8: TLabel;
Line9: TLine;
BotaoDespesas: TSpeedButton;
Rectangle11: TRectangle;
Label9: TLabel;
Line10: TLine;
IconeMenu: TImage;
Label10: TLabel;
Label11: TLabel;
Label5: TLabel;
Line5: TLine;
ImageList1: TImageList;
procedure FormCreate(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure BotaoClientesClick(Sender: TObject);
procedure BotaoCadastroClick(Sender: TObject);
procedure BotaoCategoriaClick(Sender: TObject);
procedure BotaoFornecedoresClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Voltar;
procedure MenuAparencia(MenuRet : TRectangle);
procedure Style(Cor :TAlphaColor = TAlphaColorRec.Cornflowerblue);
procedure SQLiteDB;
procedure ExitClick(Sender :TObject);
end;
var
Form2: TForm2;
implementation
{$R *.fmx}
uses FMX.Fast;
procedure TForm2.FormCreate(Sender: TObject);
begin
TabControl.TabPosition := TTabPosition.None;
TabControl.GotoVisibleTab(0);
Style(TAlphaColorRec.Darkred);
ListIcons := ImageList1;
end;
procedure TForm2.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
var
FService : IFMXVirtualKeyboardService;
begin
if Key = vkHardwareBack then begin
TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(FService));
if (FService <> nil) and (TVirtualKeyboardState.Visible in FService.VirtualKeyBoardState) then begin
// Se Botão Voltar pressionado e o teclado estiver visível não faz nada ...
end else begin
Key := 0;
Voltar;
end;
end;
end;
procedure TForm2.MenuAparencia(MenuRet : TRectangle);
var I,J :Integer;
begin
MenuRet.Height := 48;
for I := 0 to MenuRet.ControlsCount - 1 do begin
for J := 0 to (MenuRet.Controls[I]).ControlsCount - 1 do begin
if (MenuRet.Controls[I]).Controls[J].ClassName = 'TLabel' then begin
TLabel((MenuRet.Controls[I]).Controls[J]).FontColor := BarraTitulo.Fill.Color;
TLine(TLabel((MenuRet.Controls[I]).Controls[J]).Controls[0]).Stroke.Color := BarraTitulo.Fill.Color;
end else if (MenuRet.Controls[I]).Controls[J].ClassName = 'TRectangle' then begin
TRectangle((MenuRet.Controls[I]).Controls[J]).Fill.Bitmap.Bitmap.ReplaceOpaqueColor(BarraTitulo.Fill.Color);
end;
end;
end;
end;
procedure TForm2.BotaoCategoriaClick(Sender: TObject);
begin
SQLiteDB;
Dicionario.AddOrSetValue('ID_Cidade','Cidade');
Layout1.AppCadastro('SELECT * FROM Cidade')
.BarTitulo('Cadastro de Cidades')
.CorPadrao( BarraTitulo.Fill.Color)
.IndexFilters('ID,Cidade')
.Criar;
TabControl.GotoVisibleTab(1);
Menu.HideMaster;
end;
procedure TForm2.BotaoClientesClick(Sender: TObject);
begin
SQLiteDB;
Dicionario.AddOrSetValue('ID','Código');
Dicionario.AddOrSetValue('Nome','Nome do Cliente');
Dicionario.AddOrSetValue('Telefone','Celular');
Dicionario.AddOrSetValue('ID_Cidade','Cidade');
Layout1.AppCadastro('SELECT * FROM Cliente ' +
' INNER JOIN Cidade ON Cidade.ID = Cliente.ID_Cidade '
)
.BarTitulo('Cadastro de Clientes')
.CorPadrao( BarraTitulo.Fill.Color)
.IndexFilters('ID,Nome')
.IndexColunas('Nome,Email,Telefone,CPF')
.IndexFields('ID,Nome,CPF,Email,Telefone,ID_Cidade,Ativo')
.Criar;
BotaoExit.OnClick := ExitClick;
TabControl.GotoVisibleTab(1);
Menu.HideMaster;
end;
procedure TForm2.BotaoFornecedoresClick(Sender: TObject);
begin
SQLite.CreateTable('fornecedor')
.Add('ID_Cidade INTEGER,Ativo BOOLEAN')
.AddVARCHAR('CNPJ',20,'CNPJ','Informe o CNPJ',True)
.AddVARCHAR('Email',100)
.AddVARCHAR('Telefone',18)
.AddVARCHAR('Nome',100,'Nome do Fornecedor','Informe o nome do fornecedor')
.Execute;
Layout1.AppCadastro('SELECT fornecedor.ID,'+
' fornecedor.Nome,'+
' fornecedor.CNPJ,'+
' fornecedor.Email,'+
' fornecedor.Telefone,'+
' cidade.* FROM fornecedor ' +
' LEFT JOIN Cidade ON Cidade.ID = fornecedor.ID_Cidade '
)
.BarTitulo('Cadastro de Fornecedor')
.CorPadrao( BarraTitulo.Fill.Color)
.IndexFilters('ID,Nome')
.IndexColunas('Nome,Email,Telefone,CPF')
.IndexFields('ID,Nome,CNPJ,Email,Telefone,ID_Cidade,Ativo')
.Criar;
BotaoExit.OnClick := ExitClick;
TabControl.GotoVisibleTab(1);
Menu.HideMaster;
end;
procedure TForm2.ExitClick(Sender: TObject);
begin
TabControl.GotoVisibleTab(0);
end;
procedure TForm2.SQLiteDB;
begin
Dicionario.AddOrSetValue('ID','Código');
SQLite.ExecSQL('CREATE TABLE IF NOT EXISTS Cliente( '+
' ID INTEGER PRIMARY KEY AUTOINCREMENT, '+
' Nome VARCHAR(100), '+
' CPF VARCHAR(14), '+
' Email VARCHAR(100), '+
' Telefone VARCHAR(18), '+
' ID_Cidade INTEGER ' +
' Ativo BOOLEAN '+
' ); ');
SQLite.ExecSQL('DROP TRIGGER IF EXISTS Validar_Cliente; '+
'CREATE TRIGGER IF NOT EXISTS Validar_Cliente '+
'BEFORE INSERT ON Cliente '+
'BEGIN '+
' SELECT '+
' CASE '+
' WHEN 0 < (select Count(*) from Cliente WHERE CPF = NEW.CPF) THEN RAISE (ABORT,"Cpf já cadastrado ") '+
' WHEN (NEW.Nome IS NULL OR NEW.Nome ="") THEN RAISE (ABORT,"Informe o nome ") '+
' WHEN (NEW.Email IS NULL OR NEW.Email ="") THEN RAISE (ABORT,"Informe o e-mail ") '+
' WHEN (NEW.Telefone IS NULL OR NEW.Telefone ="") THEN RAISE (ABORT,"Informe um telefone ") '+
' END; '+
'END; ');
SQLite.ExecSQL('CREATE TABLE IF NOT EXISTS Cidade( '+
' ID INTEGER PRIMARY KEY AUTOINCREMENT, '+
' Cidade VARCHAR(100)); ');
end;
procedure TForm2.Style(Cor: TAlphaColor);
begin
{$IF DEFINED(android) }
CallInUIThreadAndWaitFinishing(
procedure begin
TAndroidHelper.Activity.getWindow.setStatusBarColor(Cor);
end);
{$ENDIF}
BarraTitulo.Fill.Color := Cor;
MenuAparencia(MenuCadastro);
MenuAparencia(MenuLancamento);
MenuAparencia(MenuLiquidar);
end;
procedure TForm2.Voltar;
begin
if TabControl.TabIndex = 0 then begin
TDialogServiceAsync.MessageDialog(('Sair do aplicativo?'),
system.UITypes.TMsgDlgType.mtConfirmation,
[system.UITypes.TMsgDlgBtn.mbYes, system.UITypes.TMsgDlgBtn.mbNo], system.UITypes.TMsgDlgBtn.mbYes,0,
procedure (const AResult: System.UITypes.TModalResult)
begin
case AResult of
mrYES: begin
Close;
end;
end;
end);
end else begin
TabControl.GotoVisibleTab(0);
end;
end;
procedure TForm2.BotaoCadastroClick(Sender: TObject);
begin
if TSpeedButton(Sender).Height = TRectangle(TSpeedButton(Sender).Parent).Height then begin
TRectangle(TSpeedButton(Sender).Parent).AnimateFloat('Height',
TRectangle(TSpeedButton(Sender).Parent).ControlsCount * TSpeedButton(Sender).Height,
0.3,
TAnimationType.&In,
TInterpolationType.Circular
);
end else begin
TRectangle(TSpeedButton(Sender).Parent).AnimateFloat('Height',
TSpeedButton(Sender).Height,
0.3,
TAnimationType.&In,
TInterpolationType.Circular
);
end;
end;
end.
|
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Utility Window
©František Milt 2018-10-22
Version 1.2.2
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
AuxClasses - github.com/ncs-sniper/Lib.AuxClasses
MulticastEvent - github.com/ncs-sniper/Lib.MulticastEvent
WndAlloc - github.com/ncs-sniper/Lib.WndAlloc
===============================================================================}
unit UtilityWindow;
{$IF not(defined(WINDOWS) or defined(MSWINDOWS))}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE Delphi}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
interface
uses
Windows, Messages, AuxClasses, MulticastEvent;
type
TMessageEvent = procedure(var Msg: TMessage; var Handled: Boolean) of object;
{==============================================================================}
{--- TMulticastMessageEvent declarationn --------------------------------------}
{==============================================================================}
TMulticastMessageEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TMessageEvent): Integer; reintroduce;
Function Add(Handler: TMessageEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TMessageEvent): Integer; reintroduce;
procedure Call(var Msg: TMessage; var Handled: Boolean); reintroduce;
end;
{==============================================================================}
{--- TUtilityWindow declarationn ----------------------------------------------}
{==============================================================================}
TUtilityWindow = class(TCustomObject)
private
fWindowHandle: HWND;
fOnMessage: TMulticastMessageEvent;
protected
procedure WndProc(var Msg: TMessage); virtual;
public
constructor Create;
destructor Destroy; override;
procedure ProcessMessages(Synchronous: Boolean = False); virtual;
property WindowHandle: HWND read fWindowHandle;
property OnMessage: TMulticastMessageEvent read fOnMessage;
end;
implementation
uses
SysUtils, Classes, WndAlloc;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5057:={$WARN 5057 OFF}} // Local variable "$1" does not seem to be initialized
{$ENDIF}
{==============================================================================}
{--- TMulticastMessageEvent implementation ------------------------------------}
{==============================================================================}
{=== TMulticastMessageEvent // public methods =================================}
Function TMulticastMessageEvent.IndexOf(const Handler: TMessageEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastMessageEvent.Add(Handler: TMessageEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastMessageEvent.Remove(const Handler: TMessageEvent): Integer;
begin
Result := inherited Remove(TEvent(Handler));
end;
//------------------------------------------------------------------------------
procedure TMulticastMessageEvent.Call(var Msg: TMessage; var Handled: Boolean);
var
i: Integer;
Processed: Boolean;
begin
Processed := False;
For i := 0 to Pred(Count) do
begin
TMessageEvent(Methods[i])(Msg,Processed);
If Processed then Handled := True;
end;
end;
{==============================================================================}
{--- TUtilityWindow implementation --------------------------------------------}
{==============================================================================}
{=== TUtilityWindow // protected methods ======================================}
procedure TUtilityWindow.WndProc(var Msg: TMessage);
var
Handled: Boolean;
begin
Handled := False;
fOnMessage.Call(Msg,Handled);
If not Handled then
Msg.Result := DefWindowProc(fWindowHandle,Msg.Msg,Msg.wParam,Msg.lParam);
end;
{=== TUtilityWindow // public methods =========================================}
constructor TUtilityWindow.Create;
begin
inherited;
fOnMessage := TMulticastMessageEvent.Create(Self);
fWindowHandle := WndAlloc.AllocateHWND(WndProc);
end;
//------------------------------------------------------------------------------
destructor TUtilityWindow.Destroy;
begin
fOnMessage.Clear;
WndAlloc.DeallocateHWND(fWindowHandle);
fOnMessage.Free;
inherited;
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5057{$ENDIF}
procedure TUtilityWindow.ProcessMessages(Synchronous: Boolean = False);
var
Msg: TagMSG;
begin
If Synchronous then
begin
while GetMessage(Msg,fWindowHandle,0,0) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end
else
begin
while PeekMessage(Msg,fWindowHandle,0,0,PM_REMOVE) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end.
|
unit LrPageControlRegister;
interface
procedure Register;
implementation
uses
Classes, LrPageControl;
procedure Register;
begin
RegisterComponents('LR', [ TLrTabControl, TLrCustomPageControl, TLrPageControl ]);
end;
end.
|
unit DPM.Core.Spec.Writer;
interface
uses
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Options.Spec,
DPM.Core.Spec.Interfaces;
type
TPackageSpecWriter = class(TInterfacedObject, IPackageSpecWriter)
private
FLogger : ILogger;
protected
function CreateSpecFile(const options : TSpecOptions) : Boolean;
public
constructor Create(const logger : ILogger);
end;
implementation
uses
DPM.Core.Project.Interfaces;
{ TPackageSpecWriter }
constructor TPackageSpecWriter.Create(const logger : ILogger);
begin
FLogger := logger;
end;
function TPackageSpecWriter.CreateSpecFile(const options : TSpecOptions) : Boolean;
begin
result := false;
end;
end.
|
{******************************************************************************}
{ }
{ Icon Fonts ImageList: An extended ImageList for Delphi }
{ to simplify use of Icons (resize, colors and more...) }
{ }
{ Copyright (c) 2019 (Ethea S.r.l.) }
{ Contributors: }
{ Carlo Barazzetta }
{ }
{ https://github.com/EtheaDev/IconFontsImageList }
{ }
{******************************************************************************}
{ }
{ 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 IconFontsUtils;
interface
{$INCLUDE IconFontsImageList.inc}
uses
Classes
, ImgList
, Graphics
, ComCtrls;
function UpdateIconFontListView(const AListView: TListView): Integer;
implementation
uses
SysUtils
, IconFontsImageList;
function UpdateIconFontListView(const AListView: TListView): Integer;
var
I: Integer;
LItem: TIconFontItem;
LListItem: TListItem;
LIconFontsImageList: TIconFontsImageList;
begin
LIconFontsImageList := AListView.LargeImages as TIconFontsImageList;
AListView.Items.BeginUpdate;
try
AListView.Clear;
Result := LIconFontsImageList.IconFontItems.Count;
for I := 0 to Result -1 do
begin
LItem := LIconFontsImageList.IconFontItems[I];
LListItem := AListView.Items.Add;
LListItem.Caption := Format('%d%s$%s%s%s',
[LItem.FontIconDec,sLineBreak,
LItem.FontIconHex,sLineBreak,
Litem.IconName]);
LListItem.ImageIndex := I;
end;
finally
AListView.Items.EndUpdate;
end;
end;
end.
|
unit Balldlg;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, Dialogs, ExtCtrls, Balls;
type
TBallDialog = class(TForm)
OKBtn: TBitBtn;
CancelBtn: TBitBtn;
HelpBtn: TBitBtn;
Bevel1: TBevel;
ColorDialog: TColorDialog;
ButtonColor: TSpeedButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
EditPosX: TEdit;
EditPosY: TEdit;
Label5: TLabel;
Label6: TLabel;
EditSpeedX: TEdit;
EditSpeedY: TEdit;
Label8: TLabel;
EditInterval: TEdit;
Label9: TLabel;
Label7: TLabel;
Label10: TLabel;
Label11: TLabel;
EditRadius: TEdit;
ColorDisplay: TShape;
procedure ButtonColorClick(Sender: TObject);
private
{ Private declarations }
function GetBallColor: TColor;
procedure SetBallColor(Value: TColor);
function GetPos: TPoint;
function GetRadius: Integer;
function GetSpeed: TPoint;
public
{ Public declarations }
property BallColor: TColor read GetBallColor write SetBallColor;
property Pos: TPoint read GetPos;
property Radius: Integer read GetRadius;
property Speed: TPoint read GetSpeed;
end;
var
BallDialog: TBallDialog;
implementation
uses SysUtils;
{$R *.DFM}
function TBallDialog.GetBallColor: TColor;
begin
Result := ColorDisplay.Brush.Color;
end;
procedure TBallDialog.SetBallColor(Value: TColor);
begin
ColorDisplay.Brush.Color := Value;
ColorDisplay.Brush.Color := Value;
end;
function TBallDialog.GetPos: TPoint;
begin
Result := Point(StrToInt(EditPosX.Text), StrToInt(EditPosY.Text));
end;
function TBallDialog.GetRadius: Integer;
begin
Result := StrToInt(EditRadius.Text);
end;
function TBallDialog.GetSpeed: TPoint;
begin
Result := Point(StrToInt(EditSpeedX.Text), StrToInt(EditSpeedY.Text))
end;
procedure TBallDialog.ButtonColorClick(Sender: TObject);
begin
if ColorDialog.Execute then BallColor := ColorDialog.Color
end;
end.
|
unit uDividerBase;
{$I ..\Include\IntXLib.inc}
interface
uses
uIDivider,
uStrings,
uDigitOpHelper,
uDigitHelper,
uEnums,
uConstants,
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Base class for dividers.
/// Contains default implementation of divide operation over <see cref="TIntX" /> instances.
/// </summary>
TDividerBase = class abstract(TInterfacedObject, IIDivider)
public
/// <summary>
/// Divides one <see cref="TIntX" /> by another.
/// </summary>
/// <param name="int1">First big integer.</param>
/// <param name="int2">Second big integer.</param>
/// <param name="modRes">Remainder big integer.</param>
/// <param name="resultFlags">Which operation results to return.</param>
/// <returns>Divident big integer.</returns>
/// <exception cref="EArgumentNilException"><paramref name="int1" /> or <paramref name="int2" /> is a null reference.</exception>
/// <exception cref="EDivByZero"><paramref name="int2" /> equals zero.</exception>
/// <exception cref="EArithmeticException"><paramref name="int1" /> and <paramref name="int2" /> equals zero.</exception>
function DivMod(int1: TIntX; int2: TIntX; out modRes: TIntX;
resultFlags: TDivModResultFlags): TIntX; overload; virtual;
/// <summary>
/// Divides two big integers.
/// Also modifies <paramref name="digits1" /> and <paramref name="length1"/> (it will contain remainder).
/// </summary>
/// <param name="digits1">First big integer digits.</param>
/// <param name="digitsBuffer1">Buffer for first big integer digits. May also contain remainder. Can be null - in this case it's created if necessary.</param>
/// <param name="length1">First big integer length.</param>
/// <param name="digits2">Second big integer digits.</param>
/// <param name="digitsBuffer2">Buffer for second big integer digits. Only temporarily used. Can be null - in this case it's created if necessary.</param>
/// <param name="length2">Second big integer length.</param>
/// <param name="digitsRes">Resulting big integer digits.</param>
/// <param name="resultFlags">Which operation results to return.</param>
/// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param>
/// <returns>Resulting big integer length.</returns>
function DivMod(digits1: TIntXLibUInt32Array;
digitsBuffer1: TIntXLibUInt32Array; var length1: UInt32;
digits2: TIntXLibUInt32Array; digitsBuffer2: TIntXLibUInt32Array;
length2: UInt32; digitsRes: TIntXLibUInt32Array;
resultFlags: TDivModResultFlags; cmpResult: Integer): UInt32; overload;
virtual; abstract;
/// <summary>
/// Divides two big integers.
/// Also modifies <paramref name="digitsPtr1" /> and <paramref name="length1"/> (it will contain remainder).
/// </summary>
/// <param name="digitsPtr1">First big integer digits.</param>
/// <param name="digitsBufferPtr1">Buffer for first big integer digits. May also contain remainder.</param>
/// <param name="length1">First big integer length.</param>
/// <param name="digitsPtr2">Second big integer digits.</param>
/// <param name="digitsBufferPtr2">Buffer for second big integer digits. Only temporarily used.</param>
/// <param name="length2">Second big integer length.</param>
/// <param name="digitsResPtr">Resulting big integer digits.</param>
/// <param name="resultFlags">Which operation results to return.</param>
/// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param>
/// <returns>Resulting big integer length.</returns>
function DivMod(digitsPtr1: PCardinal; digitsBufferPtr1: PCardinal;
var length1: UInt32; digitsPtr2: PCardinal; digitsBufferPtr2: PCardinal;
length2: UInt32; digitsResPtr: PCardinal; resultFlags: TDivModResultFlags;
cmpResult: Integer): UInt32; overload; virtual;
end;
implementation
function TDividerBase.DivMod(int1: TIntX; int2: TIntX; out modRes: TIntX;
resultFlags: TDivModResultFlags): TIntX;
var
divNeeded, modNeeded, resultNegative: Boolean;
compareResult: Integer;
modLength, divLength: UInt32;
divRes: TIntX;
digibuf, digires: TIntXLibUInt32Array;
begin
// Null reference exceptions
if TIntX.CompareRecords(int1, Default (TIntX)) then
raise EArgumentNilException.Create(uStrings.CantBeNull + ' int1');
if TIntX.CompareRecords(int2, Default (TIntX)) then
raise EArgumentNilException.Create(uStrings.CantBeNull + ' int2');
// Check if int2 equals zero
if (int2._length = 0) then
begin
if (int1._length = 0) then
begin
raise EArithmeticException.Create(DivisionUndefined);
end;
raise EDivByZero.Create(DivideByZero);
end;
// Get flags
divNeeded := (Ord(resultFlags) and Ord(TDivModResultFlags.dmrfDiv)) <> 0;
modNeeded := (Ord(resultFlags) and Ord(TDivModResultFlags.dmrfMod)) <> 0;
// Special situation: check if int1 equals zero; in this case zero is always returned
if (int1._length = 0) then
begin
if modNeeded then
modRes := TIntX.Create(0)
else
modRes := Default (TIntX);
if divNeeded then
begin
result := TIntX.Create(0);
Exit;
end
else
begin
result := Default (TIntX);
Exit;
end;
end;
// Special situation: check if int2 equals one - nothing to divide in this case
if ((int2._length = 1) and (int2._digits[0] = 1)) then
begin
if modNeeded then
modRes := TIntX.Create(0)
else
modRes := Default (TIntX);
if divNeeded then
begin
if int2._negative then
begin
result := -int1;
Exit;
end
else
begin
result := +int1;
Exit;
end;
end
else
begin
result := Default (TIntX);
Exit;
end;
end;
// Get resulting sign
resultNegative := int1._negative xor int2._negative;
// Check if int1 > int2
compareResult := TDigitOpHelper.Cmp(int1._digits, int1._length, int2._digits,
int2._length);
if (compareResult < 0) then
begin
if modNeeded then
begin
modRes := TIntX.Create(int1);
end
else
begin
modRes := Default (TIntX);
end;
if divNeeded then
begin
result := TIntX.Create(0);
Exit;
end
else
begin
result := Default (TIntX);
Exit;
end;
end;
if (compareResult = 0) then
begin
if modNeeded then
modRes := TIntX.Create(0)
else
begin
modRes := Default (TIntX);
end;
if divNeeded then
begin
if resultNegative then
begin
result := TIntX.Create(-1);
Exit;
end
else
begin
result := TIntX.Create(1);
Exit;
end;
end
else
begin
result := Default (TIntX);
Exit;
end;
end;
//
// Actually divide here (by Knuth algorithm)
//
// Prepare divident (if needed)
divRes := Default (TIntX);
if (divNeeded) then
begin
// Original CSharp Implementation used UInt32(1) Instead of UInt32(2).
divRes := TIntX.Create(int1._length - int2._length + UInt32(2),
resultNegative);
end;
// Prepare mod (if needed)
if (modNeeded) then
begin
// Original CSharp Implementation used UInt32(1) Instead of UInt32(2).
modRes := TIntX.Create(int1._length + UInt32(2), int1._negative);
end
else
begin
modRes := Default (TIntX);
end;
if modNeeded then
digibuf := modRes._digits
else
digibuf := Nil;
if divNeeded then
digires := divRes._digits
else
digires := Nil;
// Call procedure itself
modLength := int1._length;
divLength := DivMod(int1._digits, digibuf, modLength, int2._digits, Nil,
int2._length, digires, resultFlags, compareResult);
// Maybe set new lengths and perform normalization
if (divNeeded) then
begin
divRes._length := divLength;
divRes.TryNormalize();
end;
if (modNeeded) then
begin
modRes._length := modLength;
modRes.TryNormalize();
end;
// Return div
result := divRes;
end;
function TDividerBase.DivMod(digitsPtr1: PCardinal; digitsBufferPtr1: PCardinal;
var length1: UInt32; digitsPtr2: PCardinal; digitsBufferPtr2: PCardinal;
length2: UInt32; digitsResPtr: PCardinal; resultFlags: TDivModResultFlags;
cmpResult: Integer): UInt32;
var
divNeeded, modNeeded: Boolean;
modRes: UInt32;
begin
// Base implementation covers some special cases
divNeeded := ((Ord(resultFlags) and Ord(TDivModResultFlags.dmrfDiv)) <> 0);
modNeeded := ((Ord(resultFlags) and Ord(TDivModResultFlags.dmrfMod)) <> 0);
//
// Special cases
//
// Case when length1 = 0
if (length1 = 0) then
begin
result := 0;
Exit;
end;
// Case when both lengths are 1
if ((length1 = 1) and (length2 = 1)) then
begin
if (divNeeded) then
begin
digitsResPtr^ := digitsPtr1^ div digitsPtr2^;
if (digitsResPtr^ = 0) then
begin
length2 := 0;
end;
end;
if (modNeeded) then
begin
digitsBufferPtr1^ := digitsPtr1^ mod digitsPtr2^;
if (digitsBufferPtr1^ = 0) then
begin
length1 := 0;
end;
end;
result := length2;
Exit;
end;
// Compare digits first (if was not previously compared)
if (cmpResult = -2) then
begin
cmpResult := TDigitOpHelper.Cmp(digitsPtr1, length1, digitsPtr2, length2);
end;
// Case when first value is smaller then the second one - we will have remainder only
if (cmpResult < 0) then
begin
// Maybe we should copy first digits into remainder (if remainder is needed at all)
if (modNeeded) then
begin
TDigitHelper.DigitsBlockCopy(digitsPtr1, digitsBufferPtr1, length1);
end;
// Zero as division result
result := 0;
Exit;
end;
// Case when values are equal
if (cmpResult = 0) then
begin
// Maybe remainder must be marked as empty
if (modNeeded) then
begin
length1 := 0;
end;
// One as division result
if (divNeeded) then
begin
digitsResPtr^ := 1;
end;
result := 1;
Exit;
end;
// Case when second length equals to 1
if (length2 = 1) then
begin
// Call method basing on fact if div is needed
if (divNeeded) then
begin
length2 := TDigitOpHelper.DivMod(digitsPtr1, length1, digitsPtr2^,
digitsResPtr, modRes);
end
else
begin
modRes := TDigitOpHelper.Modulus(digitsPtr1, length1, digitsPtr2^);
end;
// Maybe save mod result
if (modNeeded) then
begin
if (modRes <> 0) then
begin
length1 := 1;
digitsBufferPtr1^ := modRes;
end
else
begin
length1 := 0;
end;
end;
result := length2;
Exit;
end;
// This is regular case, not special
result := TConstants.MaxUInt32Value;
end;
end.
|
unit SomeRegistry;
interface
type
TSomeRegistry = class
public
procedure RegisterClass(AClass: TClass);
procedure DeregisterClass(AClass: TClass);
end;
function GetSomeRegistry: TSomeRegistry;
implementation
uses Windows;
var
mSomeRegistry : TSomeRegistry = nil;
function GetSomeRegistry: TSomeRegistry;
begin
Result := mSomeRegistry;
end;
{ TSomeRegistry }
procedure TSomeRegistry.RegisterClass(AClass: TClass);
begin
WriteLn(PChar('Registry Adding: ' + AClass.ClassName));
end;
procedure TSomeRegistry.DeregisterClass(AClass: TClass);
begin
WriteLn(PChar('Registry Removing: ' + AClass.ClassName));
end;
initialization
mSomeRegistry := TSomeRegistry.Create();
finalization
mSomeRegistry.Free;
end.
|
program USBHIDLister;
{$mode objfpc}{$H+}
{ Raspberry Pi 3 Application }
{ Add your program code below, add additional units to the "uses" section if }
{ required and create new units by selecting File, New Unit from the menu. }
{ }
{ To compile your program select Run, Compile (or Run, Build) from the menu. }
{$define use_tftp}
uses
RaspberryPi3,
GlobalConfig,
GlobalConst,
GlobalTypes,
Platform,
Threads,
SysUtils,
Classes,
uLog,
USB,
Devices,
uHIDUsage,
{$ifdef use_tftp}
uTFTP, Winsock2,
{$endif}
Ultibo, Console
{ Add additional units here };
var
Console1, Console2, Console3 : TWindowHandle;
{$ifdef use_tftp}
IPAddress : string;
{$endif}
USBDriver : PUSBDriver;
procedure Log1 (s : string);
begin
ConsoleWindowWriteLn (Console1, s);
end;
procedure Log2 (s : string);
begin
ConsoleWindowWriteLn (Console2, s);
end;
procedure Log3 (s : string);
begin
ConsoleWindowWriteLn (Console3, s);
end;
procedure Msg3 (Sender : TObject; s : string);
begin
Log3 (s);
end;
{$ifdef use_tftp}
function WaitForIPComplete : string;
var
TCP : TWinsock2TCPClient;
begin
TCP := TWinsock2TCPClient.Create;
Result := TCP.LocalAddress;
if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then
begin
while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do
begin
sleep (1000);
Result := TCP.LocalAddress;
end;
end;
TCP.Free;
end;
{$endif}
procedure WaitForSDDrive;
begin
while not DirectoryExists ('C:\') do sleep (500);
end;
function USBDriverBind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord;
var
j : integer;
isHID : boolean;
buff : array [0..255] of byte;
res : LongWord;
begin
Result := USB_STATUS_DEVICE_UNSUPPORTED;
if Device = nil then exit;
if Interrface <> nil then exit;
isHID := false;
if Device^.Descriptor^.bDeviceClass = USB_CLASS_CODE_INTERFACE_SPECIFIC then
begin
for j := low (Device^.Configuration^.Interfaces) to high (Device^.Configuration^.Interfaces) do
if Device^.Configuration^.Interfaces[j]^.Descriptor^.bInterfaceClass = USB_CLASS_CODE_HID then
isHID := true;
end;
ConsoleWindowClear (Console1);
if not isHID then
begin
Log ('Not a HID Device.');
exit;
end;
Log ('VID : ' + Device^.Descriptor^.idVendor.ToHexString (4));
Log ('PID : ' + Device^.Descriptor^.idProduct.ToHexString (4));
Log ('Product : ' + Device^.Product);
Log ('SNo : ' + Device^.SerialNumber);
Log ('Configurations : ' + length (Device^.Configurations).ToString);
Log ('First Configuration ----');
Log (' Interfaces : ' + length (Device^.Configuration^.Interfaces).ToString);
for j := low (Device^.Configuration^.Interfaces) to high (Device^.Configuration^.Interfaces) do
begin
Log (' ---- Interface ' + j.ToString + ' ---- ');
if Device^.Configuration^.Interfaces[j]^.Descriptor^.bInterfaceClass <> USB_CLASS_CODE_HID then continue;
Log (' SubClass : ' + Device^.Configuration^.Interfaces[j]^.Descriptor^.bInterfaceSubClass.ToHexString (2));
Log (' Protocol : ' + Device^.Configuration^.Interfaces[j]^.Descriptor^.bInterfaceProtocol.ToHexString (2));
end;
Log ('Usage ----');
FillChar (buff, 256, 0);
res := USBControlRequestEx (Device, nil,
USB_DEVICE_REQUEST_GET_DESCRIPTOR,
USB_BMREQUESTTYPE_DIR_IN or
USB_BMREQUESTTYPE_TYPE_STANDARD or
USB_BMREQUESTTYPE_RECIPIENT_INTERFACE,
$22 shl 8, // $22 shl 8, // for Report Descriptor
0,
@buff[0],
255,
INFINITE, true);
if res = USB_STATUS_SUCCESS then PrintHIDUsage (buff)
else Log (' Error : ' + USBStatusToString (res));
end;
function USBDriverUnbind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord;
begin
Result := USB_STATUS_DEVICE_UNSUPPORTED;
end;
begin
Console1 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_LEFT, true);
Console2 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_TOPRIGHT, false);
Console3 := ConsoleWindowCreate (ConsoleDeviceGetDefault, CONSOLE_POSITION_BOTTOMRIGHT, false);
SetLogProc (@Log1);
Log2 ('HID USB Lister.');
Log2 ('Plug in device to list information.');
Log2 ('');
{$ifdef use_tftp}
IPAddress := WaitForIPComplete;
Log3 ('TFTP Usage : tftp -i ' + IPAddress + ' put kernel7.img');
SetOnMsg (@Msg3);
{$endif}
USBDriver := USBDriverCreate;
if USBDriver = nil then ThreadHalt (0);
USBDriver^.Driver.DriverName := 'GENERIC USB';
USBDriver^.DriverBind := @USBDriverBind;
USBDriver^.DriverUnbind := @USBDriverUnbind;
USBDriverRegister (USBDriver);
ThreadHalt (0);
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit TargetPlatformTests;
interface
uses
DUnitX.TestFramework;
type
{$M+}
[TestFixture]
TDPMTargetPlatformTestFixture = class(TObject)
published
procedure Can_Parse_Valid_String;
procedure Will_Throw_on_invalid_compiler_value;
procedure Will_Throw_on_invalid_platform_value;
procedure Will_Throw_on_empty_string;
procedure Will_Throw_on_missing_platform;
end;
implementation
uses
System.SysUtils,
DPM.Core.Types,
DPM.Core.TargetPlatform;
{ TDPMTargetPlatformTestFixture }
procedure TDPMTargetPlatformTestFixture.Can_Parse_Valid_String;
var
value :TTargetPlatform;
begin
Assert.IsTrue(TTargetPlatform.TryParse('RSXE7.Win32', value));
Assert.IsTrue(TTargetPlatform.TryParse('10.3.Win32', value));
end;
procedure TDPMTargetPlatformTestFixture.Will_Throw_on_empty_string;
begin
Assert.WillRaise(
procedure
var
value :TTargetPlatform;
begin
value := TTargetPlatform.Parse('');
end
, EArgumentException);
end;
procedure TDPMTargetPlatformTestFixture.Will_Throw_on_invalid_compiler_value;
begin
Assert.WillRaise(
procedure
var
value :TTargetPlatform;
begin
value := TTargetPlatform.Parse('RSXE9.Win32');
end
, EArgumentOutOfRangeException);
end;
procedure TDPMTargetPlatformTestFixture.Will_Throw_on_invalid_platform_value;
begin
Assert.WillRaise(
procedure
var
value :TTargetPlatform;
begin
value := TTargetPlatform.Parse('RSXE7.Win23');
end
, EArgumentOutOfRangeException);
end;
procedure TDPMTargetPlatformTestFixture.Will_Throw_on_missing_platform;
begin
Assert.WillRaise(
procedure
var
value :TTargetPlatform;
begin
value := TTargetPlatform.Parse('XE2.');
end
, EArgumentException);
end;
initialization
TDUnitX.RegisterTestFixture(TDPMTargetPlatformTestFixture);
end.
|
unit UHistoricoVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO;
type
[TEntity]
[TTable('Historicos')]
THistoricoVO = class(TGenericVO)
private
FIdHistorico : Integer;
FDsHistorico : String;
FFlContaCorrente : String;
public
[TId('IdHistorico')]
[TGeneratedValue(sAuto)]
property idHistorico : Integer read FIdHistorico write FIdHistorico;
[TColumn('DsHistorico','Descrição',250,[ldGrid,ldLookup,ldComboBox], False)]
property DsHistorico: String read FDsHistorico write FDsHistorico;
[TColumn('FlContaCorrente','Conta Corrente',0,[ ldLookup,ldComboBox], False)]
property FlContaCorrente : String read FFlContaCorrente write FFlContaCorrente;
Procedure ValidarCamposObrigatorios;
end;
implementation
{ THistoricoVO }
procedure THistoricoVO.ValidarCamposObrigatorios;
begin
if (Self.FDsHistorico = '') then
raise Exception.Create('O campo Descrição é obrigatório!');
if (Self.FFlContaCorrente = '') then
raise Exception.Create('O campo Conta Corrente é obrigatório!');
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 083309
////////////////////////////////////////////////////////////////////////////////
unit java.time.chrono.AbstractChronology;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.time.chrono.ChronoLocalDate,
java.time.format.ResolverStyle;
type
JAbstractChronology = interface;
JAbstractChronologyClass = interface(JObjectClass)
['{91938D75-BBA9-4E1C-8006-78F04F4A35D6}']
function compareTo(other : JChronology) : Integer; cdecl; // (Ljava/time/chrono/Chronology;)I A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function resolveDate(fieldValues : JMap; resolverStyle : JResolverStyle) : JChronoLocalDate; cdecl;// (Ljava/util/Map;Ljava/time/format/ResolverStyle;)Ljava/time/chrono/ChronoLocalDate; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
[JavaSignature('java/time/chrono/AbstractChronology')]
JAbstractChronology = interface(JObject)
['{05970935-A914-472C-9820-AD81DFCDAF38}']
function compareTo(other : JChronology) : Integer; cdecl; // (Ljava/time/chrono/Chronology;)I A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function resolveDate(fieldValues : JMap; resolverStyle : JResolverStyle) : JChronoLocalDate; cdecl;// (Ljava/util/Map;Ljava/time/format/ResolverStyle;)Ljava/time/chrono/ChronoLocalDate; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
TJAbstractChronology = class(TJavaGenericImport<JAbstractChronologyClass, JAbstractChronology>)
end;
implementation
end.
|
unit URepositorioEstado;
interface
uses
UPais
, UEstado
, UEntidade
, URepositorioDB
, URepositorioPais
, SqlExpr
;
type
TRepositorioEstado = class(TRepositorioDB<TESTADO>)
private
FRepositorioPais: TRepositorioPais;
public
constructor Create;
destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coESTADO: TESTADO); override;
procedure AtribuiEntidadeParaDB(const coESTADO: TESTADO;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
;
{ TRepositorioEstado }
procedure TRepositorioEstado.AtribuiDBParaEntidade(const coESTADO: TESTADO);
begin
inherited;
with FSQLSelect do
begin
coESTADO.NOME := FieldByName(FLD_ESTADO_NOME).AsString;
coESTADO.PAIS := TPAIS(
FRepositorioPais.Retorna(FieldByName(FLD_ESTADO_ID_PAIS).AsInteger));
end;
end;
procedure TRepositorioEstado.AtribuiEntidadeParaDB(const coESTADO: TESTADO;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_ESTADO_NOME).AsString := coESTADO.NOME;
ParamByName(FLD_ESTADO_ID_PAIS).AsInteger := coESTADO.PAIS.ID;
end;
end;
constructor TRepositorioEstado.Create;
begin
inherited Create(TESTADO, TBL_ESTADO, FLD_ENTIDADE_ID, STR_ESTADO);
FRepositorioPais := TRepositorioPais.Create;
end;
destructor TRepositorioEstado.Destroy;
begin
FreeAndNil(FRepositorioPais);
inherited;
end;
end.
|
{ ZFM-20 series fingerprint sensor support library.
Copyright (c) 2015 Dilshan R Jayakody [jayakody2000lk@gmail.com]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
library zfm20lib;
{$mode objfpc}{$H+}
{$hints off} {$warnings off} {$notes off}
uses
SysUtils, uZfm, SynaSer, Classes, Graphics, Interfaces;
{$hints on} {$warnings off} {$notes on}
const
COM_NUMBER_OF_BITS = 8; // Serial communication data bits count. (Default: 8)
HEADER_SEGMENT_SIZE = 6; // Size of the response header and module address.
MAX_ACK_BUFFER_SIZE = 32; // Default buffer size for ACK. response.
COM_SLEEP_TIME = 25; // Serial communication default delay in miliseconds.
TIME_OUT_LIMIT = 40; // Number of try counts for serial communication.
MAX_DATA_PACKAGES = 2048; // Maximum allowed data packages for each upload session.
IMG_WIDTH = 256; // Width of the fingerprint image.
IMG_HEIGHT = 288; // Height of the fingerprint image.
type
TZfmLibStatus = (zsUnknownError = 0, zsSuccessful, zsTimeout, zsNoFinger, zsFingerCollectError, zsBadResponse, zsDataError, zsIOError, zsMemoryError);
{$R *.res}
// Convert LongWord sensor address to byte buffer.
function SensorAddrToByteArray(inAddr: LongWord): TZfmBuffer;
var
returnCode: TZfmBuffer;
begin
SetLength(returnCode, 4);
returnCode[0] := inAddr shr 24;
returnCode[1] := inAddr shr 16;
returnCode[2] := inAddr shr 8;
returnCode[3] := inAddr and $000000ff;
Result := returnCode;
end;
// Ping ZFM-20 series sensor and return the status.
function Zfm20SensorAvailable(comPort: PChar; baudRate: Integer; sensorAddr: LongWord): TZfmLibStatus; stdcall;
var
dataReadCount, timeOutCounter: Integer;
sensorIntf: TZfmSensor;
comIntf: TBlockSerial;
retData, payloadBuffer: TZfmBuffer;
ackResponseBuffer: array[0..MAX_ACK_BUFFER_SIZE] of Byte;
cmdBuffer: array[0..1] of Byte = (ZFM_CMD_HANDSHAKE, 0);
begin
Result := zsUnknownError;
{$hints off}
FillChar(ackResponseBuffer[0], Length(ackResponseBuffer), 0);
{$hints on}
// Configure ZFM20 class object.
sensorIntf := TZfmSensor.Create;
sensorIntf.SetSensorAddress(SensorAddrToByteArray(sensorAddr));
// Configure serial communication interface.
comIntf := TBlockSerial.Create;
comIntf.Connect(comPort);
comIntf.Config(baudRate, COM_NUMBER_OF_BITS, 'N', SB1, false, false);
payloadBuffer := sensorIntf.CreateZfmCommand(cmdBuffer);
if(Length(payloadBuffer) > 0) then
begin
// Transfer handshake command to fingerprint sensor.
comIntf.Purge;
comIntf.SendBuffer(@payloadBuffer[0], Length(payloadBuffer));
timeOutCounter := 0;
// Waiting for response from sensor.
repeat
Inc(timeOutCounter);
Sleep(COM_SLEEP_TIME);
dataReadCount := comIntf.RecvBufferEx(@ackResponseBuffer, MAX_ACK_BUFFER_SIZE, COM_SLEEP_TIME * 4);
if(timeOutCounter > TIME_OUT_LIMIT) then
begin
Result := zsTimeout;
break;
end;
until (dataReadCount > 0);
// Decode response received from sensor.
sensorIntf.DecodeZfmAcknowledge(ackResponseBuffer, retData);
if ((Length(retData) > 0) and (retData[0] = 0)) then
begin
Result := zsSuccessful;
end;
end;
// Clean resources.
if(Assigned(comIntf)) then
begin
comIntf.CloseSocket;
FreeAndNil(comIntf);
end;
if(Assigned(sensorIntf)) then
begin
FreeAndNil(sensorIntf);
end;
end;
// Issue fingerprint capture command to ZFM-20 series sensor.
function Zfm20CaptureFingerprint(comPort: PChar; baudRate: Integer; sensorAddr: LongWord): TZfmLibStatus; stdcall;
var
dataReadCount, timeOutCounter: Integer;
sensorIntf: TZfmSensor;
comIntf: TBlockSerial;
retData, payloadBuffer: TZfmBuffer;
ackResponseBuffer: array[0..MAX_ACK_BUFFER_SIZE] of Byte;
cmdBuffer: array[0..0] of Byte = (ZFM_CMD_GEN_IMG);
begin
Result := zsUnknownError;
{$hints off}
FillChar(ackResponseBuffer[0], Length(ackResponseBuffer), 0);
{$hints on}
// Configure ZFM20 class object.
sensorIntf := TZfmSensor.Create;
sensorIntf.SetSensorAddress(SensorAddrToByteArray(sensorAddr));
// Configure serial communication interface.
comIntf := TBlockSerial.Create;
comIntf.Connect(comPort);
comIntf.Config(baudRate, COM_NUMBER_OF_BITS, 'N', SB1, false, false);
payloadBuffer := sensorIntf.CreateZfmCommand(cmdBuffer);
if(Length(payloadBuffer) > 0) then
begin
// Transfer fingerprint capture command to the sensor.
comIntf.Purge;
comIntf.SendBuffer(@payloadBuffer[0], Length(payloadBuffer));
timeOutCounter := 0;
// Waiting for response from sensor.
repeat
Inc(timeOutCounter);
Sleep(COM_SLEEP_TIME);
dataReadCount := comIntf.RecvBufferEx(@ackResponseBuffer, MAX_ACK_BUFFER_SIZE, COM_SLEEP_TIME * 4);
if(timeOutCounter > TIME_OUT_LIMIT) then
begin
Result := zsTimeout;
break;
end;
until (dataReadCount > 0);
// Decode response received from sensor.
sensorIntf.DecodeZfmAcknowledge(ackResponseBuffer, retData);
if(Length(retData) > 0) then
begin
case retData[0] of
0: Result := zsSuccessful;
2: Result := zsNoFinger;
3: Result := zsFingerCollectError;
end;
end;
end;
// Clean resources.
if(Assigned(comIntf)) then
begin
comIntf.CloseSocket;
FreeAndNil(comIntf);
end;
if(Assigned(sensorIntf)) then
begin
FreeAndNil(sensorIntf);
end;
end;
// Extract fingerprint data from sensor response data stream.
function ExtractFingerprintImage(zfmObj: TZfmSensor; var inStream: TMemoryStream; out outStream: TMemoryStream): TZfmLibStatus;
var
dataLen, packageCount: Word;
packageID: Byte;
tempBuffer: TZfmBuffer;
headerSegment: array[0..(HEADER_SEGMENT_SIZE-1)] of Byte;
// Function to calculate size of the response data buffer.
function GetWord() : Word;
var
dataB1, dataB2 : Byte;
begin
dataB1 := inStream.ReadByte;
dataB2 := inStream.ReadByte;
result := Integer((dataB2 + (dataB1 shl 8))) - 2;
end;
begin
Result := zsUnknownError;
if(Assigned(inStream) and Assigned(zfmObj)) then
begin
inStream.Position := 0;
// Extract sensor response header to validate the input stream.
{$hints off}
FillByte(headerSegment, HEADER_SEGMENT_SIZE, 0);
{$hints on}
inStream.Read(headerSegment, HEADER_SEGMENT_SIZE);
if(not zfmObj.IsValidSensorHeader(headerSegment)) then
begin
Result := zsBadResponse;
end;
// Check data package type and continue extraction.
if((Result = zsUnknownError) and (inStream.ReadByte = ZFM_PACKAGE_ID_ACK)) then
begin
// Check status and skip trail bytes of the response.
dataLen := inStream.ReadWord;
if(inStream.ReadByte = 0) then
begin
inStream.ReadWord;
outStream := TMemoryStream.Create;
packageCount := 0;
// Reading data contents.
while true do
begin
FillByte(headerSegment, HEADER_SEGMENT_SIZE, 0);
inStream.Read(headerSegment, HEADER_SEGMENT_SIZE);
if(not zfmObj.IsValidSensorHeader(headerSegment)) then
begin
// Invalid response data header.
Result := zsDataError;
break;
end;
// Read package data content and copy it to output stream.
packageID := inStream.ReadByte;
dataLen := GetWord;
SetLength(tempBuffer, dataLen);
inStream.ReadBuffer(tempBuffer[0], dataLen);
outStream.WriteBuffer(tempBuffer[0], dataLen);
if(packageID = ZFM_PACKAGE_ID_DATA) then
inStream.ReadWord
else
break;
// Check for package space overflows to avoid freeze due to data error.
Inc(packageCount);
if(packageCount >= MAX_DATA_PACKAGES) then
begin
Result := zsDataError;
Break;
end;
end;
outStream.Position := 0;
Result := zsSuccessful;
end
else
begin
Result := zsBadResponse;
end;
end;
end;
end;
// Issue command to upload content of sensor ImageBuffer to host terminal.
function UploadImageBufferToHost(comPort: PChar; baudRate: Integer; sensorAddr: LongWord; out dataStream: TMemoryStream): TZfmLibStatus;
var
timeOutCounter: Integer;
sensorIntf: TZfmSensor;
comIntf: TBlockSerial;
sensorStream: TMemoryStream;
payloadBuffer: TZfmBuffer;
cmdBuffer: array[0..0] of byte = (ZFM_CMD_UPLOAD_IMG);
begin
Result := zsUnknownError;
// Configure ZFM20 class object.
sensorIntf := TZfmSensor.Create;
sensorIntf.SetSensorAddress(SensorAddrToByteArray(sensorAddr));
// Configure serial communication interface.
comIntf := TBlockSerial.Create;
comIntf.Connect(comPort);
comIntf.Config(baudRate, COM_NUMBER_OF_BITS, 'N', SB1, false, false);
payloadBuffer := sensorIntf.CreateZfmCommand(cmdBuffer);
if(Length(payloadBuffer) > 0) then
begin
// Transfer image buffer download command to the sensor.
comIntf.Purge;
comIntf.SendBuffer(@payloadBuffer[0], Length(payloadBuffer));
timeOutCounter := 0;
// Waiting for data stream from sensor.
repeat
Inc(timeOutCounter);
Sleep(COM_SLEEP_TIME);
if(timeOutCounter > TIME_OUT_LIMIT) then
begin
Result := zsTimeout;
break;
end;
until comIntf.CanRead(COM_SLEEP_TIME * 6);
// Downloading data stream from sensor module.
if(Result <> zsTimeout) then
begin
sensorStream := TMemoryStream.Create;
comIntf.RecvStreamRaw(sensorStream, COM_SLEEP_TIME * 4);
if(sensorStream.Size > 0) then
begin
// Data downloading from sensor is completed.
Result := ExtractFingerprintImage(sensorIntf, sensorStream, dataStream);
end
else
Result := zsBadResponse;
end;
end;
// Clean resources.
if(Assigned(sensorStream)) then
begin
sensorStream.Clear;
FreeAndNil(sensorStream);
end;
if(Assigned(comIntf)) then
begin
comIntf.CloseSocket;
FreeAndNil(comIntf);
end;
if(Assigned(sensorIntf)) then
begin
FreeAndNil(sensorIntf);
end;
end;
// Load ImageBuffer content from sensor and draw it on TBitmap canvas.
function UploadImageBufferToBitmap(comPort: PChar; baudRate: Integer; sensorAddr: LongWord; out bitmapBuffer: TBitmap): TZfmLibStatus;
var
isLowNibble: Boolean;
posX, posY: Word;
sensData, colorData: Byte;
dataBuffer: TMemoryStream;
begin
Result := UploadImageBufferToHost(comPort, baudRate, sensorAddr, dataBuffer);
if(Result = zsSuccessful) then
begin
try
// Setup output image.
bitmapBuffer := TBitmap.Create;
bitmapBuffer.Width := IMG_WIDTH;
bitmapBuffer.Height := IMG_HEIGHT;
bitmapBuffer.PixelFormat := pf24bit;
dataBuffer.Position := 0;
isLowNibble := false;
// Draw fingerprint image on bitmap canvas.
for posY := 0 to (IMG_HEIGHT - 1) do
begin
for posX := 0 to (IMG_WIDTH - 1) do
begin
// Extract nibble from stream and convert it to hi-byte.
if(not isLowNibble) then
begin
sensData := dataBuffer.ReadByte;
colorData := sensData and $f0;
end
else
begin
colorData := (sensData and $0f) shl 4;
end;
isLowNibble := not isLowNibble;
bitmapBuffer.Canvas.Pixels[posX, posY] := RGBToColor(colorData, colorData, colorData);
end;
end;
except
// General exception. Fail the current task and return memory error.
Result := zsMemoryError;
end;
end;
// Clean resources.
if(Assigned(dataBuffer)) then
begin
dataBuffer.Clear;
FreeAndNil(dataBuffer);
end;
end;
// Load ImageBuffer content from sensor and save it to specified filename as bitmap image.
function Zfm20SaveFingerprintImage(comPort: PChar; baudRate: Integer; sensorAddr: LongWord; fileName: PChar): TZfmLibStatus; stdcall;
var
bitmapBuffer: TBitmap;
begin
try
Result := UploadImageBufferToBitmap(comPort, baudRate, sensorAddr, bitmapBuffer);
if(Result = zsSuccessful) then
begin
bitmapBuffer.SaveToFile(fileName);
end;
except
// General exception. Fail the current task and return memory error.
Result := zsIOError;
end;
// Clean resources.
if(Assigned(bitmapBuffer)) then
begin
bitmapBuffer.Clear;
FreeAndNil(bitmapBuffer);
end;
end;
// Load ImageBuffer content from sensor and save it to memory buffer.
function Zfm20GetFingerprintBuffer(comPort: PChar; baudRate: Integer; sensorAddr: LongWord; var outBufferSize: LongWord; var outBuffer: PByte): TZfmLibStatus; stdcall;
var
isLowNibble: Boolean;
posX, posY: Word;
sensData, colorData: Byte;
dataBuffer: TMemoryStream;
addressCounter: LongWord;
begin
Result := UploadImageBufferToHost(comPort, baudRate, sensorAddr, dataBuffer);
if(Result = zsSuccessful) then
begin
try
// Setup output buffer.
outBufferSize := IMG_HEIGHT * IMG_WIDTH;
outBuffer := AllocMem(outBufferSize);
addressCounter := 0;
dataBuffer.Position := 0;
isLowNibble := false;
// Draw fingerprint image on bitmap canvas.
for posY := 0 to (IMG_HEIGHT - 1) do
begin
for posX := 0 to (IMG_WIDTH - 1) do
begin
// Extract nibble from stream and convert it to hi-byte.
if(not isLowNibble) then
begin
sensData := dataBuffer.ReadByte;
colorData := sensData and $f0;
end
else
begin
colorData := (sensData and $0f) shl 4;
end;
isLowNibble := not isLowNibble;
outBuffer[addressCounter] := colorData;
Inc(addressCounter);
end;
end;
except
// General exception. Fail the current task and return memory error.
Result := zsMemoryError;
end;
end;
// Clean resources.
if(Assigned(dataBuffer)) then
begin
dataBuffer.Clear;
FreeAndNil(dataBuffer);
end;
end;
// Function to free allocated memory buffer(s).
function Zfm20FreeFingerprintBuffer(var dataBuffer: PByte): TZfmLibStatus; stdcall;
begin
Result := zsUnknownError;
try
Freemem(dataBuffer, (IMG_HEIGHT * IMG_WIDTH));
Result := zsSuccessful;
except
Result := zsMemoryError;
end;
end;
exports
Zfm20SensorAvailable, Zfm20CaptureFingerprint, Zfm20SaveFingerprintImage,
Zfm20GetFingerprintBuffer, Zfm20FreeFingerprintBuffer;
begin
end.
|
unit Data;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtDlgs, aiOGL, stdctrls, extctrls, jpeg;
type
TData1 = class(TDataModule)
ColorDialog: TColorDialog;
SaveDialog: TSaveDialog;
OpenDialog: TOpenPictureDialog;
OpenPictureDialog: TOpenPictureDialog;
procedure DataModuleCreate(Sender: TObject);
procedure OpenDialogSelectionChange(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure PBPaint(Sender: TObject);
private
ValidPicture: boolean;
end;
procedure ShowColor(Color: TColor; C1,C2,C3: TControl; Shape: TControl);
procedure ShowVector(Vector: TVector; C1,C2,C3: TControl);
function GetVector(C1,C2,C3: TControl): TVector;
var
Data1: TData1;
PB: TPaintBox;
PL: TLabel;
JpegImage: TJpegImage;
implementation
{$R *.DFM}
// раскладывает TColor на составляющие R G B
procedure ShowColor(Color: TColor; C1,C2,C3: TControl; Shape: TControl);
var
CB: TColorB;
begin
CB:= ColorToColorB(Color, 255);
C1.SetTextBuf(PChar(IntToStr(CB.R)));
C2.SetTextBuf(PChar(IntToStr(CB.G)));
C3.SetTextBuf(PChar(IntToStr(CB.B)));
TShape(Shape).Brush.Color:= Color;
end;
procedure ShowVector(Vector: TVector; C1,C2,C3: TControl);
begin
C1.SetTextBuf(PChar(Format('%f', [Vector.X])));
C2.SetTextBuf(PChar(Format('%f', [Vector.Y])));
C3.SetTextBuf(PChar(Format('%f', [Vector.Z])));
end;
// читает TVector без проверки на правильность ввода
function GetVector(C1,C2,C3: TControl): TVector;
var
Buffer: PChar;
begin
GetMem(Buffer, 100);
C1.GetTextBuf(Buffer, C1.GetTextLen + 1);
Result.X:= StrToFloat(Buffer);
C2.GetTextBuf(Buffer, C2.GetTextLen + 1);
Result.Y:= StrToFloat(Buffer);
C3.GetTextBuf(Buffer, C3.GetTextLen + 1);
Result.Z:= StrToFloat(Buffer);
FreeMem(Buffer, 100);
end;
procedure TData1.PBPaint(Sender: TObject);
var
DrawRect: TRect;
begin
DrawRect := PB.ClientRect;
if ValidPicture then
with DrawRect do // рисование взято из ExtDlgs.TOpenPictureDialog.PaintBoxPaint
begin
if (JpegImage.Width > Right - Left) or (JpegImage.Height > Bottom - Top) then
begin
if JpegImage.Width > JpegImage.Height then
Bottom := Top + MulDiv(JpegImage.Height, Right - Left, JpegImage.Width)
else
Right := Left + MulDiv(JpegImage.Width, Bottom - Top, JpegImage.Height);
PB.Canvas.StretchDraw(DrawRect, JpegImage);
end
else
PB.Canvas.Draw(Left + (Right - Left - JpegImage.Width) div 2, Top + (Bottom - Top -
JpegImage.Height) div 2, JpegImage);
end else
PB.Canvas.Rectangle(0, 0, PB.Width, PB.Height);
end;
procedure TData1.DataModuleCreate(Sender: TObject);
begin
OpenDialog.Filter:= '3DStudio files (*.3ds) 3da Files|*.3ds;*.3da|3DStudio files (*.3ds)|*.3ds|3da Files|*.3da';
JpegImage:= TJpegImage.Create;
PB:= OpenDialog.FindComponent('PaintBox') as TPaintBox;
PB.OnPaint:= PBPaint;
PL:= OpenDialog.FindComponent('PictureLabel') as TLabel;
end;
procedure TData1.OpenDialogSelectionChange(Sender: TObject);
var
f: TFileStream;
Pos: cardinal;
begin
ValidPicture:= False;
with OpenDialog do
if FileExists(FileName) and (UpperCase(ExtractFileExt(FileName)) = '.3DA') then
try
f:= TFileStream.Create(FileName, fmOpenRead);
try
Pos:= PicturePosition(f);
if Pos <> 0 then // если Pos = 0 - файл был сохранен без картинки
begin // PutPictureInFile: boolean = True;
f.Position:= Pos; // это позиция сохраненной картинки в jpeg формате
JpegImage.LoadFromStream(f); // загрузить
ValidPicture:= True;
PL.Caption:= Format('%d X %d', [JpegImage.Width,JpegImage.Height]);
end;
finally
f.Free;
end;
except
ValidPicture:= False;
end;
PB.Invalidate;
end;
procedure TData1.DataModuleDestroy(Sender: TObject);
begin
JpegImage.Free;
end;
end.
|
unit uMainInfoFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uMainInfoData, uFormControl, uFControl, SpFormUnit,
uLabeledFControl, uCharControl, ComCtrls, uIntControl, uSpravControl,
uEnumControl, uDateControl, Buttons, SpCommon, ExtCtrls, uInvisControl,
uMemoControl, uCommonSP;
type
TfmPCardMainInfo = class(TFrame)
qFFC_Main: TqFFormControl;
FIO: TqFCharControl;
RUS_FIO: TqFCharControl;
CardNumber: TqFIntControl;
TN: TqFIntControl;
TIN: TqFCharControl;
Sex: TqFEnumControl;
Birth_Date: TqFDateControl;
SB_ModifInfo: TSpeedButton;
FamilyStatus: TqFSpravControl;
Panel1: TPanel;
Panel2: TPanel;
SB_MainApply: TSpeedButton;
SB_MainReset: TSpeedButton;
qFIC_IdMan: TqFInvisControl;
qFMC_BirthPl: TqFMemoControl;
qFMC_LivePl: TqFMemoControl;
Label1: TLabel;
SB_Print: TSpeedButton;
qFMC_FactLivePl: TqFMemoControl;
WorkPhone: TqFCharControl;
HomePhone: TqFCharControl;
procedure NationalityOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure FamilyStatusOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure SB_MainApplyClick(Sender: TObject);
procedure SB_MainResetClick(Sender: TObject);
procedure SB_ModifInfoClick(Sender: TObject);
procedure TNChange(Sender: TObject);
procedure SB_PrintClick(Sender: TObject);
procedure WorkPhoneChange(Sender: TObject);
procedure HomePhoneChange(Sender: TObject);
private
DM: TdmPCMainInfo;
public
Id:Variant;
Mode:TFormMode;
constructor Create(AOwner: TComponent; DM: TdmPCMainInfo; Mode:TFormMode; Id_PCard: Integer);
reintroduce;
end;
implementation
uses AllPeopleUnit;
{$R *.dfm}
constructor TfmPCardMainInfo.Create(AOwner: TComponent; DM: TdmPCMainInfo; Mode:TFormMode; Id_PCard: Integer);
begin
inherited Create(AOwner);
Self.DM := DM;
Self.Mode:=Mode;
id:=Id_PCard;
qFFC_Main.Prepare(DM.DB, Mode, Id_PCard, Null);
SB_MainApply.Enabled:=(Mode=fmModify);
SB_MainReset.Enabled:=(Mode=fmModify);
label1.visible:=false;
// SB_ModifInfo.Enabled:=(Mode=fmModify);
// qFFC_Additional.Prepare(DM.DB, fmInfo, Id_PCard, Null);
end;
procedure TfmPCardMainInfo.NationalityOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
form: TSpForm;
PropParams: TSpParams;
begin
PropParams:=TSpParams.Create;
with PropParams do
begin
Table := 'Asup_Sp_Nationality';
Title := 'Національність';
IdField := 'Id_Nationality';
SpFields := 'Name_Nationality';
ColumnNames := 'Національність';
SpMode := spmSelect;
end;
form := TSpForm.Create(Self);
form.Init(PropParams);
if (form.ShowModal=mrOk) then
begin
value:=form.ResultQuery['id_Nationality'];
DisplayText:=form.ResultQuery['name_Nationality'];
end;
form.Free;
PropParams.Free;
end;
procedure TfmPCardMainInfo.FamilyStatusOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
form: TSpForm;
PropParams: TSpParams;
begin
PropParams:=TSpParams.Create;
with PropParams do
begin
Table := 'Ini_Family_Status';
Title := 'Сімейне становище';
IdField := 'Id_Family_Status';
SpFields := 'Name_Status';
SelectProcName := 'Ini_Family_Status';
ColumnNames := 'Сімейне становище,-';
ReadOnly:=True;
SpMode := spmSelect;
end;
form := TSpForm.Create(Self);
form.Init(PropParams);
if (form.ShowModal=mrOk) then
begin
if (form.ResultQuery['Id_Sex']=Sex.Value) then
begin
value:=form.ResultQuery['Id_Family_Status'];
DisplayText:=form.ResultQuery['Name_Status'];
end
else MessageDlg('Сімейне становище не відповідає статі!',mtError,[mbYes],0);
end;
form.Free;
PropParams.Free;
end;
procedure TfmPCardMainInfo.SB_MainApplyClick(Sender: TObject);
begin
if (qFFC_Main.Ok)
then label1.visible:=false;
end;
procedure TfmPCardMainInfo.SB_MainResetClick(Sender: TObject);
begin
qFFC_Main.Prepare(DM.DB, Mode, Id, Null);
label1.visible:=false;
end;
procedure TfmPCardMainInfo.SB_ModifInfoClick(Sender: TObject);
begin
AllPeopleUnit.ShowManEditForm(Self, DM.DB.Handle, qFIC_IdMan.GetValue, Mode=fmModify);
qFFC_Main.Prepare(DM.DB, Mode, Id, Null);
label1.visible:=false;
end;
procedure TfmPCardMainInfo.TNChange(Sender: TObject);
begin
label1.visible:=true;
end;
procedure TfmPCardMainInfo.SB_PrintClick(Sender: TObject);
var
sp: TSprav;
new_vers:Boolean;
i:integer;
begin
new_vers := False;
for i := 1 to ParamCount do if ParamStr(i) = 'newversion' then begin
new_vers := True;
Break;
end;
if new_vers
then begin
sp := GetSprav('UP/UpReportCard');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
// присвоить хэндл базы данных
FieldValues['DBHandle'] := Integer(DM.DB.Handle);
// MDI-окно
FieldValues['id_pcard'] := id;
// без выборки
Post;
end;
end;
// просто показать справочник
sp.Show;
end
else begin
// создать справочник
sp := GetSprav('ASUP/AsupReportCard');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
// присвоить хэндл базы данных
FieldValues['DBHandle'] := Integer(DM.DB.Handle);
// MDI-окно
FieldValues['id_pcard'] := id;
// без выборки
Post;
end;
end;
// просто показать справочник
sp.Show;
end;
end;
procedure TfmPCardMainInfo.WorkPhoneChange(Sender: TObject);
begin
Label1.Visible:=true;
end;
procedure TfmPCardMainInfo.HomePhoneChange(Sender: TObject);
begin
Label1.Visible:=true;
end;
end.
|
unit SDL2_SimpleGUI_Base;
{:< Base Unit which provides the common procedures and data that most units
need }
{ Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski,
get more infos here:
https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI.
It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal,
get it here: https://sourceforge.net/projects/lkgui.
Written permission to re-license the library has been granted to me by the
original author.
Copyright (c) 2016-2020 Matthias J. Molski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. }
interface
uses
SDL2;
type
{: Necessary to pass typed array as func./proc. parameter. It contains the
input information as returned by SDL event SDL_TextInput. }
TSDLTextInputArray = array[0..SDL_TEXTINPUTEVENT_TEXT_SIZE] of char;
type
{: Basic color type. } { TODO : Why not using SDL_Color? }
TRGBA = record
r: byte;
g: byte;
b: byte;
a: byte;
end;
TTextAlign = (Align_Left, Align_Center, Align_Right);
TVertAlign = (VAlign_Top, VAlign_Center, VAlign_Bottom);
TDirection = (Dir_Horizontal, Dir_Vertical);
TBorderStyle = (BS_None, BS_Single);
TFillStyle = (FS_None, FS_Filled);
implementation
begin
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Amazon.Storage.Service.API;
interface
uses System.Classes,
System.JSON,
System.SysUtils,
System.Generics.Collections,
Data.Cloud.CloudAPI,
Amazon.Storage.Service.API.Life.Cycle,
Xml.XMLIntf;
type
/// <summary>Bucket/Object ACL types</summary>
TAmazonACLType = (amzbaNotSpecified, amzbaPrivate, amzbaPublicRead, amzbaPublicReadWrite,
amzbaAuthenticatedRead, amzbaBucketOwnerRead, amzbaBucketOwnerFullControl,
amzbaAWSExecRead, amzbaLogDeliveryWrite);
/// <summary>Regions which can be used with Amazon Services.</summary>
TAmazonRegion = (amzrNotSpecified, amzrEUWest1, amzrEUWest2, amzrEUWest3, amzrEUCentral1,
amzrUSEast1, amzrUSWest1, amzrUSWest2, amzrAPSoutheast1, amzrAPSoutheast2,
amzrAPNortheast1, amzrAPNortheast2, amzrAPNortheast3, amzrSAEast1,
amzrUSClassic, amzrEU, amzrCNNorth1, amzrCNNorthwest1);
/// <summary>The available Grant permissions.</summary>
TAmazonGrantPermission = (amgpFullControl, amgpWrite, amgpWriteACP, amgpRead, amgpReadACP, amgpUnknown);
/// <summary>The available Grantee types.</summary>
TAmazonGranteeType = (agtCanonicalUser, agtCustomerByEmail, agtGroup, agtUnknown);
/// <summary>Amazon payer options.</summary>
TAmazonPayer = (ampRequester, ampBucketOwner, ampUnknown);
//The item names must exactly match the available Amazon attribute names, with a 3 letter prefix.
/// <summary>The available property types for an Amazon queue.</summary>
TAmazonQueueAttribute = (aqaAll, aqaApproximateNumberOfMessages, aqaApproximateNumberOfMessagesNotVisible,
aqaVisibilityTimeout, aqaCreatedTimestamp, aqaLastModifiedTimestamp,
aqaPolicy, aqaMaximumMessageSize, aqaMessageRetentionPeriod,
aqaQueueArn, aqaApproximateNumberOfMessagesDelayed, aqaDelaySeconds,
aqaReceiveMessageWaitTimeSeconds, aqaRedrivePolicy);
/// <summary>The available actions for an Amazon queue, for which permissions can be established.</summary>
TAmazonQueueActions = (aqacAll, aqacSendMessage, aqacReceiveMessage, aqacDeleteMessage,
aqacChangeMessageVisibility, aqacGetQueueAttributes);
/// <summary>Amazon specific implementation of TCloudSHA256Authentication</summary>
/// <remarks>Sets the Authorization type to 'AWS'</remarks>
TAmazonAuthentication = class(TCloudSHA256Authentication)
public const
AuthorizationType = 'AWS';
protected
/// <summary>Specifies if the Auth is in header, or as a query parameter</summary>
FAuthInHeader: Boolean;
public
/// <summary>Creates a new instance of TAmazonAuthentication</summary>
/// <remarks>Sets the authorization type (for the authorization header) to 'AWS'</remarks>
// / <param name="ConnectionInfo">The connection info to use in authentication</param>
// / <param name="AuthInHeader">Specifies if the Auth is in header, or as a query parameter</param>
constructor Create(const ConnectionInfo: TCloudConnectionInfo; AuthInHeader: Boolean = False); overload;
/// <summary>Builds the string to use as the value of the Authorization header or 'Signature' Query Parameter.</summary>
/// <remarks>The 'StringToSign' passed in is encoded using the 'ConnectionInfo' of this class,
/// and the 'SignString' function of the subclass. The result of this is then combined with
/// the result returned by 'GetAuthorizationType' to build the value string to use with the
/// Authorization header, or 'Signature' Query Parameter of all requests to the cloud.
///
/// Note that the resulting format depends on the value of 'AuthInHeader'. The signed string will
/// either be returned directly, or as part of an Authorization header formatted string.
/// </remarks>
/// <param name="StringToSign">The string to sign and use in authentication</param>
function BuildAuthorizationString(const StringToSign: string): string; override;
end;
/// <summary>Amazon AWS4 specific implementation of TCloudSHA256Authentication</summary>
/// <remarks>Sets the Authorization type to 'AWS4-HMAC-SHA256'</remarks>
TAmazonAWS4Authentication = class(TCloudSHA256Authentication)
public const
AuthorizationType = 'AWS4-HMAC-SHA256';
protected
/// <summary>Specifies if the Auth is in header, or as a query parameter</summary>
FAuthInHeader: Boolean;
procedure AssignKey(const AccountKey: string); override;
public
constructor Create(const ConnectionInfo: TCloudConnectionInfo; AuthInHeader: Boolean = False); overload;
/// <summary>Builds the string to use as the value of the Authorization header of requests.</summary>
/// <remarks>http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html</remarks>
/// <param name="StringToSign">The string to sign and use in the Authorization header value.</param>
/// <param name="DateISO">Specific date used to build the signature key.</param>
/// <param name="Region">Specific region used to build the signature key.</param>
/// <param name="SignedStrHeaders">Signed headers used to build the authorization string.</param>
function BuildAuthorizationString(const StringToSign, DateISO, Region, SignedStrHeaders: string): string; reintroduce; overload;
function BuildAuthorizationString(const StringToSign, DateISO, Region, ServiceName, SignedStrHeaders: string): string; reintroduce; overload;
end;
/// <summary>Amazon specific implementation of TCloudSHA1uthentication</summary>
/// <remarks>Sets the Authorization type to 'AWS'</remarks>
TAmazonSHA1Authentication = class(TCloudSHA1Authentication)
public const
AuthorizationType = 'AWS';
public
/// <summary>Creates a new instance of TAmazonAuthentication</summary>
/// <remarks>Sets the authorization type (for the authorization header) to 'AWS'</remarks>
// / <param name="ConnectionInfo">The connection info to use in authentication</param>
constructor Create(const ConnectionInfo: TCloudConnectionInfo); overload;
end;
/// <summary>Amazon extension of TCloudConnectionInfo</summary>
TAmazonConnectionInfo = class(TCloudConnectionInfo)
public const
DefaultStorageEndpoint = 's3.amazonaws.com';
DefaultTableEndpoint = 'sdb.amazonaws.com';
DefaultQueueEndpoint = 'queue.amazonaws.com';
RegionStorageEndpoint = 's3.%s.amazonaws.com';
RegionTableEndpoint = 'sdb.%s.amazonaws.com';
RegionQueueEndpoint = '%s.queue.amazonaws.com';
DefaultRegion = amzrUSEast1;
private
FConsistentRead: Boolean;
FMFASerialNumber: string;
FMFAAuthCode: string;
FStorageEndpoint: string;
FTableEndpoint: string;
FQueueEndpoint: string;
FRegion: TAmazonRegion;
function GetServiceURL(const AHost: string): string; overload;
function GetServiceURL(const AHost, ARegionHost: string; ARegion: TAmazonRegion): string; overload;
function GetQueueURL: string;
function GetTableURL: string;
function GetQueueEndpoint: string;
function GetTableEndpoint: string;
function GetStorageEndpoint: string;
procedure SetStorageEndpoint(const AValue: string);
procedure SetQueueEndpoint(const AValue: string);
procedure SetTableEndpoint(const AValue: string);
procedure SetRegion(const AValue: TAmazonRegion);
function GetRegion: TAmazonRegion;
function GetVirtualHost(const AHost, ARegionHost: string; ARegion: TAmazonRegion): string;
public
/// <summary>Creates a new instance of this connection info class</summary>
/// <param name="AOwner">The component owner.</param>
constructor Create(AOwner: TComponent); override;
/// <summary>The queue service URL for issuing requests.</summary>
property QueueURL: string read GetQueueURL;
/// <summary>The SimpleDB (Table service) URL for issuing requests.</summary>
property TableURL: string read GetTableURL;
/// <summary>The S3 (Storage service) URL for issuing requests.</summary>
/// <param name="ABucketName">The optional bucket name to prefix the URL with</param>
/// <param name="ARegion">The optional region of the backet</param>
/// <returns>The S3 (Storage service) URL for issuing requests.</returns>
function StorageURL(const ABucketName: string = ''; ARegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Determines S3 Virtual Host name based on bucket and endpoint.</summary>
/// <param name="ABucketName">The optional bucket name to prefix the host path</param>
/// <param name="ARegion">The optional region of the backet</param>
/// <returns>The S3 (Storage service) Virtual hostname .</returns>
function StorageVirtualHost(const ABucketName: string = ''; ARegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the string representation of the given region.</summary>
/// <param name="Region">The region</param>
/// <returns>The string representation of the given region.</returns>
class function GetRegionString(Region: TAmazonRegion): string; static;
/// <summary>Returns the region for the given string representation.</summary>
/// <param name="Region">The region in string form</param>
/// <returns>The region for the given string representation.</returns>
class function GetRegionFromString(const Region: string): TAmazonRegion; static;
published
/// <summary>Raising the property to published</summary>
property AccountName;
/// <summary>Raising the property to published</summary>
property AccountKey;
/// <summary>The protocol to use as part of the service URL (http|https)</summary>
property Protocol;
/// <summary>The proxy host to use for the HTTP requests to the cloud, or empty string to use none</summary>
property RequestProxyHost;
/// <summary>The proxy host's port to use for the HTTP requests to the cloud</summary>
property RequestProxyPort;
/// <summary>True to use consistent read, whenever possible.</summary>
/// <remarks>Amazon often uses the 'eventual consistency' read option, which doesn't promise
/// that any one read operation is returning the most recent data. Some services allow for
/// setting ConsistenRead to true, which disables this eventual consistency model.
/// </remarks>
[Default(True)]
property ConsistentRead: Boolean read FConsistentRead write FConsistentRead default True;
/// <summary>The serial number to use when MFA Delete is enabled.</summary>
property MFASerialNumber: string read FMFASerialNumber write FMFASerialNumber;
/// <summary>The authentication code to use when MFA Delete is enabled.</summary>
property MFAAuthCode: string read FMFAAuthCode write FMFAAuthCode;
/// <summary>The host/endpoint to use when connecting with the SimpleDB (Table) service.</summary>
property TableEndpoint: string read GetTableEndpoint write SetTableEndpoint;
/// <summary>The host/endpoint to use when connecting with the queue service.</summary>
property QueueEndpoint: string read GetQueueEndpoint write SetQueueEndpoint;
/// <summary>The host/endpoint to use when connecting with the S3 (Storage) service.</summary>
property StorageEndpoint: string read GetStorageEndpoint write SetStorageEndpoint;
property Region: TAmazonRegion read GetRegion write SetRegion default DefaultRegion;
/// <summary>True to use the default service URLs, false to use endpoints from the endpoint properties.
/// </summary>
property UseDefaultEndpoints;
end;
/// <summary>Abstract extension of the TCloudService class.</summary>
/// <remarks>This implements all functionality common to the Amazon S3m SQS and SimpleDB services,
/// or common to two of them (allowing the third to extend further and override.)
///</remarks>
TAmazonService = class abstract(TCloudService)
protected
/// <summary>URL encodes the given value.</summary>
/// <param name="Value">The string to URL encode</param>
/// <returns>The URL encoded value.</returns>
function URLEncodeValue(const Value: string): string; override;
/// <summary>Returns the ConnectionInfo, cast as a TAmazonConnectionInfo</summary>
/// <returns>ConnectionInfo, cast as a TAmazonConnectionInfo</returns>
function GetConnectionInfo: TAmazonConnectionInfo;
/// <summary>Returns nil, as SQS and SimpleDB don't have required header values.</summary>
/// <returns>nil</returns>
function GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings; override;
/// <summary>Returns empty string, as SQS and SimpleDB don't use Canonicalized Headers.</summary>
/// <returns>empty string</returns>
function GetCanonicalizedHeaderPrefix: string; override;
/// <summary>Returns the current time, formatted properly as a string.</summary>
/// <returns>The current time, formatted properly as a string</returns>
function CurrentTime: string; virtual;
/// <summary>Returns the authentication instance to use for the given connection info.</summary>
/// <returns>The authentication instance to use for the given connection info.</returns>
function CreateAuthInstance(const ConnectionInfo: TAmazonConnectionInfo): TCloudAuthentication; virtual; abstract;
/// <summary>Sorts the given list of Headers.</summary>
/// <remarks>Extend this if you wish to modify how the list is sorted.</remarks>
/// <param name="Headers">List of headers to sort.</param>
procedure SortHeaders(const Headers: TStringList); override;
/// <summary>Returns a ISO8601 date with no separator characters</summary>
function ISODateTime_noSeparators: string;
/// <summary>Populates the given ResponseInfo with error information, if any.</summary>
/// <remarks>If the given ResponseInfo is non-null, and the ResultString holds an XML error message,
/// then this procedure will parse the error XML and populate the ResponseInfo's message
/// with the error message.
/// </remarks>
/// <param name="ResponseInfo">The optional response info to populate, or nil</param>
/// <param name="ResultString">The request's response string to parse for an error message.</param>
procedure ParseResponseError(const ResponseInfo: TCloudResponseInfo; const ResultString: string); virtual; abstract;
public
/// <summary>Creates a new instance of TAmazonService</summary>
/// <remarks>This class does not own the ConnectionInfo instance.</remarks>
// / <param name="ConnectionInfo">The Amazon service connection info</param>
constructor Create(const ConnectionInfo: TAmazonConnectionInfo);
/// <summary>Frees the required headers list and destroys the instance</summary>
destructor Destroy; override;
end;
/// <summary>A queue permission, specifying the AWS account it applies to, and the allowed action.</summary>
TAmazonQueuePermission = record
/// <summary>The AWS account Id this permission applies to.</summary>
/// <remarks>Must be a valid 12-digit AWS account number, without hyphens</remarks>
AccountId: string;
/// <summary>The action which this permission is allowing.</summary>
Action: TAmazonQueueActions;
/// <summary>Creates a new instance of TAmazonQueuePermission</summary>
/// <param name="AccountId">The AWS account Id this permission applies to.</param>
/// <param name="Action">The action which this permission is allowing. Defaults to All</param>
/// <returns>The new initialised instance of TAmazonQueuePermission</returns>
class function Create(const AccountId: string; Action: TAmazonQueueActions = aqacAll): TAmazonQueuePermission; static;
/// <summary>Returns the string representation of the action</summary>
/// <returns>The string representation of the action</returns>
function GetAction: string;
end;
/// <summary>Authentication and other common functionality shared by table and queue services, but not S3.</summary>
TAmazonBasicService = class(TAmazonService)
protected
/// <summary>Returns the authentication instance to use for the given connection info.</summary>
/// <returns>The authentication instance to use for the given connection info.</returns>
function CreateAuthInstance(const ConnectionInfo: TAmazonConnectionInfo): TCloudAuthentication; override;
/// <summary>Handles the StringToSign after it is created.</summary>
/// <remarks>This modifies the provided URL or the content stream, adding a 'Signature' query parameter.
/// </remarks>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request.</param>
/// <param name="Headers">The header name/value pairs</param>
/// <param name="QueryParameters">The query parameter name/value pairs</param>
/// <param name="StringToSign">The StringToSign for the request</param>
/// <param name="URL">The URL of the request</param>
/// <param name="Request">The request object</param>
/// <param name="Content">The content stream of the request.</param>
procedure PrepareRequestSignature(const HTTPVerb: string;
const Headers, QueryParameters: TStringList;
const StringToSign: string;
var URL: string; Request: TCloudHTTP; var Content: TStream); override;
/// <summary>Takes in a URL and optionally uses it to parse the HTTPRequestURI</summary>
/// <remarks>The overrides the base implementation, adding "ValueOfHostHeaderInLowercase"
/// on a new line before the URI.
/// </remarks>
/// <param name="URL">The URL of the request.</param>
/// <returns>The second and third portions of the StringToSign, ending with a newline character.</returns>
function BuildStringToSignResourcePath(const URL: string): string; override;
/// <summary>Creates the list of query parameters to use for the given action.</summary>
/// <remarks>Returns the action query parameter, as well as the other parameters common to all requests.
/// The action itself should be something like "ListQueues".
/// </remarks>
/// <param name="Action">The action currently being performed</param>
/// <returns></returns>
function BuildQueryParameters(const Action: string): TStringList;
/// <summary>Sorts the query parameters by name.</summary>
/// <remarks>This sorts by name, but keeps AWSAccessKeyId at the beginning of the list.</remarks>
/// <param name="QueryParameters">The list of parameters to sort</param>
/// <param name="ForURL">True if the parameters are for use in a URL, false otherwise.</param>
procedure SortQueryParameters(const QueryParameters: TStringList; ForURL: Boolean); override;
/// <summary>Issues the request, as either a GET or a POST</summary>
/// <remarks>If the RequestStream is specified, then a POST request is issued and the stream is used
/// in the HTTP request as the body and the query parameters are placed in the URL of the request.
/// Otherwise, if it is nil, then the CanonicalizedQueryString is built from the given
/// information and is placed in the body of the request, which is issued as a GET.
/// </remarks>
/// <param name="URL">The request URL, without any query parameters</param>
/// <param name="QueryParams">The query parameters of the request</param>
/// <param name="ResponseInfo">The optional response info to populate, or nil</param>
/// <param name="ResultString">The string representation of the response content.</param>
/// <param name="RequestStream">The request stream to set as the body of the request, or nil.</param>
/// <returns>The HTTP request/response object</returns>
function IssueRequest(URL: string; QueryParams: TStringList; ResponseInfo: TCloudResponseInfo;
out ResultString: string; RequestStream: TStream = nil): TCloudHTTP; overload;
/// <summary>Issues the request, as either a GET or a POST</summary>
/// <remarks>If the RequestStream is specified, then a POST request is issued and the stream is used
/// in the HTTP request as the body and the query parameters are placed in the URL of the request.
/// Otherwise, if it is nil, then the CanonicalizedQueryString is built from the given
/// information and is placed in the body of the request, which is issued as a GET.
/// </remarks>
/// <param name="URL">The request URL, without any query parameters</param>
/// <param name="QueryParams">The query parameters of the request</param>
/// <param name="ResponseInfo">The optional response info to populate, or nil</param>
/// <param name="RequestStream">The request stream to set as the body of the request, or nil.</param>
/// <returns>The HTTP request/response object</returns>
function IssueRequest(URL: string; QueryParams: TStringList; ResponseInfo: TCloudResponseInfo;
RequestStream: TStream = nil): TCloudHTTP; overload;
/// <summary>Populates the given ResponseInfo with error information, if any.</summary>
/// <remarks>If the given ResponseInfo is non-null, and the ResultString holds an XML error message,
/// then this procedure will parse the error XML and populate the ResponseInfo's message
/// with the error message.
///
/// This also populates a header value with key 'RequestId', regardless of if the ResultString
/// is error XML, or representing a successful request.
/// </remarks>
/// <param name="ResponseInfo">The optional response info to populate, or nil</param>
/// <param name="ResultString">The request's response string to parse for an error message.</param>
procedure ParseResponseError(const ResponseInfo: TCloudResponseInfo; const ResultString: string); override;
/// <summary>Returns the version query parameter value to use in requests.</summary>
/// <returns>The version query parameter value to use in requests.</returns>
function GetServiceVersion: string; virtual; abstract;
/// <summary>Returns the host string for the service.</summary>
/// <returns>The host string for the service.</returns>
function GetServiceHost: string; virtual; abstract;
end;
/// <summary>Represents a single row to be updated in a batch execution.</summary>
TAmazonBatchRow = record
/// <summary>The unique ID of the row to update with this content</summary>
RowId: string;
/// <summary>The row content to commit</summary>
Row: TCloudTableRow;
/// <summary>True to replace any column content that matches any of the given column names.</summary>
/// <remarks>Columns can have multiple values. If this is set to false, then any existing values for
/// a column being specified here will remain, and the new value will simply be added beside it.
/// </remarks>
ReplaceAll: Boolean;
/// <summary>Creates a new instance of TAmazonBatchRow</summary>
/// <param name="RowId">The unique ID of the row to update with this content</param>
/// <param name="Row">The row content to commit</param>
/// <param name="ReplaceAll">True to replace any column content that matches any of the given column names.</param>
/// <returns>The new instance of TAmazonBatchRow</returns>
class function Create(const RowId: string; Row: TCloudTableRow;
ReplaceAll: Boolean = True): TAmazonBatchRow; static;
end;
/// <summary>Conditional for inserting/updating a row.</summary>
/// <remarks>When inserting or deleting a row (in a non-batch operation) you can specify one or more
/// conditions which must be met in order to perform the action. These conditions are either that
/// the server already contains a specific value for a specific column, or that the column doesn't exist.
/// This can be used to insure multiple processes do not overwrite each other.
/// </remarks>
TAmazonRowConditional = record
/// <summary>The column name to check.</summary>
ColumnName: string;
/// <summary>The column value to check for, if not just checking column existence.</summary>
ColumnValue: string;
/// <summary>True to check that the column exists. False to check that it doesn't exist.</summary>
ColumnExists: Boolean;
/// <summary>Creates a new instance of TAmazonRowConditional, checking only column existence.</summary>
/// <remarks>If ColumnExists is set to true, The column Value is checked.</remarks>
/// <param name="ColumnName">The name of the column to check.</param>
/// <param name="ColumnValue">The value of the column to expect and check against.</param>
/// <param name="ColumnExists">true to check if the column exists, false to check that it doesn't</param>
/// <returns>The new instance of TAmazonRowConditional</returns>
class function Create(const ColumnName, ColumnValue: string;
const ColumnExists: Boolean = True): TAmazonRowConditional; static;
end;
/// <summary>Implementation of TAmazonBasicService for managing an Amazon SimpleDB account.</summary>
TAmazonTableService = class(TAmazonBasicService)
protected
/// <summary>Returns the version query parameter value to use in requests.</summary>
/// <returns>The version query parameter value to use in requests.</returns>
function GetServiceVersion: string; override;
/// <summary>Returns the host string for the service.</summary>
/// <returns>The host string for the service.</returns>
function GetServiceHost: string; override;
public
/// <summary>Creates a table (Domain) with the given name.</summary>
/// <remarks>The name can range between 3 and 255 characters and
/// can contain the following characters: a-z, A-Z, 0-9, '_', '-', and '.'
/// </remarks>
/// <param name="TableName">The name of the table to create</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the creation was a success, false otherwise.</returns>
function CreateTable(const TableName: string; ResponseInfo: TCloudResponseInfo = nil): Boolean;
/// <summary>Deletes the table (Domain) with the given name.</summary>
/// <remarks>This marks the table for delete and hides it from future calls when querying the
/// list of available tables. However, it isn't deleted from the server right away,
/// and for a short time after calling delete, you will not be able to create a new table
/// with the same name.
/// </remarks>
/// <param name="TableName">The name of the table (Domain) to delete</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete is successful, false otherwise</returns>
function DeleteTable(const TableName: string; ResponseInfo: TCloudResponseInfo = nil): Boolean;
/// <summary>Returns an XML representation of the tables existing in the table service account.</summary>
/// <remarks>ContinuationToken is used if there exists more than 'MaxNumberOfTables' tables,
/// and a previous call didn't return the last of the tables. It would have provided a
/// ContinuationToken in the 'NextToken' XML element.
///
/// The server will default the value of MaxNumberOfTables to 100 (the maximum) if you set it to
/// a number of zero or less.
/// </remarks>
/// <param name="ContinuationToken">The optional NextToken to continue table population from.</param>
/// <param name="MaxNumberOfTables">The maximum number of tables to return</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the available tables for the service</returns>
function QueryTablesXML(const ContinuationToken: string = ''; const MaxNumberOfTables: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil): string;
/// <summary>Returns a list of the tables existing in the table service account.</summary>
/// <remarks>ContinuationToken is used if there exists more than 'MaxNumberOfTables' tables,
/// and a previous call didn't return the last of the tables. It would have provided a
/// ContinuationToken in the 'NextToken' XML element.
///
/// The server will default the value of MaxNumberOfTables to 100 (the maximum) if you set it to
/// a number of zero or less.
/// </remarks>
/// <param name="ContinuationToken">The optional NextToken to continue table population from.</param>
/// <param name="MaxNumberOfTables">The maximum number of tables to return</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of available tables for the service, or nil if a failure occurred.</returns>
function QueryTables(const ContinuationToken: string = ''; const MaxNumberOfTables: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil): TStrings;
/// <summary>Returns a list of metadata associated with the given table.</summary>
/// <remarks>Returns the following information:
/// Timestamp - the date/time the metadata was last modified
/// ItemCount - the number of items in the table (domain)
/// AttributeValueCount - The total number of name/value pairs
/// AttributeNameCount - The number of (unique) attribute names in the pairs
/// ItemNamesSizeBytes - The total size (in bytes) of all item names in the table
/// AttributeValuesSizeBytes - The total size (in bytes) of all attribute values
/// AttributeNamesSizeBytes - The total size (in bytes) of all unique attribute names
/// </remarks>
/// <param name="TableName">The name of the table (Domain) to get metadata for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the available tables for the service.</returns>
function GetTableMetadataXML(const TableName: string; ResponseInfo: TCloudResponseInfo = nil): string;
/// <summary>Returns a list of metadata associated with the given table.</summary>
/// <remarks>Returns the following information:
/// Timestamp - the date/time the metadata was last modified
/// ItemCount - the number of items in the table (domain)
/// AttributeValueCount - The total number of name/value pairs
/// AttributeNameCount - The number of (unique) attribute names in the pairs
/// ItemNamesSizeBytes - The total size (in bytes) of all item names in the table
/// AttributeValuesSizeBytes - The total size (in bytes) of all attribute values
/// AttributeNamesSizeBytes - The total size (in bytes) of all unique attribute names
/// </remarks>
/// <param name="TableName">The name of the table (Domain) to get metadata for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of available tables for the service, or nil if a failure occurred.</returns>
function GetTableMetadata(const TableName: string; ResponseInfo: TCloudResponseInfo = nil): TStrings;
/// <summary>Inserts a row into the given table.</summary>
/// <remarks>Columns can contain multiple values. You can insert one or more name-value pairs
/// where the names (which are the column names) are the same. Furthermore, values could already
/// exist on the server for a specific column. If you don't set ReplaceAll to true, then any
/// pre-existing values for a column you specify will remain, and your new value(s) will be added.
///
/// Note that if columns exist on the server, but you don't specify them in this call, then they
/// will remain on the server, regardless of the value of ReplaceAll.
///
/// Conditionals can only be used with single-values attributes.
/// </remarks>
/// <param name="TableName">The name of the table to insert the row into</param>
/// <param name="RowId">The unique Id of the row being inserted/updated</param>
/// <param name="Row">The row to insert or update</param>
/// <param name="Conditionals">The conditionals for performing the insert, or nil.</param>
/// <param name="ReplaceAll">True to replace the values already stored for any specified column names.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the insertion is successful, false otherwise</returns>
function InsertRow(const TableName, RowId: string; Row: TCloudTableRow;
Conditionals: TList<TAmazonRowConditional>;
ReplaceAll: Boolean = True;
ResponseInfo: TCloudResponseInfo = nil): Boolean;
/// <summary>Does a batch insert of the given rows into the specified table.</summary>
/// <remarks>Columns can contain multiple values. You can insert one or more name-value pairs
/// where the names (which are the column names) are the same. Furthermore, values could already
/// exist on the server for a specific column. If you don't set ReplaceAll to true, then any
/// pre-existing values for a column you specify will remain, and your new value(s) will be added.
///
/// Note that if columns exist on the server, but you don't specify them in this call, then they
/// will remain on the server, regardless of the value of ReplaceAll.
/// </remarks>
/// <param name="TableName">The name of the table to insert the rows into</param>
/// <param name="Rows">The rows to batch insert/update</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the insertion is successful, false otherwise</returns>
function InsertRows(const TableName: string; Rows: TList<TAmazonBatchRow>;
ResponseInfo: TCloudResponseInfo = nil): Boolean;
/// <summary>Returns the rows for the specified table.</summary>
/// <remarks>The select statement must be a properly formatted Select statement, beginning with "select".
/// If you want to specify the 'ItemId' column, use the string: 'ItemName()'
/// You can select any columns you wish, use where, like, order by and limit clauses,
/// as you would expect from a select statement.
///
/// If ResponseInfo is specified and there is a NextToken value specified in the resulting
/// XML, then a NextToken key/value pair will be put into the ResponseInfo's Headers list.
/// </remarks>
/// <param name="SelectStatement">The select statement to issue</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="NextToken">Continuation token (NextToken) value from a previous request</param>
/// <returns>The XML representation of the row IDs</returns>
function SelectRowsXML(const SelectStatement: string;
ResponseInfo: TCloudResponseInfo = nil;
const NextToken: string = ''): string;
/// <summary>Returns the row (Item) IDs for the specified table.</summary>
/// <remarks>This selects all attributes of all rows returned, or just the row IDs.
/// You can optionally limit the number of results. For more fine-grained control, use SelectRows.
///
/// If ResponseInfo is specified and there is a NextToken value specified in the resulting
/// XML, then a NextToken key/value pair will be put into the ResponseInfo's Headers list.
/// </remarks>
/// <param name="TableName">The name of the table to get the row IDs for</param>
/// <param name="MaxNumberOfItems">The number of rows to return, or 0 to return the maximum allowed number</param>
/// <param name="ItemIdOnly">True to only return the item name, false to return all attributes (columns)</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="NextToken">Continuation token (NextToken) value from a previous request</param>
/// <returns>The XML representation of the row IDs</returns>
function GetRowsXML(const TableName: string;
MaxNumberOfItems: Integer = 0;
ItemIdOnly: Boolean = False;
ResponseInfo: TCloudResponseInfo = nil;
const NextToken: string = ''): string;
/// <summary>Returns the rows (Items) for the specified table.</summary>
/// <remarks>This selects all attributes of all rows returned. You can optionally limit the number of results.
/// For more fine-grained control, use SelectRows.
///
/// For each row, the first column is called 'ItemName()' and is the Row's unique ID. This can not
/// be used in all situations that other column name/value pairs can be used. For example, 'ItemName()'
/// can be used in a select statement, but it cannot be deleted from a row.
/// </remarks>
/// <param name="TableName">The name of the table to get the row IDs for</param>
/// <param name="MaxNumberOfItems">The number of rows to return, or 0 to return the maximum allowed number</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="NextToken">Continuation token (NextToken) value from a previous request</param>
/// <returns>The list of rows, or nil if the call failed</returns>
function GetRows(const TableName: string;
MaxNumberOfItems: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil;
const NextToken: string = ''): TList<TCloudTableRow>;
/// <summary>Returns the row (Item) IDs for the specified table.</summary>
/// <remarks>This selects all attributes of all rows returned. You can optionally limit the number of results.
/// For more fine-grained control, use SelectRows.
/// </remarks>
/// <param name="TableName">The name of the table to get the row IDs for</param>
/// <param name="MaxNumberOfItems">The number of rows to return, or 0 to return the maximum allowed number</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="NextToken">Continuation token (NextToken) value from a previous request</param>
/// <returns>The list of row IDs, or nil if the call failed</returns>
function GetRowIDs(const TableName: string;
MaxNumberOfItems: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil;
const NextToken: string = ''): TStrings;
/// <summary>Deletes the specified columns from the given row.</summary>
/// <remarks>If no columns are specified, then the row is deleted.
/// The optional conditionals specify the condition(s) when the delete should happen,
/// and when it should not. For more information, see documentation on TAmazonRowConditional.
///
/// Each item in the list can be either just a column name, or a delimited pair of the column
/// name and the column value.
/// </remarks>
/// <param name="TableName">The name of the table the row is in</param>
/// <param name="RowId">The row to delete columns from (or the row to delete, if no columns are specified.)</param>
/// <param name="Columns">The columns to delete, or nil or empty list to delete the row</param>
/// <param name="Conditionals">The optional conditionals to be met for the delete to happen</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete terminates without exception, false otherwise.</returns>
function DeleteColumns(const TableName, RowId: string; const Columns: TStrings;
Conditionals: TList<TAmazonRowConditional>;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
/// <summary>Deletes the specified columns from the given row.</summary>
/// <remarks>If no columns are specified, then the row is deleted.
///
/// Each item in the list can be either just a column name, or a delimited pair of the column
/// name and the column value.
/// </remarks>
/// <param name="TableName">The name of the table the row is in</param>
/// <param name="RowId">The row to delete columns from (or the row to delete, if no columns are specified.)</param>
/// <param name="Columns">The columns to delete, or nil or empty list to delete the row</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete terminates without exception, false otherwise.</returns>
function DeleteColumns(const TableName, RowId: string; const Columns: TStrings;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
/// <summary>Deletes the specified row from the given table.</summary>
/// <remarks>The optional conditionals specify the condition(s) when the delete should happen,
/// and when it should not. For more information, see documentation on TAmazonRowConditional.
/// </remarks>
/// <param name="TableName">The name of the table the row is in</param>
/// <param name="RowId">The Name of the row to delete</param>
/// <param name="Conditionals">The optional conditionals to be met for the delete to happen</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete terminates without exception, false otherwise.</returns>
function DeleteRow(const TableName, RowId: string; Conditionals: TList<TAmazonRowConditional>;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
/// <summary>Deletes the specified row from the given table.</summary>
/// <param name="TableName">The name of the table the row is in</param>
/// <param name="RowId">The Name of the row to delete</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete terminates without exception, false otherwise.</returns>
function DeleteRow(const TableName, RowId: string; ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
/// <summary>Deletes the specified columns from the given row.</summary>
/// <remarks>Each TCloudTableRow in the list must have a column stored internally called 'itemName()',
/// which is the name of the row to delete columns from. This column will not be deleted unless
/// it is the last column remaining in the row after this delete operation.
///
/// Note that there is a limit of 25 items (rows) per call.
/// </remarks>
/// <param name="TableName">The name of the table the rows are in</param>
/// <param name="BatchColumns">The rows containing the columns to delete, as well as the itemName() column</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete terminates without exception, false otherwise.</returns>
function BatchDeleteColumns(const TableName: string; BatchColumns: TList<TCloudTableRow>;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
end;
/// <summary>Implementation of TAmazonBasicService for managing an Amazon Queue Service account.</summary>
TAmazonQueueService = class(TAmazonBasicService)
public type
TQueueAttributePair = TPair<TAmazonQueueAttribute, string>;
TQueueAttributePairs = TArray<TQueueAttributePair>;
private
function IsUniqueMessageId(const AMessageId: string; const AMessageList: array of TCloudQueueMessageItem): Boolean;
/// <summary>Returns messages from the given queue.</summary>
/// <remarks>The maximum ANumOfMessages allowed value is 10.
/// The maximum AVisibilityTimeout allowed value is 12 hours.
/// Note that messages returned by this call will have their PopReceipt specified, which is a
/// token unique to the message during the VisibilityTimeout which can be used to delete the message.
/// </remarks>
/// <param name="AQueueURL">The URL of the queue to get the messages for.</param>
/// <param name="ANumOfMessages">The maximum number of messages to return.</param>
/// <param name="AVisibilityTimeout">How long the messages should be reserved for.</param>
/// <param name="AResponseInfo">The class for storing response info into.</param>
/// <returns>The XML representation of the messages.</returns>
function ReceiveMessageXML(const AQueueURL: string; ANumOfMessages, AVisibilityTimeout: Integer;
const AResponseInfo: TCloudResponseInfo): string;
/// <summary>Returns one or more properties for the specified Queue.</summary>
/// <remarks>The attributes specified will be the property returned by this call. If you specify 'All'
/// as an attribute to return, then all properties of the queue will be returned.
/// If you pass an empty array, then all attributes will be returned.
/// </remarks>
/// <param name="AQueueURL">The URL of the Queue to get the attributes for</param>
/// <param name="AAttributes">The attributes (or All) to get</param>
/// <param name="AResponseInfo">The class for storing response info into</param>
/// <returns>Returns one or more properties of the given queue.</returns>
function GetQueueAttributesXML(const AQueueURL: string; AAttributes: array of TAmazonQueueAttribute;
const AResponseInfo: TCloudResponseInfo): string;
protected
/// <summary>Returns the version query parameter value to use in requests.</summary>
/// <returns>The version query parameter value to use in requests.</returns>
function GetServiceVersion: string; override;
/// <summary>Returns the Amazon name for the given attribute</summary>
/// <param name="Attribute">The attribute to get the amazon parameter name for</param>
/// <returns>The Amazon parameter name representation of the attribute</returns>
function GetQueueAttributeName(const Attribute: TAmazonQueueAttribute): string;
/// <summary>Returns the Amazon attribute for the given name</summary>
/// <param name="AAttributeName">The attribute name</param>
/// <returns>The Amazon attribute</returns>
function GetQueueAttributeFromName(const AAttributeName: string): TAmazonQueueAttribute;
/// <summary>Returns the host string for the service.</summary>
/// <returns>The host string for the service.</returns>
function GetServiceHost: string; override;
public
/// <summary>Returns the maximum number of queue messages that can be returned.</summary>
/// <returns>The number of queue messages which can be returned by the API for a given queue.</returns>
function GetMaxMessageReturnCount: Integer;
/// <summary>Lists the queues currently available in the queue service account.</summary>
/// <remarks>The supported optional parameters are: QueueNamePrefix
/// The 'QueueNamePrefix' parameter has a value which is the prefix a queue name must start with
/// in order to be includes in the list of queues returned by this request.
/// </remarks>
/// <param name="OptionalParams">Optional parameters to use in the query. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML string representing the queues</returns>
function ListQueuesXML(OptionalParams: TStrings = nil; ResponseInfo: TCloudResponseInfo = nil): string;
/// <summary>Lists the queues currently available in the queue service account.</summary>
/// <remarks>The supported optional parameters are: QueueNamePrefix
/// The 'QueueNamePrefix' parameter has a value which is the prefix a queue name must start with
/// in order to be includes in the list of queues returned by this request.
/// </remarks>
/// <param name="OptionalParams">Optional parameters to use in the query. See remarks for more information.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of queues, or an empty list</returns>
function ListQueues(OptionalParams: TStrings = nil; ResponseInfo: TCloudResponseInfo = nil): TList<TCloudQueue>;
/// <summary>Creates a queue with the given name.</summary>
/// <remarks>If DefaultVisibilityTimeout is set to -1, then the service default of 30 seconds is used.
/// </remarks>
/// <param name="QueueName">The name of the queue to create.</param>
/// <param name="DefaultVisibilityTimeout">The visibility timeout (in seconds) to use for this queue.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the create was successful, false otherwise.</returns>
function CreateQueue(const QueueName: string; const DefaultVisibilityTimeout: Integer = -1;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
/// <summary>Creates a queue with the given name.</summary>
/// <remarks>If the call is successful, it sets the value of QueueURL to the newly created Queue's URL.
/// If DefaultVisibilityTimeout is set to -1, then the service default of 30 seconds is used.
/// For the name: max 80 characters; alphanumeric, hyphens, and underscores are allowed.
/// </remarks>
/// <param name="QueueName">The name of the queue to create.</param>
/// <param name="QueueURL">The resulting queue's URL, or empty string is the request fails</param>
/// <param name="DefaultVisibilityTimeout">The visibility timeout (in seconds) to use for this queue.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the create was successful, false otherwise.</returns>
function CreateQueue(const QueueName: string; out QueueURL: string; const DefaultVisibilityTimeout: Integer = -1;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
/// <summary>Creates a queue with the given name.</summary>
/// <remarks>If the call is successful, it sets the value of QueueURL to the newly created Queue's URL.
/// For the name: max 80 characters; alphanumeric, hyphens, and underscores are allowed.
/// </remarks>
/// <param name="QueueName">The name of the queue to create.</param>
/// <param name="QueueURL">The resulting queue's URL, or empty string is the request fails</param>
/// <param name="Attributes">The list of names and values of the special request parameters the CreateQueue action uses.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the create was successful, false otherwise.</returns>
function CreateQueue(const QueueName: string; out QueueURL: string; Attributes: array of TQueueAttributePair;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload;
/// <summary>Deletes the queue with the given URL.</summary>
/// <remarks>The queue is marked for delete and won't show up in queries, but there will be a short time
/// before the server allows another queue with the same name to be created again.
/// Note that you must specify the Queue URL, and not just the queue name when deleting.
/// The queue URL is provided when calling ListQueues, and is a URL ending in the queue's name.
/// </remarks>
/// <param name="QueueURL">The URL of the queue to delete.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete is successful, false otherwise</returns>
function DeleteQueue(const QueueURL: string; ResponseInfo: TCloudResponseInfo = nil): Boolean;
/// <summary>This fuction is deprecated. Instead, use GetQueueAttributesXML function.</summary>
function GetQueuePropertiesXML(const QueueURL: string; Attribute: TAmazonQueueAttribute = aqaAll;
ResponseInfo: TCloudResponseInfo = nil): string; overload; deprecated;
/// <summary>This fuction is deprecated. Instead, use GetQueueAttributesXML function.</summary>
function GetQueuePropertiesXML(const QueueURL: string; Attributes: array of TAmazonQueueAttribute;
ResponseInfo: TCloudResponseInfo = nil): string; overload; deprecated;
/// <summary>This fuction is deprecated. Instead, use GetQueueAttributes function.</summary>
function GetQueueProperties(const QueueURL: string; Attribute: TAmazonQueueAttribute = aqaAll;
ResponseInfo: TCloudResponseInfo = nil): TStrings; overload; deprecated;
/// <summary>This fuction is deprecated. Instead, use GetQueueAttributes function.</summary>
function GetQueueProperties(const QueueURL: string; Attributes: array of TAmazonQueueAttribute;
ResponseInfo: TCloudResponseInfo = nil): TStrings; overload; deprecated;
/// <summary>Gets attributes for the specified queue.</summary>
/// <remarks>If you specify 'All' or an empty array as an attribute to return,
/// then all properties of the queue will be returned.
/// </remarks>
/// <param name="AQueueURL">The URL of the Queue to get the attributes for.</param>
/// <param name="AAttributes">The attributes (or All) to get.</param>
/// <param name="AResponseXML">The response in XML format.</param>
/// <param name="AResponseInfo">The class for storing response info into.</param>
/// <returns>Returns one or more properties of the given queue.</returns>
function GetQueueAttributes(const AQueueURL: string; AAttributes: array of TAmazonQueueAttribute;
out AResponseXML: string; const AResponseInfo: TCloudResponseInfo): TQueueAttributePairs;
/// <summary>This fuction is deprecated. Instead, use SetQueueAttributes function.</summary>
function SetQueueProperty(const QueueURL, Key, Value: string;
ResponseInfo: TCloudResponseInfo = nil): Boolean; deprecated;
/// <summary>Sets the given queue's attributes</summary>
/// <remarks>See AWS documentation for supported attributes (http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)
/// </remarks>
/// <param name="AQueueURL">The URL of the Queue to set the attributes for</param>
/// <param name="AAttributes">The list of attributes to set. See remarks for more information.</param>
/// <param name="AResponseInfo">The class for storing response info into</param>
/// <returns>True if the operation was successful, false otherwise.</returns>
function SetQueueAttributes(const AQueueURL: string; AAttributes: array of TQueueAttributePair;
const AResponseInfo: TCloudResponseInfo): Boolean;
/// <summary>This fuction is deprecated. Instead, use AddPermission function.</summary>
function AddQueuePermissions(const QueueURL, PermissionsLabel: string;
Permissions: array of TAmazonQueuePermission;
ResponseInfo: TCloudResponseInfo = nil): Boolean; deprecated;
/// <summary>Adds the given permissions to the specified queue.</summary>
/// <remarks>The specified label will uniquely identify the permission being set.
/// The label must be a maximum of 80 characters;
/// alphanumeric characters, hyphens (-), and underscores (_) are allowed.
/// </remarks>
/// <param name="AQueueURL">The URL of the Queue to add the permissions to.</param>
/// <param name="APermissionsLabel">The unique identifier for these permissions.</param>
/// <param name="APermissions">The permissions to add.</param>
/// <param name="AResponseInfo">The class for storing response info into.</param>
/// <returns>True if the operation was successful, false otherwise.</returns>
function AddPermission(const AQueueURL, APermissionsLabel: string; APermissions: array of TAmazonQueuePermission;
const AResponseInfo: TCloudResponseInfo): Boolean;
/// <summary>This fuction is deprecated. Instead, use RemovePermission function.</summary>
function RemoveQueuePermissions(const QueueURL, PermissionsLabel: string;
ResponseInfo: TCloudResponseInfo = nil): Boolean; deprecated;
/// <summary>Removes the permissions with the given label from the specified queue.</summary>
/// <param name="AQueueURL">The URL of the Queue to remove the permissions from.</param>
/// <param name="APermissionsLabel">The unique identifier for the permissions to remove.</param>
/// <param name="AResponseInfo">The class for storing response info into.</param>
/// <returns>True if the operation was successful, false otherwise.</returns>
function RemovePermission(const AQueueURL: string; const APermissionsLabel: string;
const AResponseInfo: TCloudResponseInfo): Boolean;
/// <summary>Deletes the messages in a queue specified by the queue URL.</summary>
/// <param name="AQueueURL">The URL of the Queue to remove the messages from.</param>
/// <param name="AResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the operation was successful, false otherwise.</returns>
function PurgeQueue(const AQueueURL: string; const AResponseInfo: TCloudResponseInfo): Boolean;
/// <summary>This fuction is deprecated. Instead, use SendMessage function.</summary>
function AddMessage(const QueueURL: string; const MessageText: string;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload; deprecated;
/// <summary>This fuction is deprecated. Instead, use SendMessage function.</summary>
function AddMessage(const QueueURL: string; const MessageText: string; out MessageId: string;
ResponseInfo: TCloudResponseInfo = nil): Boolean; overload; deprecated;
/// <summary>Adds a message to the given queue</summary>
/// <param name="AQueueURL">The URL of the queue to add the message to</param>
/// <param name="AMessageText">The text of the message</param>
/// <param name="AMessageId">The Id of the message in the queue, or empty string if add failed.</param>
/// <param name="AResponseInfo">The class for storing response info into</param>
/// <returns>True if the message was added successfully, false otherwise.</returns>
function SendMessage(const AQueueURL, AMessageText: string; out AMessageId: string;
const AResponseInfo: TCloudResponseInfo): Boolean;
function SendMessageBatch(const AQueueURL: string; AMessageList: TArray<string>;
const AResponseInfo: TCloudResponseInfo): TArray<string>;
/// <summary>This fuction is deprecated. Instead, use ReceiveMessageXML function.</summary>
function GetMessagesXML(const QueueURL: string;
NumOfMessages: Integer = 0;
VisibilityTimeout: Integer = -1;
ResponseInfo: TCloudResponseInfo = nil): string; deprecated;
/// <summary>This fuction is deprecated. Instead, use ReceiveMessage function.</summary>
function GetMessages(const QueueURL: string;
NumOfMessages: Integer = 0;
VisibilityTimeout: Integer = -1;
ResponseInfo: TCloudResponseInfo = nil): TList<TCloudQueueMessage>; deprecated;
/// <summary>Returns messages from the given queue.</summary>
/// <remarks>The maximum ANumOfMessages allowed value is 10.
/// The maximum AVisibilityTimeout allowed value is 12 hours.
/// Note that messages returned by this call will have their PopReceipt specified, which is a
/// token unique to the message during the VisibilityTimeout which can be used to delete the message.
/// </remarks>
/// <param name="AQueueURL">The URL of the queue to get the messages for.</param>
/// <param name="ANumOfMessages">The maximum number of messages to return.</param>
/// <param name="AVisibilityTimeout">How long the messages should be reserved for.</param>
/// <param name="AResponseXML">The response in XML format.</param>
/// <param name="AResponseInfo">The class for storing response info into.</param>
/// <returns>The list of messages, with their pop receipts populated.</returns>
function ReceiveMessage(const AQueueURL: string; ANumOfMessages: Integer; AVisibilityTimeout: Integer;
out AResponseXML: string; const AResponseInfo: TCloudResponseInfo): TArray<TCloudQueueMessageItem>;
/// <summary>This fuction is deprecated. Instead, use ReceiveMessage function.</summary>
function PeekMessages(const QueueURL: string; NumOfMessages: Integer;
ResponseInfo: TCloudResponseInfo = nil): TList<TCloudQueueMessage>; deprecated;
/// <summary>Deletes the given message from the specified queue</summary>
/// <param name="QueueURL">URL of the queue to delete a message from</param>
/// <param name="PopReceipt">The pop receipt required for deleting the message</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the delete was successful, false otherwise</returns>
function DeleteMessage(const QueueURL: string; const PopReceipt: string;
ResponseInfo: TCloudResponseInfo = nil): Boolean;
function DeleteMessageBatch(const AQueueURL: string; const APopReceiptList: TArray<string>;
const AResponseInfo: TCloudResponseInfo): Boolean;
/// <summary>Extends or ends the visibility timeout of a message.</summary>
/// <remarks>If zero is passed in as the VisibilityTimeout, then the message instantly becomes
/// visible by calls to GetMessages. Otherwise, the value passed in, which must be
/// between o and 43200 seconds (12 hours) and will be set as the new value for
/// VisibilityTimeout for the message associated with the given pop receipt, if any.
/// </remarks>
/// <param name="QueueURL">The URL of the queue to get the messages for</param>
/// <param name="PopReceipt">The previously obtained pop receipt. Associated with a message.</param>
/// <param name="VisibilityTimeout">Time (in seconds) to have the message hidden for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the operation is successful, false otherwise.</returns>
function ChangeMessageVisibility(const QueueURL: string; const PopReceipt: string;
const VisibilityTimeout: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil): Boolean;
function ChangeMessageVisibilityBatch(const AQueueURL: string; AMessageInfoList: TArray<TPair<string, integer>>;
const AResponseInfo: TCloudResponseInfo): Boolean;
function ListDeadLetterSourceQueues(const AQueueURL: string; const AResponseInfo: TCloudResponseInfo): TArray<string>;
end;
/// <summary>A storage object as returned by a get bucket request.</summary>
/// <remarks>If a VersionId is specified then this instance represents a version of the object. You can
/// use the value of IsLatest to determine if this is the latest version of the object. Also,
/// you can check the value of IsDeleted to see if a DeleteMarker is present for the object.
///
/// If the object is deleted, its size and ETag will not be populated.
/// </remarks>
TAmazonObjectResult = record
/// <summary>The name of the object within the bucket</summary>
Name: string;
/// <summary>Date and time the object was last modified.</summary>
LastModified: string;
/// <summary>The ETag (MD5 hash) of the object's content.</summary>
ETag: string;
/// <summary>The size of the object content, in bytes</summary>
Size: Int64;
/// <summary>The ID of the owner of the object</summary>
OwnerID: string;
/// <summary>Display name for the owner of the object</summary>
OwnerDisplayName: string;
/// <summary>The version ID of the object, if populated.</summary>
VersionId: string;
/// <summary>True if the object is the latest version, false otherwise.</summary>
IsLatest: Boolean;
/// <summary>True if the object has a delete marker on its latest version, false otherwise.</summary>
IsDeleted: Boolean;
/// <summary>The StorageClass value (STANDARD or REDUCED_REDUNDANCY) of the object.</summary>
StorageClass: string;
/// <summary>Creates a new instance of TAmazonObjectResult, setting its name.</summary>
/// <param name="Name">The name of the object</param>
/// <returns>The new TAmazonObjectResult instance with its name set</returns>
class function Create(const Name: string): TAmazonObjectResult; static;
end;
/// <summary>A storage bucket as returned by a get bucket request.</summary>
TAmazonBucketResult = class
private
FName: string;
FIsTruncated: Boolean;
FObjects: TList<TAmazonObjectResult>;
FPrefixes: TStrings;
FMarker: string;
FVersionIdMarker: string;
FRequestPrefix: string;
FRequestDelimiter: string;
FRequestMaxKeys: Integer;
public
/// <summary>Creates a new instance of TAmazonBucketResult, setting its name.</summary>
/// <param name="AName">The name of the bucket</param>
constructor Create(const AName: string); virtual;
/// <summary>Frees the resources and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>The name of the bucket</summary>
property Name: string read FName;
/// <summary>Whether or not all of the objects were returned with the request.</summary>
property IsTruncated: Boolean read FIsTruncated write FIsTruncated;
/// <summary>List of objects in the bucket</summary>
property Objects: TLisT<TAmazonObjectResult> read FObjects;
/// <summary>The list of prefixes</summary>
property Prefixes: TStrings read FPrefixes;
/// <summary>If the results are truncated, this will specify the next object to get.</summary>
/// <remarks>Use this in a new request to continue populated from where the previous request left off.
/// If the request is a version request, use this as the 'key-marker' value instead of 'marker'.
/// </remarks>
property Marker: string read FMarker write FMarker;
/// <summary>If the version results are truncated, this will specify the next object to get.</summary>
/// <remarks>Use this in a new version request to continue populated from where the previous request left off,
/// specifying the specific file version. This corresponds to the 'version-id-marker' parameter.
/// </remarks>
property VersionIdMarker: string read FVersionIdMarker write FVersionIdMarker;
/// <summary>The prefix value used in the request</summary>
property RequestPrefix: string read FRequestPrefix write FRequestPrefix;
/// <summary>The delimiter value used in the request</summary>
property RequestDelimiter: string read FRequestDelimiter write FRequestDelimiter;
/// <summary>The MaxKeys value used in the request.</summary>
property RequestMaxKeys: Integer read FRequestMaxKeys write FRequestMaxKeys;
end;
/// <summary>Representation of a specific ACL Grant, specifying the Grantee and permission.</summary>
TAmazonGrant = record
/// <summary>URI for identifying the Grantee</summary>
GranteeURI: string;
/// <summary>ID for identifying the Grantee</summary>
GranteeID: string;
/// <summary>Display Name for the Grantee</summary>
GranteeDisplayName: string;
/// <summary>Email address for the Grantee</summary>
GranteeEmailAddress: string;
/// <summary>The permission being granted to the given Grantee</summary>
Permission: TAmazonGrantPermission;
/// <summary>Returns the permission enum for the given string</summary>
/// <remarks>Returns amgpUnknown if the string isn't one of the expected values.</remarks>
/// <param name="PermissionString">The string to parse.</param>
/// <returns>The appropriate permission instance, or amgpUnknown</returns>
class function GetPermission(const PermissionString: string): TAmazonGrantPermission; static;
/// <summary>Creates a new instance of TAmazonGrant</summary>
/// <param name="Permission">The permission, in string format.</param>
/// <returns>The new TAmazonGrant instance.</returns>
class function Create(const Permission: string): TAmazonGrant; overload; static;
/// <summary>Creates a new instance of TAmazonGrant</summary>
/// <param name="Permission">The permission</param>
/// <returns>The new TAmazonGrant instance.</returns>
class function Create(Permission: TAmazonGrantPermission): TAmazonGrant; overload; static;
/// <summary>Returns the permission in string format.</summary>
/// <returns>The permission in string format.</returns>
function PermissionString: string;
/// <summary>Specifies if the Grantee applies to all users.</summary>
/// <returns>True if the grantee is all users, false otherwise</returns>
function IsAllUsers: Boolean;
/// <summary>Specifies if the Grantee applies to all authenticated users.</summary>
/// <returns>True if the grantee is all authenticated users, false otherwise</returns>
function IsAllAuthenticatedUsers: Boolean;
/// <summary>Specifies if the Grantee applies to the log delivery group.</summary>
/// <returns>True if the grantee is the log delivery group, false otherwise</returns>
function IsLogDelivery: Boolean;
/// <summary>Returns the grantee type based on information stored in this instance</summary>
/// <returns>The grantee type based on the grantee fields, or agtUnknown</returns>
function GranteeType: TAmazonGranteeType;
/// <summary>Returns the grantee type based on information stored in this instance</summary>
/// <returns>The grantee type (in string format) based on the grantee fields, or empty string</returns>
function GranteeTypeString: string;
end;
/// <summary>Bucket logging information, including target bucket, log prefix and permissions.</summary>
TAmazonBucketLoggingInfo = class
const
LogXMLPrefix = '<?xml version="1.0"?><BucketLoggingStatus xmlns="http://doc.s3.amazonaws.com/2006-03-01">';
LogXMLSuffix = '</BucketLoggingStatus>';
private
FTargetBucket: string;
FTargetPrefix: string;
FLoggingEnabled: Boolean;
FGrants: TList<TAmazonGrant>;
public
/// <summary>Creates a new instance of TAmazonBucketLoggingInfo with logging enabled.</summary>
/// <param name="TargetBucket">The name of the bucket to store the log in.</param>
/// <param name="TargetPrefix">The log file name prefix.</param>
constructor Create(const TargetBucket, TargetPrefix: string); overload; virtual;
/// <summary>Creates a new instance of TAmazonBucketLoggingInfo with logging disabled.</summary>
constructor Create; overload; virtual;
/// <summary>Frees the resources and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Returns the instance in XML representation.</summary>
/// <returns>The instance in XML representation.</returns>
function AsXML: string;
/// <summary>Returns the XML to use when disabling logging.</summary>
/// <returns>The XML to use when disabling logging</returns>
class function GetDisableXML: string;
/// <summary>The name of the bucket to store the log in.</summary>
property Targetbucket: string read FTargetBucket;
/// <summary>The log file name prefix.</summary>
property TargetPrefix: string read FTargetPrefix;
/// <summary>The optional list of logging permissions.</summary>
property Grants: TList<TAmazonGrant> read FGrants;
/// <summary>True if logging is enabled, false otherwise</summary>
property IsLoggingEnabled: Boolean read FLoggingEnabled;
end;
/// <summary>A topic for Amazon notification</summary>
/// <remarks>The Topic field will reference a SNS (Simple Notification Service) topic, to send notifications to.
/// Currently, the s3:ReducedRedundancyLostObject event is the only event supported by Amazon S3.
/// </remarks>
TAmazonNotificationEvent = record
/// <summary>The SNS topic to send notifications to.</summary>
Topic: string;
/// <summary>The event to notify on.</summary>
Event: string;
/// <summary>Creates a new instance of TAmazonNotificationEvent</summary>
/// <param name="Topic">The SNS topic to send notifications to.</param>
/// <param name="Event">The event to notify on.</param>
/// <returns>The new instance of TAmazonNotificationEvent</returns>
class function Create(const Topic, Event: string): TAmazonNotificationEvent; static;
end;
/// <summary>Information about a single item in a list of active multipart uploads.</summary>
TAmazonMultipartUploadItem = record
/// <summary>The item's Key (file name)</summary>
Key: string;
/// <summary>Unique identifier for a multipart upload.</summary>
UploadId: string;
/// <summary>The ID (AWS account or IAM User) of the user who initiated the multipart upload with this ID.
/// </summary>
InitiatorId: string;
/// <summary>The display name of the user who initiated the multipart upload with this ID.</summary>
InitiatorDisplayName: string;
/// <summary>The Owner's ID.</summary>
OwnerId: string;
/// <summary>The Owner's display name.</summary>
OwnerDisplayName: string;
/// <summary>False if the storage class is STANDARD, True if it is REDUCED_REDUNDANCY</summary>
IsReducedRedundancyStorage: Boolean;
/// <summary>Date and time when the multipart upload was initiated.</summary>
DateInitiated: string;
/// <summary>Creates a new instance of TAmazonMultipartUploadItem</summary>
/// <param name="AKey">A value to set as Key for the item.</param>
constructor Create(const AKey: string);
end;
/// <summary>Result of a request of all active multipart uploads</summary>
TAmazonMultipartUploadsResult = class
private
FBucket: string;
FKeyMarker: string;
FUploadIdMarker: string;
FNextKeyMarker: string;
FNextUploadIdMarker: string;
FMaxUploads: Integer;
FIsTruncated: Boolean;
FUploadItems: TList<TAmazonMultipartUploadItem>;
public
/// <summary>Creates a new instance of TAmazonMultipartUploadsResult</summary>
/// <param name="BucketName">The name of the bucket this result is for.</param>
constructor Create(const BucketName: string); virtual;
/// <summary>Frees the resources and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>The name of the bucket this result is for.</summary>
property Bucket: string read FBucket;
/// <summary>The optional key-marker passed in with the request, at or after which the listing began.</summary>
property KeyMarker: string read FKeyMarker write FKeyMarker;
/// <summary>The optional upload-id-marker after which listing began.</summary>
property UploadIdMarker: string read FUploadIdMarker write FUploadIdMarker;
/// <summary>Continuation token for key-marker if the result is truncated.</summary>
property NextKeyMarker: string read FNextKeyMarker write FNextKeyMarker;
/// <summary>Continuation token for upload-id-marker if the result is truncated.</summary>
property NextUploadIdMarker: string read FNextUploadIdMarker write FNextUploadIdMarker;
/// <summary>The maximum number of items to return before truncating.</summary>
property MaxUploads: Integer read FMaxUploads write FMaxUploads;
/// <summary>True if there are more items after these which were left out because of the MaxUploads value.
/// </summary>
property IsTruncated: Boolean read FIsTruncated write FIsTruncated;
/// <summary>The list of active multipart upload items.</summary>
property UploadItems: TList<TAmazonMultipartUploadItem> read FUploadItems;
end;
/// <summary>An access control policy, containing owner information and a list of grants.</summary>
TAmazonAccessControlPolicy = class
private
FOwnerId: string;
FOwnerDisplayName: string;
FGrants: TList<TAmazonGrant>;
public
/// <summary>Creates a new instance of TAmazonAccessControlPolicy</summary>
/// <param name="OwnerId">The Policy owner's ID</param>
/// <param name="OwnerDisplayName">The Policy owner's display name</param>
/// <param name="Grants">The list of grants or nil to create an empty list</param>
constructor Create(const OwnerId, OwnerDisplayName: string; Grants: TList<TAmazonGrant>); virtual;
/// <summary>Frees the resources and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Returns the XML representation of this instance.</summary>
function AsXML: string;
/// <summary>The Policy owner's ID</summary>
property OwnerId: string read FOwnerId;
/// <summary>The Policy owner's display name</summary>
property OwnerDisplayName: string read FOwnerDisplayName;
/// <summary>The list of grants.</summary>
property Grants: TList<TAmazonGrant> read FGrants;
end;
/// <summary>Record of optional conditional restrictions.</summary>
/// <remarks>These can be used, for example, when retrieving an object. They provide a way
/// to specify under which conditions the action should happen or not happen.
/// When doing a copy, these apply to the source object.
/// </remarks>
TAmazonActionConditional = record
/// <summary>A DateTime value. Specify this conditional header to perform the action
/// only if the object has been modified since the specified date/time.
/// </summary>
IfModifiedSince: string;
/// <summary>A DateTime value. Specify this conditional header to perform the action
/// only if the object has not been modified since the specified date/time.
/// </summary>
IfUnmodifiedSince: string;
/// <summary>Specify an ETag value to perform the action only if the object's ETag value
/// matches the value specified.
/// </summary>
IfMatch: string;
/// <summary>Specify an ETag value to perform the action only if the object's ETag value
/// does not match the value specified.
/// </summary>
IfNoneMatch: string;
/// <summary>Creates a new instance of TAmazonActionConditional</summary>
class function Create: TAmazonActionConditional; static;
/// <summary>Populates the given header list with the key/value pair of any field with an assigned value.
/// </summary>
/// <remarks>The keys used will be the header names, as required by Amazon requests. Different header
/// names will be used if ForCopy is set to True. For example, if it is false, one header will
/// be 'If-Modified-Since'. But if it is true, that header will instead be 'x-amz-copy-source-if-modified-since'
/// </remarks>
/// <param name="Headers">The headers list to populate</param>
/// <param name="ForCopy">True to set copy (source) headers, false to set regular headers.</param>
procedure PopulateHeaders(Headers: TStrings; ForCopy: Boolean = False);
end;
/// <summary>Optional inputs for a GetObject request.</summary>
/// <remarks>The response fields corresponse to 'response-' headers which can be set to specify
/// the value you want to have returned by the response for their corresponding headers.
/// </remarks>
TAmazonGetObjectOptionals = record
/// <summary>Sets the response-content-type header to the specified value.</summary>
ResponseContentType: string;
/// <summary>Sets the response-content-language header to the specified value.</summary>
ResponseContentLanguage: string;
/// <summary>Sets the response-expires header to the specified value.</summary>
ResponseExpires: string;
/// <summary>Sets the reponse-cache-control header to the specified value.</summary>
ResponseCacheControl: string;
/// <summary>Sets the response-content-disposition header to the specified value.</summary>
ResponseContentDisposition: string;
/// <summary>Sets the response-content-encoding header to the specified value.</summary>
ResponseContentEncoding: string;
/// <summary>Conditional for object retrieval.</summary>
Condition: TAmazonActionConditional;
/// <summary>Set when retrieving a range of bytes instead of a whole object.</summary>
RangeStartByte: int64;
/// <summary>Set when retrieving a range of bytes instead of a whole object.</summary>
RangeEndByte: int64;
/// <summary>Creates a new instance of TAmazonGetObjectOptionals</summary>
class function Create: TAmazonGetObjectOptionals; static;
/// <summary>Populates the given header list with the key/value pair of any field with an assigned value.
/// </summary>
/// <remarks>This also calls into TAmazonActionConditional.PopulateHeaders for the specified Condition.
/// </remarks>
/// <param name="Headers">The headers list to populate</param>
procedure PopulateHeaders(Headers: TStrings);
end;
/// <summary>Optional header values for a Copy Object Request.</summary>
TAmazonCopyObjectOptionals = class
private
FCopyMetadata: Boolean;
FMetadata: TStrings;
FACL: TAmazonACLType;
FUseReducedRedundancy: Boolean;
public
/// <summary>Conditional for object retrieval.</summary>
Condition: TAmazonActionConditional;
/// <summary>Creates a new instance of TAmazonCopyObjectOptionals</summary>
constructor Create; virtual;
/// <summary>Frees the resources and destroys the instance.</summary>
destructor Destroy; override;
/// <summary>Populates the given header list with the key/value pair of any field with an assigned value.
/// </summary>
/// <remarks>This also calls into TAmazonActionConditional.PopulateHeaders for the specified Condition.
/// </remarks>
/// <param name="Headers">The headers list to populate</param>
procedure PopulateHeaders(Headers: TStrings);
/// <summary>True to copy the source object's metadata to the target object. If false, then the target
/// object will have its metadata set based on the content of the Metadata list stored here.
///</summary>
property CopyMetadata: Boolean read FCopyMetadata write FCopyMetadata;
/// <summary>True to use reduced redundancy for the target object, false to use standard redundancy.</summary>
property UseReducedRedundancy: Boolean read FUseReducedRedundancy write FUseReducedRedundancy;
/// <summary>The target object's ACL to set.</summary>
property ACL: TAmazonACLType read FACL write FACL;
/// <summary>Metadata to set onto the target object, if 'CopyMetadata' is False.</summary>
property Metadata: TStrings read FMetadata;
end;
/// <summary>Stores Part information for a single part of a multipart upload.</summary>
/// <remarks>This information will be required to commit the part when completing the multipart upload.
/// </remarks>
TAmazonMultipartPart = record
/// <summary>The part's number in the multipart upload.</summary>
PartNumber: Integer;
/// <summary>The parts ETag as returned by the server when the part was uploaded.</summary>
ETag: string;
/// <summary>The date the part was last modified.</summary>
LastModified: string;
/// <summary>The current size of the part</summary>
Size: Int64;
/// <summary>Creates a new instance of TAmazonMultipartPart</summary>
/// <param name="APartNumber">The part number to set</param>
/// <param name="AETag">The ETag value to set</param>
constructor Create(APartNumber: Integer; AETag: string);
/// <summary>Returns the xml representation of this part.</summary>
function AsXML: string;
end;
/// <summary>Result item for a ListParts request.</summary>
TAmazonListPartsResult = class
private
FBucket: string;
FObjectName: string;
FUploadId: string;
FInitiatorId: string;
FInitiatorDisplayName: string;
FOwnerId: string;
FOwnerDisplayName: string;
FIsReducedRedundancyStorage: Boolean;
FPartNumberMarker: Integer;
FNextPartNumberMarker: Integer;
FMaxParts: Integer;
FIsTruncated: Boolean;
FParts: TList<TAmazonMultipartPart>;
public
/// <summary>Creates a new instance of TAmazonListPartsResult.</summary>
/// <param name="BucketName">The bucket this result is for.</param>
/// <param name="ObjectName">The object (key) that this result is for.</param>
/// <param name="UploadId">The multipart upload ID this result represents.</param>
constructor Create(const BucketName, ObjectName, UploadId: string); virtual;
/// <summary>Frees the required headers list and destroys the instance</summary>
destructor Destroy; override;
/// <summary>The name of the bucket this result is for.</summary>
property Bucket: string read FBucket;
/// <summary>The name of the object (key) that this result is for.</summary>
property ObjectName: string read FObjectName;
/// <summary>The multipart upload ID this result represents.</summary>
property UploadId: string read FUploadId write FUploadId;
/// <summary>The unique ID of the initiator of the multipart upload.</summary>
/// <remarks>This will be the same as the owner if an AWS account was used. For IAM users the
/// value will be the user's ARN.
/// </remarks>
property InitiatorId: string read FInitiatorId write FInitiatorId;
/// <summary>The display name of the initiator.</summary>
property InitiatorDisplayName: string read FInitiatorDisplayName write FInitiatorDisplayName;
/// <summary>The AWS Id of the owner of the multipart upload.</summary>
property OwnerId: string read FOwnerId write FOwnerId;
/// <summary>The display name of the owner of the multipart upload.</summary>
property OwnerDisplayName: string read FOwnerDisplayName write FOwnerDisplayName;
/// <summary>True if the storage type is REDUCED_REDUNDANCY, false if it is STANDARD.</summary>
property IsReducedRedundancyStorage: Boolean read FIsReducedRedundancyStorage write FIsReducedRedundancyStorage;
/// <summary>Part number after which listing begins.</summary>
property PartNumberMarker: Integer read FPartNumberMarker write FPartNumberMarker;
/// <summary>Continuation token for when result is truncated.</summary>
/// <remarks>Use this as the value of PartNumberMarker in the next call to continue population.</remarks>
property NextPartNumberMarker: Integer read FNextPartNumberMarker write FNextPartNumberMarker;
/// <summary>The maximum number of parts that were allowed for the request.</summary>
property MaxParts: Integer read FMaxParts write FMaxParts;
/// <summary>True if more parts exist which weren't returned, false if these were the last parts.</summary>
property IsTruncated: Boolean read FIsTruncated write FIsTruncated;
/// <summary>The list of parts for the multipart upload.</summary>
property Parts: TList<TAmazonMultipartPart> read FParts;
end;
/// <summary>Implementation of TAmazonService for managing an Amazon Simple Storage Service (S3) account.</summary>
TAmazonStorageService = class(TAmazonService)
private
function InitHeaders(const BucketName: string; BucketRegion: TAmazonRegion): TStringList;
procedure AddAndValidateHeaders(const defaultHeaders, customHeaders: TStrings);
function PopulateResultItem(ObjectNode: IXMLNode; out ResultItem: TAmazonObjectResult): Boolean;
procedure PopulateGrants(GrantsNode: IXMLNode; Grants: TList<TAmazonGrant>);
function GetBucketInternal(const XML: string; ResponseInfo: TCloudResponseInfo): TAmazonBucketResult;
function GetBucketXMLInternal(const BucketName: string; OptionalParams: TStrings;
VersionInfo: Boolean; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
function GetNotificationXML(Events: TList<TAmazonNotificationEvent>): string;
function DeleteObjectInternal(const BucketName, ObjectName, VersionId: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
function GetObjectInternal(const BucketName, ObjectName, VersionId: string;
OptionalParams: TAmazonGetObjectOptionals; ResponseInfo: TCloudResponseInfo;
ObjectStream: TStream; BucketRegion: TAmazonRegion): Boolean;
/// <summary>Determines S3 region name based on the endpoint string.</summary>
function GetRegionFromEndpoint(const Endpoint: string): string;
function BuildObjectURL(const BucketName, ObjectName: string; ARegion: TAmazonRegion): string;
protected
/// <summary>The lazy-loaded list of required header names.</summary>
FRequiredHeaderNames: TStrings;
/// <summary>URL Encodes the param name and value.</summary>
/// <remarks>Skips encoding if not for URL.</remarks>
/// <param name="ForURL">True if the parameter is for a URL, false if it is for a signature.</param>
/// <param name="ParamName">Name of the parameter</param>
/// <param name="ParamValue">Value of the parameter</param>
procedure URLEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: string); override;
/// <summary>Returns the authentication instance to use for the given connection info.</summary>
/// <returns>The authentication instance to use for the given connection info.</returns>
function CreateAuthInstance(const ConnectionInfo: TAmazonConnectionInfo): TCloudAuthentication; override;
/// <summary>Builds the StringToSign value, based on the given information.</summary>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request type.</param>
/// <param name="Headers">The list of headers in the request, or nil</param>
/// <param name="QueryParameters">The list of query parameters for the request, or nil</param>
/// <param name="QueryPrefix">The string to prefix the query parameter string with.</param>
/// <param name="URL">The URL of the request.</param>
/// <returns>The StringToSign, which will be encoded and used for authentication.</returns>
function BuildStringToSign(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix, URL: string): string; override;
/// <summary>Handles the StringToSign after it is created.</summary>
/// <remarks>This modifies the provided URL or the content stream, adding a 'Signature' query parameter.
/// </remarks>
/// <param name="HTTPVerb">The HTTP verb (eg: GET, POST) of the request.</param>
/// <param name="Headers">The header name/value pairs</param>
/// <param name="QueryParameters">The query parameter name/value pairs</param>
/// <param name="StringToSign">The StringToSign for the request</param>
/// <param name="URL">The URL of the request</param>
/// <param name="Request">The request object</param>
/// <param name="Content">The content stream of the request.</param>
procedure PrepareRequestSignature(const HTTPVerb: string;
const Headers, QueryParameters: TStringList;
const StringToSign: string;
var URL: string; Request: TCloudHTTP; var Content: TStream); override;
/// <summary>Builds the StringToSign value's header part</summary>
/// <remarks>This will include both the required and optional headers, and end with a newline character.
/// </remarks>
/// <param name="Headers">The list of headers in the request, or nil</param>
/// <returns>The headers portion of the StringToSign</returns>
function BuildStringToSignHeaders(Headers: TStringList): string; override;
/// <summary>Returns the list of required header names</summary>
/// <remarks>Implementation of abstract declaration in parent class.
/// Lazy-loads and returns FRequiredHeaderNames. Sets InstanceOwner to false,
/// since this class instance will manage the memory for the object.
/// </remarks>
/// <param name="InstanceOwner">Returns false, specifying the caller doesn't own the list.</param>
/// <returns>The list of required hear names. No values.</returns>
function GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings; override;
/// <summary>Returns the header name prefix for Amazon services, for headers to be included
/// as name/value pairs in the StringToSign in authentication.
/// </summary>
/// <returns>The header prefix (x-amz-)</returns>
function GetCanonicalizedHeaderPrefix: string; override;
/// <summary>Returns the current time, formatted properly as a string.</summary>
/// <returns>The current time, formatted properly as a string</returns>
function CurrentTime: string; override;
/// <summary>Populates the given ResponseInfo with error information, if any.</summary>
/// <remarks>If the given ResponseInfo is non-null, and the ResultString holds an XML error message,
/// then this procedure will parse the error XML and populate the ResponseInfo's message
/// with the error message.
/// </remarks>
/// <param name="ResponseInfo">The optional response info to populate, or nil</param>
/// <param name="ResultString">The request's response string to parse for an error message.</param>
procedure ParseResponseError(const ResponseInfo: TCloudResponseInfo; const ResultString: string); override;
/// <summary>Sorts the given list of Headers.</summary>
/// <remarks>Extend this if you wish to modify how the list is sorted.</remarks>
/// <param name="Headers">List of headers to sort.</param>
procedure SortHeaders(const Headers: TStringList); override;
function BuildQueryParameterString(const QueryPrefix: string; QueryParameters: TStringList;
DoSort: Boolean = False; ForURL: Boolean = True): string; override;
public
/// <summary>Creates a new instance of TAmazonStorageService</summary>
/// <remarks>This class does not own the ConnectionInfo instance.</remarks>
// / <param name="ConnectionInfo">The Amazon service connection info</param>
constructor Create(const ConnectionInfo: TAmazonConnectionInfo);
/// <summary>Frees the required headers list and destroys the instance</summary>
destructor Destroy; override;
/// <summary>Returns the string representation of the given region.</summary>
/// <param name="Region">The region</param>
/// <returns>The string representation of the given region.</returns>
class function GetRegionString(Region: TAmazonRegion): string; static;
/// <summary>Returns the region for the given string representation.</summary>
/// <param name="Region">The region in string form</param>
/// <returns>The region for the given string representation.</returns>
class function GetRegionFromString(const Region: string): TAmazonRegion; static;
/// <summary>Lists the buckets owned by the current AWS account.</summary>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of all the account's buckets.</returns>
function ListBucketsXML(const ResponseInfo: TCloudResponseInfo = nil): string;
/// <summary>Lists the buckets owned by the current AWS account.</summary>
/// <remarks>The list returned are key/value pairs, where the keys are the bucket names,
/// and the values are the creation dates for each bucket. The date is in the
/// format: 2011-01-21T10:30:57.000Z ('yyyy-mm-ddThh:nn:ss.zzzZ')
/// Note that when parsing the date you may need to escape the 'T' and 'Z'.
/// </remarks>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The list of all the account's buckets.</returns>
function ListBuckets(const ResponseInfo: TCloudResponseInfo = nil): TStrings;
/// <summary>Creates a new bucket with the given name on the S3 service.</summary>
/// <remarks>Bucket names must be unique to the S3 service. That means if someone else has already used a
/// given bucket name with their account, you cannot create a bucket with the same name.
///
/// Bucket names have some restrictions:
/// They must start with a number or letter.
/// They can contain periods, underscores and dashes, numbers and lowercase letters.
/// They must be between 3 and 255 characters (although shouldn't be longer than 63 characters.)
/// They must not be formatted like an IP address (e.g., 192.168.0.1)
///
/// Furthermore, if you specify a Region when creating the bucket, you must also follow these rules:
/// The name can't contain underscores.
/// The name must be between 3 and 63 characters long.
/// The name can't end in a dash
/// The name cannot contain two adjacent periods
/// The name cannot contain a dash next to a period. (e.g., 'my.-bucket')
///
/// You can choose to set the Bucket's access control list and/or the region with this call.
/// You can choose a Region to reduce costs or to optimize latency.
/// For example, if you are in Europe, you will probably want to create buckets in the EU Region.
/// </remarks>
/// <param name="BucketName">The name of the bucket to create</param>
/// <param name="BucketACL">The ACL value to use in the bucket creation</param>
/// <param name="BucketRegion">The region to create the bucket in</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>True if the creation was successful, false otherwise.</returns>
function CreateBucket(const BucketName: string; BucketACL: TAmazonACLType = amzbaPrivate;
BucketRegion: TAmazonRegion = amzrNotSpecified;
ResponseInfo: TCloudResponseInfo = nil): Boolean;
/// <summary>Deletes the given Bucket.</summary>
/// <param name="BucketName">The name of the bucket to delete</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket to delete</param>
/// <returns>True if the deletion was successful, false otherwise.</returns>
function DeleteBucket(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Deletes the policy on the given Bucket.</summary>
/// <param name="BucketName">The name of the bucket to delete the policy for</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket to delete</param>
/// <returns>True if the deletion was successful, false otherwise.</returns>
function DeleteBucketPolicy(const BucketName: string; ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Returns some or all of the objects of a given bucket.</summary>
/// <remarks>The optional parameters allow for filtering the results as well as creating a virtual
/// directory structure. The supported parameters include:
/// delimiter: commonly set to '/' this sets the character to denote a directory
/// prefix: Limits the response to object names that begin with the specified prefix
/// marker: continuation token, specifying the name of the object to begin population at
/// max-keys: (integer) the max number of objects to return.
///
/// If you want to traverse the objects in a directory structure, then sent the delimiter to
/// a character to be used as a path separator, such as a slash character ('/'). The results
/// you get back will contain any objects under the 'root directory' and will also contain a
/// list of 'prefixes' which are the names of the subdirectories. To traverse the subdirectories,
/// set the absolute path of the subdirectory (the prefix value) as the 'prefix' in the next call
/// leaving the 'delimiter' as a slash.
///
/// When more than the maximum number of objects to return exists, 'Truncated' will be set to true.
/// To get more objects, use the name of the last object you got as the 'marker' value. That object
/// will be populated again in the next call, but none that came before it will.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the objects for</param>
/// <param name="OptionalParams">Optional parameters for filtering the results. See remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the bucket's objects and additional information.</returns>
function GetBucketXML(const BucketName: string; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns some or all of the objects of a given bucket.</summary>
/// <remarks>For information on the Optional parameters, see remarks on GetBucketXML.
///
/// When more than the maximum number of objects to return exists, 'Truncated' will be set to true.
/// To get more objects, use the name of the last object you got as the 'marker' value. That object
/// will be populated again in the next call, but none that came before it will. For convenience,
/// this marker value will be placed in the ResponseInfo header 'marker' is a ResponseInfo instance
/// is provided and the list of bucket objects is truncated.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the objects for</param>
/// <param name="OptionalParams">Optional parameters for filtering the results. See remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The bucket's objects and additional information.</returns>
function GetBucket(const BucketName: string; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TAmazonBucketResult;
/// <summary>Returns the given bucket's ACL</summary>
/// <remarks>To get the ACL of the bucket, you must have READ_ACP access to the bucket.
/// If READ_ACP permission is set for anonymous users, you can return the bucket's ACL
/// without using an authorization header.
///
/// The possible permissions are:
/// FULL_CONTROL
/// WRITE
/// WRITE_ACP - allow writing the ACL of the bucket
/// READ
/// READ_ACP - allow reading the ACL of the bucket
///
/// Users assigned multiple permissions will appear multiple times in the Grant list.
///
/// All users are granted a permission when the Grantee has a URI of:
/// http://acs.amazonaws.com/groups/global/AllUsers.
/// All authenticated users are granted a permission when the Grantee has a URI of:
/// http://acs.amazonaws.com/groups/global/AuthenticatedUsers.
/// The Log delivery group is granted permission when the Grantee has a URI of:
/// http://acs.amazonaws.com/groups/global/LogDelivery
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the access control list for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the bucket's ACL</returns>
function GetBucketACLXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the given bucket's ACL</summary>
/// <remarks>Users assigned multiple permissions will appear multiple times in the Grant list.
/// For more information, see remarks on GetBucketACLXML;
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the access control list for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The bucket's ACL</returns>
function GetBucketACL(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TList<TAmazonGrant>;
/// <summary>Returns the given bucket's policies</summary>
/// <remarks>This returns a string which, if the request is successful, is a JSON representation of
/// the policies. See the Amazon S3 documentation for more information on the format.
///
/// If no policy exists for the given bucket, then the response will be in XML, and will be an error
/// message explaining that that the bucket policy doesn't exist. The response code will be 404.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the policies for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The JSON String representation of the bucket's policies</returns>
function GetBucketPolicyJSON(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the given bucket's policies</summary>
/// <remarks>If the request is successful this returns a JSON representation of
/// the policies. See the Amazon S3 documentation for more information on the format.
///
/// If no policy exists for the given bucket, then the response will be nil and
/// the response code will be 404.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the policies for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The JSON String representation of the bucket's policies</returns>
function GetBucketPolicy(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TJSONObject;
/// <summary>Returns the given bucket's location</summary>
/// <remarks>The location will be one of:
/// 'EU' | 'us-west-1' | 'ap-southeast-1' | '' (empty string - US Classic Region)
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the location for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The XML representation of the bucket's location</returns>
function GetBucketLocationXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil): string;
/// <summary>Returns the given bucket's location</summary>
/// <remarks>Returns amzrNotSpecified if the request fails.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the location for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <returns>The bucket's region, or empty string for US Classic</returns>
function GetBucketLocation(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil): TAmazonRegion;
/// <summary>Returns the given bucket's logging information</summary>
/// <remarks>This returns the logging status for the bucket as well as the permissions users have
/// to view and modify the status.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the logging information for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the bucket's logging information</returns>
function GetBucketLoggingXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the given bucket's logging information</summary>
/// <remarks>This returns the logging status for the bucket as well as the permissions users have
/// to view and modify the status.
///
/// Returns nil if the request fails. Returns a TAmazonBucketLoggingInfo with IsLoggingEnabled
/// returning False if logging is disabled on the bucket.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the logging information for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The bucket's logging information</returns>
function GetBucketLogging(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TAmazonBucketLoggingInfo;
/// <summary>Returns the given bucket's notification configuration</summary>
/// <remarks>Currently, the s3:ReducedRedundancyLostObject event is the only event supported by Amazon S3.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the notification configuration for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The optional region for the notification config</param>
/// <returns>The XML representation of the bucket's notification configuration</returns>
function GetBucketNotificationXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the given bucket's notification configuration</summary>
/// <remarks>If the request fails nil will be returned.
/// Currently, the s3:ReducedRedundancyLostObject event is the only event supported by Amazon S3.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the notification configuration for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The optional region for the notification config</param>
/// <returns>The bucket's notification configuration</returns>
function GetBucketNotification(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TList<TAmazonNotificationEvent>;
/// <summary>Returns some or all of the objects of a given bucket, returning all versions of each object.</summary>
/// <remarks>The optional parameters include all optional parameters supported by the GetBucket command,
/// except that 'marker' should be called 'key-marker'. Also, 'version-id-marker' is also supported,
/// which can be used as a continuation token for a specific file version to continue from.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the objects/versions for</param>
/// <param name="OptionalParams">Optional parameters for filtering the results. See remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the bucket's objects/versions and additional information.</returns>
function GetBucketObjectVersionsXML(const BucketName: string; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns some or all of the objects of a given bucket.</summary>
/// <remarks>See remarks on GetBucketObjectVersionsXML for more information.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the objects/versions for</param>
/// <param name="OptionalParams">Optional parameters for filtering the results. See remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The bucket's objects/versions and additional information.</returns>
function GetBucketObjectVersions(const BucketName: string; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TAmazonBucketResult;
/// <summary>Returns the user who pays for the given bucket's access.</summary>
/// <remarks>The options are either the current requester (requires AWS authentication) or the bucket owner.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the payer information for</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the bucket's payer information.</returns>
function GetRequestPaymentXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the user who pays for the given bucket's access.</summary>
/// <remarks>The options are either the current requester (requires AWS authentication) or the bucket owner.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the payer information for</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The bucket's payer, or ampUnknown if the request fails.</returns>
function GetRequestPayment(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TAmazonPayer;
/// <summary>Returns the versioning configuration for the specified bucket.</summary>
/// <remarks>The status is 'Enabled' if the given bucket has versioning turned on. Otherwise,
/// it is 'Suspended' if versioning has ever been turned on or not specified at all
/// if versioning has never been enabled for the specified bucket.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the versioning state for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the versioning configuration.</returns>
function GetBucketVersioningXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the state of versioning for the specified bucket.</summary>
/// <remarks>Returns true if versioning is enabled for the given bucket. If false is returned
/// than either versioning is suspended, or has never been enabled.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the versioning state for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if versioning is enabled, false otherwise.</returns>
function GetBucketVersioning(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Returns the state of MFA (Multi-Factor-Authentication) Delete for the specified bucket.</summary>
/// <remarks>Returns true if MFA Delete is enabled for the given bucket, false otherwise.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the MFA Delete state for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if MFA is enabled, false otherwise or if the request fails.</returns>
function GetBucketMFADelete(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Returns the lifecycle configuration information set on the bucket.</summary>
/// <remarks>
/// To use this operation, you must have permission to perform the s3:GetLifecycleConfiguration action.
/// The bucket owner has this permission, by default. The bucket owner can grant this permission to others.
/// </remarks>
/// <param name="ABucketName">The name of the bucket to get the lifecycle.</param>
/// <param name="AResponseInfo">The optional class for storing response info into.</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the stored lifecycle.</returns>
function GetBucketLifecycleXML(const ABucketName: string;
AResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns a list of the current active Multipart Uploads.</summary>
/// <remarks>This lists in-progress multipart uploads and all of their parts.
/// The call returns, at most, 1000 result items. The supported optional parameters include:
/// delimiter: used to group keys or traverse a virtual directory structure (e.g., '/').
/// prefix: Limits the response to object names that begin with the specified prefix
/// max-uploads: integer between 1 and 1000. Maximum number of items to return.
/// key-marker: Says which file to begin population from. If upload-id-marker isn't specified then
/// population begins from the next file after this file name. Otherwise, population
/// begins at the next upload part if one exists, or the next file.
/// upload-id-marker: specifies the multipart upload item to continue population from.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the list of active multipart uploads for.</param>
/// <param name="OptionalParams">The optional request parameters. See Remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the active multipart upload list.</returns>
function ListMultipartUploadsXML(const BucketName: string;
const OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns a list of the current active Multipart Uploads.</summary>
/// <remarks>This lists in-progress multipart uploads and all of their parts.
/// For information on the OptionalParams, see remarks on ListMultipartUploadsXML.
/// </remarks>
/// <param name="BucketName">The name of the bucket to get the list of active multipart uploads for.</param>
/// <param name="OptionalParams">The optional request parameters. See Remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The ative multipart uploads result, or nil if the request fails.</returns>
function ListMultipartUploads(const BucketName: string;
const OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TAmazonMultipartUploadsResult;
/// <summary>Sets the ACL for the given bucket.</summary>
/// <remarks>The given ACP holds the owner information as well as the ACL.
/// </remarks>
/// <param name="BucketName">The name of the bucket to set the ACL for.</param>
/// <param name="ACP">The access control policy containing owner info and the ACL.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetBucketACL(const BucketName: string; ACP: TAmazonAccessControlPolicy;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Sets the Policy for the given bucket.</summary>
/// <remarks>For information on the Policy JSON format, see the Amazon S3 documentation.
/// http://docs.amazonwebservices.com/AmazonS3/latest/API/index.html?RESTBucketPUTpolicy.html
/// </remarks>
/// <param name="BucketName">The name of the bucket to set the policy for.</param>
/// <param name="Policy">The policy, formatted as a JSON Object.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetBucketPolicy(const BucketName: string; Policy: TJSONObject;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Sets the logging state as well as any Grant information.</summary>
/// <remarks>If LoggingInfo is nil, logging will be suspended for the given bucket.
/// </remarks>
/// <param name="BucketName">The name of the bucket to set the logging state for.</param>
/// <param name="LoggingInfo">The logging info to set</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetBucketLogging(const BucketName: string; LoggingInfo: TAmazonBucketLoggingInfo;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Sets the notification events for the given bucket.</summary>
/// <remarks>If Events is nil or an empty list, then notifications will be disabled for the bucket.
/// Note that currently only one event type is supported: s3:ReducedRedundancyLostObject
/// See the documentation on TAmazonNotificationEvent for more information.
/// </remarks>
/// <param name="BucketName">The name of the bucket to set the notification events for.</param>
/// <param name="Events">The notification events to set</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The optional region for the notification config</param>
/// <returns>True if successful, false otherwise.</returns>
function SetBucketNotification(const BucketName: string; Events: TList<TAmazonNotificationEvent>;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Sets who pays for bucket requests.</summary>
/// <remarks>If anything other than BucketOwner or Requester is passed as the Payer, the request will fail.
/// </remarks>
/// <param name="BucketName">The name of the bucket to set the Payer for.</param>
/// <param name="Payer">The user who pays for bucket activity (BucketOwner, Requester)</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetBucketRequestPayment(const BucketName: string; Payer: TAmazonPayer;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Enables or disables bucket versioning and MFA Delete.</summary>
/// <remarks>To enable MFA (Multi-Factor-Authentication) Delete, the MFA published properties on the
/// Amazon Connection must be set. To enable the ability to use MFA and obtain the
/// serial key and token, log into your Amazon account and find the appropriate service.
///
/// Requests that with MFA (x-amz-mfa) must use HTTPS.
/// </remarks>
/// <param name="BucketName">The name of the bucket to set the versioning for.</param>
/// <param name="Enabled">True to enable versioning, false to disable it.</param>
/// <param name="MFADelete">True to Enable MFA delete, false to disable it.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetBucketVersioning(const BucketName: string; Enabled: Boolean; MFADelete: Boolean = False;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Creates a new lifecycle configuration for the bucket or replaces an existing lifecycle configuration.</summary>
/// <remarks>For this operation, a user must get the s3:PutLifecycleConfiguration permission.</remarks>
/// <param name="BucketName">The name of the bucket to set the lifecycle.</param>
/// <param name="LifeCycle">The lifecycle configuration to set.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetBucketLifecycle(const BucketName: string; const LifeCycle: TAmazonLifeCycleConfiguration;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Deletes the specified object from the given bucket.</summary>
/// <remarks>Use this call when versioning is disabled on the bucket.
/// </remarks>
/// <param name="BucketName">The name of the bucket to delete the object from.</param>
/// <param name="ObjectName">The name of the object to delete</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function DeleteObject(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Deletes the specified object's version from the given bucket.</summary>
/// <remarks>You must be the bucket owner to make this call. If the specified version is a delete marker
/// and you have provided a ResponseInfo instance, then a 'x-amz-marker' header will be added
/// with a value of 'true'.
///
/// If MFA Delete is enabled then this call will need to be made over HTTPS and values
/// must be set on the connection for the MFA Serial Number and MFA Authentication Code.
/// </remarks>
/// <param name="BucketName">The name of the bucket to delete the object version from.</param>
/// <param name="ObjectName">The name of the object to delete a version of</param>
/// <param name="VersionId">Id of the version to delete from the specified object.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function DeleteObjectVersion(const BucketName, ObjectName, VersionId: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Deletes the lifecycle configuration from the specified bucket.</summary>
/// <remarks>
/// To use this operation, you must have permission to perform the s3:PutLifecycleConfiguration action.
/// By default, the bucket owner has this permission and the bucket owner can grant this permission to others.
/// </remarks>
/// <param name="BucketName">The name of the bucket to delete the lifecycle.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function DeleteBucketLifecycle(const BucketName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Writes the stream for the given object, or nil.</summary>
/// <remarks>You can use the OptionalParams instance to control the request.
/// The returned stream is nil if the request failed. If the request fails on a 404 (File Not Found)
/// error, then the requested object may have been deleted. If you provide a ResponseInfo instance,
/// then you can check if the object was deleted by verifying there is a 'x-amz-delete-marker'
/// response header, and its value is set to 'true'.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get</param>
/// <param name="OptionalParams">The optional parameters/headers to use in the request.</param>
/// <param name="ObjectStream">The stream to write to. Must not be nil.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The Object's stream or nil.</returns>
function GetObject(const BucketName, ObjectName: string; OptionalParams: TAmazonGetObjectOptionals;
ObjectStream: TStream; ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>Writes the stream for the given object, or nil.</summary>
/// <remarks>If the request fails on a 404 (File Not Found) error, then the requested object may have
/// been deleted. If you provide a ResponseInfo instance, then you can check if the object was
/// deleted by verifying there is a 'x-amz-delete-marker' response header, and its value
/// is set to 'true'.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get</param>
/// <param name="ObjectStream">The stream to write to. Must not be nil.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The Object's stream or nil.</returns>
function GetObject(const BucketName, ObjectName: string;
ObjectStream: TStream; ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>Writes the stream for the given object version, or nil.</summary>
/// <remarks>See GetObject for more information.</remarks>
/// <param name="BucketName"></param>
/// <param name="ObjectName"></param>
/// <param name="VersionId"></param>
/// <param name="OptionalParams">The optional parameters/headers to use in the request.</param>
/// <param name="ObjectStream">The stream to write to. Must not be nil.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The Object's stream or nil.</returns>
function GetObjectVersion(const BucketName, ObjectName, VersionId: string;
OptionalParams: TAmazonGetObjectOptionals;
ObjectStream: TStream; ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>Writes the stream for the given object version, or nil.</summary>
/// <remarks>See GetObject for more information.</remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get a version of</param>
/// <param name="VersionId">The Id of the version to get.</param>
/// <param name="ObjectStream">The stream to write to. Must not be nil.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The Object's stream or nil.</returns>
function GetObjectVersion(const BucketName, ObjectName, VersionId: string;
ObjectStream: TStream; ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>This returns the XML representation of the specified Object's ACL</summary>
/// <remarks>To use this operation, you must have READ_ACP access to the object.</remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get the ACL for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the Object's Access Control Policy</returns>
function GetObjectACLXML(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Returns the given object's ACL</summary>
/// <remarks>For more information, see remarks on GetObjectACLXML.</remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get the ACL for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The object's ACL grant list</returns>
function GetObjectACL(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TList<TAmazonGrant>;
/// <summary>Writes the stream for the given object's torrent, or nil.</summary>
/// <remarks>You can get torrent only for objects that are less than 5 GB in size.</remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get</param>
/// <param name="ObjectStream">The stream to write to. Must not be nil.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The Object's stream or nil.</returns>
function GetObjectTorrent(const BucketName, ObjectName: string; ObjectStream: TStream;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>This returns the metadata for the specified object.</summary>
/// <remarks>An empty list will be returned if no metadata was included on the object.
/// The Response* fields of the OptionalParams instance are not used in this call.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get metadata for.</param>
/// <param name="OptionalParams">The optional parameters/headers to use in the request.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The metadata key/value pairs, or nil if the request fails.</returns>
function GetObjectMetadata(const BucketName, ObjectName: string; OptionalParams: TAmazonGetObjectOptionals;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TStrings; overload;
/// <summary>This returns the metadata for the specified object.</summary>
/// <remarks>An empty list will be returned if no metadata was included on the object.</remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get metadata for.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The metadata key/value pairs, or nil if the request fails.</returns>
function GetObjectMetadata(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TStrings; overload;
/// <summary>This returns the properties and metadata for the specified object.</summary>
/// <remarks>The Response* fields of the OptionalParams instance are not used in this call.
/// Empty lists will be returned if no metadata was included on the object.
/// The Response* fields of the OptionalParams instance are not used in this call.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get metadata for.</param>
/// <param name="OptionalParams">The optional parameters/headers to use in the request.</param>
/// <param name="Properties">The object's properties</param>
/// <param name="Metadata">The object's metadata</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if the request was successful, false otherwise.</returns>
function GetObjectProperties(const BucketName, ObjectName: string;
OptionalParams: TAmazonGetObjectOptionals;
out Properties, Metadata: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>This returns the properties and metadata for the specified object.</summary>
/// <remarks>Empty lists will be returned if no metadata was included on the object.
/// The Response* fields of the OptionalParams instance are not used in this call.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to get metadata for.</param>
/// <param name="Properties">The object's properties</param>
/// <param name="Metadata">The object's metadata</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if the request was successful, false otherwise.</returns>
function GetObjectProperties(const BucketName, ObjectName: string;
out Properties, Metadata: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>Uploads the given object, optionally setting metadata on it.</summary>
/// <remarks>Several optional headers can be set to the request. To see a full list, view the Amazon API:
/// http://docs.amazonwebservices.com/AmazonS3/latest/API/index.html?RESTObjectPUT.html
/// Some include: Content-MD5, Content-Type, x-amz-storage-class and several more.
///
/// If you provide a ResponseInfo instance and versioning is enabled, then a successful request
/// will result in a 'x-amz-version-id' header being populated, which is the uploaded object's
/// version.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name to use for the object being uploaded.</param>
/// <param name="Content">The Object's content, in bytes.</param>
/// <param name="ReducedRedundancy">True to use REDUCED_REDUNDANCY as the object's storage class.</param>
/// <param name="Metadata">The optional metadata to set on the object, or nil.</param>
/// <param name="Headers">Optional request headers to use. See remarks.</param>
/// <param name="ACL">Optional ACL to apply to the object. If unspecified, will default to private.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if the request was successful, false otherwise.</returns>
function UploadObject(const BucketName, ObjectName: string; Content: TArray<Byte>; ReducedRedundancy: Boolean = false;
Metadata: TStrings = nil;
Headers: TStrings = nil; ACL: TAmazonACLType = amzbaPrivate;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Sets the ACL for the given object.</summary>
/// <remarks>The given ACP holds the owner information as well as the ACL.
///
/// Several optional headers can be set to the request. To see a full list, view the Amazon API:
/// http://docs.amazonwebservices.com/AmazonS3/latest/API/index.html?RESTObjectPUTacl.html
/// Some include: Content-MD5, Content-Type, x-amz-storage-class and several more.
///
/// If you provide a ResponseInfo instance and versioning is enabled, then a successful request
/// will result in a 'x-amz-version-id' header being populated, which is the updated object's
/// version.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to set the ACL for.</param>
/// <param name="ACP">The access control policy containing owner info and the ACL.</param>
/// <param name="Headers">Optional request headers to use. See remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetObjectACL(const BucketName, ObjectName: string; ACP: TAmazonAccessControlPolicy;
Headers: TStrings = nil; ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>Sets the ACL for the given object.</summary>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The name of the object to set the ACL for.</param>
/// <param name="ACL">The ACL to apply to the object. If unspecified, will default to private.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetObjectACL(const BucketName, ObjectName: string; ACL: TAmazonACLType;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean; overload;
/// <summary>Copies the specified source object to the given target object.</summary>
/// <remarks>The OptionalParams instance can be set to provide more control over the request.
/// If you provide a ResponseInfo instance, then you can check the value of the
/// 'x-amz-version-id' header to get the VersionId of the resulting (target) object if
/// versioning is enabled. If versioning is enabled then this copy will copy the most
/// recent soruce object. The 'x-amz-copy-source-version-id' result header will specify
/// the VersionId of the source object that was copied.
/// See the comments on TAmazonCopyObjectOptionals for more information.
///
/// You can change the storage class of an existing object by copying it to the same name
/// in the same bucket. To do that, you use the following request optional parameter:
/// x-amz-storage-class set to STANDARD or REDUCED_REDUNDANCY
/// </remarks>
/// <param name="DestinationBucket">The bucket the object will be copied into.</param>
/// <param name="DestinationObjectName">The name of the resulting object after the copy.</param>
/// <param name="SourceBucket">The bucket the object being copied is in.</param>
/// <param name="SourceObjectName">The name of the object being copied.</param>
/// <param name="OptionalParams">Optional parameters to refine the request. See remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function CopyObject(const DestinationBucket, DestinationObjectName: string;
const SourceBucket, SourceObjectName: string;
OptionalParams: TAmazonCopyObjectOptionals = nil;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Sets the metadata on the given object.</summary>
/// <remarks>This performs a copy object, with the source and destination the same.
/// Any previous metadata on the object will be lost.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The object to set the metadata for</param>
/// <param name="Metadata">The metadata to set on the object</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function SetObjectMetadata(const BucketName, ObjectName: string; Metadata: TStrings;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Copies the specified source object's version to the given target object.</summary>
/// <remarks>See the comments on CopyObject for more information.
/// </remarks>
/// <param name="DestinationBucket">The bucket the object will be copied into.</param>
/// <param name="DestinationObjectName">The name of the resulting object after the copy.</param>
/// <param name="SourceBucket">The bucket the object being copied is in.</param>
/// <param name="SourceObjectName">The name of the object being copied.</param>
/// <param name="SourceVersionId">The Version of the object to copy</param>
/// <param name="OptionalParams">Optional parameters to refine the request. See remarks.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function CopyObjectVersion(const DestinationBucket, DestinationObjectName: string;
const SourceBucket, SourceObjectName, SourceVersionId: string;
OptionalParams: TAmazonCopyObjectOptionals = nil;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Start a new multipart upload.</summary>
/// <remarks>The XML returned contains the UploadId. This is required for future calls to 'UploadPart'
/// or for stopping/cancelling the multipart upload.
///
/// There are several supported optional parameters. For a list of them and their functionality,
/// go to the Amazon documentation:
///
/// http://docs.amazonwebservices.com/AmazonS3/latest/API/index.html?mpUploadInitiate.html
/// </remarks>
/// <param name="BucketName">The name of the bucket the object will be in.</param>
/// <param name="ObjectName">The name of the object this multipart upload will create.</param>
/// <param name="Metadata">The metadata to set on the resulting object, or nil.</param>
/// <param name="Headers">Optional headers to set. See remarks.</param>
/// <param name="ACL">Optional ACL to set on the resulting object.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>XML containing the UploadId to use for subsequent calls.</returns>
function InitiateMultipartUploadXML(const BucketName, ObjectName: string; Metadata: TStrings = nil;
Headers: TStrings = nil;
ACL: TAmazonACLType = amzbaPrivate;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Start a new multipart upload.</summary>
/// <remarks>See comments on InitiateMultipartUploadXML for more information.
/// </remarks>
/// <param name="BucketName">The name of the bucket the object will be in.</param>
/// <param name="ObjectName">The name of the object this multipart upload will create.</param>
/// <param name="Metadata">The metadata to set on the resulting object, or nil.</param>
/// <param name="Headers">Optional headers to set. See remarks.</param>
/// <param name="ACL">Optional ACL to set on the resulting object.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The UploadId to use for subsequent calls.</returns>
function InitiateMultipartUpload(const BucketName, ObjectName: string; Metadata: TStrings = nil;
Headers: TStrings = nil;
ACL: TAmazonACLType = amzbaPrivate;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Aborts a previously initiated multipart upload.</summary>
/// <remarks>All storage consumed by previously uplaoded parts for this multipart upload will be freed.
/// However, if there are any in-progress part uploads for this UploadId when you abort it,
/// then the part may be uploaded successfully and you would then be required to
/// abort the UploadId again to free any additional parts.
/// </remarks>
/// <param name="BucketName">The bucket the multipart upload object was to be stored.</param>
/// <param name="ObjectName">The name of the object that would have resulted from the multipart upload.</param>
/// <param name="UploadId">The UploadId originally returned when the multipart upload was initiated.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function AbortMultipartUpload(const BucketName, ObjectName, UploadId: string;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Uploads a part to an initiated multipart upload.</summary>
/// <remarks>All parts except the last part must be at least 5 MB in size.
/// Part numbers can be any number from 1 to 10,000, inclusive. If you specify a part number that
/// already had been uploaded, the content will be replaced by this content.
/// </remarks>
/// <param name="BucketName">The name of the bucket the multipart upload's object is for.</param>
/// <param name="ObjectName">The name of the multipart upload's object.</param>
/// <param name="UploadId">The multipart upload's unique Id.</param>
/// <param name="PartNumber">The part number to assign to this content.</param>
/// <param name="Content">The content to upload.</param>
/// <param name="Part">The part result (ETag and Number) if the request was successful.</param>
/// <param name="ContentMD5">The optional MD5 of the content being sent, for integrity checking.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>True if successful, false otherwise.</returns>
function UploadPart(const BucketName, ObjectName, UploadId: string; PartNumber: Integer; Content: TArray<Byte>;
out Part: TAmazonMultipartPart;
const ContentMD5: string = '';
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Completes the given multipart upload, committing the specified parts.</summary>
/// <param name="BucketName">The name of the bucket the object is in.</param>
/// <param name="ObjectName">The object the multipart upload is for.</param>
/// <param name="UploadId">The multipart upload's unique Id.</param>
/// <param name="Parts">The list of parts to build the resulting object from.</param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>true if successful, false otherwise.</returns>
function CompleteMultipartUpload(const BucketName, ObjectName, UploadId: string;
Parts: TList<TAmazonMultipartPart>;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): Boolean;
/// <summary>Lists the currently uploaded parts for multipart upload with the given ID.</summary>
/// <remarks>MaxParts can be set to a number from 2 to 1000. Set it to 0 to use the server default value.
/// PartNumberMarker is the continuation token returned from a previous call, in the XML element
/// with the same name.
/// </remarks>
/// <param name="BucketName">The name of the bucket the multipart upload is for.</param>
/// <param name="ObjectName">The name of the object the multipart upload is for.</param>
/// <param name="UploadId">The UploadId identifying the multipart upload.</param>
/// <param name="MaxParts">The maximum number of parts to return, or 0 for server default.</param>
/// <param name="PartNumberMarker">The part number to continue population from,
/// or 0 to start from the beginning.
/// </param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The XML representation of the multipart upload parts.</returns>
function ListMultipartUploadPartsXML(const BucketName, ObjectName, UploadId: string;
MaxParts: Integer = 0; PartNumberMarker: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): string;
/// <summary>Lists the currently uploaded parts for multipart upload with the given ID.</summary>
/// <remarks>MaxParts can be set to a number from 2 to 1000. Set it to 0 to use the server default value.
/// PartNumberMarker is the continuation token returned from a previous call, in the property
/// with the same name.
/// </remarks>
/// <param name="BucketName">The name of the bucket the multipart upload is for.</param>
/// <param name="ObjectName">The name of the object the multipart upload is for.</param>
/// <param name="UploadId">The UploadId identifying the multipart upload.</param>
/// <param name="MaxParts">The maximum number of parts to return, or 0 for server default.</param>
/// <param name="PartNumberMarker">The part number to continue population from,
/// or 0 to start from the beginning.
/// </param>
/// <param name="ResponseInfo">The optional class for storing response info into</param>
/// <param name="BucketRegion">The region of the bucket</param>
/// <returns>The list of multipart upload parts and additional metadata, or nil if the request fails.
/// </returns>
function ListMultipartUploadParts(const BucketName, ObjectName, UploadId: string;
MaxParts: Integer = 0; PartNumberMarker: Integer = 0;
ResponseInfo: TCloudResponseInfo = nil;
BucketRegion: TAmazonRegion = amzrNotSpecified): TAmazonListPartsResult;
/// <summary>Determines S3 Endpoint name based on the region key.</summary>
function GetEndpointFromRegion(ARegion: TAmazonRegion): string;
end;
const
/// <summary>Set as the datatype for a column to force replacement of any previous data for that column
/// </summary>
TABLE_ROW_DATATYPE_REPLACE = 'replace';
/// <summary>Set as the datatype for a column to prevent replacement of any previous data for that column</summary>
TABLE_ROW_DATATYPE_DO_NOT_REPLACE = 'noreplace';
/// <summary>Group URI for AllUsers Grantee</summary>
ALL_USERS_GROUP = 'http://acs.amazonaws.com/groups/global/AllUsers';
/// <summary>Group URI for AllAuthenticatedUsers Grantee</summary>
ALL_AUTHENTICATED_USERS_GROUP = 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers';
/// <summary>Group URI for LogDelivery Grantee</summary>
LOG_DELIVERY_GROUP = 'http://acs.amazonaws.com/groups/s3/LogDelivery';
implementation
uses
System.Hash, System.NetConsts, System.Net.HTTPClient, System.TypInfo, System.DateUtils,
Xml.XMLDoc, System.StrUtils, System.NetEncoding, System.Net.URLClient
{$IFDEF MACOS}
, Macapi.CoreFoundation
{$ENDIF MACOS}
;
const
NODE_QUEUES = 'ListQueuesResult';
NODE_QUEUE = 'QueueUrl';
NODE_ERRORS = 'Errors';
NODE_ERROR = 'Error';
NODE_ERROR_MESSAGE = 'Message';
NODE_ERROR_CODE = 'Code';
NODE_REQUEST_ID = 'RequestId';
NODE_RESPONSE_METADATA = 'ResponseMetadata';
NODE_QUEUE_CREATE_RESULT = 'CreateQueueResult';
NODE_QUEUE_ATTRIBS_RESULT = 'GetQueueAttributesResult';
NODE_ATTRIBUTES = 'Attribute';
NODE_NAME = 'Name';
NODE_VALUE = 'Value';
NODE_QUEUE_MESSAGE_RESULT = 'SendMessageResult';
NODE_QUEUE_MESSAGE_ID = 'MessageId';
NODE_QUEUE_MESSAGE_RECEIVE_RESULT = 'ReceiveMessageResult';
NODE_QUEUE_MESSAGE_MD5 = 'MD5OfBody';
NODE_QUEUE_MESSAGE_POPRECEIPT = 'ReceiptHandle';
NODE_QUEUE_MESSAGE_BODY = 'Body';
NODE_QUEUE_MESSAGE = 'Message';
NODE_BATCH_QUEUE_MESSAGE_RESULT = 'SendMessageBatchResult';
NODE_BATCH_QUEUE_MESSAGE_RESULT_ENTRY = 'SendMessageBatchResultEntry';
NODE_DEAD_LETTER_SOURCE_QUEUES = 'ListDeadLetterSourceQueuesResult';
CLASS_REDUCED_REDUNDANCY = 'REDUCED_REDUNDANCY';
AmazonGranteeTypeStr: array[TAmazonGranteeType] of string =
('CanonicalUser', 'CustomerByEmail', 'Group', 'Unknown');
AmazonGrantPermissionStr: array[TAmazonGrantPermission] of string =
('FULL_CONTROL', 'WRITE', 'WRITE_ACP', 'READ', 'READ_ACP', 'UNKNOWN');
procedure AddS3MetadataHeaders(Headers, Metadata: TStrings);
var
I, Count: Integer;
MetaName: string;
begin
//add the specified metadata into the headers, prefixing each
//metadata header name with 'x-ms-meta-' if it wasn't already.
if (MetaData <> nil) and (Headers <> nil) then
begin
Count := MetaData.Count;
for I := 0 to Count - 1 do
begin
MetaName := MetaData.Names[I];
if not AnsiStartsText('x-amz-meta-', MetaName) then
MetaName := 'x-amz-meta-' + MetaName;
Headers.Values[MetaName] := MetaData.ValueFromIndex[I];
end;
end;
end;
function GetACLTypeString(BucketACL: TAmazonACLType): string;
begin
case BucketACL of
amzbaPrivate: Result := 'private';
amzbaPublicRead: Result := 'public-read';
amzbaPublicReadWrite: Result := 'public-read-write';
amzbaAuthenticatedRead: Result := 'authenticated-read';
amzbaBucketOwnerRead: Result := 'bucket-owner-read';
amzbaBucketOwnerFullControl: Result := 'bucket-owner-full-control';
amzbaAWSExecRead: Result := 'aws-exec-read';
amzbaLogDeliveryWrite: Result := 'log-delivery-write';
else
Result := 'private';
end;
end;
function CaseSensitiveNameCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
if List <> nil then
//CompareStr is used here because Amazon sorts strings based on ASCII order,
//while AnsiCompareStr does not. (lower-case vs. upper-case)
Result := CompareStr(List.Names[Index1], List.Names[Index2])
else
Result := 0;
end;
function CaseSensitiveHyphenCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
if List <> nil then
//case sensitive stringSort is needed to sort with hyphen (-) precedence
Result := string.Compare(List.Strings[Index1], List.Strings[Index2], [coStringSort])
else
Result := 0;
end;
{ TAmazonAuthentication }
function TAmazonAuthentication.BuildAuthorizationString(const StringToSign: string): string;
begin
if FAuthInHeader then
Result := inherited BuildAuthorizationString(StringToSign)
else
Result := TNetEncoding.Base64.EncodeBytesToString(SignString(FSHAKey,StringToSign));
end;
constructor TAmazonAuthentication.Create(const ConnectionInfo: TCloudConnectionInfo; AuthInHeader: Boolean);
begin
inherited Create(ConnectionInfo, AuthorizationType); {do not localize}
FAuthInHeader := AuthInHeader;
end;
{ TAmazonAWS4Authentication }
procedure TAmazonAWS4Authentication.AssignKey(const AccountKey: string);
begin
if AccountKey = '' then
raise Exception.Create('AccountKey is not specified');
FSHAKey := TEncoding.Default.GetBytes('AWS4'+AccountKey);
end;
function TAmazonAWS4Authentication.BuildAuthorizationString(const StringToSign,
DateISO, Region, ServiceName, SignedStrHeaders: string): string;
function GetSignatureKey(const datestamp, region, serviceName: string): TBytes;
begin
Result := SignString(FSHAKey, datestamp); //'20130524'
Result := SignString(Result, region);
Result := SignString(Result, serviceName);
Result := SignString(Result, 'aws4_request');
end;
var
Signature, Credentials, SignedHeaders: string;
SigningKey : TBytes;
begin
SigningKey := GetSignatureKey(DateISO, Region, ServiceName);
Credentials := 'Credential='+FConnectionInfo.AccountName + '/'+ DateISO + '/'+Region+ '/' + ServiceName + '/aws4_request'+',';
SignedHeaders := 'SignedHeaders='+SignedStrHeaders + ',';
Signature := 'Signature='+THash.DigestAsString(SignString(SigningKey, StringToSign));
Result := GetAuthorizationType +' '+ Credentials + SignedHeaders + Signature;
end;
function TAmazonAWS4Authentication.BuildAuthorizationString(const StringToSign,
DateISO, Region, SignedStrHeaders: string): string;
begin
Result := BuildAuthorizationString(StringToSign, DateISO, Region, 's3', SignedStrHeaders);
end;
constructor TAmazonAWS4Authentication.Create(const ConnectionInfo: TCloudConnectionInfo; AuthInHeader: Boolean);
begin
inherited Create(ConnectionInfo, AuthorizationType); {do not localize}
FAuthInHeader := AuthInHeader;
end;
{ TAmazonSHA1Authentication }
constructor TAmazonSHA1Authentication.Create(const ConnectionInfo: TCloudConnectionInfo);
begin
inherited Create(ConnectionInfo, AuthorizationType); {do not localize}
end;
{ TAmazonConnectionInfo }
constructor TAmazonConnectionInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ConsistentRead := True;
FStorageEndpoint := DefaultStorageEndpoint;
FTableEndpoint := DefaultTableEndpoint;
FQueueEndpoint := DefaultQueueEndpoint;
FRegion := DefaultRegion;
UseDefaultEndpoints := True;
end;
procedure TAmazonConnectionInfo.SetStorageEndpoint(const AValue: string);
begin
FStorageEndpoint := AValue;
if AValue <> DefaultStorageEndpoint then
UseDefaultEndpoints := False;
end;
procedure TAmazonConnectionInfo.SetQueueEndpoint(const AValue: string);
begin
FQueueEndpoint := AValue;
if AValue <> DefaultQueueEndpoint then
UseDefaultEndpoints := False;
end;
procedure TAmazonConnectionInfo.SetTableEndpoint(const AValue: string);
begin
FTableEndpoint := AValue;
if AValue <> DefaultTableEndpoint then
UseDefaultEndpoints := False;
end;
procedure TAmazonConnectionInfo.SetRegion(const AValue: TAmazonRegion);
begin
FRegion := AValue;
if AValue <> DefaultRegion then
UseDefaultEndpoints := False;
end;
function TAmazonConnectionInfo.GetStorageEndpoint: string;
begin
if UseDefaultEndpoints then
Result := DefaultStorageEndpoint
else
Result := FStorageEndpoint;
end;
function TAmazonConnectionInfo.GetQueueEndpoint: string;
begin
if UseDefaultEndpoints then
Result := DefaultQueueEndpoint
else
Result := FQueueEndpoint;
end;
function TAmazonConnectionInfo.GetTableEndpoint: string;
begin
if UseDefaultEndpoints then
Result := DefaultTableEndpoint
else
Result := FTableEndpoint;
end;
function TAmazonConnectionInfo.GetRegion: TAmazonRegion;
begin
if UseDefaultEndpoints then
Result := DefaultRegion
else
Result := FRegion;
end;
//note: endpoints and regions may change in the future
class function TAmazonConnectionInfo.GetRegionFromString(const Region: string): TAmazonRegion;
begin
if Region.Equals('EU') then
Result := amzrEUWest1
else if Region.Equals('eu-west-1') then
Result := amzrEUWest1
else if Region.Equals('eu-west-2') then
Result := amzrEUWest2
else if Region.Equals('eu-west-3') then
Result := amzrEUWest3
else if Region.Equals('eu-central-1') then
Result := amzrEUCentral1
else if Region.Equals('us-east-1') then
Result := amzrUSEast1
else if Region.Equals('us-west-1') then
Result := amzrUSWest1
else if Region.Equals( 'us-west-2') then
Result := amzrUSWest2
else if Region.Equals('ap-southeast-1') then
Result := amzrAPSoutheast1
else if Region.Equals('ap-southeast-2') then
Result := amzrAPSoutheast2
else if Region.Equals('ap-northeast-1') then
Result := amzrAPNortheast1
else if Region.Equals('ap-northeast-2') then
Result := amzrAPNortheast2
else if Region.Equals('ap-northeast-3') then
Result := amzrAPNortheast3
else if Region.Equals('sa-east-1') then
Result := amzrSAEast1
else if Region.Equals('cn-north-1') then
Result := amzrCNNorth1
else if Region.Equals('cn-northwest-1') then
Result := amzrCNNorthwest1
else
Result := amzrUSEast1;
end;
//note: endpoints and regions may change in the future
class function TAmazonConnectionInfo.GetRegionString(Region: TAmazonRegion): string;
begin
case Region of
amzrEU: Result := 'eu-west-1'; // deprecate
amzrEUWest1: Result := 'eu-west-1';
amzrEUWest2: Result := 'eu-west-2';
amzrEUWest3: Result := 'eu-west-3';
amzrEUCentral1: Result := 'eu-central-1';
amzrUSEast1: Result := 'us-east-1';
amzrUSWest1: Result := 'us-west-1';
amzrUSWest2: Result := 'us-west-2';
amzrAPSoutheast1: Result := 'ap-southeast-1';
amzrAPSoutheast2: Result := 'ap-southeast-2';
amzrAPNortheast1: Result := 'ap-northeast-1';
amzrAPNortheast2: Result := 'ap-northeast-2';
amzrAPNortheast3: Result := 'ap-northeast-3';
amzrSAEast1: Result := 'sa-east-1';
amzrUSClassic: Result := 'us-east-1'; // deprecate
amzrNotSpecified: Result := 'us-east-1'; // deprecate
amzrCNNorth1: Result := 'cn-north-1';
amzrCNNorthwest1: Result := 'cn-northwest-1';
else
Result := 'us-east-1';
end;
end;
function TAmazonConnectionInfo.GetVirtualHost(const AHost, ARegionHost: string;
ARegion: TAmazonRegion): string;
var
LRegion: TAmazonRegion;
begin
LRegion := ARegion;
if LRegion = amzrNotSpecified then
LRegion := Region;
if LRegion = amzrNotSpecified then
LRegion := DefaultRegion;
// https://docs.aws.amazon.com/general/latest/gr/rande.html
if LRegion <> DefaultRegion then
Result := Format(ARegionHost, [GetRegionString(LRegion)])
else
Result := AHost;
end;
function TAmazonConnectionInfo.GetServiceURL(const AHost: string): string;
begin
Result := Format('%s://%s', [Protocol, AHost]);
end;
function TAmazonConnectionInfo.GetServiceURL(const AHost, ARegionHost: string; ARegion: TAmazonRegion): string;
begin
Result := GetServiceURL(GetVirtualHost(AHost, ARegionHost, ARegion));
end;
function TAmazonConnectionInfo.GetQueueURL: string;
begin
Result := GetServiceURL(QueueEndpoint, RegionQueueEndpoint, amzrNotSpecified);
end;
function TAmazonConnectionInfo.GetTableURL: string;
begin
Result := GetServiceURL(TableEndpoint, RegionTableEndpoint, amzrNotSpecified);
end;
function TAmazonConnectionInfo.StorageVirtualHost(const ABucketName: string; ARegion: TAmazonRegion): string;
begin
Result := GetVirtualHost(StorageEndpoint, RegionStorageEndpoint, ARegion);
if ABucketName <> EmptyStr then
Result := Format('%s.%s', [ABucketName, Result]);
end;
function TAmazonConnectionInfo.StorageURL(const ABucketName: string; ARegion: TAmazonRegion): string;
begin
Result := GetServiceURL(StorageVirtualHost(ABucketName, ARegion));
end;
{ TAmazonRowConditional }
class function TAmazonRowConditional.Create(const ColumnName, ColumnValue: string;
const ColumnExists: Boolean): TAmazonRowConditional;
var
Inst: TAmazonRowConditional;
begin
Inst.ColumnName := ColumnName;
Inst.ColumnValue := ColumnValue;
Inst.ColumnExists := ColumnExists;
Result := Inst;
end;
{ TAmazonService }
constructor TAmazonService.Create(const ConnectionInfo: TAmazonConnectionInfo);
begin
inherited Create(ConnectionInfo, CreateAuthInstance(ConnectionInfo));
FUseCanonicalizedHeaders := False;
FUseCanonicalizedResource := True;
FUseResourcePath := True;
//The QueryPrefix (HTTPRequestURI) is on a different line than the query parameters in the StringToSign,
//but has no start character. So set empty string here.
FQueryStartChar := #0;
end;
function TAmazonService.CurrentTime: string;
begin
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz"Z"', TTimeZone.Local.ToUniversalTime(Now),
TFormatSettings.Create('en-US'));
end;
destructor TAmazonService.Destroy;
begin
inherited;
end;
function TAmazonService.GetCanonicalizedHeaderPrefix: string;
begin
Result := EmptyStr;
end;
function TAmazonService.GetConnectionInfo: TAmazonConnectionInfo;
begin
Result := TAmazonConnectionInfo(ConnectionInfo);
end;
function TAmazonService.GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings;
begin
InstanceOwner := False;
Result := nil;
end;
procedure TAmazonService.SortHeaders(const Headers: TStringList);
begin
if (Headers <> nil) then
begin
Headers.CustomSort(CaseSensitiveNameCompare);
end;
end;
function TAmazonService.URLEncodeValue(const Value: string): string;
begin
//Amazon services expect these characters to be encoded
Result := URLEncode(Value, ['=', ':', '/', '+', '(', ')', '/', '!', '"', '$', '@', '&', ',', '''', '?', ';']);
end;
function TAmazonService.ISODateTime_noSeparators: string;
begin
Result := DateToISO8601(TTimeZone.Local.ToUniversalTime(Now),True);
Result := StringReplace(Result,'-','',[rfReplaceAll]);
Result := StringReplace(Result,'+','',[rfReplaceAll]);
Result := StringReplace(Result,':','',[rfReplaceAll]);
Result := LeftStr(Result,Pos('.',Result)-1)+'Z';
end;
{ TAmazonQueuePermission }
class function TAmazonQueuePermission.Create(const AccountId: string; Action: TAmazonQueueActions): TAmazonQueuePermission;
var
Inst: TAmazonQueuePermission;
begin
Inst.AccountId := AccountId;
Inst.Action := Action;
Result := Inst;
end;
function TAmazonQueuePermission.GetAction: string;
begin
case Action of
aqacAll : Exit('*');
aqacSendMessage : Exit('SendMessage');
aqacReceiveMessage : Exit('ReceiveMessage');
aqacDeleteMessage : Exit('DeleteMessage');
aqacChangeMessageVisibility : Exit('ChangeMessageVisibility');
aqacGetQueueAttributes : Exit('GetQueueAttributes');
end;
end;
{ TAmazonBatchRow }
class function TAmazonBatchRow.Create(const RowId: string; Row: TCloudTableRow;
ReplaceAll: Boolean): TAmazonBatchRow;
var
Inst: TAmazonBatchRow;
begin
Inst.RowId := RowId;
Inst.Row := Row;
Inst.ReplaceAll := ReplaceAll;
Result := Inst;
end;
{ TAmazonQueueService }
function TAmazonQueueService.GetQueueAttributeName(const Attribute: TAmazonQueueAttribute): string;
begin
case Attribute of
aqaAll: Exit('All');
aqaApproximateNumberOfMessages: Exit('ApproximateNumberOfMessages');
aqaApproximateNumberOfMessagesNotVisible: Exit('ApproximateNumberOfMessagesNotVisible');
aqaVisibilityTimeout: Exit('VisibilityTimeout');
aqaCreatedTimestamp: Exit('CreatedTimestamp');
aqaLastModifiedTimestamp: Exit('LastModifiedTimestamp');
aqaPolicy: Exit('Policy');
aqaMaximumMessageSize: Exit('MaximumMessageSize');
aqaMessageRetentionPeriod: Exit('MessageRetentionPeriod');
aqaQueueArn: Exit('QueueArn');
aqaApproximateNumberOfMessagesDelayed: Exit('ApproximateNumberOfMessagesDelayed');
aqaDelaySeconds: Exit('DelaySeconds');
aqaReceiveMessageWaitTimeSeconds: Exit('ReceiveMessageWaitTimeSeconds');
aqaRedrivePolicy: Exit('RedrivePolicy');
end;
end;
function TAmazonQueueService.GetQueueAttributeFromName(const AAttributeName: string): TAmazonQueueAttribute;
begin
if AAttributeName.Equals('All') then Exit(TAmazonQueueAttribute.aqaAll);
if AAttributeName.Equals('ApproximateNumberOfMessages') then Exit(TAmazonQueueAttribute.aqaApproximateNumberOfMessages);
if AAttributeName.Equals('ApproximateNumberOfMessagesNotVisible') then Exit(TAmazonQueueAttribute.aqaApproximateNumberOfMessagesNotVisible);
if AAttributeName.Equals('VisibilityTimeout') then Exit(TAmazonQueueAttribute.aqaVisibilityTimeout);
if AAttributeName.Equals('CreatedTimestamp') then Exit(TAmazonQueueAttribute.aqaCreatedTimestamp);
if AAttributeName.Equals('LastModifiedTimestamp') then Exit(TAmazonQueueAttribute.aqaLastModifiedTimestamp);
if AAttributeName.Equals('Policy') then Exit(TAmazonQueueAttribute.aqaPolicy);
if AAttributeName.Equals('MaximumMessageSize') then Exit(TAmazonQueueAttribute.aqaMaximumMessageSize);
if AAttributeName.Equals('MessageRetentionPeriod') then Exit(TAmazonQueueAttribute.aqaMessageRetentionPeriod);
if AAttributeName.Equals('QueueArn') then Exit(TAmazonQueueAttribute.aqaQueueArn);
if AAttributeName.Equals('ApproximateNumberOfMessagesDelayed') then Exit(TAmazonQueueAttribute.aqaApproximateNumberOfMessagesDelayed);
if AAttributeName.Equals('DelaySeconds') then Exit(TAmazonQueueAttribute.aqaDelaySeconds);
if AAttributeName.Equals('ReceiveMessageWaitTimeSeconds') then Exit(TAmazonQueueAttribute.aqaReceiveMessageWaitTimeSeconds);
if AAttributeName.Equals('RedrivePolicy') then Exit(TAmazonQueueAttribute.aqaRedrivePolicy);
Exit(TAmazonQueueAttribute.aqaAll);
end;
function TAmazonQueueService.ListQueuesXML(OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo): string;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('ListQueues');
if OptionalParams <> nil then
QueryParams.AddStrings(OptionalParams);
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.QueueURL, QueryParams, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonQueueService.ListQueues(OptionalParams: TStrings; ResponseInfo: TCloudResponseInfo): TList<TCloudQueue>;
var
xml: string;
xmlDoc: IXMLDocument;
QueuesXMLNode: IXMLNode;
QueueNode: IXMLNode;
begin
xml := ListQueuesXML(OptionalParams, ResponseInfo);
if XML = EmptyStr then
Exit(nil);
Result := TList<TCloudQueue>.Create;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(XML);
QueuesXMLNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_QUEUES);
if (QueuesXMLNode <> nil) and (QueuesXMLNode.HasChildNodes) then
begin
QueueNode := QueuesXMLNode.ChildNodes.FindNode(NODE_QUEUE);
while (QueueNode <> nil) do
begin
if QueueNode.NodeName = NODE_QUEUE then
begin
//the Queue node ('QueueUrl') has only a text value, which is the Queue URL
Result.Add(TCloudQueue.Create(QueueNode.Text));
end;
QueueNode := QueueNode.NextSibling;
end;
end;
end;
function TAmazonQueueService.CreateQueue(const QueueName: string; const DefaultVisibilityTimeout: Integer;
ResponseInfo: TCloudResponseInfo): Boolean;
var
URL: string;
begin
Result := CreateQueue(QueueName, URL, DefaultVisibilityTimeout, ResponseInfo);
end;
function TAmazonQueueService.CreateQueue(const QueueName: string; out QueueURL: string;
const DefaultVisibilityTimeout: Integer;
ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
xml: string;
xmlDoc: IXMLDocument;
ResultNode, QueueNode: IXMLNode;
begin
QueryParams := BuildQueryParameters('CreateQueue');
QueryParams.Values['QueueName'] := QueueName;
if DefaultVisibilityTimeout > -1 then
begin
QueryParams.Values['Attribute.1.Name'] := 'VisibilityTimeout';
QueryParams.Values['Attribute.1.Value'] := IntToStr(DefaultVisibilityTimeout);
end;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.QueueURL, QueryParams, ResponseInfo, xml);
Result := (Response <> nil) and (Response.ResponseCode = 200);
FreeAndNil(Response);
if Result and (xml <> EmptyStr) then
begin
//Parse XML and get QueueURL value
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(XML);
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_QUEUE_CREATE_RESULT);
if (ResultNode <> nil) and (ResultNode.HasChildNodes) then
begin
QueueNode := ResultNode.ChildNodes.FindNode(NODE_QUEUE);
if (QueueNode <> nil) and (QueueNode.IsTextElement) then
QueueURL := QueueNode.Text;
end;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonQueueService.CreateQueue(const QueueName: string; out QueueURL: string;
Attributes: array of TQueueAttributePair;
ResponseInfo: TCloudResponseInfo = nil): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
attribute: TQueueAttributePair;
nattr: Integer;
xml: string;
xmlDoc: IXMLDocument;
ResultNode, QueueNode: IXMLNode;
begin
QueryParams := BuildQueryParameters('CreateQueue');
QueryParams.Values['QueueName'] := QueueName;
for nAttr := 0 to Length(Attributes)-1 do
begin
attribute := Attributes[nAttr];
QueryParams.Values[Format('Attribute.%d.Name',[nAttr+1])] := GetQueueAttributeName(attribute.key);
QueryParams.Values[Format('Attribute.%d.Value',[nAttr+1])] := attribute.Value;
end;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.QueueURL, QueryParams, ResponseInfo, xml);
Result := (Response <> nil) and (Response.ResponseCode = 200);
if Result and (xml <> EmptyStr) then
begin
//Parse XML and get QueueURL value
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(XML);
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_QUEUE_CREATE_RESULT);
if (ResultNode <> nil) and (ResultNode.HasChildNodes) then
begin
QueueNode := ResultNode.ChildNodes.FindNode(NODE_QUEUE);
if (QueueNode <> nil) and (QueueNode.IsTextElement) then
QueueURL := QueueNode.Text;
end;
end;
finally
Response.Free;
QueryParams.Free;
end;
end;
function TAmazonQueueService.DeleteMessage(const QueueURL, PopReceipt: string;
ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('DeleteMessage');
QueryParams.Values['ReceiptHandle'] := PopReceipt;
Response := nil;
try
Response := IssueRequest(QueueURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonQueueService.DeleteMessageBatch(const AQueueURL: string; const APopReceiptList: TArray<string>;
const AResponseInfo: TCloudResponseInfo): Boolean;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
LPopReceipt: string;
I: Integer;
begin
LQueryParams := BuildQueryParameters('DeleteMessageBatch');
I := 1;
for LPopReceipt in APopReceiptList do
begin
LQueryParams.Values['DeleteMessageBatchRequestEntry.' + I.ToString + '.Id'] := 'delete_msg_' + i.ToString;
LQueryParams.Values['DeleteMessageBatchRequestEntry.' + I.ToString + '.ReceiptHandle'] := LPopReceipt;
inc(I);
end;
LResponse := nil;
try
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
function TAmazonQueueService.DeleteQueue(const QueueURL: string; ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('DeleteQueue');
Response := nil;
try
Response := IssueRequest(QueueURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonQueueService.GetQueuePropertiesXML(const QueueURL: string;
Attributes: array of TAmazonQueueAttribute;
ResponseInfo: TCloudResponseInfo): string;
begin
Result := GetQueueAttributesXML(QueueURL, Attributes, ResponseInfo);
end;
function TAmazonQueueService.GetQueueAttributesXML(const AQueueURL: string; AAttributes: array of TAmazonQueueAttribute;
const AResponseInfo: TCloudResponseInfo): string;
var
LQueryParams: TStringList;
LIndex: Integer;
LAttr: TAmazonQueueAttribute;
LResponse: TCloudHTTP;
begin
LResponse := nil;
LQueryParams := nil;
try
LQueryParams := BuildQueryParameters('GetQueueAttributes');
if Length(AAttributes) = 0 then
LQueryParams.Values['AttributeName'] := 'All'
else
begin
LIndex := 1;
for LAttr in AAttributes do
begin
LQueryParams.Values['AttributeName.' + LIndex.ToString] := GetQueueAttributeName(LAttr);
Inc(LIndex);
end;
end;
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo, Result);
finally
LQueryParams.Free;
LResponse.Free;
end;
end;
function TAmazonQueueService.GetServiceHost: string;
begin
Result := GetConnectionInfo.QueueEndpoint;
end;
function TAmazonQueueService.GetServiceVersion: string;
begin
Result := '2012-11-05';
end;
function TAmazonQueueService.GetQueuePropertiesXML(const QueueURL: string; Attribute: TAmazonQueueAttribute;
ResponseInfo: TCloudResponseInfo): string;
begin
Result := GetQueueAttributesXML(QueueURL, [Attribute], ResponseInfo);
end;
function TAmazonQueueService.GetQueueProperties(const QueueURL: string; Attribute: TAmazonQueueAttribute;
ResponseInfo: TCloudResponseInfo): TStrings;
var
LXML: string;
LAttrs: TQueueAttributePairs;
LAttr: TQueueAttributePair;
begin
Result := nil;
LAttrs := GetQueueAttributes(QueueURL, [Attribute], LXML, ResponseInfo);
if Length(LAttrs) > 0 then
begin
Result := TStringList.Create;
for LAttr in LAttrs do
Result.Values[GetQueueAttributeName(LAttr.Key)] := LAttr.Value;
end;
end;
function TAmazonQueueService.GetQueueProperties(const QueueURL: string;
Attributes: array of TAmazonQueueAttribute;
ResponseInfo: TCloudResponseInfo): TStrings;
var
LXML: string;
LAttrs: TQueueAttributePairs;
LAttr: TQueueAttributePair;
begin
Result := nil;
LAttrs := GetQueueAttributes(QueueURL, Attributes, LXML, ResponseInfo);
if Length(LAttrs) > 0 then
begin
Result := TStringList.Create;
for LAttr in LAttrs do
Result.Values[GetQueueAttributeName(LAttr.Key)] := LAttr.Value;
end;
end;
function TAmazonQueueService.GetQueueAttributes(const AQueueURL: string; AAttributes: array of TAmazonQueueAttribute;
out AResponseXML: string; const AResponseInfo: TCloudResponseInfo): TQueueAttributePairs;
var
LXMLDoc: IXMLDocument;
LRootNode, LQueueAttrsNode, LAttrNode, LAux: IXMLNode;
LNodeName: string;
begin
AResponseXML := GetQueueAttributesXML(AQueueURL, AAttributes, AResponseInfo);
if not AResponseXML.IsEmpty then
begin
LXMLDoc := TXMLDocument.Create(nil);
LXMLDoc.LoadFromXML(AResponseXML);
LRootNode := LXMLDoc.DocumentElement;
if LRootNode.HasChildNodes then
begin
LQueueAttrsNode := LRootNode.ChildNodes.FindNode(NODE_QUEUE_ATTRIBS_RESULT);
if (LQueueAttrsNode <> nil) and LQueueAttrsNode.HasChildNodes then
begin
LAttrNode := GetFirstMatchingChildNode(LQueueAttrsNode, NODE_ATTRIBUTES);
while LAttrNode <> nil do
begin
LAux := LAttrNode.ChildNodes.FindNode(NODE_NAME);
if (LAux <> nil) and LAux.IsTextElement then
begin
LNodeName := LAux.Text;
LAux := LAttrNode.ChildNodes.FindNode(NODE_VALUE);
if (LAux <> nil) and LAux.IsTextElement then
Result := Result + [TQueueAttributePair.Create(GetQueueAttributeFromName(LNodeName), LAux.Text)];
end;
LAttrNode := LAttrNode.NextSibling;
end;
end;
end;
end;
end;
function TAmazonQueueService.SetQueueProperty(const QueueURL, Key, Value: string;
ResponseInfo: TCloudResponseInfo): Boolean;
begin
Result := SetQueueAttributes(QueueURL, [TQueueAttributePair.Create(GetQueueAttributeFromName(Key), Value)],
ResponseInfo);
end;
function TAmazonQueueService.SetQueueAttributes(const AQueueURL: string; AAttributes: array of TQueueAttributePair;
const AResponseInfo: TCloudResponseInfo): Boolean;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
LAttribute: TQueueAttributePair;
LIndex: Integer;
begin
LResponse := nil;
LQueryParams := nil;
try
LQueryParams := BuildQueryParameters('SetQueueAttributes');
LIndex := 1;
for LAttribute in AAttributes do
begin
LQueryParams.Values['Attribute.' + LIndex.ToString + '.Name' ] := GetQueueAttributeName(LAttribute.Key);
LQueryParams.Values['Attribute.' + LIndex.ToString + '.Value'] := LAttribute.Value;
Inc(LIndex);
end;
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
function TAmazonQueueService.AddQueuePermissions(const QueueURL, PermissionsLabel: string;
Permissions: array of TAmazonQueuePermission;
ResponseInfo: TCloudResponseInfo): Boolean;
begin
Result := AddPermission(QueueURL, PermissionsLabel, Permissions, ResponseInfo);
end;
function TAmazonQueueService.AddPermission(const AQueueURL, APermissionsLabel: string;
APermissions: array of TAmazonQueuePermission; const AResponseInfo: TCloudResponseInfo): Boolean;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
LIndex: Integer;
LPermission: TAmazonQueuePermission;
begin
LResponse := nil;
LQueryParams := nil;
try
LQueryParams := BuildQueryParameters('AddPermission');
LQueryParams.Values['Label'] := APermissionsLabel;
LIndex := 1;
for LPermission in APermissions do
begin
LQueryParams.Values['AWSAccountId.' + LIndex.ToString] := LPermission.AccountId;
LQueryParams.Values['ActionName.' + LIndex.ToString] := LPermission.GetAction;
Inc(LIndex);
end;
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
function TAmazonQueueService.RemoveQueuePermissions(const QueueURL, PermissionsLabel: string;
ResponseInfo: TCloudResponseInfo): Boolean;
begin
Result := RemovePermission(QueueURL, PermissionsLabel, ResponseInfo);
end;
function TAmazonQueueService.RemovePermission(const AQueueURL: string; const APermissionsLabel: string;
const AResponseInfo: TCloudResponseInfo): Boolean;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
begin
LResponse := nil;
LQueryParams := nil;
try
LQueryParams := BuildQueryParameters('RemovePermission');
LQueryParams.Values['Label'] := APermissionsLabel;
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
function TAmazonQueueService.PurgeQueue(const AQueueURL: string; const AResponseInfo: TCloudResponseInfo): Boolean;
var
LQueryParams: TStringList;
LResponse: TCloudHTTP;
begin
LResponse := nil;
LQueryParams := nil;
try
LQueryParams := BuildQueryParameters('PurgeQueue');
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
finally
LQueryParams.Free;
LResponse.Free;
end;
end;
function TAmazonQueueService.AddMessage(const QueueURL, MessageText: string;
ResponseInfo: TCloudResponseInfo): Boolean;
var
MsgId: string;
begin
Result := SendMessage(QueueURL, MessageText, MsgId, ResponseInfo);
end;
function TAmazonQueueService.AddMessage(const QueueURL, MessageText: string; out MessageId: string;
ResponseInfo: TCloudResponseInfo): Boolean;
begin
Result := SendMessage(QueueURL, MessageText, MessageId, ResponseInfo);
end;
function TAmazonQueueService.SendMessage(const AQueueURL: string; const AMessageText: string; out AMessageId: string;
const AResponseInfo: TCloudResponseInfo): Boolean;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
LXML: string;
LXMLDoc: IXMLDocument;
LRootNode, LResultNode, LIdNode: IXMLNode;
begin
LResponse := nil;
LQueryParams := nil;
try
LQueryParams := BuildQueryParameters('SendMessage');
LQueryParams.Values['MessageBody'] := AMessageText;
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo, LXML);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
//parse the XML to get the MessageId
if Result and not LXML.IsEmpty then
begin
LXMLDoc := TXMLDocument.Create(nil);
LXMLDoc.LoadFromXML(LXML);
LRootNode := LXMLDoc.DocumentElement;
if (LRootNode <> nil) and (LRootNode.HasChildNodes) then
begin
LResultNode := LRootNode.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_RESULT);
if (LResultNode <> nil) and (LResultNode.HasChildNodes) then
begin
LIdNode := LResultNode.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_ID);
if (LIdNode <> nil) and LIdNode.IsTextElement then
AMessageId := LIdNode.Text;
end;
end;
end;
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
function TAmazonQueueService.SendMessageBatch(const AQueueURL: string; AMessageList: TArray<string>;
const AResponseInfo: TCloudResponseInfo): TArray<string>;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
LMessage: string;
LXML: string;
LXMLDoc: IXMLDocument;
LRootNode, LBatchResult, LBatchEntry, LIdNode: IXMLNode;
I: Integer;
LResult: Boolean;
begin
LQueryParams := BuildQueryParameters('SendMessageBatch');
I := 1;
for LMessage in AMessageList do
begin
LQueryParams.Values['SendMessageBatchRequestEntry.' + I.ToString + '.Id'] := 'msg' + I.ToString;
LQueryParams.Values['SendMessageBatchRequestEntry.' + I.ToString + '.MessageBody'] := LMessage;
Inc(I);
end;
LResponse := nil;
try
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo, LXML);
LResult := (LResponse <> nil) and (LResponse.ResponseCode = 200);
//parse the XML to get the MessageId
if LResult and not LXML.IsEmpty then
begin
LXMLDoc := TXMLDocument.Create(nil);
LXMLDoc.LoadFromXML(LXML);
LRootNode := LXMLDoc.DocumentElement;
if (LRootNode <> nil) and (LRootNode.HasChildNodes) then
begin
LBatchResult := LRootNode.ChildNodes.FindNode(NODE_BATCH_QUEUE_MESSAGE_RESULT);
LBatchEntry := LBatchResult.ChildNodes.FindNode(NODE_BATCH_QUEUE_MESSAGE_RESULT_ENTRY);
while (LBatchEntry <> nil) do
begin
LIdNode := LBatchEntry.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_ID);
if (LIdNode <> nil) and LIdNode.IsTextElement then
Result := Result + [LIdNode.Text];
LBatchEntry := LBatchEntry.NextSibling;
end;
end;
end;
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
function TAmazonQueueService.GetMessagesXML(const QueueURL: string; NumOfMessages, VisibilityTimeout: Integer;
ResponseInfo: TCloudResponseInfo): string;
begin
Result := ReceiveMessageXML(QueueURL, NumOfMessages, VisibilityTimeout, ResponseInfo);
end;
function TAmazonQueueService.ReceiveMessageXML(const AQueueURL: string; ANumOfMessages, AVisibilityTimeout: Integer;
const AResponseInfo: TCloudResponseInfo): string;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
begin
LResponse := nil;
LQueryParams := nil;
try
LQueryParams := BuildQueryParameters('ReceiveMessage');
//get all attributes associated with the message
LQueryParams.Values['AttributeName'] := 'All';
if ANumOfMessages > 0 then
LQueryParams.Values['MaxNumberOfMessages'] := IntToStr(ANumOfMessages);
if AVisibilityTimeout > -1 then
LQueryParams.Values['VisibilityTimeout'] := IntToStr(AVisibilityTimeout);
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo, Result);
finally
LQueryParams.Free;
LResponse.Free;
end;
end;
function TAmazonQueueService.GetMaxMessageReturnCount: Integer;
begin
Result := 10;
end;
function TAmazonQueueService.IsUniqueMessageId(const AMessageId: string;
const AMessageList: array of TCloudQueueMessageItem): Boolean;
var
LItem: TCloudQueueMessageItem;
begin
if AMessageId.IsEmpty then
Exit(False);
Result := True;
//MessageId is not valid if the given list already contains it
for LItem in AMessageList do
if LItem.MessageId.Equals(AMessageId) then
Exit(False);
end;
function TAmazonQueueService.GetMessages(const QueueURL: string; NumOfMessages, VisibilityTimeout: Integer;
ResponseInfo: TCloudResponseInfo): TList<TCloudQueueMessage>;
var
LXML: string;
LMessages: TArray<TCloudQueueMessageItem>;
LMessage: TCloudQueueMessageItem;
begin
Result := TList<TCloudQueueMessage>.Create;
LMessages := ReceiveMessage(QueueURL, NumOfMessages, VisibilityTimeout, LXML, ResponseInfo);
if Length(LMessages) > 0 then
for LMessage in LMessages do
Result.Add(TCloudQueueMessage.CreateFromRecord(LMessage));
end;
function TAmazonQueueService.ReceiveMessage(const AQueueURL: string; ANumOfMessages: Integer; AVisibilityTimeout: Integer;
out AResponseXML: string; const AResponseInfo: TCloudResponseInfo): TArray<TCloudQueueMessageItem>;
var
LXMLDoc: IXMLDocument;
LRootNode, LResultNode, LMessageNode, LItemNode, LAttrNode: IXMLNode;
LMessageId: string;
LItem: TCloudQueueMessageItem;
begin
SetLength(Result, 0);
AResponseXML := ReceiveMessageXML(AQueueURL, ANumOfMessages, AVisibilityTimeout, AResponseInfo);
if not AResponseXML.IsEmpty then
begin
LXMLDoc := TXMLDocument.Create(nil);
LXMLDoc.LoadFromXML(AResponseXML);
LRootNode := LXMLDoc.DocumentElement;
if LRootNode.HasChildNodes then
begin
LResultNode := LRootNode.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_RECEIVE_RESULT);
if (LResultNode <> nil) and LResultNode.HasChildNodes then
begin
LMessageNode := GetFirstMatchingChildNode(LResultNode, NODE_QUEUE_MESSAGE);
while LMessageNode <> nil do
begin
//Get the MessageId, then if that is siccessful, populate the message body
//all other attributes are optional
LItemNode := LMessageNode.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_ID);
if (LItemNode <> nil) and LItemNode.IsTextElement then
begin
LMessageId := LItemNode.Text;
if IsUniqueMessageId(LMessageId, Result) then
begin
LItemNode := LMessageNode.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_BODY);
if (LItemNode <> nil) and LItemNode.IsTextElement then
begin
//populate optional attributes and pop receipt
LItem.MessageId := LMessageID;
LItem.MessageText := LItemNode.Text;
//populate the pop receipt (called ReceiptHandle in Amazon)
//only do this if VisibilityTimeout was set to something greater than zero.
if AVisibilityTimeout > 0 then
begin
LItemNode := LMessageNode.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_POPRECEIPT);
if (LItemNode <> nil) and LItemNode.IsTextElement then
LItem.PopReceipt := LItemNode.Text;
end;
LItemNode := LMessageNode.ChildNodes.FindNode(NODE_QUEUE_MESSAGE_MD5);
if (LItemNode <> nil) and LItemNode.IsTextElement then
begin
// LProp.Key := 'MD5OfBody';
// LProp.Value := LItemNode.Text;
LItem.Properties := LItem.Properties + [TPair<string, string>.Create('MD5OfBody', LItemNode.Text)]; //LProp
end;
//populate the other attributes
LAttrNode := GetFirstMatchingChildNode(LMessageNode, NODE_ATTRIBUTES);
while LAttrNode <> nil do
begin
if LAttrNode.NodeName.Equals(NODE_ATTRIBUTES) then
LItem.Properties := LItem.Properties +
[TPair<string, string>.Create(
LAttrNode.ChildNodes.FindNode('Name').Text,
LAttrNode.ChildNodes.FindNode('Value').Text)
];
LAttrNode := LAttrNode.NextSibling;
end;
Result := Result + [LItem];
end;
end;
end;
LMessageNode := LMessageNode.NextSibling;
end;
end;
end;
end;
end;
function TAmazonQueueService.PeekMessages(const QueueURL: string; NumOfMessages: Integer;
ResponseInfo: TCloudResponseInfo): TList<TCloudQueueMessage>;
var
LMessages: TArray<TCloudQueueMessageItem>;
LMessage: TCloudQueueMessageItem;
LResponseXML: string;
begin
Result := nil;
//Set VisibilityTimeout to 0, so that messages are instantly visible to other callers.
LMessages := ReceiveMessage(QueueURL, NumOfMessages, 0, LResponseXML, ResponseInfo);
if Length(LMessages) > 0 then
begin
Result := TList<TCloudQueueMessage>.Create;
for LMessage in LMessages do
Result.Add(TCloudQueueMessage.CreateFromRecord(LMessage));
end;
end;
function TAmazonQueueService.ChangeMessageVisibility(const QueueURL, PopReceipt: string;
const VisibilityTimeout: Integer; ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('ChangeMessageVisibility');
QueryParams.Values['ReceiptHandle'] := PopReceipt;
QueryParams.Values['VisibilityTimeout'] := IntToStr(VisibilityTimeout);
Response := nil;
try
Response := IssueRequest(QueueURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonQueueService.ChangeMessageVisibilityBatch(const AQueueURL: string;
AMessageInfoList: TArray<TPair<string, integer>>; const AResponseInfo: TCloudResponseInfo): Boolean;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
LAmazonQueueInfo: TPair<string, Integer>;
I: Integer;
begin
LQueryParams := BuildQueryParameters('ChangeMessageVisibilityBatch');
I := 1;
for LAmazonQueueInfo in AMessageInfoList do
begin
LQueryParams.Values['ChangeMessageVisibilityBatchRequestEntry.' + I.ToString + '.Id'] := 'change_visibility_msg_' + i.ToString;
LQueryParams.Values['ChangeMessageVisibilityBatchRequestEntry.' + I.ToString + '.ReceiptHandle'] := LAmazonQueueInfo.Key;
LQueryParams.Values['ChangeMessageVisibilityBatchRequestEntry.' + I.ToString + '.VisibilityTimeout'] := LAmazonQueueInfo.Value.ToString;
inc(I);
end;
LResponse := nil;
try
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
function TAmazonQueueService.ListDeadLetterSourceQueues(const AQueueURL: string; const AResponseInfo: TCloudResponseInfo): TArray<string>;
var
LResponse: TCloudHTTP;
LQueryParams: TStringList;
LXML: string;
LXMLDoc: IXMLDocument;
LDeadLetterQueuesNode, LQueuesNode, LQueueURL: IXMLNode;
LResult: Boolean;
begin
LQueryParams := BuildQueryParameters('ListDeadLetterSourceQueues');
LResponse := nil;
try
LResponse := IssueRequest(AQueueURL, LQueryParams, AResponseInfo, LXML);
LResult := (LResponse <> nil) and (LResponse.ResponseCode = 200);
if LResult and not LXML.IsEmpty then
begin
//Parse XML and get QueueURL value
LXMLDoc := TXMLDocument.Create(nil);
LXMLDoc.LoadFromXML(LXML);
LDeadLetterQueuesNode := LXMLDoc.DocumentElement;
LQueuesNode := LDeadLetterQueuesNode.ChildNodes.FindNode(NODE_DEAD_LETTER_SOURCE_QUEUES);
if (LQueuesNode <> nil) and LQueuesNode.HasChildNodes then
begin
LQueueURL := LQueuesNode.ChildNodes.FindNode(NODE_QUEUE);
while LQueueURL <> nil do
begin
if (LQueueURL <> nil) and LQueueURL.IsTextElement then
Result := Result + [LQueueURL.Text];
LQueueURL := LQueueURL.NextSibling;
end;
end;
end;
finally
LResponse.Free;
LQueryParams.Free;
end;
end;
{ TAmazonObjectResult }
class function TAmazonObjectResult.Create(const Name: string): TAmazonObjectResult;
var
Inst: TAmazonObjectResult;
begin
Inst.Name := Name;
Result := Inst;
Inst.IsLatest := True;
Inst.IsDeleted := False;
end;
{ TAmazonBasicService }
function TAmazonBasicService.BuildQueryParameters(const Action: string): TStringList;
begin
Result := TStringList.Create;
Result.Values['Action'] := Action;
Result.Values['AWSAccessKeyId'] := ConnectionInfo.AccountName;
Result.Values['SignatureMethod'] := 'HmacSHA256';
Result.Values['SignatureVersion'] := '2';
Result.Values['Version'] := GetServiceVersion;
Result.Values['Timestamp'] := CurrentTime;
end;
function TAmazonBasicService.BuildStringToSignResourcePath(const URL: string): string;
begin
Result := TURI.Create(URL).Host + #10 + inherited BuildStringToSignResourcePath(URL);
end;
function TAmazonBasicService.CreateAuthInstance(const ConnectionInfo: TAmazonConnectionInfo): TCloudAuthentication;
begin
Result := TAmazonAuthentication.Create(ConnectionInfo, False); //authentication isn't put in header
end;
function TAmazonBasicService.IssueRequest(URL: string; QueryParams: TStringList; ResponseInfo: TCloudResponseInfo;
out ResultString: string; RequestStream: TStream): TCloudHTTP;
var
DoAsPost: Boolean;
ContentStream: TStream;
begin
ContentStream := RequestStream;
DoAsPost := RequestStream <> nil;
try
if DoAsPost then
Result := IssuePostRequest(URL, nil, QueryParams, EmptyStr, ResponseInfo, ContentStream, ResultString)
else
Result := IssueGetRequest(URL, nil, QueryParams, EmptyStr, ResponseInfo, ResultString);
finally
ParseResponseError(ResponseInfo, ResultString);
end;
end;
function TAmazonBasicService.IssueRequest(URL: string; QueryParams: TStringList; ResponseInfo: TCloudResponseInfo;
RequestStream: TStream): TCloudHTTP;
var
OutStr: string;
begin
Result := IssueRequest(URL, QueryParams, ResponseInfo, OutStr, RequestStream);
end;
procedure TAmazonBasicService.ParseResponseError(const ResponseInfo: TCloudResponseInfo; const ResultString: string);
var
xmlDoc: IXMLDocument;
Aux, ErrorNode, MessageNode: IXMLNode;
ErrorCode, ErrorMsg: string;
IsErrors: Boolean;
begin
//If the ResponseInfo instance exists (to be populated) and the passed in string is Error XML, then
//continue, otherwise exit doing nothing.
if (ResponseInfo = nil) or (ResultString = EmptyStr) then
Exit;
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(ResultString);
IsErrors := AnsiPos(Format('<%s>', [NODE_ERRORS]), ResultString) > 0;
//Parse the error and update the ResponseInfo StatusMessage
if IsErrors or (AnsiPos('<ErrorResponse', ResultString) > 0) then
begin
//Amazon has different formats for returning errors as XML
if IsErrors then
begin
ErrorNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_ERRORS);
ErrorNode := ErrorNode.ChildNodes.FindNode(NODE_ERROR);
end
else
ErrorNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_ERROR);
if (ErrorNode <> nil) and (ErrorNode.HasChildNodes) then
begin
MessageNode := ErrorNode.ChildNodes.FindNode(NODE_ERROR_MESSAGE);
if (MessageNode <> nil) then
ErrorMsg := MessageNode.Text;
if ErrorMsg <> EmptyStr then
begin
//Populate the error code
Aux := ErrorNode.ChildNodes.FindNode(NODE_ERROR_CODE);
if (Aux <> nil) then
ErrorCode := Aux.Text;
ResponseInfo.StatusMessage := Format('%s - %s (%s)', [ResponseInfo.StatusMessage, ErrorMsg, ErrorCode]);
end;
end;
//populate the RequestId, which is structured differently than if this is not an error response
Aux := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_REQUEST_ID);
if (Aux <> nil) and (Aux.IsTextElement) then
ResponseInfo.Headers.Values[NODE_REQUEST_ID] := Aux.Text;
end
//Otherwise, it isn't an error, but try to pase the RequestId anyway.
else
begin
Aux := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_RESPONSE_METADATA);
if Aux <> nil then
begin
Aux := Aux.ChildNodes.FindNode(NODE_REQUEST_ID);
if Aux <> nil then
ResponseInfo.Headers.Values[NODE_REQUEST_ID] := Aux.Text;
end;
end;
end;
procedure TAmazonBasicService.PrepareRequestSignature(const HTTPVerb: string;
const Headers, QueryParameters: TStringList;
const StringToSign: string;
var URL: string; Request: TCloudHTTP;
var Content: TStream);
var
AuthorizationString, QueryString: string;
begin
if FAuthenticator <> nil then
begin
AuthorizationString := FAuthenticator.BuildAuthorizationString(StringToSign);
QueryParameters.Values['Signature'] := AuthorizationString;
//If this is a GET request, or the content stream is currently in use by actual request data,
// then the parameters are in the URL, so add Signature to the URL
if (HTTPVerb = 'GET') or (Content <> nil) then
URL := BuildQueryParameterString(URL, QueryParameters, False, True)
//Otherwise, this is a POST and the parameters should all be put in the content of the request
else
begin
Request.Client.ContentType := 'application/x-www-form-urlencoded; charset=utf-8';
//Skip the first character, because it is the query prefix character (?) which isn't used
//when the query string is in the body of the request.
QueryString := BuildQueryParameterString(EmptyStr, QueryParameters, False, True).Substring(1);
Content := TStringStream.Create(QueryString);
end;
end;
end;
procedure TAmazonBasicService.SortQueryParameters(const QueryParameters: TStringList; ForURL: Boolean);
begin
if (QueryParameters <> nil) and (not ForURL) then
begin
QueryParameters.CustomSort(CaseSensitiveNameCompare);
end;
end;
{ TAmazonTableService }
function TAmazonTableService.GetServiceHost: string;
begin
Result := GetConnectionInfo.TableEndpoint;
end;
function TAmazonTableService.GetServiceVersion: string;
begin
Result := '2009-04-15';
end;
function TAmazonTableService.GetTableMetadataXML(const TableName: string;
ResponseInfo: TCloudResponseInfo): string;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('DomainMetadata');
QueryParams.Values['DomainName'] := TableName;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.InsertRow(const TableName, RowId: string; Row: TCloudTableRow;
Conditionals: TList<TAmazonRowConditional>; ReplaceAll: Boolean;
ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
Item: TCloudTableColumn;
Conditional: TAmazonRowConditional;
Index: Integer;
begin
QueryParams := BuildQueryParameters('PutAttributes');
QueryParams.Values['DomainName'] := TableName;
QueryParams.Values['ItemName'] := RowId;
if (Row <> nil) and (Row.Columns <> nil) then
begin
Index := 0;
for Item in Row.Columns do
begin
QueryParams.Values[Format('Attribute.%d.Name', [Index])] := Item.Name;
QueryParams.Values[Format('Attribute.%d.Value', [Index])] := Item.Value;
if (ReplaceAll and (not AnsiSameText(Item.DataType, TABLE_ROW_DATATYPE_DO_NOT_REPLACE))) or
((not ReplaceAll) and AnsiSameText(Item.DataType, TABLE_ROW_DATATYPE_REPLACE)) then
QueryParams.Values[Format('Attribute.%d.Replace', [Index])] := 'true';
Inc(Index);
end;
end;
if Conditionals <> nil then
begin
Index := 0;
for Conditional In Conditionals do
begin
QueryParams.Values[Format('Expected.%d.Name', [Index])] := Conditional.ColumnName;
if not Conditional.ColumnExists then
QueryParams.Values[Format('Expected.%d.Exists', [Index])] := BoolToStr(False)
else
QueryParams.Values[Format('Expected.%d.Value', [Index])] := Conditional.ColumnValue;
Inc(Index);
end;
end;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.InsertRows(const TableName: string; Rows: TList<TAmazonBatchRow>;
ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
Item: TCloudTableColumn;
BatchRow: TAmazonBatchRow;
Row: TCloudTableRow;
ItemIndex, AttributeIndex: Integer;
begin
QueryParams := BuildQueryParameters('BatchPutAttributes');
QueryParams.Values['DomainName'] := TableName;
if Rows <> nil then
begin
ItemIndex := 0;
for BatchRow in Rows do
begin
AttributeIndex := 0;
QueryParams.Values[Format('Item.%d.ItemName', [ItemIndex])] := BatchRow.RowId;
Row := BatchRow.Row;
if (Row <> nil) and (Row.Columns <> nil) then
begin
for Item in Row.Columns do
begin
QueryParams.Values[Format('Item.%d.Attribute.%d.Name', [ItemIndex, AttributeIndex])] := Item.Name;
QueryParams.Values[Format('Item.%d.Attribute.%d.Value', [ItemIndex, AttributeIndex])] := Item.Value;
if (BatchRow.ReplaceAll and (not AnsiSameText(Item.DataType, TABLE_ROW_DATATYPE_DO_NOT_REPLACE))) or
((not BatchRow.ReplaceAll) and AnsiSameText(Item.DataType, TABLE_ROW_DATATYPE_REPLACE)) then
QueryParams.Values[Format('Item.%d.Attribute.%d.Replace', [ItemIndex, AttributeIndex])] := 'true';
Inc(AttributeIndex);
end;
end;
Inc(ItemIndex);
end;
end;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.GetTableMetadata(const TableName: string;
ResponseInfo: TCloudResponseInfo): TStrings;
var
xml: string;
xmlDoc: IXMLDocument;
ResultNode, ItemNode: IXMLNode;
begin
xml := GetTableMetadataXML(TableName, ResponseInfo);
Result := nil;
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(Result);
end;
Result := TStringList.Create;
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode('DomainMetadataResult');
if (ResultNode <> nil) and ResultNode.HasChildNodes then
begin
ItemNode := ResultNode.ChildNodes.First;
while (ItemNode <> nil) do
begin
try
if ItemNode.IsTextElement then
Result.Values[ItemNode.NodeName] := ItemNode.Text;
finally
ItemNode := ItemNode.NextSibling;
end;
end;
end;
end;
end;
function TAmazonTableService.CreateTable(const TableName: string; ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('CreateDomain');
QueryParams.Values['DomainName'] := TableName;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.DeleteTable(const TableName: string; ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('DeleteDomain');
QueryParams.Values['DomainName'] := TableName;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.QueryTablesXML(const ContinuationToken: string; const MaxNumberOfTables: Integer;
ResponseInfo: TCloudResponseInfo): string;
var
Response: TCloudHTTP;
QueryParams: TStringList;
begin
QueryParams := BuildQueryParameters('ListDomains');
if MaxNumberOfTables > 0 then
QueryParams.Values['MaxNumberOfDomains'] := IntToStr(MaxNumberOfTables);
if ContinuationToken <> EmptyStr then
QueryParams.Values['NextToken'] := ContinuationToken;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.QueryTables(const ContinuationToken: string; const MaxNumberOfTables: Integer;
ResponseInfo: TCloudResponseInfo): TStrings;
var
xml: string;
xmlDoc: IXMLDocument;
ResultNode, TableNode: IXMLNode;
begin
xml := QueryTablesXML(ContinuationToken, MaxNumberOfTables, ResponseInfo);
Result := nil;
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(Result);
end;
Result := TStringList.Create;
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode('ListDomainsResult');
if (ResultNode <> nil) and ResultNode.HasChildNodes then
begin
TableNode := ResultNode.ChildNodes.First;
while (TableNode <> nil) do
begin
try
if AnsiSameText(TableNode.NodeName, 'DomainName') then
begin
if TableNode.IsTextElement then
Result.Add(TableNode.Text);
end
else if (ResponseInfo <> nil) and AnsiSameText(TableNode.NodeName, 'NextToken') then
ResponseInfo.Headers.Values['NextToken'] := TableNode.Text;
finally
TableNode := TableNode.NextSibling;
end;
end;
end;
end;
end;
function TAmazonTableService.SelectRowsXML(const SelectStatement: string; ResponseInfo: TCloudResponseInfo;
const NextToken: string): string;
var
Response: TCloudHTTP;
QueryParams: TStringList;
xmlDoc: IXMLDocument;
ResultNode, NextTokenNode: IXMLNode;
begin
QueryParams := BuildQueryParameters('Select');
if GetConnectionInfo.ConsistentRead then
QueryParams.Values['ConsistentRead'] := 'true';
QueryParams.Values['SelectExpression'] := SelectStatement;
//Specify the NextToken, if one exists. This will start reading from the previous value
//of MaxNumberOfItems, plus one. (or if 0, then from the server default.)
if NextToken <> EmptyStr then
QueryParams.Values['NextToken'] := NextToken;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo, Result);
//populate the NextToken header value in the ResponseInfo, from the XML
if (ResponseInfo <> nil) and (ResponseInfo.StatusCode = 200) and (Result <> EmptyStr) then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(Result);
except
Exit(Result);
end;
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode('SelectResult');
if (ResultNode <> nil) and (ResultNode.HasChildNodes) then
begin
NextTokenNode := GetFirstMatchingChildNode(ResultNode, 'NextToken');
if (NextTokenNode <> nil) and NextTokenNode.IsTextElement then
ResponseInfo.Headers.Values['NextToken'] := NextTokenNode.Text;
end;
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.GetRowsXML(const TableName: string; MaxNumberOfItems: Integer;
ItemIdOnly: Boolean; ResponseInfo: TCloudResponseInfo;
const NextToken: string): string;
var
SelectStatement, ToSelect, LimitBy: string;
begin
//Get all columns or just the item names
if ItemIdOnly then
ToSelect := 'itemName()'
else
ToSelect := '*';
//optionally limit the number of returned rows
if MaxNumberOfItems > 0 then
LimitBy := Format(' limit %d', [MaxNumberOfItems]);
//Set the select expression to use, specifying the columns to get and how many rows to return
SelectStatement := Format('select %s from %s%s', [ToSelect, TableName, LimitBy]);
Result := SelectRowsXML(SelectStatement, ResponseInfo, NextToken);
end;
function TAmazonTableService.GetRowIDs(const TableName: string; MaxNumberOfItems: Integer;
ResponseInfo: TCloudResponseInfo; const NextToken: string): TStrings;
var
xml: string;
xmlDoc: IXMLDocument;
ResultNode, ItemNode, NameNode: IXMLNode;
begin
Result := nil;
xml := GetRowsXML(TableName, MaxNumberOfItems, True, ResponseInfo, NextToken);
if (xml <> EmptyStr) then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(Result);
end;
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode('SelectResult');
if (ResultNode <> nil) and ResultNode.HasChildNodes then
begin
Result := TStringList.Create;
ItemNode := ResultNode.ChildNodes.First;
while (ItemNode <> nil) do
begin
try
if AnsiSameText(ItemNode.NodeName, 'Item') then
begin
NameNode := ItemNode.ChildNodes.FindNode('Name');
if (NameNode <> nil) and NameNode.IsTextElement then
Result.Add(NameNode.Text);
end;
finally
ItemNode := ItemNode.NextSibling;
end;
end;
end;
end;
end;
function TAmazonTableService.GetRows(const TableName: string; MaxNumberOfItems: Integer;
ResponseInfo: TCloudResponseInfo;
const NextToken: string): TList<TCloudTableRow>;
var
xml: string;
xmlDoc: IXMLDocument;
ResultNode, ItemNode, ColumnNode, NameNode, ValueNode: IXMLNode;
Row: TCloudTableRow;
begin
Result := nil;
xml := GetRowsXML(TableName, MaxNumberOfItems, False, ResponseInfo, NextToken);
if (xml <> EmptyStr) then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(Result);
end;
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode('SelectResult');
if (ResultNode <> nil) and ResultNode.HasChildNodes then
begin
Result := TList<TCloudTableRow>.Create;
ItemNode := ResultNode.ChildNodes.First;
while (ItemNode <> nil) do
begin
try
if AnsiSameText(ItemNode.NodeName, 'Item') then
begin
ColumnNode := ItemNode.ChildNodes.FindNode('Name');
if (ColumnNode <> nil) and ColumnNode.IsTextElement then
begin
//Amazon doesn't support column datatype info
Row := TCloudTableRow.Create(False);
Result.Add(Row);
Row.SetColumn('itemName()', ColumnNode.Text);
ColumnNode := ItemNode.ChildNodes.First;
while (ColumnNode <> nil) do
begin
try
if AnsiSameText(ColumnNode.NodeName, 'Attribute') and ColumnNode.HasChildNodes then
begin
NameNode := ColumnNode.ChildNodes.FindNode('Name');
ValueNode := ColumnNode.ChildNodes.FindNode('Value');
if (NameNode <> nil) and (ValueNode <> nil) and
NameNode.IsTextElement and ValueNode.IsTextElement then
Row.SetColumn(NameNode.Text, ValueNode.Text, EmptyStr, False); //don't replace, may have multiple values
end;
finally
ColumnNode := ColumnNode.NextSibling;
end;
end;
end;
end;
finally
ItemNode := ItemNode.NextSibling;
end;
end;
end;
end;
end;
function TAmazonTableService.DeleteColumns(const TableName, RowId: string; const Columns: TStrings;
Conditionals: TList<TAmazonRowConditional>;
ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
Conditional: TAmazonRowConditional;
Index, I, Count: Integer;
Val, ColName, ColVal: string;
begin
QueryParams := BuildQueryParameters('DeleteAttributes');
QueryParams.Values['DomainName'] := TableName;
QueryParams.Values['ItemName'] := RowId;
if Columns <> nil then
begin
Index := 0;
Count := Columns.Count;
//iterate over each specified column
//each item in the list can be either just a column name,
//or a delimited pair of the column name and the column value
for I := 0 to Count - 1 do
begin
ColName := EmptyStr;
ColVal := EmptyStr;
Val := Columns[I];
if AnsiPos(Columns.Delimiter, Val) > 0 then
begin
ColName := Columns.Names[I];
ColVal := Columns.ValueFromIndex[I];
end
else
ColName := Val;
//don't allow a call to delete the itemName() column.
if not AnsiSameText('itemName()', ColName) then
begin
QueryParams.Values[Format('Attribute.%d.Name', [Index])] := ColName;
if ColVal <> EmptyStr then
QueryParams.Values[Format('Attribute.%d.Value', [Index])] := ColVal;
end;
Inc(Index);
end;
end;
if Conditionals <> nil then
begin
Index := 0;
for Conditional In Conditionals do
begin
QueryParams.Values[Format('Expected.%d.Name', [Index])] := Conditional.ColumnName;
if not Conditional.ColumnExists then
QueryParams.Values[Format('Expected.%d.Exists', [Index])] := BoolToStr(False)
else
QueryParams.Values[Format('Expected.%d.Value', [Index])] := Conditional.ColumnValue;
Inc(Index);
end;
end;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
function TAmazonTableService.DeleteColumns(const TableName, RowId: string; const Columns: TStrings;
ResponseInfo: TCloudResponseInfo): Boolean;
begin
Result := DeleteColumns(TableName, RowId, Columns, nil, ResponseInfo);
end;
function TAmazonTableService.DeleteRow(const TableName, RowId: string;
Conditionals: TList<TAmazonRowConditional>;
ResponseInfo: TCloudResponseInfo): Boolean;
begin
Result := DeleteColumns(TableName, RowId, nil, Conditionals, ResponseInfo);
end;
function TAmazonTableService.DeleteRow(const TableName, RowId: string;
ResponseInfo: TCloudResponseInfo): Boolean;
begin
Result := DeleteColumns(TableName, RowId, nil, nil, ResponseInfo);
end;
function TAmazonTableService.BatchDeleteColumns(const TableName: string; BatchColumns: TList<TCloudTableRow>;
ResponseInfo: TCloudResponseInfo): Boolean;
var
Response: TCloudHTTP;
QueryParams: TStringList;
ItemIndex, ColIndex, I, Count: Integer;
ColName, ColVal: string;
Row: TCloudTableRow;
begin
QueryParams := BuildQueryParameters('BatchDeleteAttributes');
QueryParams.Values['DomainName'] := TableName;
if BatchColumns <> nil then
begin
ItemIndex := 0;
for Row In BatchColumns do
begin
ColIndex := 0;
Count := Row.Columns.Count;
//iterate over each specified column and add query parameters for deleting it
for I := 0 to Count - 1 do
begin
ColName := Row.Columns[I].Name;
ColVal := Row.Columns[I].Value;
if AnsiSameText('itemName()', ColName) then
begin
QueryParams.Values[Format('Item.%d.ItemName', [ItemIndex])] := ColVal;
end
else
begin
QueryParams.Values[Format('Item.%d.Attribute.%d.Name', [ItemIndex, ColIndex])] := ColName;
if ColVal <> EmptyStr then
QueryParams.Values[Format('Item.%d.Attribute.%d.Value', [ItemIndex, ColIndex])] := ColVal;
end;
Inc(ColIndex);
end;
Inc(ItemIndex);
end;
end;
Response := nil;
try
Response := IssueRequest(GetConnectionInfo.TableURL, QueryParams, ResponseInfo);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
end;
end;
{ TAmazonBucketResult }
constructor TAmazonBucketResult.Create(const AName: string);
begin
FName := AName;
FObjects := TList<TAmazonObjectResult>.Create;
FPrefixes := TStringList.Create;
end;
destructor TAmazonBucketResult.Destroy;
begin
FreeAndNil(FObjects);
FreeAndNil(FPrefixes);
inherited;
end;
{ TAmazonGrant }
class function TAmazonGrant.Create(Permission: TAmazonGrantPermission): TAmazonGrant;
begin
Result.Permission := Permission;
end;
class function TAmazonGrant.Create(const Permission: string): TAmazonGrant;
begin
Result.Permission := GetPermission(Permission);
end;
class function TAmazonGrant.GetPermission(const PermissionString: string): TAmazonGrantPermission;
begin
if PermissionString.ToUpper.Equals('FULL_CONTROL') then
Exit(amgpFullControl);
if PermissionString.ToUpper.Equals('WRITE') then
Exit(amgpWrite);
if PermissionString.ToUpper.Equals('WRITE_ACP') then
Exit(amgpWriteACP);
if PermissionString.ToUpper.Equals('READ') then
Exit(amgpRead);
if PermissionString.ToUpper.Equals('READ_ACP') then
Exit(amgpReadACP);
Result := amgpUnknown;
end;
function TAmazonGrant.GranteeType: TAmazonGranteeType;
begin
Result := agtUnknown;
if GranteeURI <> EmptyStr then
Exit(agtGroup);
if GranteeEmailAddress <> EmptyStr then
Exit(agtCustomerByEmail);
if GranteeID <> EmptyStr then
Exit(agtCanonicalUser);
end;
function TAmazonGrant.GranteeTypeString: string;
begin
Result := AmazonGranteeTypeStr[GranteeType];
end;
function TAmazonGrant.PermissionString: string;
begin
Result := AmazonGrantPermissionStr[Permission];
end;
function TAmazonGrant.IsAllAuthenticatedUsers: Boolean;
begin
Result := AnsiSameText(GranteeURI, ALL_AUTHENTICATED_USERS_GROUP);
end;
function TAmazonGrant.IsAllUsers: Boolean;
begin
Result := AnsiSameText(GranteeURI, ALL_USERS_GROUP);
end;
function TAmazonGrant.IsLogDelivery: Boolean;
begin
Result := AnsiSameText(GranteeURI, LOG_DELIVERY_GROUP);
end;
{ TAmazonBucketLoggingInfo }
constructor TAmazonBucketLoggingInfo.Create(const TargetBucket, TargetPrefix: string);
begin
FTargetBucket := TargetBucket;
FTargetPrefix := TargetPrefix;
FGrants := TList<TAmazonGrant>.Create;
FLoggingEnabled := True;
end;
constructor TAmazonBucketLoggingInfo.Create;
begin
FLoggingEnabled := False;
end;
destructor TAmazonBucketLoggingInfo.Destroy;
begin
FreeAndNil(FGrants);
inherited;
end;
class function TAmazonBucketLoggingInfo.GetDisableXML: string;
begin
Result := LogXMLPrefix + LogXMLSuffix;
end;
function TAmazonBucketLoggingInfo.AsXML: string;
var
sb: TStringBuilder;
Grant: TAmazonGrant;
TypeStr, GranteeStr: string;
begin
sb := TStringBuilder.Create(256);
try
sb.Append(LogXMLPrefix);
//only add information under the root logging node if logging is enabled.
if FLoggingEnabled then
begin
sb.Append('<LoggingEnabled><TargetBucket>');
sb.Append(FTargetBucket);
sb.Append('</TargetBucket><TargetPrefix>');
sb.Append(FTargetPrefix);
sb.Append('</TargetPrefix>');
if FGrants.Count > 0 then
begin
sb.Append('<TargetGrants>');
for Grant In FGrants do
begin
if Grant.GranteeEmailAddress <> EmptyStr then
begin
TypeStr := 'AmazonCustomerByEmail';
GranteeStr := '<EmailAddress>' + Grant.GranteeEmailAddress + '</EmailAddress>';
end
else if Grant.GranteeURI <> EmptyStr then
begin
TypeStr := 'Group';
GranteeStr := '<URI>' + Grant.GranteeURI + '</URI>';
end
else
begin
TypeStr := 'CanonicalUser';
GranteeStr := '<ID>' + Grant.GranteeID + '</ID>';
if Grant.GranteeDisplayName <> EmptyStr then
GranteeStr := GranteeStr + '<DisplayName>' + Grant.GranteeDisplayName + '</DisplayName>';
end;
sb.Append('<Grant><Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="');
sb.Append(TypeStr);
sb.Append('">');
sb.Append(GranteeStr);
sb.Append('</Grantee><Permission>');
sb.Append(Grant.PermissionString);
sb.Append('</Permission></Grant>');
end;
sb.Append('</TargetGrants>');
end;
sb.Append('</LoggingEnabled>');
end;
sb.Append(LogXMLSuffix);
Result := sb.ToString(True);
finally
sb.Free;
end;
end;
{ TAmazonNotificationTopic }
class function TAmazonNotificationEvent.Create(const Topic, Event: string): TAmazonNotificationEvent;
begin
Result.Topic := Topic;
Result.Event := Event;
end;
{ TAmazonMultipartUploadItem }
constructor TAmazonMultipartUploadItem.Create(const AKey: string);
begin
Key := AKey;
end;
{ TAmazonMultipartUploadsResult }
constructor TAmazonMultipartUploadsResult.Create(const BucketName: string);
begin
FBucket := BucketName;
FUploadItems := TList<TAmazonMultipartUploadItem>.Create;
end;
destructor TAmazonMultipartUploadsResult.Destroy;
begin
FreeAndNil(FUploadItems);
inherited;
end;
{ TAmazonAccessControlPolicy }
constructor TAmazonAccessControlPolicy.Create(const OwnerId, OwnerDisplayName: string;
Grants: TList<TAmazonGrant>);
begin
FOwnerID := OwnerId;
FOwnerDisplayName := OwnerDisplayName;
if Grants <> nil then
FGrants := Grants
else
FGrants := TList<TAmazonGrant>.Create;
end;
function TAmazonAccessControlPolicy.AsXML: string;
var
sb: TStringBuilder;
Grant: TAmazonGrant;
GranteeType: TAmazonGranteeType;
begin
sb := TStringBuilder.Create(256);
try
sb.Append('<AccessControlPolicy><Owner><ID>');
sb.Append(OwnerId);
sb.Append('</ID><DisplayName>');
sb.Append(OwnerDisplayName);
sb.Append('</DisplayName></Owner><AccessControlList>');
for Grant In Grants do
begin
GranteeType := Grant.GranteeType;
if GranteeType <> agtUnknown then
begin
sb.Append('<Grant><Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="');
sb.Append(Grant.GranteeTypeString).Append('">');
case GranteeType of
agtCanonicalUser:
begin
sb.Append('<ID>').Append(Grant.GranteeID).Append('</ID><DisplayName>');
sb.Append(Grant.GranteeDisplayName).Append('</DisplayName>');
end;
agtCustomerByEmail:
sb.Append('<EmailAddress>').Append(Grant.GranteeEmailAddress).Append('</EmailAddress>');
agtGroup:
sb.Append('<URI>').Append(Grant.GranteeURI).Append('</URI>');
end;
sb.Append('</Grantee><Permission>').Append(Grant.PermissionString).Append('</Permission></Grant>');
end;
end;
sb.Append('</AccessControlList></AccessControlPolicy>');
Result := sb.ToString(True);
finally
sb.Free;
end;
end;
destructor TAmazonAccessControlPolicy.Destroy;
begin
FreeAndNil(FGrants);
inherited;
end;
{ TAmazonActionConditional }
class function TAmazonActionConditional.Create: TAmazonActionConditional;
var
Inst: TAmazonActionConditional;
begin
Exit(Inst);
end;
procedure TAmazonActionConditional.PopulateHeaders(Headers: TStrings; ForCopy: Boolean);
begin
if Headers <> nil then
begin
if not ForCopy then
begin
Headers.Values['If-Modified-Since'] := IfModifiedSince;
Headers.Values['If-Unmodified-Since'] := IfUnmodifiedSince;
Headers.Values['If-Match'] := IfMatch;
Headers.Values['If-None-Match'] := IfNoneMatch;
end
else
begin
Headers.Values['x-amz-copy-source-if-modified-since'] := IfModifiedSince;
Headers.Values['x-amz-copy-source-if-unmodified-since'] := IfUnmodifiedSince;
Headers.Values['x-amz-copy-source-if-match'] := IfMatch;
Headers.Values['x-amz-copy-source-if-none-match'] := IfNoneMatch;
end;
end;
end;
{ TAmazonGetObjectOptionals }
class function TAmazonGetObjectOptionals.Create: TAmazonGetObjectOptionals;
begin
Result.RangeStartByte := 0;
Result.RangeEndByte := 0;
end;
procedure TAmazonGetObjectOptionals.PopulateHeaders(Headers: TStrings);
begin
if Headers <> nil then
begin
Condition.PopulateHeaders(Headers, False);
if ResponseContentType <> EmptyStr then
Headers.Values['response-content-type'] := ResponseContentType;
if ResponseContentLanguage <> EmptyStr then
Headers.Values['response-content-language'] := ResponseContentLanguage;
if ResponseExpires <> EmptyStr then
Headers.Values['response-expires'] := ResponseExpires;
if ResponseCacheControl <> EmptyStr then
Headers.Values['reponse-cache-control'] := ResponseCacheControl;
if ResponseContentDisposition <> EmptyStr then
Headers.Values['response-content-disposition'] := ResponseContentDisposition;
if ResponseContentEncoding <> EmptyStr then
Headers.Values['response-content-encoding'] := ResponseContentEncoding;
if RangeEndByte > RangeStartByte then
Headers.Values['Range'] := Format('bytes=%d-%d', [RangeStartByte, RangeEndByte]);
end;
end;
{ TAmazonCopyObjectOptionals }
constructor TAmazonCopyObjectOptionals.Create;
begin
FMetadata := TStringList.Create;
ACL := amzbaPrivate;
FUseReducedRedundancy := False;
FCopyMetadata := False;
end;
destructor TAmazonCopyObjectOptionals.Destroy;
begin
FreeAndNil(FMetadata);
inherited;
end;
procedure TAmazonCopyObjectOptionals.PopulateHeaders(Headers: TStrings);
begin
if Headers <> nil then
begin
Condition.PopulateHeaders(Headers, True);
if FCopyMetadata then
Headers.Values['x-amz-metadata-directive'] := 'COPY'
else
begin
Headers.Values['x-amz-metadata-directive'] := 'REPLACE';
AddS3MetadataHeaders(Headers, Metadata);
end;
Headers.Values['x-amz-acl'] := GetACLTypeString(FACL);
if FUseReducedRedundancy then
Headers.Values['x-amz-storage-class'] := CLASS_REDUCED_REDUNDANCY
else
Headers.Values['x-amz-storage-class'] := 'STANDARD';
end;
end;
{ TAmazonMultipartPart }
constructor TAmazonMultipartPart.Create(APartNumber: Integer; AETag: string);
begin
PartNumber := APartNumber;
ETag := AETag;
Size := 0;
end;
function TAmazonMultipartPart.AsXML: string;
begin
Result := Format('<Part><PartNumber>%d</PartNumber><ETag>%s</ETag></Part>', [PartNumber, ETag]);
end;
{ TAmazonListPartsResult }
constructor TAmazonListPartsResult.Create(const BucketName, ObjectName, UploadId: string);
begin
FBucket := BucketName;
FObjectName := ObjectName;
FUploadId := UploadId;
FParts := TList<TAmazonMultipartPart>.Create;
end;
destructor TAmazonListPartsResult.Destroy;
begin
FreeAndNil(FParts);
inherited;
end;
{ TAmazonStorageService }
constructor TAmazonStorageService.Create(const ConnectionInfo: TAmazonConnectionInfo);
begin
inherited Create(ConnectionInfo);
FUseCanonicalizedHeaders := True;
FUseResourcePath := True;
//The QueryPrefix is on the same line for S3, so re-add the question mark
FQueryStartChar := '?';
end;
procedure TAmazonStorageService.URLEncodeQueryParams(const ForURL: Boolean; var ParamName, ParamValue: string);
begin
if ForURL then
inherited;
end;
function TAmazonStorageService.BuildObjectURL(const BucketName, ObjectName: string;
ARegion: TAmazonRegion): string;
begin
Result := GetConnectionInfo.StorageURL(BucketName, ARegion) + '/' +
TURLEncoding.URL.Encode(ObjectName, [Ord('#')], []);
end;
function TAmazonStorageService.CreateAuthInstance(const ConnectionInfo: TAmazonConnectionInfo): TCloudAuthentication;
begin
Result := TAmazonAWS4Authentication.Create(ConnectionInfo, True); //S3 uses HMAC-SHA256
end;
function TAmazonStorageService.BuildStringToSignHeaders(Headers: TStringList): string;
var
RequiredHeadersInstanceOwner: Boolean;
RequiredHeaders: TStringList;
I, ReqCount: Integer;
Aux: string;
lastParam, nextParam, ConHeadPrefix: string;
begin
//AWS always has required headers
RequiredHeaders := TStringList(GetRequiredHeaderNames(RequiredHeadersInstanceOwner));
Assert(RequiredHeaders <> nil);
Assert(Headers <> nil);
//if (Headers = nil) then
// Headers.AddStrings(RequiredHeaders);
//AWS4 - content-type must be included in string to sign if found in headers
if Headers.IndexOfName('content-type') > -1 then //Headers.Find('content-type',Index) then
RequiredHeaders.Add('content-type');
if Headers.IndexOfName('content-md5') > -1 then
RequiredHeaders.Add('content-md5');
RequiredHeaders.Sorted := True;
RequiredHeaders.Duplicates := TDuplicates.dupIgnore;
ConHeadPrefix := AnsiLowerCase(GetCanonicalizedHeaderPrefix);
for I := 0 to Headers.Count - 1 do
begin
Aux := AnsiLowerCase(Headers.Names[I]);
if AnsiStartsStr(ConHeadPrefix, Aux) then
RequiredHeaders.Add(Aux);
end;
RequiredHeaders.Sorted := False;
//custom sorting
SortHeaders(RequiredHeaders);
ReqCount := RequiredHeaders.Count;
//AWS4 get value pairs (ordered + lowercase)
if FUseCanonicalizedHeaders and (Headers <> nil) then
begin
for I := 0 to ReqCount - 1 do
begin
Aux := AnsiLowerCase(RequiredHeaders[I]);
if Headers.IndexOfName(Aux) < 0 then
raise Exception.Create('Missing Required Header: '+RequiredHeaders[I]);
nextParam := Aux;
if lastParam = EmptyStr then
begin
lastParam := nextParam;
Result := Result + Format('%s:%s', [nextParam, Headers.Values[lastParam]]);
end
else
begin
lastParam := nextParam;
Result := Result + Format(#10'%s:%s', [nextParam, Headers.Values[lastParam]]);
end;
end;
if lastParam <> EmptyStr then
Result := Result + #10'';
end;
// string of header names
Result := Result + #10'';
for I := 0 to ReqCount - 1 do
begin
Result := Result + Format('%s;', [RequiredHeaders[I]]);
end;
SetLength(Result,Length(Result)-1);
if RequiredHeadersInstanceOwner then
FreeAndNil(RequiredHeaders);
end;
//Expected format version 4 AWS
//<HTTPMethod>\n
//<CanonicalURI>\n
//<CanonicalQueryString>\n
//<CanonicalHeaders>\n
//<SignedHeaders>\n
//<HashedPayload>
function TAmazonStorageService.BuildStringToSign(const HTTPVerb: string; Headers, QueryParameters: TStringList;
const QueryPrefix, URL: string): string;
var
CanRequest, Scope, LdateISO, Ldate, Lregion : string;
URLrec : TURI;
LParams: TStringList;
VPParam : TNameValuePair;
begin
LParams := nil;
try
//Build the first part of the string to sign, including HTTPMethod
CanRequest := BuildStringToSignPrefix(HTTPVerb);
//find and encode the requests resource
URLrec := TURI.Create(URL);
//CanonicalURI URL encoded
CanRequest := CanRequest + TNetEncoding.URL.EncodePath(URLrec.Path,
[Ord('"'), Ord(''''), Ord(':'), Ord(';'), Ord('<'), Ord('='), Ord('>'),
Ord('@'), Ord('['), Ord(']'), Ord('^'), Ord('`'), Ord('{'), Ord('}'),
Ord('|'), Ord('/'), Ord('\'), Ord('?'), Ord('#'), Ord('&'), Ord('!'),
Ord('$'), Ord('('), Ord(')'), Ord(',')]) + #10;
//CanonicalQueryString encoded
if not URLrec.Query.IsEmpty then
begin
if Length(URLrec.Params) = 1 then
CanRequest := CanRequest + URLrec.Query + #10
else
begin
LParams := TStringList.Create;
for VPParam in URLrec.Params do
LParams.Append(VPParam.Name+'='+VPParam.Value);
CanRequest := CanRequest + BuildStringToSignResources('', LParams).Substring(1) + #10
end;
end
else
CanRequest := CanRequest + #10;
//add sorted headers and header names in series for signedheader part
CanRequest := CanRequest + BuildStringToSignHeaders(Headers) + #10;
CanRequest := CanRequest + Headers.Values['x-amz-content-sha256'];
LdateISO := Headers.Values['x-amz-date'];
Ldate := Leftstr(LdateISO,8);
Lregion := GetRegionFromEndpoint(Headers.Values['Host']);
Scope := Ldate + '/'+Lregion+ '/s3' + '/aws4_request';
Result := 'AWS4-HMAC-SHA256' + #10 + LdateISO + #10 + Scope + #10 + TCloudSHA256Authentication.GetHashSHA256Hex(CanRequest);
finally
LParams.Free;
end;
end;
procedure TAmazonStorageService.PrepareRequestSignature(const HTTPVerb: string;
const Headers, QueryParameters: TStringList;
const StringToSign: string;
var URL: string; Request: TCloudHTTP; var Content: TStream);
var
AuthorizationString, SignStrHeaders, LdateISO, Lregion: string;
RequiredHeadersInstanceOwner : Boolean;
SignedHeaders: TStringList;
begin
if FAuthenticator <> nil then
begin
SignedHeaders := TStringList(GetRequiredHeaderNames(RequiredHeadersInstanceOwner));
SignedHeaders.Delimiter := ';';
SignStrHeaders := SignedHeaders.DelimitedText;
LdateISO := Leftstr(Headers.Values['x-amz-date'],8);
Lregion := GetRegionFromEndpoint(Headers.Values['Host']);
AuthorizationString := TAmazonAWS4Authentication(FAuthenticator).BuildAuthorizationString(StringToSign, LdateISO, Lregion, SignStrHeaders);
Request.Client.CustomHeaders['Authorization'] := AuthorizationString;
SignedHeaders.Clear;
if RequiredHeadersInstanceOwner then
FreeAndNil(SignedHeaders);
end;
end;
function TAmazonStorageService.GetCanonicalizedHeaderPrefix: string;
begin
Result := 'x-amz-';
end;
function TAmazonStorageService.GetNotificationXML(Events: TList<TAmazonNotificationEvent>): string;
var
sb: TStringBuilder;
Event: TAmazonNotificationEvent;
begin
if (Events = nil) or (Events.Count = 0) then
Exit('<NotificationConfiguration />');
sb := TStringBuilder.Create(256);
try
sb.Append('<NotificationConfiguration>');
for Event In Events do
begin
sb.Append('<TopicConfiguration><Topic>');
sb.Append(Event.Topic);
sb.Append('</Topic><Event>');
sb.Append(Event.Event);
sb.Append('</Event></TopicConfiguration>');
end;
sb.Append('</NotificationConfiguration>');
Result := sb.ToString(True);
finally
sb.Free;
end;
end;
//note: endpoints and regions may change in the future
function TAmazonStorageService.GetRegionFromEndpoint(const Endpoint: string): string;
var
LStartIdx: Integer;
begin
if Endpoint.EndsWith('s3.amazonaws.com') or
Endpoint.EndsWith('s3-external-1.amazonaws.com') then
Exit('us-east-1')
else if Endpoint.EndsWith('.amazonaws.com') then
begin
if EndPoint.StartsWith('s3.') or EndPoint.StartsWith('s3-') then
LStartIdx := 3
else
begin
LStartIdx := Pos('s3.', EndPoint);
if LStartIdx = 0 then
LStartIdx := Pos('s3-', EndPoint);
Inc(LStartIdx, 2);
end;
Exit(EndPoint.Substring(LStartIdx, EndPoint.Length - LStartIdx - '.amazonaws.com'.Length))
end
else
Exit('us-east-1');
end;
class function TAmazonStorageService.GetRegionFromString(const Region: string): TAmazonRegion;
begin
Result := TAmazonConnectionInfo.GetRegionFromString(Region);
end;
class function TAmazonStorageService.GetRegionString(Region: TAmazonRegion): string;
begin
Result := TAmazonConnectionInfo.GetRegionString(Region);
end;
//http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
//note: endpoints and regions may change in the future
function TAmazonStorageService.GetEndpointFromRegion(ARegion: TAmazonRegion): string;
begin
Result := GetConnectionInfo.StorageVirtualHost('', ARegion);
end;
function TAmazonStorageService.GetRequiredHeaderNames(out InstanceOwner: Boolean): TStrings;
begin
InstanceOwner := False;
if (FRequiredHeaderNames = nil) or (FRequiredHeaderNames.Count = 0) then
begin
FRequiredHeaderNames.Free;
FRequiredHeaderNames := TStringList.Create;
FRequiredHeaderNames.Add('host');
FRequiredHeaderNames.Add('x-amz-content-sha256');
FRequiredHeaderNames.Add('x-amz-date');
end;
Result := FRequiredHeaderNames;
end;
procedure TAmazonStorageService.AddAndValidateHeaders(const defaultHeaders, customHeaders: TStrings);
var
IsInstanceOwner: Boolean;
RequiredHeaders: TStrings;
I: Integer;
begin
RequiredHeaders := GetRequiredHeaderNames(IsInstanceOwner);
for I := 0 to customHeaders.Count - 1 do
begin
if not (RequiredHeaders.IndexOfName(customHeaders.Names[I]) > -1) then
defaultHeaders.Append(customHeaders[I]);
end;
if IsInstanceOwner then
FreeAndNil(RequiredHeaders);
end;
function TAmazonStorageService.InitHeaders(const BucketName: string; BucketRegion: TAmazonRegion): TStringList;
begin
Result := TStringList.Create;
Result.CaseSensitive := false;
Result.Duplicates := TDuplicates.dupIgnore;
Result.Values['host'] := GetConnectionInfo.StorageVirtualHost(BucketName, BucketRegion);
Result.Values['x-amz-content-sha256'] := 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; //empty string
Result.Values['x-amz-date'] := ISODateTime_noSeparators;
end;
procedure TAmazonStorageService.PopulateGrants(GrantsNode: IXMLNode; Grants: TList<TAmazonGrant>);
var
GrantNode, GranteeNode, Aux: IXMLNode;
PermissionStr, GranteeID, GranteeDisplayName: string;
Grant: TAmazonGrant;
begin
GrantNode := GrantsNode.ChildNodes.First;
while GrantNode <> nil do
begin
GranteeDisplayName := EmptyStr;
GranteeNode := GrantNode.ChildNodes.FindNode('Grantee');
Aux := GrantNode.ChildNodes.FindNode('Permission');
if (Aux <> nil) and Aux.IsTextElement then
begin
PermissionStr := Aux.Text;
if (GranteeNode <> nil) and GranteeNode.HasChildNodes then
begin
Aux := GranteeNode.ChildNodes.FindNode('URI');
if (Aux <> nil) and Aux.IsTextElement then
begin
Grant := TAmazonGrant.Create(PermissionStr);
Grant.GranteeURI := Aux.Text;
Grants.Add(Grant);
end
else
begin
Aux := GranteeNode.ChildNodes.FindNode('EmailAddress');
if (Aux <> nil) and Aux.IsTextElement then
begin
Grant := TAmazonGrant.Create(PermissionStr);
Grant.GranteeEmailAddress := Aux.Text;
Grants.Add(Grant);
end
else
begin
Aux := GranteeNode.ChildNodes.FindNode('ID');
if (Aux <> nil) and Aux.IsTextElement then
begin
GranteeID := Aux.Text;
Aux := GranteeNode.ChildNodes.FindNode('DisplayName');
if (Aux <> nil) and Aux.IsTextElement then
GranteeDisplayName := Aux.Text;
Grant := TAmazonGrant.Create(PermissionStr);
Grant.GranteeID := GranteeID;
Grant.GranteeDisplayName := GranteeDisplayName;
Grants.Add(Grant);
end;
end;
end;
end;
end;
GrantNode := GrantNode.NextSibling;
end;
end;
function TAmazonStorageService.PopulateResultItem(ObjectNode: IXMLNode;
out ResultItem: TAmazonObjectResult): Boolean;
var
ItemNode, Aux: IXMLNode;
NodeName: string;
begin
Result := False;
if (ObjectNode <> nil) and ObjectNode.HasChildNodes then
begin
ItemNode := ObjectNode.ChildNodes.First;
while ItemNode <> nil do
begin
NodeName := ItemNode.NodeName;
if AnsiSameText(NodeName, 'Key') then
ResultItem.Name := ItemNode.Text
else if AnsiSameText(NodeName, 'LastModified') then
ResultItem.LastModified := ItemNode.Text
else if AnsiSameText(NodeName, 'ETag') then
ResultItem.ETag := ItemNode.Text
else if AnsiSameText(NodeName, 'StorageClass') then
ResultItem.StorageClass := ItemNode.Text
else if AnsiSameText(NodeName, 'VersionId') then
ResultItem.VersionId := ItemNode.Text
else if AnsiSameText(NodeName, 'IsLatest') then
ResultItem.IsLatest := AnsiSameText(ItemNode.Text, 'true')
else if AnsiSameText(NodeName, 'Size') then
ResultItem.Size := StrToInt64(ItemNode.Text)
else if AnsiSameText(NodeName, 'Owner') then
begin
Aux := ItemNode.ChildNodes.FindNode('ID');
if (Aux <> nil) and Aux.IsTextElement then
ResultItem.OwnerID := Aux.Text;
Aux := ItemNode.ChildNodes.FindNode('DisplayName');
if (Aux <> nil) and Aux.IsTextElement then
ResultItem.OwnerDisplayName := Aux.Text;
end;
ItemNode := ItemNode.NextSibling;
end;
Result := ResultItem.Name <> EmptyStr;
end;
end;
procedure TAmazonStorageService.ParseResponseError(const ResponseInfo: TCloudResponseInfo;
const ResultString: string);
var
xmlDoc: IXMLDocument;
Aux, ErrorNode, MessageNode: IXMLNode;
ErrorCode, ErrorMsg: string;
begin
//If the ResponseInfo instance exists (to be populated) and the passed in string is Error XML, then
//continue, otherwise exit doing nothing.
if (ResponseInfo = nil) or (ResultString = EmptyStr) then
Exit;
if (AnsiPos('<Error', ResultString) > 0) then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(ResultString);
except
//Response content isn't XML
Exit;
end;
//Amazon has different formats for returning errors as XML
ErrorNode := xmlDoc.DocumentElement;
if (ErrorNode <> nil) and (ErrorNode.HasChildNodes) then
begin
MessageNode := ErrorNode.ChildNodes.FindNode(NODE_ERROR_MESSAGE);
if (MessageNode <> nil) then
ErrorMsg := MessageNode.Text;
if ErrorMsg <> EmptyStr then
begin
//Populate the error code
Aux := ErrorNode.ChildNodes.FindNode(NODE_ERROR_CODE);
if (Aux <> nil) then
ErrorCode := Aux.Text;
ResponseInfo.StatusMessage := Format('%s - %s (%s)', [ResponseInfo.StatusMessage, ErrorMsg, ErrorCode]);
end;
end;
end
end;
function TAmazonStorageService.CurrentTime: string;
begin
Result := FormatDateTime('ddd, dd mmm yyyy hh:nn:ss "GMT"',
TTimeZone.Local.ToUniversalTime(Now),
TFormatSettings.Create('en-US'));
end;
destructor TAmazonStorageService.Destroy;
begin
FreeAndNil(FRequiredHeaderNames);
inherited;
end;
function TAmazonStorageService.CreateBucket(const BucketName: string; BucketACL: TAmazonACLType;
BucketRegion: TAmazonRegion;
ResponseInfo: TCloudResponseInfo): Boolean;
var
BucketACLStr: string;
RegionStr: string;
url, virtualhost: string;
contentStream: TStringStream;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
RespStr: string;
ContentStr: string;
ContentLength: Integer;
begin
contentStream := nil;
Headers := InitHeaders(BucketName, BucketRegion);
BucketACLStr := GetACLTypeString(BucketACL);
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/';
virtualhost := GetConnectionInfo.StorageVirtualHost(BucketName, BucketRegion);
RegionStr := GetRegionFromEndpoint(virtualhost); //create bucket in same region as endpoint
Headers.Values['host'] := virtualhost;
//Optionally add in the ACL value
if not BucketACLStr.IsEmpty then
Headers.Values['x-amz-acl'] := BucketACLStr;
if not RegionStr.Equals('us-east-1') then
begin
ContentStr := '<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' +
'<LocationConstraint>' + RegionStr + '</LocationConstraint>' +
'</CreateBucketConfiguration>';
contentStream := TStringStream.Create;
contentStream.WriteString(ContentStr);
ContentLength := contentStream.Size;
contentStream.position := 0;
end
else
ContentLength := 0;
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(ContentStr);
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
QueryPrefix := '/' + BucketName + '/';
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, RespStr);
ParseResponseError(ResponseInfo, RespStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(contentStream);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.ListBucketsXML(const ResponseInfo: TCloudResponseInfo): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.StorageURL('', TAmazonConnectionInfo.DefaultRegion);
Headers := InitHeaders('', TAmazonConnectionInfo.DefaultRegion);
QueryPrefix := '/';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.ListBuckets(const ResponseInfo: TCloudResponseInfo): TStrings;
var
xml: string;
xmlDoc: IXMLDocument;
ResultNode, BucketNode, Aux: IXMLNode;
Name: string;
begin
Result := nil;
xml := ListBucketsXML(ResponseInfo);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(Result);
end;
ResultNode := xmlDoc.DocumentElement.ChildNodes.FindNode('Buckets');
if ResultNode <> nil then
begin
Result := TStringList.Create;
if not ResultNode.HasChildNodes then
Exit(Result);
BucketNode := ResultNode.ChildNodes.First;
while BucketNode <> nil do
begin
if AnsiSameText(BucketNode.NodeName, 'Bucket') and BucketNode.HasChildNodes then
begin
Aux := BucketNode.ChildNodes.FindNode('Name');
if (Aux <> nil) and Aux.IsTextElement then
begin
Name := Aux.Text;
Aux := BucketNode.ChildNodes.FindNode('CreationDate');
if (Aux <> nil) and Aux.IsTextElement then
begin
Result.Values[Name] := Aux.Text;
end;
end;
end;
BucketNode := BucketNode.NextSibling;
end;
end;
end;
end;
function TAmazonStorageService.DeleteBucket(const BucketName: string; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
RespStr: string;
begin
Response := nil;
Headers := nil;
try
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/';
Response := IssueDeleteRequest(url, Headers, nil, QueryPrefix, ResponseInfo, RespStr);
ParseResponseError(ResponseInfo, RespStr);
Result := (Response <> nil) and (Response.ResponseCode = 204);
finally
Response.Free;
Headers.Free;
end;
end;
function TAmazonStorageService.DeleteBucketPolicy(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
RespStr: string;
begin
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?policy=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?policy';
Response := nil;
try
Response := IssueDeleteRequest(url, Headers, nil, QueryPrefix, ResponseInfo, RespStr);
ParseResponseError(ResponseInfo, RespStr);
Result := (Response <> nil) and (Response.ResponseCode = 204);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucketXML(const BucketName: string; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
begin
Result := GetBucketXMLInternal(BucketName, OptionalParams, False, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.GetBucketXMLInternal(const BucketName: string; OptionalParams: TStrings;
VersionInfo: Boolean; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryParams: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
QueryParams := nil;
Response := nil;
try
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/';
Headers := InitHeaders(BucketName, BucketRegion);
if VersionInfo then
begin
if QueryParams = nil then
QueryParams := TStringList.Create;
QueryParams.Values['versions'] := ' ';
end;
if (OptionalParams <> nil) and (OptionalParams.Count > 0) then
begin
if QueryParams = nil then
QueryParams := TStringList.Create;
QueryParams.AddStrings(OptionalParams);
end;
if QueryParams <> nil then
url := BuildQueryParameterString(url, QueryParams, False, True);
QueryPrefix := '/' + BucketName + '/';
if VersionInfo then
QueryPrefix := QueryPrefix + '?versions';
Response := IssueGetRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
QueryParams.Free;
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucket(const BucketName: string; OptionalParams: TStrings;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TAmazonBucketResult;
var
xml: string;
begin
xml := GetBucketXML(BucketName, OptionalParams, ResponseInfo, BucketRegion);
Result := GetBucketInternal(xml, ResponseInfo);
end;
function TAmazonStorageService.GetBucketInternal(const XML: string;
ResponseInfo: TCloudResponseInfo): TAmazonBucketResult;
var
xmlDoc: IXMLDocument;
RootNode, ItemNode, Aux: IXMLNode;
NodeName: string;
ResultItem: TAmazonObjectResult;
IsVersionRequest: Boolean;
begin
Result := nil;
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(nil);
end;
RootNode := xmlDoc.DocumentElement;
IsVersionRequest := AnsiSameText(RootNode.NodeName, 'ListVersionsResult');
//if it isn't a bucket content request or a version request, return nil
if not (IsVersionRequest or AnsiSameText(RootNode.NodeName, 'ListBucketResult')) then
Exit(nil);
ItemNode := RootNode.ChildNodes.FindNode('Name');
if (ItemNode = nil) or (not ItemNode.IsTextElement) then
Exit(nil);
Result := TAmazonBucketResult.Create(ItemNode.Text);
ItemNode := RootNode.ChildNodes.First;
while ItemNode <> nil do
begin
NodeName := ItemNode.NodeName;
if AnsiSameText(NodeName, 'Prefix') then
Result.RequestPrefix := ItemNode.Text
else if AnsiSameText(NodeName, 'Delimiter') then
Result.RequestDelimiter := ItemNode.Text
else if (AnsiSameText(NodeName, 'Marker') or AnsiSameText(NodeName, 'KeyMarker') or
AnsiSameText(NodeName, 'NextMarker')) and not ItemNode.Text.IsEmpty then
Result.Marker := ItemNode.Text
else if IsVersionRequest and AnsiSameText(NodeName, 'VersionIdMarker') then
Result.VersionIdMarker := ItemNode.Text
else if AnsiSameText(NodeName, 'MaxKeys') then
try
Result.RequestMaxKeys := StrToInt(ItemNode.Text);
except
end
else if AnsiSameText(NodeName, 'IsTruncated') then
Result.IsTruncated := not AnsiSameText(ItemNode.Text, 'false')
else if AnsiSameText(NodeName, 'Contents') or AnsiSameText(NodeName, 'Version') then
begin
if PopulateResultItem(ItemNode, ResultItem) then
Result.Objects.Add(ResultItem);
end
else if AnsiSameText(NodeName, 'CommonPrefixes') then
begin
Aux := ItemNode.ChildNodes.First;
while Aux <> nil do
begin
if AnsiSameText(Aux.NodeName, 'Prefix') and Aux.IsTextElement then
Result.Prefixes.Add(Aux.Text);
Aux := Aux.NextSibling;
end;
end;
ItemNode := ItemNode.NextSibling;
end;
//populate the appropriate marker header values, depending on if it was a Content or Version population
if Result.IsTruncated and (ResponseInfo <> nil) and (Result.Objects.Count > 1) then
begin
ResultItem := Result.Objects.Last;
//If it was a version population, all objects will have a VersionId
//and the marker parameters for a subsequent request will be different.
if IsVersionRequest then
begin
ResponseInfo.Headers.Values['key-marker'] := ResultItem.Name;
ResponseInfo.Headers.Values['version-id-marker'] := ResultItem.VersionId;
end
else
ResponseInfo.Headers.Values['marker'] := ResultItem.Name;
end;
end;
end;
function TAmazonStorageService.GetBucketACLXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?acl=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?acl';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucketACL(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TList<TAmazonGrant>;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, ListNode: IXMLNode;
begin
Result := nil;
xml := GetBucketACLXML(BucketName, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(nil);
end;
RootNode := xmlDoc.DocumentElement;
if not AnsiSameText(RootNode.NodeName, 'AccessControlPolicy') then
Exit(nil);
Result := TList<TAmazonGrant>.Create;
ListNode := RootNode.ChildNodes.FindNode('AccessControlList');
if (ListNode = nil) then
Exit(Result);
PopulateGrants(ListNode, Result);
end;
end;
function TAmazonStorageService.GetBucketPolicyJSON(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?policy=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?policy';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucketPolicy(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TJSONObject;
var
jsonString: string;
begin
Result := nil;
jsonString := GetBucketPolicyJSON(BucketName, ResponseInfo, BucketRegion);
if AnsiStartsStr('{', jsonString) then
begin
try
Result := TJSONObject(TJSONObject.ParseJSONValue(jsonString));
except
Result := nil;
end;
end;
end;
function TAmazonStorageService.GetBucketLocationXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.GetServiceURL(GetConnectionInfo.DefaultStorageEndpoint) + '/'+ BucketName + '/?location=';
Headers := InitHeaders(BucketName, TAmazonConnectionInfo.DefaultRegion);
Headers.Values['host'] := GetConnectionInfo.DefaultStorageEndpoint;
QueryPrefix := '/' + BucketName + '/?location';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucketLocation(const BucketName: string;
ResponseInfo: TCloudResponseInfo): TAmazonRegion;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode: IXMLNode;
begin
Result := amzrNotSpecified;
xml := GetBucketLocationXML(BucketName, ResponseInfo);
if (ResponseInfo.StatusCode = 200) and not xml.IsEmpty then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit;
end;
RootNode := xmlDoc.DocumentElement;
if RootNode.NodeName.Equals('LocationConstraint') and RootNode.IsTextElement then
Result := TAmazonConnectionInfo.GetRegionFromString(RootNode.Text);
end;
end;
function TAmazonStorageService.GetBucketLoggingXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?logging=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?logging';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucketLogging(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TAmazonBucketLoggingInfo;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, ItemNode, Aux: IXMLNode;
TargetBucket: string;
begin
Result := nil;
xml := GetBucketLoggingXML(BucketName, ResponseInfo, BucketRegion);
if xml = EmptyStr then
Exit;
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit;
end;
RootNode := xmlDoc.DocumentElement;
if not AnsiSameText(RootNode.NodeName, 'BucketLoggingStatus') then
Exit;
try
if RootNode.HasChildNodes then
begin
ItemNode := RootNode.ChildNodes.FindNode('LoggingEnabled');
if (ItemNode <> nil) and ItemNode.HasChildNodes then
begin
Aux := ItemNode.ChildNodes.FindNode('TargetBucket');
if (Aux <> nil) and Aux.IsTextElement then
begin
TargetBucket := Aux.Text;
Aux := ItemNode.ChildNodes.FindNode('TargetPrefix');
if (Aux <> nil) and Aux.IsTextElement then
begin
Result := TAmazonBucketLoggingInfo.Create(TargetBucket, Aux.Text);
//Optionally populate Grant information
Aux := ItemNode.ChildNodes.FindNode('TargetGrants');
if (Aux <> nil) and Aux.HasChildNodes then
begin
PopulateGrants(Aux, Result.Grants);
end;
end;
end;
end;
end;
finally
//If returning nil, then create a logging info instance with logging disabled
if Result = nil then
Result := TAmazonBucketLoggingInfo.Create;
end;
end;
function TAmazonStorageService.GetBucketNotificationXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
Response := nil;
try
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?notification=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?notification';
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
Response.Free;
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucketNotification(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TList<TAmazonNotificationEvent>;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, TopicNode, Aux: IXMLNode;
TopicStr: string;
begin
Result := nil;
xml := GetBucketNotificationXML(BucketName, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit;
end;
RootNode := xmlDoc.DocumentElement;
if AnsiSameText(RootNode.NodeName, 'NotificationConfiguration') then
begin
Result := TList<TAmazonNotificationEvent>.Create;
if RootNode.HasChildNodes then
begin
//Currently there will only be one TopicConfiguration node, but this will
//allow for gracefully handling the case if/when more TopicConfigurations are allowed.
TopicNode := RootNode.ChildNodes.First;
while TopicNode <> nil do
begin
if AnsiSameText(TopicNode.NodeName, 'TopicConfiguration') and TopicNode.HasChildNodes then
begin
Aux := TopicNode.ChildNodes.FindNode('Topic');
if (Aux <> nil) and Aux.IsTextElement then
begin
TopicStr := Aux.Text;
Aux := TopicNode.ChildNodes.FindNode('Event');
if (Aux <> nil) and Aux.IsTextElement then
begin
Result.Add(TAmazonNotificationEvent.Create(TopicStr, Aux.Text));
end;
end;
end;
TopicNode := TopicNode.NextSibling;
end;
end;
end;
end;
end;
function TAmazonStorageService.GetBucketObjectVersionsXML(const BucketName: string;
OptionalParams: TStrings; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
begin
Result := GetBucketXMLInternal(BucketName, OptionalParams, True, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.GetBucketObjectVersions(const BucketName: string;
OptionalParams: TStrings; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TAmazonBucketResult;
var
xml: string;
begin
xml := GetBucketObjectVersionsXML(BucketName, OptionalParams, ResponseInfo, BucketRegion);
Result := GetBucketInternal(xml, ResponseInfo);
end;
function TAmazonStorageService.GetRequestPaymentXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?requestPayment=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?requestPayment';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetRequestPayment(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TAmazonPayer;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, AuxNode: IXMLNode;
begin
Result := ampUnknown;
xml := GetRequestPaymentXML(BucketName, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit;
end;
RootNode := xmlDoc.DocumentElement;
if AnsiSameText(RootNode.NodeName, 'RequestPaymentConfiguration') and RootNode.HasChildNodes then
begin
AuxNode := RootNode.ChildNodes.FindNode('Payer');
if (AuxNode <> nil) and AuxNode.IsTextElement then
begin
if AnsiSameText(AuxNode.Text, 'Requester') then
Result := ampRequester
else
Result := ampBucketOwner;
end;
end;
end;
end;
function TAmazonStorageService.GetBucketVersioningXML(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?versioning=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?versioning';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetBucketVersioning(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, AuxNode: IXMLNode;
begin
Result := false;
xml := GetBucketVersioningXML(BucketName, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit;
end;
RootNode := xmlDoc.DocumentElement;
if AnsiSameText(RootNode.NodeName, 'VersioningConfiguration') and RootNode.HasChildNodes then
begin
AuxNode := RootNode.ChildNodes.FindNode('Status');
if (AuxNode <> nil) and AuxNode.IsTextElement then
Result := AnsiSameText(AuxNode.Text, 'Enabled');
end;
end;
end;
function TAmazonStorageService.GetBucketMFADelete(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, AuxNode: IXMLNode;
begin
Result := false;
xml := GetBucketVersioningXML(BucketName, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit;
end;
RootNode := xmlDoc.DocumentElement;
if AnsiSameText(RootNode.NodeName, 'VersioningConfiguration') and RootNode.HasChildNodes then
begin
AuxNode := RootNode.ChildNodes.FindNode('MfaDelete');
if (AuxNode <> nil) and AuxNode.IsTextElement then
Result := AnsiSameText(AuxNode.Text, 'Enabled');
end;
end;
end;
function TAmazonStorageService.GetBucketLifecycleXML(const ABucketName: string;
AResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
LUrl: string;
LHeaders: TStringList;
LResponse: TCloudHTTP;
begin
LResponse := nil;
LHeaders := nil;
try
LUrl := GetConnectionInfo.StorageURL(ABucketName, BucketRegion) + '/?lifecycle=';
LHeaders := InitHeaders(ABucketName, BucketRegion);
LResponse := IssueGetRequest(LUrl, LHeaders, nil, '', AResponseInfo, Result);
ParseResponseError(AResponseInfo, Result);
finally
LResponse.Free;
LHeaders.Free;
end;
end;
function TAmazonStorageService.ListMultipartUploadsXML(const BucketName: string;
const OptionalParams: TStrings; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryParams: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/';
QueryParams := TStringList.Create;
QueryParams.Values['uploads'] := ' ';
if (OptionalParams <> nil) and (OptionalParams.Count > 0) then
QueryParams.AddStrings(OptionalParams);
url := BuildQueryParameterString(url, QueryParams, False, True);
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?uploads';
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(QueryParams);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.ListMultipartUploads(const BucketName: string;
const OptionalParams: TStrings; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): TAmazonMultipartUploadsResult;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, ItemNode, UploadItemNode: IXMLNode;
Item: TAmazonMultipartUploadItem;
begin
Result := nil;
xml := ListMultipartUploadsXML(BucketName, OptionalParams, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit;
end;
RootNode := xmlDoc.DocumentElement;
if AnsiSameText(RootNode.NodeName, 'ListMultipartUploadsResult') and RootNode.HasChildNodes then
begin
ItemNode := RootNode.ChildNodes.FindNode('Bucket');
if (ItemNode = nil) or (not ItemNode.IsTextElement) then
Exit;
Result := TAmazonMultipartUploadsResult.Create(ItemNode.Text);
ItemNode := RootNode.ChildNodes.First;
while ItemNode <> nil do
begin
if AnsiSameText(ItemNode.NodeName, 'KeyMarker') then
Result.KeyMarker := ItemNode.Text
else if AnsiSameText(ItemNode.NodeName, 'UploadIdMarker') then
Result.UploadIdMarker := ItemNode.Text
else if AnsiSameText(ItemNode.NodeName, 'NextKeyMarker') then
Result.NextKeyMarker := ItemNode.Text
else if AnsiSameText(ItemNode.NodeName, 'NextUploadIdMarker') then
Result.NextUploadIdMarker := ItemNode.Text
else if AnsiSameText(ItemNode.NodeName, 'MaxUploads') then
try
Result.MaxUploads := StrToInt(ItemNode.Text);
except
end
else if AnsiSameText(ItemNode.NodeName, 'IsTruncated') then
Result.IsTruncated := AnsiSameText(ItemNode.Text, 'true')
else if AnsiSameText(ItemNode.NodeName, 'Upload') and ItemNode.HasChildNodes then
begin
UploadItemNode := ItemNode.ChildNodes.FindNode('Key');
if (UploadItemNode <> nil) and UploadItemNode.IsTextElement then
begin
Item := TAmazonMultipartUploadItem.Create(UploadItemNode.Text);
UploadItemNode := ItemNode.ChildNodes.First;
while UploadItemNode <> nil do
begin
if AnsiSameText(UploadItemNode.NodeName, 'UploadId') then
Item.UploadId := UploadItemNode.Text
else if AnsiSameText(UploadItemNode.NodeName, 'StorageClass') then
Item.IsReducedRedundancyStorage := AnsiSameText(UploadItemNode.Text, 'REDUCED_REDUDANCY')
else if AnsiSameText(UploadItemNode.NodeName, 'Initiated') then
Item.DateInitiated := UploadItemNode.Text
else if AnsiSameText(UploadItemNode.NodeName, 'Initiator') and UploadItemNode.HasChildNodes then
begin
Item.InitiatorId := GetChildText('ID', UploadItemNode);
Item.InitiatorDisplayName := GetChildText('DisplayName', UploadItemNode);
end
else if AnsiSameText(UploadItemNode.NodeName, 'Owner') and UploadItemNode.HasChildNodes then
begin
Item.OwnerId := GetChildText('ID', UploadItemNode);
Item.OwnerDisplayName := GetChildText('DisplayName', UploadItemNode);
end;
UploadItemNode := UploadItemNode.NextSibling;
end;
Result.UploadItems.Add(Item);
end;
end;
ItemNode := ItemNode.NextSibling;
end;
end;
end;
end;
function TAmazonStorageService.SetBucketACL(const BucketName: string;
ACP: TAmazonAccessControlPolicy; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
var
xml: string;
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Integer;
contentStream: TStringStream;
responseStr: string;
begin
if (BucketName = EmptyStr) or (ACP = nil) then
Exit(False);
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?acl=';
xml := ACP.AsXML;
contentStream := TStringStream.Create;
contentStream.WriteString(xml);
contentStream.position := 0;
ContentLength := contentStream.Size;
Headers := InitHeaders(BucketName, BucketRegion);
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(xml);
QueryPrefix := '/' + BucketName + '/?acl';
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.SetBucketPolicy(const BucketName: string;
Policy: TJSONObject; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
policyString: string;
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Integer;
contentStream: TStringStream;
responseStr: string;
begin
if (BucketName = EmptyStr) or (Policy = nil) then
Exit(False);
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?policy=';
policyString := Policy.ToString;
contentStream := TStringStream.Create;
contentStream.WriteString(policyString);
contentStream.position := 0;
ContentLength := contentStream.Size;
Headers := InitHeaders(BucketName, BucketRegion);
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(policyString);
QueryPrefix := '/' + BucketName + '/?policy';
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 204);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.SetBucketLogging(const BucketName: string;
LoggingInfo: TAmazonBucketLoggingInfo; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
var
loggingString: string;
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Integer;
contentStream: TStringStream;
responseStr: string;
begin
if (BucketName = EmptyStr) then
Exit(False);
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?logging=';
if LoggingInfo = nil then
loggingString := TAmazonBucketLoggingInfo.GetDisableXML
else
loggingString := LoggingInfo.AsXML;
contentStream := TStringStream.Create;
contentStream.WriteString(loggingString);
contentStream.position := 0;
ContentLength := contentStream.Size;
Headers := InitHeaders(BucketName, BucketRegion);
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(loggingString);
QueryPrefix := '/' + BucketName + '/?logging';
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.SetBucketNotification(const BucketName: string;
Events: TList<TAmazonNotificationEvent>; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
var
xml: string;
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Integer;
contentStream: TStringStream;
responseStr: string;
begin
if (BucketName = EmptyStr)then
Exit(False);
contentStream := nil;
Response := nil;
try
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?notification=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := '/' + BucketName + '/?notification';
xml := GetNotificationXML(Events);
contentStream := TStringStream.Create;
contentStream.WriteString(xml);
contentStream.position := 0;
ContentLength := contentStream.Size;
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(xml);
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
Response.Free;
FreeAndNil(Headers);
contentStream.Free;
end;
end;
function TAmazonStorageService.SetBucketRequestPayment(const BucketName: string;
Payer: TAmazonPayer; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
sb: TStringBuilder;
xml: string;
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Integer;
contentStream: TStringStream;
responseStr: string;
begin
//must be a valid Payer
if (BucketName = EmptyStr) or ((Payer <> ampRequester) and (Payer <> ampBucketOwner)) then
Exit(False);
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?requestPayment=';
sb := TStringBuilder.Create(256);
try
sb.Append('<RequestPaymentConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Payer>');
if Payer = ampRequester then
sb.Append('Requester')
else
sb.Append('BucketOwner');
sb.Append('</Payer></RequestPaymentConfiguration>');
xml := sb.ToString(True);
finally
sb.Free;
end;
contentStream := TStringStream.Create;
contentStream.WriteString(xml);
contentStream.position := 0;
ContentLength := contentStream.Size;
Headers := InitHeaders(BucketName, BucketRegion);
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(xml);
QueryPrefix := '/' + BucketName + '/?requestPayment';
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.SetBucketVersioning(const BucketName: string;
Enabled, MFADelete: Boolean; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
var
sb: TStringBuilder;
xml: string;
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Integer;
contentStream: TStringStream;
responseStr: string;
MFAInfoAvailable: Boolean;
begin
if (BucketName = EmptyStr) then
Exit(False);
//MFA can only be used when the protocol is HTTPS
MFAInfoAvailable := (GetConnectionInfo.MFASerialNumber <> EmptyStr) and
(GetConnectionInfo.MFAAuthCode <> EmptyStr) and
AnsiSameText(GetConnectionInfo.Protocol, 'https');
//Fail if enabling MFA Delete but no MFA information is specified on the connection.
if MFADelete and (not MFAInfoAvailable) then
Exit(False);
url := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?versioning=';
sb := TStringBuilder.Create(256);
try
sb.Append('<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>');
if Enabled then
sb.Append('Enabled')
else
sb.Append('Suspended');
sb.Append('</Status><MfaDelete>');
if MFADelete then
sb.Append('Enabled')
else
sb.Append('Disabled');
sb.Append('</MfaDelete></VersioningConfiguration>');
xml := sb.ToString(True);
finally
sb.Free;
end;
contentStream := TStringStream.Create;
contentStream.WriteString(xml);
contentStream.position := 0;
ContentLength := contentStream.Size;
Headers := InitHeaders(BucketName, BucketRegion);
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(xml);
//set the MFA Info if it is available
if MFAInfoAvailable then
Headers.Values['x-amz-mfa'] :=
Format('%s %s', [GetConnectionInfo.MFASerialNumber, GetConnectionInfo.MFAAuthCode]);
QueryPrefix := '/' + BucketName + '/?versioning';
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.SetBucketLifecycle(const BucketName: string;
const LifeCycle: TAmazonLifeCycleConfiguration; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): boolean;
var
LContentStream: TStringStream;
LContentLength: Integer;
LHeaders: TStringList;
LUrl, LXml: string;
LResponse: TCloudHTTP;
begin
LResponse := nil;
LHeaders := nil;
LContentStream := nil;
try
LUrl := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?lifecycle=';
LXml := LifeCycle.XML;
LContentStream := TStringStream.Create;
LContentStream.WriteString(LXml);
LContentStream.Position := 0;
LContentLength := LContentStream.Size;
LHeaders := InitHeaders(BucketName, BucketRegion);
LHeaders.Values['Content-Length'] := IntToStr(LContentLength);
LHeaders.Values['Content-MD5'] := TNetEncoding.Base64.EncodeBytesToString(THashMD5.GetHashBytes(LXml));
if LContentLength > 0 then
LHeaders.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(LXml);
LResponse := IssuePutRequest(LUrl, LHeaders, nil, '', ResponseInfo, LContentStream);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 200);
finally
LContentStream.Free;
LHeaders.Free;
LResponse.Free;
end;
end;
function TAmazonStorageService.DeleteObjectInternal(const BucketName, ObjectName, VersionId: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryParams: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
RespStr: string;
MFAInfoAvailable: Boolean;
begin
QueryParams := nil;
url := BuildObjectURL(BucketName, ObjectName, BucketRegion);
if VersionId <> EmptyStr then
begin
QueryParams := TStringList.Create;
QueryParams.Values['versionId'] := VersionId;
url := BuildQueryParameterString(url, QueryParams, False, True);
end;
//MFA can only be used when the protocol is HTTPS and a versioned object is being deleted
MFAInfoAvailable := (VersionId <> EmptyStr) and
(GetConnectionInfo.MFASerialNumber <> EmptyStr) and
(GetConnectionInfo.MFAAuthCode <> EmptyStr) and
AnsiSameText(GetConnectionInfo.Protocol, 'https');
Headers := InitHeaders(BucketName, BucketRegion);
//set the MFA Info if it is available
if MFAInfoAvailable then
Headers.Values['x-amz-mfa'] :=
Format('%s %s', [GetConnectionInfo.MFASerialNumber, GetConnectionInfo.MFAAuthCode]);
QueryPrefix := '/' + BucketName + '/' + ObjectName;
Response := nil;
try
Response := IssueDeleteRequest(url, Headers, QueryParams, QueryPrefix, ResponseInfo, RespStr);
ParseResponseError(ResponseInfo, RespStr);
Result := (Response <> nil) and (Response.ResponseCode = 204);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(QueryParams);
end;
end;
function TAmazonStorageService.DeleteObject(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
begin
Result := DeleteObjectInternal(BucketName, ObjectName, EmptyStr, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.DeleteObjectVersion(const BucketName, ObjectName, VersionId: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
begin
Result := DeleteObjectInternal(BucketName, ObjectName, VersionId, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.DeleteBucketLifecycle(const BucketName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
LUrl: string;
LHeaders: TStringList;
LResponse: TCloudHTTP;
begin
LResponse := nil;
LHeaders := nil;
try
LUrl := GetConnectionInfo.StorageURL(BucketName, BucketRegion) + '/?lifecycle=';
LHeaders := InitHeaders(BucketName, BucketRegion);
LResponse := IssueDeleteRequest(LUrl, LHeaders, nil, '', ResponseInfo);
Result := (LResponse <> nil) and (LResponse.ResponseCode = 204);
finally
LHeaders.Free;
LResponse.Free;
end;
end;
function TAmazonStorageService.GetObject(const BucketName, ObjectName: string;
OptionalParams: TAmazonGetObjectOptionals; ObjectStream: TStream;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
begin
Result := GetObjectInternal(BucketName, ObjectName, EmptyStr, OptionalParams,
ResponseInfo, ObjectStream, BucketRegion);
end;
function TAmazonStorageService.GetObject(const BucketName, ObjectName: string;
ObjectStream: TStream; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
begin
Result := GetObject(BucketName, ObjectName, TAmazonGetObjectOptionals.Create,
ObjectStream, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.GetObjectVersion(const BucketName, ObjectName, VersionId: string;
OptionalParams: TAmazonGetObjectOptionals; ObjectStream: TStream;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
begin
Result := GetObjectInternal(BucketName, ObjectName, VersionId, OptionalParams,
ResponseInfo, ObjectStream, BucketRegion);
end;
function TAmazonStorageService.GetObjectVersion(const BucketName, ObjectName, VersionId: string;
ObjectStream: TStream; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
begin
Result := GetObjectVersion(BucketName, ObjectName, VersionId, TAmazonGetObjectOptionals.Create,
ObjectStream, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.GetObjectInternal(const BucketName, ObjectName, VersionId: string;
OptionalParams: TAmazonGetObjectOptionals; ResponseInfo: TCloudResponseInfo;
ObjectStream: TStream; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
if (BucketName = EmptyStr)then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion);
Headers := InitHeaders(BucketName, BucketRegion);
OptionalParams.PopulateHeaders(Headers);
QueryPrefix := Format('/%s/%s', [BucketName, ObjectName]);
if VersionId <> EmptyStr then
begin
url := Format('%s?versionId=%s', [url, VersionId]);
QueryPrefix := Format('%s?versionId=%s', [QueryPrefix, VersionId]);
end;
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, ObjectStream);
//A 404 error means that the object was deleted. So in a way the request would also
//be successful when a 404 response code is returned, but the returned stream wouldn't be valid.
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetObjectACLXML(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) then
Exit;
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + '?acl=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := Format('/%s/%s?acl', [BucketName, ObjectName]);
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetObjectACL(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TList<TAmazonGrant>;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, ListNode: IXMLNode;
begin
Result := nil;
xml := GetObjectACLXML(BucketName, ObjectName, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(nil);
end;
RootNode := xmlDoc.DocumentElement;
if not AnsiSameText(RootNode.NodeName, 'AccessControlPolicy') then
Exit(nil);
Result := TList<TAmazonGrant>.Create;
ListNode := RootNode.ChildNodes.FindNode('AccessControlList');
if (ListNode = nil) then
Exit(Result);
PopulateGrants(ListNode, Result);
end;
end;
function TAmazonStorageService.GetObjectTorrent(const BucketName, ObjectName: string;
ObjectStream: TStream; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
if (BucketName = EmptyStr)then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + '?torrent=';
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := Format('/%s/%s?torrent', [BucketName, ObjectName]);
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, ObjectStream);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.GetObjectMetadata(const BucketName, ObjectName: string;
OptionalParams: TAmazonGetObjectOptionals; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): TStrings;
var
Properties: TStrings;
begin
GetObjectProperties(BucketName, ObjectName, TAmazonGetObjectOptionals.Create,
Properties, Result, ResponseInfo, BucketRegion);
FreeAndNil(Properties);
end;
function TAmazonStorageService.GetObjectMetadata(const BucketName, ObjectName: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TStrings;
begin
Result := GetObjectMetadata(BucketName, ObjectName, TAmazonGetObjectOptionals.Create,
ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.GetObjectProperties(const BucketName, ObjectName: string;
OptionalParams: TAmazonGetObjectOptionals; out Properties, Metadata: TStrings;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
CurrentHeaderName, QueryPrefix, url: string;
Headers: TStringList;
Response: TCloudHTTP;
FreeResponseInfo: Boolean;
I, Count: Integer;
begin
Result := False;
Properties := nil;
Metadata := nil;
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion);
Headers := InitHeaders(BucketName, BucketRegion);
try
OptionalParams.PopulateHeaders(Headers);
QueryPrefix := string.Format('/%s/%s', [BucketName, ObjectName]);
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssueHeadRequest(url, Headers, nil, QueryPrefix, ResponseInfo);
if (Response <> nil) and (Response.ResponseCode = 200) then
begin
Result := True;
Properties := TStringList.Create;
Metadata := TStringList.Create;
Count := ResponseInfo.Headers.Count;
for I := 0 to Count - 1 do
begin
CurrentHeaderName := ResponseInfo.Headers.Names[I];
if AnsiStartsText('x-amz-meta-', CurrentHeaderName) then
begin
//strip the "x-amz-meta-" prefix from the name of the header,
//to get the original metadata header name, as entered by the user.
CurrentHeaderName := CurrentHeaderName.Substring(11);
Metadata.Values[CurrentHeaderName] := ResponseInfo.Headers.ValueFromIndex[I];
end
else
Properties.Values[CurrentHeaderName] := ResponseInfo.Headers.ValueFromIndex[I];
end;
end;
finally
Response.Free;
if FreeResponseInfo then
ResponseInfo.Free;
end;
finally
Headers.Free;
end;
end;
function TAmazonStorageService.GetObjectProperties(const BucketName, ObjectName: string;
out Properties, Metadata: TStrings; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
begin
Result := GetObjectProperties(BucketName, ObjectName, TAmazonGetObjectOptionals.Create,
Properties, Metadata, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.UploadObject(const BucketName, ObjectName: string;
Content: TArray<Byte>; ReducedRedundancy: Boolean; Metadata, Headers: TStrings;
ACL: TAmazonACLType; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
LHeaders: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
contentStream: TBytesStream;
responseStr: string;
ContentLength: Integer;
begin
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion);
LHeaders := InitHeaders(BucketName, BucketRegion);
//if unspecified amazon sets content-type to 'binary/octet-stream';
if ReducedRedundancy then
LHeaders.Values['x-amz-storage-class'] := CLASS_REDUCED_REDUNDANCY;
LHeaders.Values['x-amz-acl'] := GetACLTypeString(ACL);
if Headers <> nil then
AddAndValidateHeaders(LHeaders,Headers);
AddS3MetadataHeaders(LHeaders, Metadata);
QueryPrefix := Format('/%s/%s', [BucketName, ObjectName]);
contentStream := TBytesStream.Create(Content);
contentStream.position := 0;
ContentLength := contentStream.Size;
if ContentLength > 0 then
LHeaders.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetStreamToHashSHA256Hex(contentStream);
LHeaders.Values['Content-Length'] := IntToStr(ContentLength);
Response := nil;
try
Response := IssuePutRequest(url, LHeaders, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and ((Response.ResponseCode = 200) or (Response.ResponseCode = 100));
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(LHeaders);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.SetObjectACL(const BucketName, ObjectName: string;
ACP: TAmazonAccessControlPolicy; Headers: TStrings; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
var
xml: string;
url: string;
LHeaders: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Integer;
contentStream: TStringStream;
responseStr: string;
begin
if (BucketName = EmptyStr) or (ACP = nil) then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + '?acl=';
xml := ACP.AsXML;
contentStream := TStringStream.Create;
contentStream.WriteString(xml);
contentStream.position := 0;
ContentLength := contentStream.Size;
LHeaders := InitHeaders(BucketName, BucketRegion);
if Headers <> nil then
LHeaders.AddStrings(Headers);
LHeaders.Values['Content-Length'] := IntToStr(ContentLength);
LHeaders.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
LHeaders.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(xml);
QueryPrefix := '/' + BucketName + '/' + ObjectName + '?acl';
Response := nil;
try
Response := IssuePutRequest(url, LHeaders, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(LHeaders);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.SetObjectACL(const BucketName, ObjectName: string;
ACL: TAmazonACLType; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
responseStr: string;
contentStream: TStringStream;
begin
if BucketName.IsEmpty then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + '?acl=';
Headers := InitHeaders(BucketName, BucketRegion);
Headers.Values['x-amz-acl'] := GetACLTypeString(ACL);
Headers.Values['Content-Length'] := '0';
QueryPrefix := '/' + BucketName + '/' + ObjectName + '?acl';
contentStream := TStringStream.Create;
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.CopyObject(const DestinationBucket, DestinationObjectName,
SourceBucket, SourceObjectName: string; OptionalParams: TAmazonCopyObjectOptionals;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
begin
Result := CopyObjectVersion(DestinationBucket, DestinationObjectName, SourceBucket,
SourceObjectName, EmptyStr, OptionalParams, ResponseInfo, BucketRegion);
end;
function TAmazonStorageService.SetObjectMetadata(const BucketName, ObjectName: string;
Metadata: TStrings; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
Optionals: TAmazonCopyObjectOptionals;
begin
try
Optionals := TAmazonCopyObjectOptionals.Create;
Optionals.FCopyMetadata := False;
Optionals.FMetadata.AddStrings(Metadata);
Result := CopyObject(BucketName, ObjectName, BucketName, ObjectName, Optionals,
ResponseInfo, BucketRegion);
finally
FreeAndNil(Optionals);
end;
end;
procedure TAmazonStorageService.SortHeaders(const Headers: TStringList);
begin
if (Headers <> nil) then
begin
Headers.CustomSort(CaseSensitiveHyphenCompare);
end;
end;
// For Amazon, add a '=' between each query parameter name anad value, even if a parameter value is empty
function TAmazonStorageService.BuildQueryParameterString(const QueryPrefix: string; QueryParameters: TStringList;
DoSort, ForURL: Boolean): string;
var
Count: Integer;
I: Integer;
lastParam, nextParam: string;
QueryStartChar, QuerySepChar, QueryKeyValueSepChar: Char;
CurrValue: string;
CommaVal: string;
begin
//if there aren't any parameters, just return the prefix
if (QueryParameters = nil) or (QueryParameters.Count = 0) then
Exit(QueryPrefix);
if ForURL then
begin
//If the query parameter string is beign created for a URL, then
//we use the default characters for building the strings, as will be required in a URL
QueryStartChar := '?';
QuerySepChar := '&';
QueryKeyValueSepChar := '=';
end
else
begin
//otherwise, use the characters as they need to appear in the signed string
QueryStartChar := FQueryStartChar;
QuerySepChar := FQueryParamSeparator;
QueryKeyValueSepChar := FQueryParamKeyValueSeparator;
end;
if DoSort and not QueryParameters.Sorted then
SortQueryParameters(QueryParameters, ForURL);
Count := QueryParameters.Count;
lastParam := QueryParameters.Names[0];
CurrValue := Trim(QueryParameters.ValueFromIndex[0]);
//URL Encode the firs set of params
URLEncodeQueryParams(ForURL, lastParam, CurrValue);
Result := QueryPrefix + QueryStartChar + lastParam + QueryKeyValueSepChar + CurrValue;
//in the URL, the comma character must be escaped. In the StringToSign, it shouldn't be.
//this may need to be pulled out into a function which can be overridden by individual Cloud services.
if ForURL then
CommaVal := '%2c'
else
CommaVal := ',';
//add the remaining query parameters, if any
for I := 1 to Count - 1 do
begin
nextParam := Trim(QueryParameters.Names[I]);
CurrValue := QueryParameters.ValueFromIndex[I];
URLEncodeQueryParams(ForURL, nextParam, CurrValue);
//match on key name only if the key names are not empty string.
//if there is a key with no value, it should be formatted as in the else block
if (lastParam <> EmptyStr) and (AnsiCompareText(lastParam, nextParam) = 0) then
Result := Result + CommaVal + CurrValue
else begin
if (not ForURL) or (nextParam <> EmptyStr) then
Result := Result + QuerySepChar + nextParam + QueryKeyValueSepChar + CurrValue;
lastParam := nextParam;
end;
end;
end;
function TAmazonStorageService.CopyObjectVersion(const DestinationBucket,
DestinationObjectName, SourceBucket, SourceObjectName, SourceVersionId: string;
OptionalParams: TAmazonCopyObjectOptionals; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
responseStr: string;
LSourceBucketName, LDestBucketName: string;
begin
if (DestinationBucket = EmptyStr) or (DestinationObjectName = EmptyStr) or
(SourceBucket = EmptyStr) or (SourceObjectName = EmptyStr) then
Exit(False);
LSourceBucketName := AnsiLowerCase(SourceBucket);
LDestBucketName := AnsiLowerCase(DestinationBucket);
url := BuildObjectURL(LDestBucketName, DestinationObjectName, BucketRegion);
QueryPrefix := Format('/%s/%s', [LDestBucketName, DestinationObjectName]);
Headers := InitHeaders(LDestBucketName, BucketRegion);
Headers.Values['Content-Length'] := '0';
if OptionalParams <> nil then
OptionalParams.PopulateHeaders(Headers);
if SourceVersionId <> EmptyStr then
Headers.Values['x-amz-copy-source'] :=
Format('/%s/%s?versionId=%s', [LSourceBucketName, SourceObjectName, SourceVersionId])
else
Headers.Values['x-amz-copy-source'] := Format('/%s/%s', [LSourceBucketName, SourceObjectName]);
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, nil, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.InitiateMultipartUploadXML(const BucketName, ObjectName: string;
Metadata, Headers: TStrings; ACL: TAmazonACLType; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): string;
var
url: string;
LHeaders: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
begin
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) then
Exit(EmptyStr);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + '?uploads=';
QueryPrefix := Format('/%s/%s?uploads', [BucketName, ObjectName]);
LHeaders := InitHeaders(BucketName, BucketRegion);
if Headers <> nil then
LHeaders.AddStrings(Headers);
AddS3MetadataHeaders(LHeaders, Metadata);
LHeaders.Values['Content-Length'] := '0';
LHeaders.Values['x-amz-acl'] := GetACLTypeString(ACL);
Response := nil;
try
Response := IssuePostRequest(url, LHeaders, nil, QueryPrefix, ResponseInfo, nil, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(LHeaders);
end;
end;
function TAmazonStorageService.InitiateMultipartUpload(const BucketName, ObjectName: string;
Metadata, Headers: TStrings; ACL: TAmazonACLType; ResponseInfo: TCloudResponseInfo;
BucketRegion: TAmazonRegion): string;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, IDNode: IXMLNode;
begin
xml := InitiateMultipartUploadXML(BucketName, ObjectName, Metadata, Headers,
ACL, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(EmptyStr);
end;
RootNode := xmlDoc.DocumentElement;
if not AnsiSameText(RootNode.NodeName, 'InitiateMultipartUploadResult') then
Exit(EmptyStr);
IDNode := RootNode.ChildNodes.FindNode('UploadId');
if (IDNode <> nil) and IDNode.IsTextElement then
Result := IDNode.Text;
end;
end;
function TAmazonStorageService.AbortMultipartUpload(const BucketName, ObjectName, UploadId: string;
ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
responseStr: string;
begin
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + '?uploadId=' + UploadId;
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := Format('/%s/%s?uploadId=%s', [BucketName, ObjectName, UploadId]);
Response := nil;
try
Response := IssueDeleteRequest(url, Headers, nil, QueryPrefix, ResponseInfo, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 204);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.UploadPart(const BucketName, ObjectName, UploadId: string;
PartNumber: Integer; Content: TArray<Byte>; out Part: TAmazonMultipartPart;
const ContentMD5: string; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
contentStream: TBytesStream;
responseStr: string;
FreeResponseInfo: Boolean;
ContentLength: Int64;
begin
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) or (UploadId = EmptyStr) or (Content = nil) then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) +
Format('?partNumber=%d&uploadId=%s', [PartNumber, UploadId]);
Headers := InitHeaders(BucketName, BucketRegion);
QueryPrefix := Format('/%s/%s', [BucketName, ObjectName]);
QueryPrefix := Format('%s?partNumber=%d&uploadId=%s', [QueryPrefix, PartNumber, UploadId]);
contentStream := TBytesStream.Create(Content);
ContentLength := contentStream.Size;
contentStream.position := 0;
Headers.Values['Content-Length'] := IntToStr(ContentLength);
Headers.Values['Content-Type'] := 'application/x-www-form-urlencoded; charset=utf-8';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetStreamToHashSHA256Hex(contentStream);
if ContentMD5 <> EmptyStr then
Headers.Values['Content-MD5'] := ContentMD5;
FreeResponseInfo := ResponseInfo = nil;
if FreeResponseInfo then
ResponseInfo := TCloudResponseInfo.Create;
Response := nil;
try
Response := IssuePutRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
if Result then
begin
Part.PartNumber := PartNumber;
Part.ETag := ResponseInfo.Headers.Values['ETag'];
Part.Size := ContentLength;
Part.LastModified := ResponseInfo.Headers.Values['Date'];
end;
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
if FreeResponseInfo then
ResponseInfo.Free;
end;
end;
function TAmazonStorageService.CompleteMultipartUpload(const BucketName, ObjectName, UploadId: string;
Parts: TList<TAmazonMultipartPart>; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): Boolean;
var
xml: string;
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
ContentLength: Int64;
contentStream: TStringStream;
responseStr: string;
sb: TStringBuilder;
Part: TAmazonMultipartPart;
begin
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) or (UploadId = EmptyStr) or (Parts = nil) then
Exit(False);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + '?uploadId=' + URLEncodeValue(UploadId);
sb := TStringBuilder.Create(256);
try
sb.Append('<CompleteMultipartUpload>');
for Part In Parts do
sb.Append(Part.AsXML);
sb.Append('</CompleteMultipartUpload>');
xml := sb.ToString(True);
finally
sb.Free;
end;
contentStream := TStringStream.Create;
contentStream.WriteString(xml);
contentStream.position := 0;
ContentLength := contentStream.Size;
Headers := InitHeaders(BucketName, BucketRegion);
Headers.Values['Content-Length'] := IntToStr(ContentLength);
// When the platform is not Windows, it's necessary to specify that we are sending binary content
Headers.Values['Content-Type'] := 'application/octet-stream';
if ContentLength > 0 then
Headers.Values['x-amz-content-sha256'] := TCloudSHA256Authentication.GetHashSHA256Hex(xml);
QueryPrefix := '/' + BucketName + '/' + ObjectName + '?uploadId=' + UploadId;
Response := nil;
try
Response := IssuePostRequest(url, Headers, nil, QueryPrefix, ResponseInfo, contentStream, responseStr);
ParseResponseError(ResponseInfo, responseStr);
Result := (Response <> nil) and (Response.ResponseCode = 200);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
FreeAndNil(contentStream);
end;
end;
function TAmazonStorageService.ListMultipartUploadPartsXML(const BucketName, ObjectName, UploadId: string;
MaxParts, PartNumberMarker: Integer; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): string;
var
url: string;
Headers: TStringList;
QueryPrefix: string;
Response: TCloudHTTP;
QuerySuffix: string;
begin
if (BucketName = EmptyStr) or (ObjectName = EmptyStr) or (UploadId = EmptyStr) then
Exit(EmptyStr);
QuerySuffix := '?uploadId=' + UploadId;
if MaxParts > 0 then
QuerySuffix := QuerySuffix + '&max-parts=' + IntToStr(MaxParts);
if PartNumberMarker > 0 then
QuerySuffix := QuerySuffix + '&part-number-marker=' + IntToStr(PartNumberMarker);
url := BuildObjectURL(BucketName, ObjectName, BucketRegion) + QuerySuffix;
QueryPrefix := Format('/%s/%s%s', [BucketName, ObjectName, QuerySuffix]);
Headers := InitHeaders(BucketName, BucketRegion);
Response := nil;
try
Response := IssueGetRequest(url, Headers, nil, QueryPrefix, ResponseInfo, Result);
ParseResponseError(ResponseInfo, Result);
finally
if Assigned(Response) then
FreeAndNil(Response);
FreeAndNil(Headers);
end;
end;
function TAmazonStorageService.ListMultipartUploadParts(const BucketName, ObjectName, UploadId: string;
MaxParts, PartNumberMarker: Integer; ResponseInfo: TCloudResponseInfo; BucketRegion: TAmazonRegion): TAmazonListPartsResult;
var
xml: string;
xmlDoc: IXMLDocument;
RootNode, ItemNode: IXMLNode;
PartNumber: Integer;
ETag: string;
Part: TAmazonMultipartPart;
begin
result := nil;
xml := ListMultipartUploadPartsXML(BucketName, ObjectName, UploadId, MaxParts,
PartNumberMarker, ResponseInfo, BucketRegion);
if xml <> EmptyStr then
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.LoadFromXML(xml);
except
Exit(nil);
end;
RootNode := xmlDoc.DocumentElement;
if not AnsiSameText(RootNode.NodeName, 'ListPartsResult') then
Exit(nil);
Result := TAmazonListPartsResult.Create(BucketName, ObjectName, UploadId);
ItemNode := RootNode.ChildNodes.First;
while ItemNode <> nil do
begin
if AnsiSameText(ItemNode.NodeName, 'Initiator') then
begin
Result.InitiatorId := GetChildText('ID', ItemNode);
Result.InitiatorDisplayName := GetChildText('DisplayName', ItemNode);
end
else if AnsiSameText(ItemNode.NodeName, 'Owner') then
begin
Result.OwnerId := GetChildText('ID', ItemNode);
Result.OwnerDisplayName := GetChildText('DisplayName', ItemNode);
end
else if AnsiSameText(ItemNode.NodeName, 'StorageClass') then
Result.IsReducedRedundancyStorage := AnsiSameText(ItemNode.Text, 'REDUCED_REDUDANCY')
else if AnsiSameText(ItemNode.NodeName, 'PartNumberMarker') then
try
Result.PartNumberMarker := StrToInt(ItemNode.Text)
except
end
else if AnsiSameText(ItemNode.NodeName, 'NextPartNumberMarker') then
try
Result.NextPartNumberMarker := StrToInt(ItemNode.Text)
except
end
else if AnsiSameText(ItemNode.NodeName, 'MaxParts') then
try
Result.MaxParts := StrToInt(ItemNode.Text)
except
end
else if AnsiSameText(ItemNode.NodeName, 'IsTruncated') then
Result.IsTruncated := AnsiSameText(ItemNode.Text, 'true')
else if AnsiSameText(ItemNode.NodeName, 'Part') then
begin
try
PartNumber := StrToInt(GetChildText('PartNumber', ItemNode));
ETag := GetChildText('ETag', ItemNode);
Part := TAmazonMultipartPart.Create(PartNumber, ETag);
Part.LastModified := GetChildText('LastModified', ItemNode);
Part.Size := StrToInt64(GetChildText('Size', ItemNode));
Result.Parts.Add(Part);
except
end;
end;
ItemNode := ItemNode.NextSibling;
end;
end;
end;
end.
|
unit TITaxInvoices_ImportReestr;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxDBEdit, cxLabel, cxProgressBar,
StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxButtonEdit, ibase,TiMessages, TIImportDBFData,TiCommonTypes,cxDataStorage,
TICommonLoader, TiWaitForm,kernel;
type TTaxInvocesUser = record
id_user:Integer;
name_user:string;
name_computer:string;
ip_computer:string;
end;
type
TImportReestrForm = class(TForm)
FileOpenGroup: TGroupBox;
eFileNameEdit: TcxButtonEdit;
ImportPanel: TGroupBox;
StartBtn: TcxButton;
ProgressBar: TcxProgressBar;
GroupBox1: TGroupBox;
PeriodLabel: TcxLabel;
PeriodDBTextEdit: TcxDBTextEdit;
NumReestrLabel: TcxLabel;
NumReestrDBTextEdit: TcxDBTextEdit;
GroupBox2: TGroupBox;
NaklLabel: TcxLabel;
SaveDialog: TSaveDialog;
OpenDialog: TOpenDialog;
GroupBox3: TGroupBox;
SubdivisionButtonEdit: TcxButtonEdit;
procedure StartBtnClick(Sender: TObject);
procedure eFileNameEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure SubdivisionButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
PDb_Handle : TISC_DB_HANDLE;
is_vid_nakl_ins : Integer;
TaxInvoicesUser : TTaxInvocesUser;
public
ReestrParam : TReestrParam;
id_subdivision : Integer;
name_subdivision : string;
constructor Create (AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE; is_vid_nakl:Integer);reintroduce;
end;
var
ImportReestrForm: TImportReestrForm;
implementation
uses TITaxInvoicesDM, DB;
{$R *.dfm}
constructor TImportReestrForm.Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE;is_vid_nakl:Integer);
begin
inherited Create(AOwner);
PDb_Handle := DB_HANDLE;
is_vid_nakl_ins := is_vid_nakl;
//--------------------------------------------------------------------
TaxInvoicesDM.UserDSet.Close;
TaxInvoicesDM.UserDSet.SelectSQL.Text := 'select * from TI_USER_INFO';
TaxInvoicesDM.UserDSet.Open;
TaxInvoicesUser.id_user := TaxInvoicesDM.UserDSet['ID_USER'];
TaxInvoicesUser.name_user := TaxInvoicesDM.UserDSet['USER_FIO'];
TaxInvoicesUser.name_computer := TaxInvoicesDM.UserDSet['HOST_NAME'];
TaxInvoicesUser.ip_computer := TaxInvoicesDM.UserDSet['IP_ADRESS'];
end;
procedure TImportReestrForm.StartBtnClick(Sender: TObject);
var
RecordCount : Integer;
LastNomer : Integer;
Id_Type_Doc : Integer;
Name_Type_Doc : string;
CharCod : string;
name_contragent : string;
ViewForm : TImportDBFForm;
i,j : Integer;
wf : TForm;
LastNumVidNakl : Integer;
id_vid_nakl : Integer;
KEY_SESSION : Int64;
workdate : TDate;
STRU : KERNEL_MODE_STRUCTURE;
DoResult : Boolean;
ErrorList : TStringList;
s : string;
LastNumOtrNakl : Integer;
id_otr_nakl : Integer;
begin
if (eFileNameEdit.Text='') then
begin
TiShowMessage('Увага!','Оберіть файл для імпорту',mtWarning,[mbOK]);
Exit;
end;
if (SubdivisionButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть назву організації, дані якої будут імпортуватися',mtWarning,[mbOK]);
SubdivisionButtonEdit.SetFocus;
Exit;
end;
ReestrParam.Id_reestr := TaxInvoicesDM.ReestrDSet['ID_REESTR'];
ReestrParam.Num_Reestr := TaxInvoicesDM.ReestrDSet['NUM_REESTR'];
ReestrParam.Kod_setup_Reestr := TaxInvoicesDM.ReestrDSet['KOD_SETUP_OUT'];
ReestrParam.DATABEG_REESTR := TaxInvoicesDM.ReestrDSet['DATABEG_REESTR'];
ReestrParam.DATAEND_REESTR := TaxInvoicesDM.ReestrDSet['DATAEND_REESTR'];
ViewForm := TImportDBFForm.Create(Self, TaxInvoicesDM.DB.Handle, ReestrParam);
if (is_vid_nakl_ins = 1)then //выданные накладные
begin
TaxInvoicesDM.IMPORT.Close;
TaxInvoicesDM.IMPORT.Open;
ViewForm.DBFDataVidNaklGridTableView1.DataController.RecordCount := TaxInvoicesDM.IMPORT.RecordCount;
ViewForm.DBFDataVidNaklGridTableView_NUM_ORDER.DataBinding.ValueTypeClass := TcxIntegerValueType;
ViewForm.DBFDataVidNaklGridTableView_DATA_VIPISKI.DataBinding.ValueTypeClass := TcxDateTimeValueType;
ViewForm.DBFDataVidNaklGridTableView_NUM_NAKL.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataVidNaklGridTableView_NAME_TYPE_DOCUMENT.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataVidNaklGridTableView_NAME_CUSTOMER.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataVidNaklGridTableView_IPN_CUSTOMER.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataVidNaklGridTableView_SUMMA_ALL_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataVidNaklGridTableView_SUMMA_TAXABLE_20.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataVidNaklGridTableView_SUMMA_TAXABLE_0.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataVidNaklGridTableView_SUMMA_EXEMPT.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataVidNaklGridTableView_SUMMA_EXPORT.DataBinding.ValueTypeClass := TcxFloatValueType;
// начало импорта выданных налоговых накладных
if (TaxInvoicesDM.IMPORT.RecordCount <> 0) then
begin
// поиск последнего номера в реестре
LastNomer := 0;
TaxInvoicesDM.WriteTransaction.StartTransaction;
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_LAST_NOMER_NAKL_SEARCH';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := TaxInvoicesDM.ReestrDSet['ID_REESTR'];
TaxInvoicesDM.pFIBStoredProc.ParamByName('TYPE_NAKL').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
TaxInvoicesDM.WriteTransaction.Commit;
LastNomer := TaxInvoicesDM.pFIBStoredProc.ParamByName('LAST_NUM_ORDER').Value;
ViewForm.DBFDataVidNaklGridTableView1.DataController.RecordCount := TaxInvoicesDM.IMPORT.RecordCount;
TaxInvoicesDM.IMPORT.First;
for i := 0 to TaxInvoicesDM.IMPORT.RecordCount-1 do
begin
name_contragent := '';
name_contragent := TaxInvoicesDM.IMPORT['NAZP'];
OemToAnsi(PAnsiChar(name_contragent),PAnsiChar(name_contragent));
Name_Type_Doc := TaxInvoicesDM.IMPORT['WMDTYPESTR'];
OemToAnsi(PAnsiChar(Name_Type_Doc),PAnsiChar(Name_Type_Doc));
ViewForm.DBFDataVidNaklGridTableView_NUM_ORDER.DataBinding.DataController.Values[i,0] := LastNomer+i;
ViewForm.DBFDataVidNaklGridTableView_DATA_VIPISKI.DataBinding.DataController.Values[i,1] := TaxInvoicesDM.IMPORT['DATEV'] ;
ViewForm.DBFDataVidNaklGridTableView_NUM_NAKL.DataBinding.DataController.Values[i,2] := TaxInvoicesDM.IMPORT['NUM'] ;
ViewForm.DBFDataVidNaklGridTableView_NAME_TYPE_DOCUMENT.DataBinding.DataController.Values[i,3] := Name_Type_Doc;
ViewForm.DBFDataVidNaklGridTableView_NAME_CUSTOMER.DataBinding.DataController.Values[i,4] := name_contragent ;
if ((TaxInvoicesDM.IMPORT['IPN'] = '') or (TaxInvoicesDM.IMPORT['IPN'] = null)) then
ViewForm.DBFDataVidNaklGridTableView_IPN_CUSTOMER.DataBinding.DataController.Values[i,5] := 0
else
ViewForm.DBFDataVidNaklGridTableView_IPN_CUSTOMER.DataBinding.DataController.Values[i,5] := TaxInvoicesDM.IMPORT['IPN'];
ViewForm.DBFDataVidNaklGridTableView_SUMMA_ALL_PDV.DataBinding.DataController.Values[i,6] := TaxInvoicesDM.IMPORT['ZAGSUM'];
ViewForm.DBFDataVidNaklGridTableView_SUMMA_TAXABLE_20.DataBinding.DataController.Values[i,7] := TaxInvoicesDM.IMPORT['BAZOP20'];
ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.DataController.Values[i,8] := TaxInvoicesDM.IMPORT['SUMPDV'];
ViewForm.DBFDataVidNaklGridTableView_SUMMA_TAXABLE_0.DataBinding.DataController.Values[i,9] := TaxInvoicesDM.IMPORT['BAZOP0'];
ViewForm.DBFDataVidNaklGridTableView_SUMMA_EXEMPT.DataBinding.DataController.Values[i,10] := TaxInvoicesDM.IMPORT['ZVILN'];
ViewForm.DBFDataVidNaklGridTableView_SUMMA_EXPORT.DataBinding.DataController.Values[i,11] := TaxInvoicesDM.IMPORT['EXPORT'];
TaxInvoicesDM.IMPORT.Next;
end;
end;
ViewForm.ShowModal;
if ViewForm.ModalResult = mrOk then
begin
TaxInvoicesDM.WriteTransaction.StartTransaction;
wf:=ShowWaitForm(Application.MainForm,wfImportData);
ProgressBar.Properties.Max := TaxInvoicesDM.IMPORT.RecordCount;
//---------------------импорт выданных накладных
if (TaxInvoicesDM.IMPORT.RecordCount)<>0 then
begin
for i :=0 to ViewForm.DBFDataVidNaklGridTableView1.DataController.RecordCount - 1 do
begin
//поиск номера
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_LAST_NOMER_NAKL_SEARCH';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := ReestrParam.Id_reestr;
TaxInvoicesDM.pFIBStoredProc.ParamByName('TYPE_NAKL').Value := 1; //выданные накладные
TaxInvoicesDM.pFIBStoredProc.ExecProc;
LastNumVidNakl := TaxInvoicesDM.pFIBStoredProc.ParamByName('LAST_NUM_ORDER').Value;
//поиск кода
Id_Type_Doc := 0;
Name_Type_Doc := '';
CharCod := ViewForm.DBFDataVidNaklGridTableView_NAME_TYPE_DOCUMENT.DataBinding.DataController.Values[i,3];
//TaxInvoicesDM.WriteTransaction.StartTransaction;
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_TYPE_DOC_SEARCH';
TaxInvoicesDM.pFIBStoredProc.ParamByName('KOD').Value := CharCod;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IDSPR').Value := 2;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
//TaxInvoicesDM.WriteTransaction.Commit;
Id_Type_Doc := TaxInvoicesDM.pFIBStoredProc.ParamByName('id_type_doc').Value;
name_type_doc := TaxInvoicesDM.pFIBStoredProc.ParamByName('name_type_doc').Value;
// добавление записи в таблицу выданных накладных
// TaxInvoicesDM.WriteTransaction.StartTransaction;
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_INS';
TaxInvoicesDM.pFIBStoredProc.ParamByName('data_vipiski').Value := StrToDate(ViewForm.DBFDataVidNaklGridTableView_DATA_VIPISKI.DataBinding.DataController.Values[i,1]);
TaxInvoicesDM.pFIBStoredProc.ParamByName('NUM_NAKL').Value := ViewForm.DBFDataVidNaklGridTableView_NUM_NAKL.DataBinding.DataController.Values[i,2];
TaxInvoicesDM.pFIBStoredProc.ParamByName('NUM_ORDER').Value := LastNumVidNakl;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_TYPE_DOCUMENT').Value := Id_Type_Doc;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_TYPE_DOCUMENT').Value := name_type_doc;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_CUSTOMER').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_CUSTOMER').Value := ViewForm.DBFDataVidNaklGridTableView_NAME_CUSTOMER.DataBinding.DataController.Values[i,4];
TaxInvoicesDM.pFIBStoredProc.ParamByName('ipn_customer').Value := ViewForm.DBFDataVidNaklGridTableView_IPN_CUSTOMER.DataBinding.DataController.Values[i,5];
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_USER_CREATE').Value := TaxInvoicesUser.id_user;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_USER_CREATE').Value := TaxInvoicesUser.name_user;
TaxInvoicesDM.pFIBStoredProc.ParamByName('date_time_create').Value := Now;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_IMPORT').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_SYSTEM').Value := name_subdivision;
TaxInvoicesDM.pFIBStoredProc.ParamByName('id_subdivision').Value := id_subdivision;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_SCHET_IMPORT').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_PDV_20').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.DataController.Values[i,8];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_TAXABLE_20').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_TAXABLE_20.DataBinding.DataController.Values[i,7];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_TAXABLE_0').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_TAXABLE_0.DataBinding.DataController.Values[i,9];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_EXEMPT').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_EXEMPT.DataBinding.DataController.Values[i,10];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_EXPORT').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_EXPORT.DataBinding.DataController.Values[i,11];
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_KORIG').Value := 0;// ?
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_EXPANSION').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_SIGN').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_TAXLIABILITIES').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_TAXLIABILITIES').Value := '';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := ReestrParam.Id_reestr;;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_NAKL_DOCUMENT').Value := StrToInt('-1');
TaxInvoicesDM.pFIBStoredProc.ParamByName('pk_id').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('is_import').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_LGOTA').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_LGOTA').Value := '';
TaxInvoicesDM.pFIBStoredProc.ExecProc;
id_vid_nakl := TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_').Value;
// проверка настройки подразделений
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_IMPORT_PROVERKA';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_SUBDIVISION').Value := ID_SUBDIVISION;
if (ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.DataController.Values[i,8] <> 0) then
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 1;
end
else
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 0;
end;
if (ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.DataController.Values[i,8] <> 0) then
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 1;
end
else
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
if (TaxInvoicesDM.pFIBStoredProc.ParamByName('OUT').Value = 1)then
begin
TiShowMessage('Виникла помилка!',TaxInvoicesDM.pFIBStoredProc.ParamByName('error_message').Value,mtError,[mbOK]);
TaxInvoicesDM.WriteTransaction.Rollback;
CloseWaitForm(wf);
Exit;
end;
// добавление бюджетов в таблицу TI_BUDGET_NDS
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_IMPORT';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_SUBDIVISION').Value := ID_SUBDIVISION;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_NAKL').Value := id_vid_nakl;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_VID').Value := 1;
if (ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.DataController.Values[i,8] <> 0) then
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_not_nds').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_TAXABLE_20.DataBinding.DataController.Values[i,7];
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_nds').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.DataController.Values[i,8];
end
else
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_not_nds').Value := ViewForm.DBFDataVidNaklGridTableView_SUMMA_EXEMPT.DataBinding.DataController.Values[i,10];
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_nds').Value := 0;
end;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
//добавление проводки по этой налоговой накладной
//проверка - необходимо ли отражать её в бухгалтерию
if (ViewForm.DBFDataVidNaklGridTableView_SUMMA_PDV_20.DataBinding.DataController.Values[i,8] <> 0)then
begin
//добавление проводок в буфера
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_PROVODKA_VID_NAKL';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_VID_NAKL').Value := id_vid_nakl;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IP_ADRESS_COMPUTER').Value := TaxInvoicesUser.ip_computer;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
//TaxInvoicesDM.WriteTransaction.Commit;
//TaxInvoicesDM.WriteTransaction.StartTransaction;
// добавление проводки
KEY_SESSION := TaxInvoicesDM.pFIBStoredProc.ParamByName('KEY_SESSION_DOC').value;
workdate := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_PROV').value;
//ShowMessage(IntToStr(KEY_SESSION));
STRU.KEY_SESSION := KEY_SESSION;
STRU.WORKDATE := WORKDATE;
STRU.DBHANDLE := TaxInvoicesDM.DB.Handle;
STRU.TRHANDLE := TaxInvoicesDM.WriteTransaction.Handle;
STRU.KERNEL_ACTION := 1;
STRU.ID_USER := TaxInvoicesUser.id_user;
try
DoResult:=Kernel.KernelDo(@STRU);
except
on E:Exception do
begin
ShowMessage('Помилка ядра ' + E.Message);
Exit;
end;
end;
if not DoResult then
begin
ErrorList := Kernel.GetDocErrorsListEx(@STRU);
s := '';
for j:=0 to ErrorList.Count - 1 do
begin
if s <> '' then s := s + #13;
s := s + ErrorList.Strings[j];
end;
ShowMessage(s);
TaxInvoicesDM.WriteTransaction.Rollback;
Exit;
end;
end;
ProgressBar.Position:=ProgressBar.Position+1;
end;//конец цикла
CloseWaitForm(wf);
TaxInvoicesDM.WriteTransaction.Commit;
TiShowMessage('Увага!','Дані Імпортовано.',mtWarning,[mbOK]);
Close;
end;
end;
end;
if (is_vid_nakl_ins = 0)then //полученные накладные
begin
TaxInvoicesDM.IMPORT.Close;
TaxInvoicesDM.IMPORT.Open;
ViewForm.DBFDataOtrNaklGridTableView1.DataController.RecordCount := TaxInvoicesDM.IMPORT.RecordCount+1;
ViewForm.DBFDataOtrNaklGridTableView_DATA_OTR.DataBinding.ValueTypeClass := TcxDateTimeValueType;
ViewForm.DBFDataOtrNaklGridTableView_DATA_VIPISKI.DataBinding.ValueTypeClass := TcxDateTimeValueType;
ViewForm.DBFDataOtrNaklGridTableView_NUM_NAKL.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataOtrNaklGridTableView_NAME_TYPE_DOCUMENT.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataOtrNaklGridTableView_NAME_PROVIDER.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataOtrNaklGridTableView_IPN_PROVIDER.DataBinding.ValueTypeClass := TcxStringValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_ALL_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_NOT_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_EXEMPT_NOT_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_EXEMPT_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_ECON_ACTIV_NOT_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView1_SUMMA_ECON_ACTIV_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_DELIVERY_NOT_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_DELIVERY_PDV.DataBinding.ValueTypeClass := TcxFloatValueType;
// начало импорта полученных налоговых накладных
if (TaxInvoicesDM.IMPORT.RecordCount <> 0) then
begin
// поиск последнего номера в реестре
LastNomer := 0;
TaxInvoicesDM.WriteTransaction.StartTransaction;
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_LAST_NOMER_NAKL_SEARCH';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := TaxInvoicesDM.ReestrDSet['ID_REESTR'];
TaxInvoicesDM.pFIBStoredProc.ParamByName('TYPE_NAKL').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
TaxInvoicesDM.WriteTransaction.Commit;
LastNomer := TaxInvoicesDM.pFIBStoredProc.ParamByName('LAST_NUM_ORDER').Value;
ViewForm.DBFDataOtrNaklGridTableView1.DataController.RecordCount := TaxInvoicesDM.IMPORT.RecordCount;
TaxInvoicesDM.IMPORT.First;
for i := 0 to TaxInvoicesDM.IMPORT.RecordCount-1 do
begin
name_contragent := '';
name_contragent := TaxInvoicesDM.IMPORT['NAZP'];
OemToAnsi(PAnsiChar(name_contragent),PAnsiChar(name_contragent));
Name_Type_Doc := TaxInvoicesDM.IMPORT['WMDTYPESTR'];
OemToAnsi(PAnsiChar(Name_Type_Doc),PAnsiChar(Name_Type_Doc));
ViewForm.DBFDataOtrNaklGridTableView_DATA_OTR.DataBinding.DataController.Values[i,0] := TaxInvoicesDM.IMPORT['DATEV'];
ViewForm.DBFDataOtrNaklGridTableView_DATA_VIPISKI.DataBinding.DataController.Values[i,1] := TaxInvoicesDM.IMPORT['DTVP'];
ViewForm.DBFDataOtrNaklGridTableView_NUM_NAKL.DataBinding.DataController.Values[i,2] := LastNomer + i ;
ViewForm.DBFDataOtrNaklGridTableView_NAME_TYPE_DOCUMENT.DataBinding.DataController.Values[i,3] := Name_Type_Doc ;
ViewForm.DBFDataOtrNaklGridTableView_NAME_PROVIDER.DataBinding.DataController.Values[i,4] := name_contragent ;
if ((TaxInvoicesDM.IMPORT['IPN'] = '') or (TaxInvoicesDM.IMPORT['IPN'] = null)) then
ViewForm.DBFDataOtrNaklGridTableView_IPN_PROVIDER.DataBinding.DataController.Values[i,5] := 0
else
ViewForm.DBFDataOtrNaklGridTableView_IPN_PROVIDER.DataBinding.DataController.Values[i,5] := TaxInvoicesDM.IMPORT['IPN'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_ALL_PDV.DataBinding.DataController.Values[i,6] := TaxInvoicesDM.IMPORT['ZAGSUM'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_NOT_PDV.DataBinding.DataController.Values[i,7] := TaxInvoicesDM.IMPORT['VART7'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.DataController.Values[i,8] := TaxInvoicesDM.IMPORT['SUM8'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_EXEMPT_NOT_PDV.DataBinding.DataController.Values[i,9] := TaxInvoicesDM.IMPORT['VART9'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_EXEMPT_PDV.DataBinding.DataController.Values[i,10] := TaxInvoicesDM.IMPORT['SUM10'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_ECON_ACTIV_NOT_PDV.DataBinding.DataController.Values[i,11] := TaxInvoicesDM.IMPORT['VART11'];
ViewForm.DBFDataOtrNaklGridTableView1_SUMMA_ECON_ACTIV_PDV.DataBinding.DataController.Values[i,12] := TaxInvoicesDM.IMPORT['SUM12'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_DELIVERY_NOT_PDV.DataBinding.DataController.Values[i,13] := TaxInvoicesDM.IMPORT['VART13'];
ViewForm.DBFDataOtrNaklGridTableView_SUMMA_DELIVERY_PDV.DataBinding.DataController.Values[i,14] := TaxInvoicesDM.IMPORT['SUM14'];
TaxInvoicesDM.IMPORT.Next;
end;
ViewForm.ShowModal;
end;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesDM.WriteTransaction.StartTransaction;
wf:=ShowWaitForm(Application.MainForm,wfImportData);
ProgressBar.Properties.Max := TaxInvoicesDM.IMPORT.RecordCount;
//---------------------импорт полученных накладных
if (TaxInvoicesDM.IMPORT.RecordCount)<>0 then
begin
for i :=0 to ViewForm.DBFDataOtrNaklGridTableView1.DataController.RecordCount - 1 do
begin
//поиск номера
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_LAST_NOMER_NAKL_SEARCH';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := ReestrParam.Id_reestr;
TaxInvoicesDM.pFIBStoredProc.ParamByName('TYPE_NAKL').Value := 0; //полученные накладные
TaxInvoicesDM.pFIBStoredProc.ExecProc;
LastNumOtrNakl := TaxInvoicesDM.pFIBStoredProc.ParamByName('LAST_NUM_ORDER').Value;
//поиск кода
Id_Type_Doc := 0;
Name_Type_Doc := '';
CharCod := ViewForm.DBFDataOtrNaklGridTableView_NAME_TYPE_DOCUMENT.DataBinding.DataController.Values[i,3];
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_TYPE_DOC_SEARCH';
TaxInvoicesDM.pFIBStoredProc.ParamByName('KOD').Value := CharCod;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IDSPR').Value := 1; // полученные- 1 выданные- 2
TaxInvoicesDM.pFIBStoredProc.ExecProc;
if (TaxInvoicesDM.pFIBStoredProc.ParamByName('id_type_doc').Value = null) then
begin
Id_Type_Doc := 0;
Name_Type_Doc := '';
end
else
begin
Id_Type_Doc := TaxInvoicesDM.pFIBStoredProc.ParamByName('id_type_doc').Value;
name_type_doc := TaxInvoicesDM.pFIBStoredProc.ParamByName('name_type_doc').Value;
end;
//Id_Type_Doc := TaxInvoicesDM.pFIBStoredProc.ParamByName('id_type_doc').Value;
// name_type_doc := TaxInvoicesDM.pFIBStoredProc.ParamByName('name_type_doc').Value;
// добавление записи в таблицу полученных накладных
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_SP_OTR_NAKL_INS';
TaxInvoicesDM.pFIBStoredProc.ParamByName('DATA_OTR').Value := StrToDate(ViewForm.DBFDataOtrNaklGridTableView_DATA_OTR.DataBinding.DataController.Values[i,0]);
TaxInvoicesDM.pFIBStoredProc.ParamByName('DATA_VIPISKI').Value := StrToDate(ViewForm.DBFDataOtrNaklGridTableView_DATA_VIPISKI.DataBinding.DataController.Values[i,1]);
TaxInvoicesDM.pFIBStoredProc.ParamByName('NUM_NAKL').Value := ViewForm.DBFDataOtrNaklGridTableView_NUM_NAKL.DataBinding.DataController.Values[i,2];
TaxInvoicesDM.pFIBStoredProc.ParamByName('NUM_ORDER').Value := LastNumOtrNakl;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_TYPE_DOCUMENT').Value := Id_Type_Doc;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_TYPE_DOCUMENT').Value := name_type_doc;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_PROVIDER').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_PROVIDER').Value := ViewForm.DBFDataOtrNaklGridTableView_NAME_PROVIDER.DataBinding.DataController.Values[i,4];
TaxInvoicesDM.pFIBStoredProc.ParamByName('IPN_PROVIDER').Value := ViewForm.DBFDataOtrNaklGridTableView_IPN_PROVIDER.DataBinding.DataController.Values[i,5];
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_USER_CREATE').Value := TaxInvoicesUser.id_user;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_USER_CREATE').Value := TaxInvoicesUser.name_user;
TaxInvoicesDM.pFIBStoredProc.ParamByName('date_time_create').Value := Now;
TaxInvoicesDM.pFIBStoredProc.ParamByName('pk_id').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('is_import').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_20_0_NOT_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_NOT_PDV.DataBinding.DataController.Values[i,7];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_20_0_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.DataController.Values[i,8];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_EXEMPT_NOT_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_EXEMPT_NOT_PDV.DataBinding.DataController.Values[i,9];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_EXEMPT_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_EXEMPT_PDV.DataBinding.DataController.Values[i,10];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_ECON_ACTIV_NOT_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_ECON_ACTIV_NOT_PDV.DataBinding.DataController.Values[i,11];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_ECON_ACTIV_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView1_SUMMA_ECON_ACTIV_PDV.DataBinding.DataController.Values[i,12];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_DELIVERY_NOT_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_DELIVERY_NOT_PDV.DataBinding.DataController.Values[i,13];
TaxInvoicesDM.pFIBStoredProc.ParamByName('SUMMA_DELIVERY_PDV').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_DELIVERY_PDV.DataBinding.DataController.Values[i,14];
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_KORIG').Value := 0;// ?
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_EXPANSION').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_TAXLIABILITIES').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('NAME_TAXLIABILITIES').Value := '';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_SUBDIVISION').Value := id_subdivision;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := ReestrParam.Id_reestr;;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
//TaxInvoicesDM.WriteTransaction.Commit;
id_otr_nakl := TaxInvoicesDM.pFIBStoredProc.ParamByName('id_otr_nakl_').Value;
// проверка настройки подразделений
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_IMPORT_PROVERKA';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_SUBDIVISION').Value := ID_SUBDIVISION;
if (ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.DataController.Values[i,8] <> 0) then
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 1;
end
else
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 0;
end;
if (ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.DataController.Values[i,8] <> 0) then
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 1;
end
else
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
if (TaxInvoicesDM.pFIBStoredProc.ParamByName('OUT').Value = 1)then
begin
TiShowMessage('Виникла помилка!',TaxInvoicesDM.pFIBStoredProc.ParamByName('error_message').Value,mtError,[mbOK]);
TaxInvoicesDM.WriteTransaction.Rollback;
CloseWaitForm(wf);
Exit;
end;
// добавление бюджетов в таблицу TI_BUDGET_NDS
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_IMPORT';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_SUBDIVISION').Value := ID_SUBDIVISION;
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_NAKL').Value := id_otr_nakl;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_VID').Value := 0;
if (ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.DataController.Values[i,8] <> 0) then
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 1;
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_not_nds').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_NOT_PDV.DataBinding.DataController.Values[i,7];
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_nds').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.DataController.Values[i,8];
end
else
begin
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IS_NOT_NDS').Value := 0;
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_not_nds').Value := ViewForm.DBFDataOtrNaklGridTableView_SUMMA_EXEMPT_NOT_PDV.DataBinding.DataController.Values[i,9];
TaxInvoicesDM.pFIBStoredProc.ParamByName('summa_nds').Value := 0;
end;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
//добавление проводки по этой налоговой накладной
//проверка - необходимо ли отражать её в бухгалтерию
if (ViewForm.DBFDataOtrNaklGridTableView_SUMMA_20_0_PDV.DataBinding.DataController.Values[i,8] <> 0)then
begin
//добавление проводок в буфера
TaxInvoicesDM.pFIBStoredProc.StoredProcName := 'TI_PROVODKA_OTR_NAKL';
TaxInvoicesDM.pFIBStoredProc.ParamByName('ID_OTR_NAKL').Value := id_otr_nakl;
TaxInvoicesDM.pFIBStoredProc.ParamByName('IP_ADRESS_COMPUTER').Value := TaxInvoicesUser.ip_computer;
TaxInvoicesDM.pFIBStoredProc.ExecProc;
//TaxInvoicesDM.WriteTransaction.Commit;
//TaxInvoicesDM.WriteTransaction.StartTransaction;
// добавление проводки
KEY_SESSION := TaxInvoicesDM.pFIBStoredProc.ParamByName('KEY_SESSION_DOC').value;
workdate := TaxInvoicesDM.pFIBStoredProc.ParamByName('DATE_PROV').value;
//ShowMessage(IntToStr(KEY_SESSION));
STRU.KEY_SESSION := KEY_SESSION;
STRU.WORKDATE := WORKDATE;
STRU.DBHANDLE := TaxInvoicesDM.DB.Handle;
STRU.TRHANDLE := TaxInvoicesDM.WriteTransaction.Handle;
STRU.KERNEL_ACTION := 1;
STRU.ID_USER := TaxInvoicesUser.id_user;
try
DoResult:=Kernel.KernelDo(@STRU);
except
on E:Exception do
begin
ShowMessage('Помилка ядра ' + E.Message);
Exit;
end;
end;
if not DoResult then
begin
ErrorList := Kernel.GetDocErrorsListEx(@STRU);
s := '';
for j:=0 to ErrorList.Count - 1 do
begin
if s <> '' then s := s + #13;
s := s + ErrorList.Strings[j];
end;
ShowMessage(s);
TaxInvoicesDM.WriteTransaction.Rollback;
Exit;
end;
end;
ProgressBar.Position:=ProgressBar.Position+1;
end;
CloseWaitForm(wf);
TaxInvoicesDM.WriteTransaction.Commit;
TiShowMessage('Увага!','Дані Імпортовано.',mtWarning,[mbOK]);
Close;
end;
end
end;
end;
procedure TImportReestrForm.eFileNameEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
//SaveDialog.FileName:='Reestr_vid_Nakl.dbf';
if OpenDialog.Execute then
begin
eFileNameEdit.Text:=OpenDialog.FileName;
TaxInvoicesDM.IMPORT.DatabaseName:=ExtractFileDir(OpenDialog.FileName);
TaxInvoicesDM.IMPORT.TableName:=ExtractFileName(OpenDialog.FileName);
end;
end;
procedure TImportReestrForm.SubdivisionButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter : TTiSimpleParam;
SubDivision : Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesDM.DB.Handle;
Parameter.Owner := self;
SubDivision := DoFunctionFromPackage(Parameter,Subdivision_Const);
Parameter.Destroy;
If VarArrayDimCount(SubDivision)>0 then
begin
SubdivisionButtonEdit.Text := SubDivision[1];
name_subdivision := SubDivision[1];
id_subdivision := SubDivision[0];
SubdivisionButtonEdit.SetFocus;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.