text
stringlengths
14
6.51M
unit inline_method_2; interface implementation type TRec = record FD1: Int32; FD2: Int32; procedure SetData(D1, D2: Int32); inline; end; procedure TRec.SetData(D1, D2: Int32); begin FD1 := D1; FD2 := D2; end; var R: TRec; procedure Test; begin R.SetData(12, 13); end; initialization Test(); finalization Assert(R.FD1 = 12); Assert(R.FD2 = 13); end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLSLBumpShader<p> A GLSL shader that applies bump mapping.<p> <b>History : </b><font size=-1><ul> <li>16/03/11 - Yar - Fixes after emergence of GLMaterialEx <li>20/10/10 - Yar - Bugfixed memory leak <li>23/08/10 - Yar - Replaced OpenGL1x to OpenGLTokens <li>07/01/10 - DaStr - Bugfixed all DoInitialize() calls (thanks YarUnderoaker) <li>24/07/09 - DaStr - TGLShader.DoInitialize() now passes rci (BugTracker ID = 2826217) Fixed a bug with "fRDotV" clamping, which occured on all GeForce 8x and later graphic cards <li>20/03/07 - DaStr - Made changes related to the new parameter passing model <li>06/03/07 - DaStr - Again replaced DecimalSeparator stuff with a single Str procedure (thanks Uwe Raabe) <li>03/03/07 - DaStr - Made compatible with Delphi6 <li>22/02/07 - DaStr - Initial version (contributed to GLScene) This is a collection of GLSL Bump shaders, comes in these variaties (to know what these abriviations mean, see GLCustomShader.pas): - TGLSLBumpShader - TGLSLBumpShaderMT - TGLSLBumpShaderAM - TGLSLMLBumpShader - TGLSLMLBumpShaderMT Notes: 1) Alpha is a synthetic property, in real life your should set each color's Alpha individualy 2) TGLSLMLBumpShader takes all Light parameters directly from OpenGL (that includes TGLLightSource's) TODO: 1) Implement IGLShaderDescription in all shaders. Previous version history: v1.0 03 September '2006 Creation v1.1 09 September '2006 Camera Positioning bugfix Artefacts on the non-lit side removed v1.2 16 September '2006 Shader made ATI-compatible v1.2.2 02 November '2006 Small optimization if Do(Un)Apply v1.3 27 November '2006 TGLCustomGLSLMLBumpShaderMT added v1.3.2 30 November '2006 LightCompensation added gl_FragColor() calculation optimized a bit v1.4 16 December '2006 All Shaders renamed according to the new naming convention SCS_SHADER_NEEDS_AT_LEAST_ONE_LIGHT_SOURCE moved to GLCustomShader TGLBaseCustomGLSLBumpShader, TGLBaseMatlibGLSLBumpShader(MT) abstracted 7 diferent versions of this shader added All shaders made design-time compatible v1.4.2 18 December '2006 MultiLight versions of this shader bugfixed (the specular light was sometimes "cut") The use of SpecularMap made optional v1.4.6 20 December '2006 TGLBaseMatlibGLSLBumpShader and TGLBaseCustomGLSLBumpShader merged The use of NormalMap is optional MultiLight shaders optimized a bit v1.4.8 06 February '2007 IGLMaterialLibrarySupported renamed to IGLMaterialLibrarySupported v1.5 16 February '2007 Updated to the latest CVS version of GLscene v1.5.2 18 February '2007 Removed the StrangeTextureUtilities dependancy } unit GLSLBumpShader; interface {$I GLScene.inc} uses // VCL Classes, SysUtils, // GLScene GLTexture, GLScene, GLVectorGeometry, GLVectorTypes, GLCadencer, GLStrings, OpenGLTokens, GLSLShader, GLCustomShader, GLColor, GLRenderContextInfo, GLMaterial; type EGLSLBumpShaderException = class(EGLSLShaderException); // An abstract class. TGLBaseCustomGLSLBumpShader = class(TGLCustomGLSLShader, IGLMaterialLibrarySupported) private FBumpHeight: Single; FBumpSmoothness: Integer; FSpecularPower: Single; FSpecularSpread: Single; FLightPower: Single; FMaterialLibrary: TGLMaterialLibrary; FNormalTexture: TGLTexture; FSpecularTexture: TGLTexture; FNormalTextureName: TGLLibMaterialName; FSpecularTextureName: TGLLibMaterialName; function GetNormalTextureName: TGLLibMaterialName; function GetSpecularTextureName: TGLLibMaterialName; procedure SetNormalTextureName(const Value: TGLLibMaterialName); procedure SetSpecularTextureName(const Value: TGLLibMaterialName); procedure SetSpecularTexture(const Value: TGLTexture); procedure SetNormalTexture(const Value: TGLTexture); // Implementing IGLMaterialLibrarySupported. function GetMaterialLibrary: TGLAbstractMaterialLibrary; protected procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci: TRenderContextInfo): Boolean; override; procedure SetMaterialLibrary(const Value: TGLMaterialLibrary); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; property BumpHeight: Single read FBumpHeight write FBumpHeight; property BumpSmoothness: Integer read FBumpSmoothness write FBumpSmoothness; property SpecularPower: Single read FSpecularPower write FSpecularPower; property SpecularSpread: Single read FSpecularSpread write FSpecularSpread; property LightPower: Single read FLightPower write FLightPower; property NormalTexture: TGLTexture read FNormalTexture write SetNormalTexture; property SpecularTexture: TGLTexture read FSpecularTexture write SetSpecularTexture; property NormalTextureName: TGLLibMaterialName read GetNormalTextureName write SetNormalTextureName; property SpecularTextureName: TGLLibMaterialName read GetSpecularTextureName write SetSpecularTextureName; property MaterialLibrary: TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; end; // An abstract class. TGLBaseCustomGLSLBumpShaderMT = class(TGLBaseCustomGLSLBumpShader) private FMainTexture: TGLTexture; FMainTextureName: TGLLibMaterialName; function GetMainTextureName: string; procedure SetMainTextureName(const Value: string); protected procedure SetMaterialLibrary(const Value: TGLMaterialLibrary); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public property MainTexture: TGLTexture read FMainTexture write FMainTexture; property MainTextureName: TGLLibMaterialName read GetMainTextureName write SetMainTextureName; end; // One Light shaders. TGLCustomGLSLBumpShaderAM = class(TGLBaseCustomGLSLBumpShaderMT) private FAmbientColor: TGLColor; FDiffuseColor: TGLColor; FSpecularColor: TGLColor; function GetAlpha: Single; procedure SetAlpha(const Value: Single); protected procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TRenderContextInfo; Sender : TObject); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; property AmbientColor: TGLColor read FAmbientColor; property DiffuseColor: TGLColor read FDiffuseColor; property SpecularColor: TGLColor read FSpecularColor; property Alpha: Single read GetAlpha write SetAlpha; end; TGLCustomGLSLBumpShaderMT = class(TGLBaseCustomGLSLBumpShaderMT) protected procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TRenderContextInfo; Sender : TObject); override; end; TGLCustomGLSLBumpShader = class(TGLBaseCustomGLSLBumpShader, IGLShaderDescription) private // Implementing IGLShaderDescription. procedure SetShaderTextures(const Textures: array of TGLTexture); procedure GetShaderTextures(var Textures: array of TGLTexture); procedure SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure SetShaderMiscParameters(const ACadencer: TGLCadencer; const AMatLib: TGLMaterialLibrary; const ALightSources: TGLLightSourceSet); procedure GetShaderMiscParameters(var ACadencer: TGLCadencer; var AMatLib: TGLMaterialLibrary; var ALightSources: TGLLightSourceSet); function GetShaderAlpha: Single; procedure SetShaderAlpha(const Value: Single); function GetShaderDescription: string; protected procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TRenderContextInfo; Sender : TObject); override; end; // MultiLight shaders. TGLCustomGLSLMLBumpShader = class(TGLBaseCustomGLSLBumpShader, IGLShaderDescription) private FLightSources: TGLLightSourceSet; FLightCompensation: Single; procedure SetLightSources(const Value: TGLLightSourceSet); procedure SetLightCompensation(const Value: Single); // Implementing IGLShaderDescription. procedure SetShaderTextures(const Textures: array of TGLTexture); procedure GetShaderTextures(var Textures: array of TGLTexture); procedure SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); procedure SetShaderMiscParameters(const ACadencer: TGLCadencer; const AMatLib: TGLMaterialLibrary; const ALightSources: TGLLightSourceSet); procedure GetShaderMiscParameters(var ACadencer: TGLCadencer; var AMatLib: TGLMaterialLibrary; var ALightSources: TGLLightSourceSet); function GetShaderAlpha: Single; procedure SetShaderAlpha(const Value: Single); function GetShaderDescription: string; protected procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TRenderContextInfo; Sender : TObject); override; public constructor Create(AOwner : TComponent); override; property LightSources: TGLLightSourceSet read FLightSources write SetLightSources default [1]; {: Setting LightCompensation to a value less than 1 decreeses individual light intensity when using multiple lights } property LightCompensation: Single read FLightCompensation write SetLightCompensation; end; TGLCustomGLSLMLBumpShaderMT = class(TGLBaseCustomGLSLBumpShaderMT) private FLightSources: TGLLightSourceSet; FLightCompensation: Single; procedure SetLightSources(const Value: TGLLightSourceSet); procedure SetLightCompensation(const Value: Single); protected procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override; procedure DoInitialize(var rci : TRenderContextInfo; Sender : TObject); override; public constructor Create(AOwner : TComponent); override; property LightSources: TGLLightSourceSet read FLightSources write SetLightSources default [1]; {: Setting LightCompensation to a value less than 1 decreeses individual light intensity when using multiple lights } property LightCompensation: Single read FLightCompensation write SetLightCompensation; end; {************** Published **************} // One light shaders. TGLSLBumpShaderMT = class(TGLCustomGLSLBumpShaderMT) published property MainTextureName; property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; end; TGLSLBumpShader = class(TGLCustomGLSLBumpShader) published property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; end; TGLSLBumpShaderAM = class(TGLCustomGLSLBumpShaderAM) published property AmbientColor; property DiffuseColor; property SpecularColor; property Alpha stored False; property MainTextureName; property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; end; // Multi light shaders. TGLSLMLBumpShader = class(TGLCustomGLSLMLBumpShader) published property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; property LightSources; property LightCompensation; end; TGLSLMLBumpShaderMT = class(TGLCustomGLSLMLBumpShaderMT) published property MainTextureName; property NormalTextureName; property SpecularTextureName; property MaterialLibrary; property BumpHeight; property BumpSmoothness; property SpecularPower; property SpecularSpread; property LightPower; property LightSources; property LightCompensation; end; implementation procedure GetVertexProgramCode(const Code: TStrings); begin with Code do begin Clear; Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add('varying vec3 LightDirection; '); Add(' '); Add('void main( void ) '); Add('{ '); Add(' gl_Position = ftransform(); '); Add(' Texcoord = gl_MultiTexCoord0.xy; '); Add(' '); Add(' vec3 fvViewDirection = (gl_ModelViewMatrix * gl_Vertex).xyz; '); Add(' vec3 fvLightDirection = gl_LightSource[0].position.xyz - fvViewDirection; '); Add(' '); Add(' vec3 fvNormal = gl_NormalMatrix * gl_Normal; '); Add(' vec3 fvBinormal = gl_NormalMatrix * gl_MultiTexCoord2.xyz; '); Add(' vec3 fvTangent = gl_NormalMatrix * gl_MultiTexCoord1.xyz; '); Add(' '); Add(' ViewDirection.x = dot( fvTangent, fvViewDirection ); '); Add(' ViewDirection.y = dot( fvBinormal, fvViewDirection ); '); Add(' ViewDirection.z = dot( fvNormal, fvViewDirection ); '); Add(' '); Add(' LightDirection.x = dot( fvTangent, fvLightDirection ); '); Add(' LightDirection.y = dot( fvBinormal, fvLightDirection ); '); Add(' LightDirection.z = dot( fvNormal, fvLightDirection ); '); Add(' '); Add(' LightDirection = normalize(LightDirection); '); Add(' ViewDirection = normalize(ViewDirection); '); Add('} '); end; end; procedure GetFragmentProgramCodeMP(const Code: TStrings; const UseSpecularMap: Boolean; const UseNormalMap: Boolean); begin with Code do begin Clear; Add('uniform vec4 fvAmbient; '); Add('uniform vec4 fvSpecular; '); Add('uniform vec4 fvDiffuse; '); Add(' '); Add('uniform float fLightPower; '); Add('uniform float fSpecularPower; '); Add('uniform float fSpecularSpread; '); if UseNormalMap then begin Add('uniform sampler2D bumpMap; '); Add('uniform float fBumpHeight; '); Add('uniform float fBumpSmoothness; '); end; Add(' '); Add('uniform sampler2D baseMap; '); if UseSpecularMap then Add('uniform sampler2D specMap; '); Add(' '); Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add('varying vec3 LightDirection; '); Add(' '); Add('void main( void ) '); Add('{ '); if UseNormalMap then Add(' vec3 fvNormal = normalize( ( texture2D( bumpMap, Texcoord ).xyz * fBumpSmoothness) - fBumpHeight * fBumpSmoothness); ') else Add(' vec3 fvNormal = vec3(0.0, 0.0, 1);'); Add(' '); Add(' float fNDotL = dot( fvNormal, LightDirection ); '); Add(' vec3 fvReflection = normalize( ( (fSpecularSpread * fvNormal ) * fNDotL ) - LightDirection ); '); Add(' '); Add(' float fRDotV = max( dot( fvReflection, -ViewDirection ), 0.0 ); '); Add(' '); Add(' vec4 fvBaseColor = texture2D( baseMap, Texcoord ); '); if UseSpecularMap then Add(' vec4 fvSpecColor = texture2D( specMap, Texcoord ) * fvSpecular; ') else Add(' vec4 fvSpecColor = fvSpecular; '); Add(' '); Add(' vec4 fvTotalDiffuse = clamp(fvDiffuse * fNDotL, 0.0, 1.0); '); Add(' '); Add(' // (fvTotalDiffuse + 0.2) / 1.2 is used for removing artefacts on the non-lit side '); Add(' vec4 fvTotalSpecular = clamp((pow(fRDotV, fSpecularPower ) ) * (fvTotalDiffuse + 0.2) / 1.2 * fvSpecColor, 0.0, 1.0); '); Add(' '); Add(' gl_FragColor = fLightPower * (fvBaseColor * ( fvAmbient + fvTotalDiffuse ) + fvTotalSpecular); '); Add('} '); end; end; procedure GetFragmentProgramCode(const Code: TStrings; const UseSpecularMap: Boolean; const UseNormalMap: Boolean); begin with Code do begin Clear; Add('uniform float fLightPower; '); Add('uniform float fSpecularPower; '); Add('uniform float fSpecularSpread; '); if UseNormalMap then begin Add('uniform sampler2D bumpMap; '); Add('uniform float fBumpHeight; '); Add('uniform float fBumpSmoothness; '); end; Add(' '); Add('uniform sampler2D baseMap; '); if UseSpecularMap then Add('uniform sampler2D specMap; '); Add(' '); Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add('varying vec3 LightDirection; '); Add(' '); Add('void main( void ) '); Add('{ '); if UseNormalMap then Add(' vec3 fvNormal = normalize( ( texture2D( bumpMap, Texcoord ).xyz * fBumpSmoothness) - fBumpHeight * fBumpSmoothness); ') else Add(' vec3 fvNormal = vec3(0.0, 0.0, 1.0);'); Add(' '); Add(' float fNDotL = dot( fvNormal, LightDirection ); '); Add(' vec3 fvReflection = normalize( ( (fSpecularSpread * fvNormal ) * fNDotL ) - LightDirection ); '); Add(' '); Add(' float fRDotV = max(dot( fvReflection, -ViewDirection ), 0.0); '); Add(' '); Add(' vec4 fvBaseColor = texture2D( baseMap, Texcoord ); '); if UseSpecularMap then Add(' vec4 fvSpecColor = texture2D( specMap, Texcoord ) * gl_LightSource[0].specular; ') else Add(' vec4 fvSpecColor = gl_LightSource[0].specular; '); Add(' '); Add(' vec4 fvTotalDiffuse = clamp(gl_LightSource[0].diffuse * fNDotL, 0.0, 1.0); '); Add(' '); Add(' // (fvTotalDiffuse + 0.2) / 1.2 is used for removing artefacts on the non-lit side '); Add(' vec4 fvTotalSpecular = clamp((pow(fRDotV, fSpecularPower ) ) * (fvTotalDiffuse + 0.2) / 1.2 * fvSpecColor, 0.0, 1.0); '); Add(' '); Add(' gl_FragColor = fLightPower * (fvBaseColor * ( gl_LightSource[0].ambient + fvTotalDiffuse ) + fvTotalSpecular); '); Add('} '); end; end; procedure GetMLVertexProgramCode(const Code: TStrings); begin with Code do begin Clear; Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add(' '); Add('varying vec3 fvViewDirection; '); Add('varying vec3 fvNormal; '); Add('varying vec3 fvBinormal; '); Add('varying vec3 fvTangent; '); Add(' '); Add('void main( void ) '); Add('{ '); Add(' gl_Position = ftransform(); '); Add(' Texcoord = gl_MultiTexCoord0.xy; '); Add(' '); Add(' fvViewDirection = (gl_ModelViewMatrix * gl_Vertex).xyz; '); Add(' '); Add(' fvNormal = gl_NormalMatrix * gl_Normal; '); Add(' fvBinormal = gl_NormalMatrix * gl_MultiTexCoord2.xyz; '); Add(' fvTangent = gl_NormalMatrix * gl_MultiTexCoord1.xyz; '); Add(' '); Add(' ViewDirection.x = dot( fvTangent, fvViewDirection ); '); Add(' ViewDirection.y = dot( fvBinormal, fvViewDirection ); '); Add(' ViewDirection.z = dot( fvNormal, fvViewDirection ); '); Add(' '); Add(' ViewDirection = normalize(ViewDirection); '); Add('} '); end; end; procedure GetMLFragmentProgramCodeBeg(const Code: TStrings; const UseSpecularMap: Boolean; const UseNormalMap: Boolean); begin with Code do begin Clear; Add('uniform float fLightPower; '); Add('uniform float fSpecularPower; '); Add('uniform float fSpecularSpread; '); if UseNormalMap then begin Add('uniform sampler2D bumpMap; '); Add('uniform float fBumpHeight; '); Add('uniform float fBumpSmoothness; '); end; Add(' '); Add('uniform sampler2D baseMap; '); if UseSpecularMap then Add('uniform sampler2D specMap; '); Add(' '); Add('varying vec2 Texcoord; '); Add('varying vec3 ViewDirection; '); Add(' '); Add('varying vec3 fvViewDirection; '); Add('varying vec3 fvNormal; '); Add('varying vec3 fvBinormal; '); Add('varying vec3 fvTangent; '); Add(' '); Add('void main( void ) '); Add('{ '); Add(' vec3 LightDirection;'); Add(' vec3 fvLightDirection; '); Add(' '); if UseNormalMap then Add(' vec3 fvBumpNormal = normalize( ( texture2D( bumpMap, Texcoord ).xyz * fBumpSmoothness) - fBumpHeight * fBumpSmoothness); ') else Add(' vec3 fvBumpNormal = vec3(0.0, 0.0, 1);'); Add(' '); Add(' float fNDotL ; '); Add(' vec3 fvReflection ; '); Add(' float fRDotV ; '); Add(' vec4 fvBaseColor = texture2D( baseMap, Texcoord ); '); if UseSpecularMap then Add(' vec4 fvSpecColor = texture2D( specMap, Texcoord ); ') else Add(' vec4 fvSpecColor = vec4(1.0, 1.0, 1.0, 1.0); '); Add(' vec4 fvNewDiffuse ; '); Add(' vec4 fvTotalDiffuse = vec4(0, 0, 0, 0); '); Add(' vec4 fvTotalAmbient = vec4(0, 0, 0, 0); '); Add(' vec4 fvTotalSpecular = vec4(0, 0, 0, 0); '); end; end; procedure GetMLFragmentProgramCodeMid(const Code: TStrings; const CurrentLight: Integer); begin with Code do begin Add(' fvLightDirection = gl_LightSource[' + IntToStr(CurrentLight) + '].position.xyz - fvViewDirection; '); Add(' '); Add(' LightDirection.x = dot( fvTangent, fvLightDirection ); '); Add(' LightDirection.y = dot( fvBinormal, fvLightDirection ); '); Add(' LightDirection.z = dot( fvNormal, fvLightDirection ); '); Add(' LightDirection = normalize(LightDirection); '); Add(' '); Add(' fNDotL = dot( fvBumpNormal, LightDirection ); '); Add(' fvReflection = normalize( ( (fSpecularSpread * fvBumpNormal ) * fNDotL ) - LightDirection ); '); Add(' fRDotV = max( dot( fvReflection, -ViewDirection ), 0.0 ); '); Add(' fvNewDiffuse = clamp(gl_LightSource[' + IntToStr(CurrentLight) + '].diffuse * fNDotL, 0.0, 1.0); '); Add(' fvTotalDiffuse = min(fvTotalDiffuse + fvNewDiffuse, 1.0); '); Add(' fvTotalSpecular = min(fvTotalSpecular + clamp((pow(fRDotV, fSpecularPower ) ) * (fvNewDiffuse + 0.2) / 1.2 * (fvSpecColor * gl_LightSource[' + IntToStr(CurrentLight) + '].specular), 0.0, 1.0), 1.0); '); Add(' fvTotalAmbient = fvTotalAmbient + gl_LightSource[' + IntToStr(CurrentLight) + '].ambient; '); end; end; procedure GetMLFragmentProgramCodeEnd(const Code: TStrings; const FLightCount: Integer; const FLightCompensation: Single); var Temp: AnsiString; begin with Code do begin Str((1 + (FLightCount - 1) * FLightCompensation) / FLightCount :1 :1, Temp); if (FLightCount = 1) or (FLightCompensation = 1) then Add(' gl_FragColor = fLightPower * (fvBaseColor * ( fvTotalAmbient + fvTotalDiffuse ) + fvTotalSpecular); ') else Add(' gl_FragColor = fLightPower * (fvBaseColor * ( fvTotalAmbient + fvTotalDiffuse ) + fvTotalSpecular) * ' + string(Temp) + '; '); Add('} '); end; end; { TGLBaseCustomGLSLBumpShader } constructor TGLBaseCustomGLSLBumpShader.Create(AOwner: TComponent); begin inherited; FSpecularPower := 6; FSpecularSpread := 1.5; FLightPower := 1; FBumpHeight := 0.5; FBumpSmoothness := 300; TStringList(VertexProgram.Code).OnChange := nil; TStringList(FragmentProgram.Code).OnChange := nil; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; end; procedure TGLBaseCustomGLSLBumpShader.DoApply( var rci: TRenderContextInfo; Sender: TObject); begin // Don't inherit not to call the event. GetGLSLProg.UseProgramObject; Param['fSpecularPower'].AsVector1f := FSpecularPower; Param['fSpecularSpread'].AsVector1f := FSpecularSpread; Param['fLightPower'].AsVector1f := FLightPower; if FSpecularTexture <> nil then Param['specMap'].AsTexture2D[2] := FSpecularTexture; {$IFNDEF GLS_OPTIMIZATIONS} if FNormalTexture <> nil then {$ENDIF} begin Param['bumpMap'].AsTexture2D[1] := FNormalTexture; Param['fBumpHeight'].AsVector1f := FBumpHeight; Param['fBumpSmoothness'].AsVector1f := FBumpSmoothness; end; end; function TGLBaseCustomGLSLBumpShader.DoUnApply( var rci: TRenderContextInfo): Boolean; begin //don't inherit not to call the event Result := False; GetGLSLProg.EndUseProgramObject; end; function TGLBaseCustomGLSLBumpShader.GetMaterialLibrary: TGLAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; function TGLBaseCustomGLSLBumpShader.GetNormalTextureName: TGLLibMaterialName; begin Result := FMaterialLibrary.GetNameOfTexture(FNormalTexture); if Result = '' then Result := FNormalTextureName; end; function TGLBaseCustomGLSLBumpShader.GetSpecularTextureName: TGLLibMaterialName; begin Result := FMaterialLibrary.GetNameOfTexture(FSpecularTexture); if Result = '' then Result := FSpecularTextureName; end; procedure TGLBaseCustomGLSLBumpShader.Notification( AComponent: TComponent; Operation: TOperation); var Index: Integer; begin inherited; if Operation = opRemove then if AComponent = FMaterialLibrary then if FMaterialLibrary <> nil then begin // Need to nil the textures that were ownned by it. if FNormalTexture <> nil then begin Index := FMaterialLibrary.Materials.GetTextureIndex(FNormalTexture); if Index <> -1 then SetNormalTexture(nil); end; if FSpecularTexture <> nil then begin Index := FMaterialLibrary.Materials.GetTextureIndex(FSpecularTexture); if Index <> -1 then SetSpecularTexture(nil); end; FMaterialLibrary := nil; end; end; procedure TGLBaseCustomGLSLBumpShader.SetMaterialLibrary( const Value: TGLMaterialLibrary); begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary := Value; if FMaterialLibrary <> nil then begin FMaterialLibrary.FreeNotification(Self); if FNormalTextureName <> '' then SetNormalTextureName(FNormalTextureName); if FSpecularTextureName <> '' then SetSpecularTextureName(FSpecularTextureName); end else begin FNormalTextureName := ''; FSpecularTextureName := ''; end; end; procedure TGLBaseCustomGLSLBumpShader.SetNormalTexture( const Value: TGLTexture); begin FNormalTexture := Value; FinalizeShader; end; procedure TGLBaseCustomGLSLBumpShader.SetNormalTextureName( const Value: TGLLibMaterialName); begin if FMaterialLibrary = nil then begin FNormalTextureName := Value; if not (csLoading in ComponentState) then raise EGLSLBumpShaderException.Create(glsErrorEx + glsMatLibNotDefined); end else begin SetNormalTexture(FMaterialLibrary.TextureByName(Value)); FNormalTextureName := ''; end; end; procedure TGLBaseCustomGLSLBumpShader.SetSpecularTexture( const Value: TGLTexture); begin FSpecularTexture := Value; FinalizeShader; end; procedure TGLBaseCustomGLSLBumpShader.SetSpecularTextureName( const Value: TGLLibMaterialName); begin if FMaterialLibrary = nil then begin FSpecularTextureName := Value; if not (csLoading in ComponentState) then raise EGLSLBumpShaderException.Create(glsErrorEx + glsMatLibNotDefined); end else begin SetSpecularTexture(FMaterialLibrary.TextureByName(Value)); FSpecularTextureName := ''; end; end; { TGLBaseCustomGLSLBumpShaderMT } function TGLBaseCustomGLSLBumpShaderMT.GetMainTextureName: TGLLibMaterialName; begin Result := FMaterialLibrary.GetNameOfTexture(FMainTexture); if Result = '' then Result := FMainTextureName; end; procedure TGLBaseCustomGLSLBumpShaderMT.Notification( AComponent: TComponent; Operation: TOperation); var Index: Integer; begin if Operation = opRemove then if AComponent = FMaterialLibrary then if FMaterialLibrary <> nil then begin //need to nil the textures that were ownned by it if FMainTexture <> nil then begin Index := FMaterialLibrary.Materials.GetTextureIndex(FMainTexture); if Index <> -1 then FMainTexture := nil; end; end; inherited; end; procedure TGLBaseCustomGLSLBumpShaderMT.SetMainTextureName( const Value: TGLLibMaterialName); begin if FMaterialLibrary = nil then begin FMainTextureName := Value; if not (csLoading in ComponentState) then raise EGLSLBumpShaderException.Create(glsErrorEx + glsMatLibNotDefined); end else begin FMainTexture := FMaterialLibrary.TextureByName(Value); FMainTextureName := ''; end; end; procedure TGLBaseCustomGLSLBumpShaderMT.SetMaterialLibrary( const Value: TGLMaterialLibrary); begin inherited; if FMaterialLibrary <> nil then begin if FMainTextureName <> '' then SetMainTextureName(FMainTextureName); end else FMainTextureName := ''; end; { TGLCustomGLSLBumpShaderAM } constructor TGLCustomGLSLBumpShaderAM.Create(AOwner: TComponent); begin inherited; FAmbientColor := TGLColor.Create(Self); FDiffuseColor := TGLColor.Create(Self); FSpecularColor := TGLColor.Create(Self); // Setup initial parameters. FAmbientColor.SetColor(0.15, 0.15, 0.15, 1); FDiffuseColor.SetColor(1, 1, 1, 1); FSpecularColor.SetColor(1, 1, 1, 1); end; destructor TGLCustomGLSLBumpShaderAM.Destroy; begin FAmbientColor.Destroy; FDiffuseColor.Destroy; FSpecularColor.Destroy; inherited; end; procedure TGLCustomGLSLBumpShaderAM.DoApply(var rci: TRenderContextInfo; Sender: TObject); begin inherited; Param['fvAmbient'].AsVector4f := FAmbientColor.Color; Param['fvDiffuse'].AsVector4f := FDiffuseColor.Color; Param['fvSpecular'].AsVector4f := FSpecularColor.Color; Param['baseMap'].AsTexture2D[0] := FMainTexture; end; procedure TGLCustomGLSLBumpShaderAM.DoInitialize(var rci : TRenderContextInfo; Sender : TObject); begin GetVertexProgramCode(VertexProgram.Code); GetFragmentProgramCodeMP(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; function TGLCustomGLSLBumpShaderAM.GetAlpha: Single; begin Result := (FAmbientColor.Alpha + FDiffuseColor.Alpha + FSpecularColor.Alpha) / 3; end; procedure TGLCustomGLSLBumpShaderAM.SetAlpha(const Value: Single); begin FAmbientColor.Alpha := Value; FDiffuseColor.Alpha := Value; FSpecularColor.Alpha := Value; end; { TGLCustomGLSLMLBumpShaderMT } constructor TGLCustomGLSLMLBumpShaderMT.Create(AOwner: TComponent); begin inherited; FLightSources := [1]; FLightCompensation := 1; end; procedure TGLCustomGLSLMLBumpShaderMT.DoApply(var rci: TRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsTexture2D[0] := FMainTexture; end; procedure TGLCustomGLSLMLBumpShaderMT.DoInitialize(var rci : TRenderContextInfo; Sender : TObject); var I: Integer; lLightCount: Integer; begin GetMLVertexProgramCode(VertexProgram.Code); with FragmentProgram.Code do begin GetMLFragmentProgramCodeBeg(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); lLightCount := 0; // Repeat for all lights. for I := 0 to glsShaderMaxLightSources - 1 do if I + 1 in FLightSources then begin GetMLFragmentProgramCodeMid(FragmentProgram.Code, I); Inc(lLightCount); end; GetMLFragmentProgramCodeEnd(FragmentProgram.Code, lLightCount, FLightCompensation); end; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; procedure TGLCustomGLSLMLBumpShaderMT.SetLightCompensation( const Value: Single); begin FLightCompensation := Value; FinalizeShader; end; procedure TGLCustomGLSLMLBumpShaderMT.SetLightSources( const Value: TGLLightSourceSet); begin Assert(Value <> [], glsErrorEx + glsShaderNeedsAtLeastOneLightSource); FLightSources := Value; FinalizeShader; end; { TGLCustomGLSLBumpShaderMT } procedure TGLCustomGLSLBumpShaderMT.DoApply( var rci: TRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsTexture2D[0] := FMainTexture; end; procedure TGLCustomGLSLBumpShaderMT.DoInitialize(var rci : TRenderContextInfo; Sender : TObject); begin GetVertexProgramCode(VertexProgram.Code); GetFragmentProgramCode(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); inherited; end; { TGLCustomGLSLBumpShader } procedure TGLCustomGLSLBumpShader.DoApply(var rci: TRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsVector1i := 0; // Use the current texture. end; procedure TGLCustomGLSLBumpShader.DoInitialize(var rci : TRenderContextInfo; Sender : TObject); begin GetVertexProgramCode(VertexProgram.Code); GetFragmentProgramCode(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; function TGLCustomGLSLBumpShader.GetShaderAlpha: Single; begin //ignore Result := -1; end; procedure TGLCustomGLSLBumpShader.GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore AAmbientColor := NullHmgVector; ADiffuseColor := NullHmgVector; ASpecularcolor := NullHmgVector; end; procedure TGLCustomGLSLBumpShader.GetShaderTextures( var Textures: array of TGLTexture); begin Textures[0] := FNormalTexture; Textures[1] := FSpecularTexture; end; procedure TGLCustomGLSLBumpShader.GetShaderMiscParameters(var ACadencer: TGLCadencer; var AMatLib: TGLMaterialLibrary; var ALightSources: TGLLightSourceSet); begin ACadencer := nil; AMatLib := FMaterialLibrary; ALightSources := [0]; end; procedure TGLCustomGLSLBumpShader.SetShaderAlpha(const Value: Single); begin //ignore end; procedure TGLCustomGLSLBumpShader.SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore end; procedure TGLCustomGLSLBumpShader.SetShaderMiscParameters( const ACadencer: TGLCadencer; const AMatLib: TGLMaterialLibrary; const ALightSources: TGLLightSourceSet); begin SetMaterialLibrary(AMatLib); end; procedure TGLCustomGLSLBumpShader.SetShaderTextures( const Textures: array of TGLTexture); begin SetNormalTexture(Textures[0]); SetSpecularTexture(Textures[1]); end; function TGLCustomGLSLBumpShader.GetShaderDescription: string; begin Result := 'ShaderTexture1 is NormalMap, ShaderTexture2 is SpecularMap' end; { TGLCustomGLSLMLBumpShader } constructor TGLCustomGLSLMLBumpShader.Create(AOwner: TComponent); begin inherited; FLightSources := [1]; FLightCompensation := 1; end; procedure TGLCustomGLSLMLBumpShader.DoApply(var rci: TRenderContextInfo; Sender: TObject); begin inherited; Param['baseMap'].AsVector1i := 0; // Use the current texture. end; procedure TGLCustomGLSLMLBumpShader.DoInitialize(var rci : TRenderContextInfo; Sender : TObject); var I: Integer; lLightCount: Integer; begin GetMLVertexProgramCode(VertexProgram.Code); with FragmentProgram.Code do begin GetMLFragmentProgramCodeBeg(FragmentProgram.Code, FSpecularTexture <> nil, FNormalTexture <> nil); lLightCount := 0; // Repeat for all lights. for I := 0 to glsShaderMaxLightSources - 1 do if I + 1 in FLightSources then begin GetMLFragmentProgramCodeMid(FragmentProgram.Code, I); Inc(lLightCount); end; GetMLFragmentProgramCodeEnd(FragmentProgram.Code, lLightCount, FLightCompensation); end; VertexProgram.Enabled := True; FragmentProgram.Enabled := True; inherited; end; procedure TGLCustomGLSLMLBumpShader.SetLightCompensation( const Value: Single); begin FLightCompensation := Value; FinalizeShader; end; procedure TGLCustomGLSLMLBumpShader.SetLightSources( const Value: TGLLightSourceSet); begin Assert(Value <> [], glsErrorEx + glsShaderNeedsAtLeastOneLightSource); FLightSources := Value; FinalizeShader; end; function TGLCustomGLSLMLBumpShader.GetShaderAlpha: Single; begin //ignore Result := -1; end; procedure TGLCustomGLSLMLBumpShader.GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore AAmbientColor := NullHmgVector; ADiffuseColor := NullHmgVector; ASpecularcolor := NullHmgVector; end; function TGLCustomGLSLMLBumpShader.GetShaderDescription: string; begin Result := 'ShaderTexture1 is NormalMap, ShaderTexture2 is SpecularMap'; end; procedure TGLCustomGLSLMLBumpShader.GetShaderMiscParameters( var ACadencer: TGLCadencer; var AMatLib: TGLMaterialLibrary; var ALightSources: TGLLightSourceSet); begin ACadencer := nil; AMatLib := FMaterialLibrary; ALightSources := FLightSources; end; procedure TGLCustomGLSLMLBumpShader.GetShaderTextures( var Textures: array of TGLTexture); begin Textures[0] := FNormalTexture; Textures[1] := FSpecularTexture; end; procedure TGLCustomGLSLMLBumpShader.SetShaderAlpha(const Value: Single); begin //ignore end; procedure TGLCustomGLSLMLBumpShader.SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f); begin //ignore end; procedure TGLCustomGLSLMLBumpShader.SetShaderMiscParameters( const ACadencer: TGLCadencer; const AMatLib: TGLMaterialLibrary; const ALightSources: TGLLightSourceSet); begin SetMaterialLibrary(AMatLib); SetLightSources(ALightSources); end; procedure TGLCustomGLSLMLBumpShader.SetShaderTextures( const Textures: array of TGLTexture); begin SetNormalTexture(Textures[0]); SetSpecularTexture(Textures[1]); end; initialization RegisterClasses([TGLSLBumpShaderMT, TGLSLBumpShader, TGLSLBumpShaderAM, TGLSLMLBumpShader, TGLSLMLBumpShaderMT]); end.
{******************************************} { TeeChart Pro VML Canvas and Exporting } { VML : Vector Markup Language } { Copyright (c) 2001-2004 by David Berneda } { All Rights Reserved } {******************************************} unit TeeVMLCanvas; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, {$ENDIF} Classes, {$IFDEF CLX} QGraphics, QForms, Types, {$ELSE} Graphics, Forms, {$ENDIF} TeCanvas, TeeProcs, TeeExport; type TVMLCanvas = class(TTeeCanvas3D) private { Private declarations } FBackColor : TColor; FBackMode : TCanvasBackMode; FTextAlign : TCanvasTextAlign; FX : Integer; FY : Integer; FStrings : TStrings; // IPenEndStyle : TPenEndStyle; IPenStyle : TPenStyle; IPenWidth : Integer; ITransp : TTeeTransparency; Procedure Add(Const S:String); procedure ChangedPen(Sender: TObject); Procedure InternalRect(Const Rect:TRect; UsePen,IsRound:Boolean); Function PointToStr(X,Y:Integer):String; Function PrepareShape:String; Function TheBounds:String; protected { Protected declarations } Procedure PolygonFour; override; { 2d } procedure SetPixel(X, Y: Integer; Value: TColor); override; Function GetTextAlign:TCanvasTextAlign; override; { 3d } procedure SetPixel3D(X,Y,Z:Integer; Value: TColor); override; Procedure SetBackMode(Mode:TCanvasBackMode); override; Function GetMonochrome:Boolean; override; Procedure SetMonochrome(Value:Boolean); override; Procedure SetBackColor(Color:TColor); override; Function GetBackMode:TCanvasBackMode; override; Function GetBackColor:TColor; override; procedure SetTextAlign(Align:TCanvasTextAlign); override; Function VmlPen(const Element:String):String; public { Public declarations } Constructor Create(AStrings:TStrings); Function InitWindow( DestCanvas:TCanvas; A3DOptions:TView3DOptions; ABackColor:TColor; Is3D:Boolean; Const UserRect:TRect):TRect; override; procedure AssignVisiblePenColor(APen:TPen; AColor:TColor); override; // 7.0 procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override; procedure Draw(X, Y: Integer; Graphic: TGraphic); override; procedure FillRect(const Rect: TRect); override; procedure Ellipse(X1, Y1, X2, Y2: Integer); override; procedure LineTo(X,Y:Integer); override; procedure MoveTo(X,Y:Integer); override; procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override; procedure Rectangle(X0,Y0,X1,Y1:Integer); reintroduce; override; procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); override; procedure StretchDraw(const Rect: TRect; Graphic: TGraphic); override; Procedure TextOut(X,Y:Integer; const Text:String); override; Procedure DoHorizLine(X0,X1,Y:Integer); override; Procedure DoVertLine(X,Y0,Y1:Integer); override; procedure ClipRectangle(Const Rect:TRect); override; procedure ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer); override; procedure UnClipRectangle; override; Procedure GradientFill( Const Rect:TRect; StartColor,EndColor:TColor; Direction:TGradientDirection; Balance:Integer=50); override; procedure RotateLabel(x,y:Integer; Const St:String; RotDegree:Double); override; procedure RotateLabel3D(x,y,z:Integer; Const St:String; RotDegree:Double); override; Procedure Line(X0,Y0,X1,Y1:Integer); override; Procedure Polygon(const Points: array of TPoint); override; Procedure Polyline(const Points: {$IFDEF D5}Array of TPoint{$ELSE}TPointArray{$ENDIF}); override; Function BeginBlending(const R:TRect; Transparency:TTeeTransparency):TTeeBlend; override; procedure EndBlending(Blend:TTeeBlend); override; { 3d } Procedure ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect); override; procedure EllipseWithZ(X1, Y1, X2, Y2, Z:Integer); override; Procedure HorizLine3D(Left,Right,Y,Z:Integer); override; procedure LineTo3D(X,Y,Z:Integer); override; Procedure LineWithZ(X0,Y0,X1,Y1,Z:Integer); override; procedure MoveTo3D(X,Y,Z:Integer); override; Procedure TextOut3D(X,Y,Z:Integer; const Text:String); override; Procedure VertLine3D(X,Top,Bottom,Z:Integer); override; Procedure ZLine3D(X,Y,Z0,Z1:Integer); override; published end; TVMLExportFormat=class(TTeeExportFormat) private protected Procedure DoCopyToClipboard; override; public function Description:String; override; function FileExtension:String; override; function FileFilter:String; override; Function VML:TStringList; Function Options(Check:Boolean=True):TForm; override; Procedure SaveToStream(Stream:TStream); override; end; procedure TeeSaveToVMLFile( APanel:TCustomTeePanel; const FileName: WideString; AWidth:Integer=0; AHeight: Integer=0); implementation Uses {$IFDEF CLX} QClipbrd, {$ELSE} Clipbrd, {$ENDIF} TeeConst, SysUtils; { TVMLCanvas } Constructor TVMLCanvas.Create(AStrings:TStrings); begin inherited Create; FStrings:=AStrings; UseBuffer:=False; { start } Add('<xml:namespace prefix="v"/>'); Add('<style>v\:* {behavior=url(#default#VML)}</style>'); end; Procedure TVMLCanvas.ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect); begin { finish } Add('</v:group>'); Pen.OnChange:=nil; end; Procedure TVMLCanvas.Add(Const S:String); begin FStrings.Add(S); end; Function VMLColorInternal(AColor:TColor):String; begin AColor:=ColorToRGB(AColor); case AColor of clBlack: result:='black'; clWhite: result:='white'; clRed: result:='red'; clGreen: result:='green'; clBlue: result:='blue'; clYellow: result:='yellow'; clGray: result:='gray'; clNavy: result:='navy'; clOlive: result:='olive'; clLime: result:='lime'; clTeal: result:='teal'; clSilver: result:='silver'; clPurple: result:='purple'; clFuchsia: result:='fuchsia'; clMaroon: result:='maroon'; else begin result:='#'+IntToHex(GetRValue(AColor),2)+ IntToHex(GetGValue(AColor),2)+ IntToHex(GetBValue(AColor),2); if result='#000000' then result:='#0'; end; end; end; Function VMLColor(AColor:TColor):String; begin result:='"'+VMLColorInternal(AColor)+'"'; end; procedure TVMLCanvas.Rectangle(X0,Y0,X1,Y1:Integer); begin InternalRect(TeeRect(X0,Y0,X1,Y1),True,False); end; procedure TVMLCanvas.MoveTo(X, Y: Integer); begin FX:=X; FY:=Y; end; procedure TVMLCanvas.AssignVisiblePenColor(APen:TPen; AColor:TColor); begin IPenStyle:=APen.Style; IPenWidth:=APen.Width; Pen.OnChange:=nil; inherited; Pen.OnChange:=ChangedPen; end; Function TVMLCanvas.VmlPen(const Element:String):String; Function IsSmallDots:Boolean; begin result:=(Pen is TChartPen) and TChartPen(Pen).SmallDots; end; Function PenStyle:String; begin if IsSmallDots then result:='dot' else Case IPenStyle of psSolid: ; psDash: result:='dash'; psDot: result:='dot'; psDashDot: result:='dashdot'; psDashDotDot: result:='longdashdotdot'; end; end; function PenWidth(const Element:String):String; begin if IPenWidth>1 then result:=' '+Element+'="'+TeeStr(IPenWidth)+'" ' else result:=''; end; begin result:='" strokecolor='+VMLColor(Pen.Color); if (IPenStyle<>psSolid) or IsSmallDots then result:=result+'><v:stroke dashstyle="'+PenStyle+'"'+PenWidth('weight')+'/></v:'+Element+'>' else result:=result+PenWidth('strokeweight')+'/>'; end; procedure TVMLCanvas.LineTo(X, Y: Integer); begin Add('<v:line from="'+PointToStr(FX,FY)+'" to="'+PointToStr(X,Y)+VmlPen('line')); FX:=X; FY:=Y; end; procedure TVMLCanvas.ClipRectangle(Const Rect:TRect); begin end; procedure TVMLCanvas.ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer); begin end; procedure TVMLCanvas.UnClipRectangle; begin end; function TVMLCanvas.GetBackColor:TColor; begin result:=FBackColor; end; procedure TVMLCanvas.SetBackColor(Color:TColor); begin FBackColor:=Color; end; procedure TVMLCanvas.SetBackMode(Mode:TCanvasBackMode); begin FBackMode:=Mode; end; Function TVMLCanvas.GetMonochrome:Boolean; begin result:=False; end; Procedure TVMLCanvas.SetMonochrome(Value:Boolean); begin end; procedure TVMLCanvas.StretchDraw(const Rect: TRect; Graphic: TGraphic); begin end; procedure TVMLCanvas.Draw(X, Y: Integer; Graphic: TGraphic); begin end; Function TVMLCanvas.TheBounds:String; begin result:='width:'+IntToStr(Bounds.Right-Bounds.Left)+ ';height:'+IntToStr(Bounds.Bottom-Bounds.Top); end; Function TVMLCanvas.PointToStr(X,Y:Integer):String; begin result:=IntToStr(X)+','+IntToStr(Y); end; Procedure TVMLCanvas.GradientFill( Const Rect:TRect; StartColor,EndColor:TColor; Direction:TGradientDirection; Balance:Integer=50); var TheAngle : Integer; begin Case Direction of gdTopBottom : TheAngle:=180; gdBottomTop : TheAngle:=0; gdLeftRight : TheAngle:=270; gdRightLeft : TheAngle:=90; gdFromCenter : TheAngle:=0; { to-do } gdFromTopLeft: TheAngle:=315; else TheAngle:=225; { gdFromBottomLeft } end; Add('<v:shape style="position:absolute;'+TheBounds+';" stroked="f">'); Add(' <v:path v="M '+PointToStr(Rect.Left,Rect.Top)+' L '+ PointToStr(Rect.Right,Rect.Top)+' '+ PointToStr(Rect.Right,Rect.Bottom)+' '+ PointToStr(Rect.Left,Rect.Bottom)+' X E"/>'); Add(' <v:fill type="gradient" color='+VMLColor(StartColor)+' color2='+VMLColor(EndColor)); if ITransp<>0 then Add(' opacity="'+FloatToStr((100-ITransp)*0.01)+'"'); Add(' method="sigma" angle="'+IntToStr(TheAngle)+'" focus="100%"/>'); Add('</v:shape>'); end; procedure TVMLCanvas.FillRect(const Rect: TRect); begin InternalRect(Rect,False,False); end; Procedure TVMLCanvas.InternalRect(Const Rect:TRect; UsePen,IsRound:Boolean); var tmp : String; tmpElement : String; tmpR : TRect; begin if (Brush.Style<>bsClear) or (UsePen and (Pen.Style<>psClear)) then begin tmp:='<v:'; if IsRound then tmpElement:='roundrect' else tmpElement:='rect'; tmp:=tmp+tmpElement; tmpR:=OrientRectangle(Rect); tmp:=tmp+' style="position:absolute;left:'+ TeeStr(tmpR.Left)+';top:'+TeeStr(tmpR.Top)+';width:'+ TeeStr(tmpR.Right-tmpR.Left-1)+';height:'+ TeeStr(tmpR.Bottom-tmpR.Top-1)+'"'; if Brush.Style<>bsClear then tmp:=tmp+' fillcolor='+VMLColor(Brush.Color) else tmp:=tmp+' filled="false"'; if UsePen and (Pen.Style<>psClear) then tmp:=tmp+' strokecolor='+VMLColor(Pen.Color) else tmp:=tmp+' stroked="f"'; if ITransp<>0 then tmp:=tmp+' opacity="'+FloatToStr((100-ITransp)*0.01)+'"'; Add(tmp+VmlPen(tmpElement)); end; end; procedure TVMLCanvas.Ellipse(X1, Y1, X2, Y2: Integer); begin EllipseWithZ(X1,Y1,X2,Y2,0); end; procedure TVMLCanvas.EllipseWithZ(X1, Y1, X2, Y2, Z: Integer); begin Calc3DPos(X1,Y1,Z); Calc3DPos(X2,Y2,Z); if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then Add('<v:oval style="position:absolute;left:'+IntToStr(X1)+';top:'+IntToStr(Y1)+ ';height:'+IntToStr(Y2-Y1)+';width:'+IntToStr(X2-X1)+'" fillcolor='+ VMLColor(Brush.Color)+VmlPen('oval')); end; procedure TVMLCanvas.SetPixel3D(X,Y,Z:Integer; Value: TColor); begin if Pen.Style<>psClear then begin Calc3DPos(x,y,z); Pen.Color:=Value; MoveTo(x,y); LineTo(x,y); end; end; procedure TVMLCanvas.SetPixel(X, Y: Integer; Value: TColor); begin if Pen.Style<>psClear then begin Pen.Color:=Value; MoveTo(x,y); LineTo(x,y); end; end; procedure TVMLCanvas.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); var tmpSt : String; begin if Pen.Style<>psClear then begin PrepareShape; tmpSt:=' <v:path v="ar '; tmpSt:=tmpSt+PointToStr(X1,Y1)+' '+PointToStr(X2,Y2)+' '+ PointToStr(X3,Y3)+' '+PointToStr(X4,Y4); Add(tmpSt+' e"/>'); Add('</v:shape>'); end; end; procedure TVMLCanvas.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); var tmpSt : String; begin if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then begin PrepareShape; tmpSt:=' <v:path v="m '+PointToStr((X2+X1) div 2,(Y2+Y1) div 2)+' at '; tmpSt:=tmpSt+PointToStr(X1,Y1)+' '+PointToStr(X2,Y2)+' '+ PointToStr(X3,Y3)+' '+PointToStr(X4,Y4); Add(tmpSt+' x e"/>'); Add('</v:shape>'); end; end; procedure TVMLCanvas.RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); begin InternalRect(TeeRect(X1,Y1,X2,Y2),True,True); end; Procedure TVMLCanvas.TextOut3D(X,Y,Z:Integer; const Text:String); Function FontStyle:String; begin if Font.Style=[] then result:='' else begin result:=''; if fsBold in Font.Style then result:=' font-weight=bold;'; if fsItalic in Font.Style then result:=result+' font-style=italic;'; if fsUnderline in Font.Style then result:=result+' text-decoration=underline;'; if fsStrikeOut in Font.Style then result:=result+' text-decoration=line-through;'; end; end; Procedure DoText(AX,AY:Integer; AColor:TColor); begin if (TextAlign and TA_CENTER)=TA_CENTER then Dec(AX,TextWidth(Text) div 2) else if (TextAlign and TA_RIGHT)=TA_RIGHT then Dec(AX,TextWidth(Text)); Inc(AX); Inc(AY); Add('<v:textbox style="position:absolute; left:'+IntToStr(AX)+'; top:'+IntToStr(AY)+ '; color:'+VMLColorInternal(AColor)+'; text-align:left; '+ ' font-family:'+Font.Name+'; font-size:'+TeeStr(Round(Font.Size*1.4))+'; '+FontStyle+'">'); Add(Text); Add('</v:textbox>'); end; Var tmpX : Integer; tmpY : Integer; begin Calc3DPos(x,y,z); if Assigned(IFont) then With IFont.Shadow do if (HorizSize<>0) or (VertSize<>0) then begin if HorizSize<0 then begin tmpX:=X; X:=X-HorizSize; end else tmpX:=X+HorizSize; if VertSize<0 then begin tmpY:=Y; Y:=Y-VertSize; end else tmpY:=Y+VertSize; DoText(tmpX,tmpY,IFont.Shadow.Color) end; DoText(X,Y,IFont.Color); end; Procedure TVMLCanvas.TextOut(X,Y:Integer; const Text:String); begin TextOut3D(x,y,0,Text); end; procedure TVMLCanvas.MoveTo3D(X,Y,Z:Integer); begin Calc3DPos(x,y,z); MoveTo(x,y); end; procedure TVMLCanvas.LineTo3D(X,Y,Z:Integer); begin Calc3DPos(x,y,z); LineTo(x,y); end; Function TVMLCanvas.GetTextAlign:TCanvasTextAlign; begin result:=FTextAlign; end; Procedure TVMLCanvas.DoHorizLine(X0,X1,Y:Integer); begin MoveTo(X0,Y); LineTo(X1,Y); end; Procedure TVMLCanvas.DoVertLine(X,Y0,Y1:Integer); begin MoveTo(X,Y0); LineTo(X,Y1); end; procedure TVMLCanvas.RotateLabel3D(x,y,z:Integer; Const St:String; RotDegree:Double); begin //TODO: RotDegree rotation Calc3DPos(x,y,z); TextOut(X,Y,St); end; procedure TVMLCanvas.RotateLabel(x,y:Integer; Const St:String; RotDegree:Double); begin RotateLabel3D(x,y,0,St,RotDegree); end; Procedure TVMLCanvas.Line(X0,Y0,X1,Y1:Integer); begin MoveTo(X0,Y0); LineTo(X1,Y1); end; Procedure TVMLCanvas.HorizLine3D(Left,Right,Y,Z:Integer); begin MoveTo3D(Left,Y,Z); LineTo3D(Right,Y,Z); end; Procedure TVMLCanvas.VertLine3D(X,Top,Bottom,Z:Integer); begin MoveTo3D(X,Top,Z); LineTo3D(X,Bottom,Z); end; Procedure TVMLCanvas.ZLine3D(X,Y,Z0,Z1:Integer); begin MoveTo3D(X,Y,Z0); LineTo3D(X,Y,Z1); end; Procedure TVMLCanvas.LineWithZ(X0,Y0,X1,Y1,Z:Integer); begin MoveTo3D(X0,Y0,Z); LineTo3D(X1,Y1,Z); end; Function TVMLCanvas.GetBackMode:TCanvasBackMode; begin result:=FBackMode; end; Procedure TVMLCanvas.PolygonFour; begin Polygon(IPoints); end; Function TVMLCanvas.PrepareShape:String; begin result:='<v:shape style="position:absolute;'+TheBounds+'"'; if Brush.Style<>bsClear then result:=result+' fillcolor='+VMLColor(Brush.Color) else result:=result+' filled="f"'; if Pen.Style=psClear then result:=result+' stroked="f"' else result:=result+' strokecolor='+VMLColor(Pen.Color); Add(result+'>'); end; Procedure TVMLCanvas.Polygon(const Points: Array of TPoint); var tmpSt : String; t : Integer; begin if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then begin PrepareShape; tmpSt:=' <v:path v="m '+PointToStr(Points[0].X,Points[0].Y)+' l '; for t:=1 to High(Points) do tmpSt:=tmpSt+PointToStr(Points[t].X,Points[t].Y)+' '; Add(tmpSt+' x e"/>'); Add('</v:shape>'); end; end; Procedure TVMLCanvas.Polyline(const Points: {$IFDEF D5}Array of TPoint{$ELSE}TPointArray{$ENDIF}); var tmpSt : String; t : Integer; begin if Pen.Style<>psClear then begin PrepareShape; tmpSt:=' <v:path v="m '+PointToStr(Points[0].X,Points[0].Y)+' l '; for t:=1 to High(Points) do tmpSt:=tmpSt+PointToStr(Points[t].X,Points[t].Y)+' '; Add(tmpSt+' e"/>'); Add('</v:shape>'); end; end; function TVMLCanvas.InitWindow(DestCanvas: TCanvas; A3DOptions: TView3DOptions; ABackColor: TColor; Is3D: Boolean; const UserRect: TRect): TRect; begin result:=inherited InitWindow(DestCanvas,A3DOptions,ABackColor,Is3D,UserRect); Add('<v:group style="'+TheBounds+ '" coordsize="'+ PointToStr(Bounds.Right-Bounds.Left,Bounds.Bottom-Bounds.Top)+'"'+ ' coordorigin="'+PointToStr(Bounds.Top,Bounds.Left)+ '">'); Pen.OnChange:=ChangedPen; end; procedure TVMLCanvas.ChangedPen(Sender: TObject); begin IPenStyle:=Pen.Style; IPenWidth:=Pen.Width; end; procedure TVMLCanvas.SetTextAlign(Align: TCanvasTextAlign); begin FTextAlign:=Align; end; function TVMLCanvas.BeginBlending(const R: TRect; Transparency: TTeeTransparency): TTeeBlend; begin ITransp:=Transparency; result:=nil; end; procedure TVMLCanvas.EndBlending(Blend: TTeeBlend); begin // reset to zero ITransp:=0; end; { TVMLExportFormat } function TVMLExportFormat.Description: String; begin result:=TeeMsg_AsVML; end; procedure TVMLExportFormat.DoCopyToClipboard; begin with VML do try Clipboard.AsText:=Text; finally Free; end; end; function TVMLExportFormat.FileExtension: String; begin result:='HTM'; end; function TVMLExportFormat.FileFilter: String; begin result:=TeeMsg_VMLFilter; end; function TVMLExportFormat.Options(Check:Boolean=True): TForm; begin result:=nil; end; procedure TVMLExportFormat.SaveToStream(Stream: TStream); begin with VML do try SaveToStream(Stream); finally Free; end; end; type TTeePanelAccess=class(TCustomTeePanel); // Returns a panel or chart in VML format into a StringList function TVMLExportFormat.VML: TStringList; var tmp : TCanvas3D; begin CheckSize; result:=TStringList.Create; Panel.AutoRepaint:=False; try {$IFNDEF CLR} // Protected across assemblies tmp:=TTeePanelAccess(Panel).InternalCanvas; TTeePanelAccess(Panel).InternalCanvas:=nil; {$ENDIF} Panel.Canvas:=TVMLCanvas.Create(result); try Panel.Draw(Panel.Canvas.ReferenceCanvas,TeeRect(0,0,Width,Height)); { insert html headings at top } result.Insert(0,'<!-- Generated by TeeChart Pro Version '+TeeChartVersion+' -->'); result.Insert(0,'<body>'); result.Insert(0,'<html>'); { add html headings at bottom } result.Add('</body>'); result.Add('</html>'); finally {$IFNDEF CLR} // Protected across assemblies Panel.Canvas:=tmp; {$ENDIF} end; finally Panel.AutoRepaint:=True; end; end; procedure TeeSaveToVMLFile( APanel:TCustomTeePanel; const FileName: WideString; AWidth:Integer=0; AHeight: Integer=0); begin { save panel or chart to filename in VML (html) format } with TVMLExportFormat.Create do try Panel:=APanel; Height:=AHeight; Width:=AWidth; SaveToFile(FileName); finally Free; end; end; initialization RegisterTeeExportFormat(TVMLExportFormat); finalization UnRegisterTeeExportFormat(TVMLExportFormat); end.
unit Unit1; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, //GLS GLScene, GLObjects, GLTeapot, GLTexture, GLPhongShader, GLWin32Viewer, GLAsyncTimer, GLCadencer, GLCustomShader, GLAsmShader, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLMaterialLibrary1: TGLMaterialLibrary; GLPhongShader1: TGLPhongShader; GLCamera1: TGLCamera; GLTeapot1: TGLTeapot; GLDummyCube1: TGLDummyCube; GLLightSource1: TGLLightSource; GLCadencer1: TGLCadencer; AsyncTimer1: TGLAsyncTimer; CheckBox1: TCheckBox; procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure AsyncTimer1Timer(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); private { Private declarations } public { Public declarations } mx, my : Integer; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx:=x; my:=y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if ssLeft in Shift then GLCamera1.MoveAroundTarget(my-y, mx-x); mx:=x; my:=y; end; procedure TForm1.AsyncTimer1Timer(Sender: TObject); begin Form1.Caption:='Phong Shader - '+GLSceneViewer1.FramesPerSecondText; GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin GLPhongShader1.Enabled:=CheckBox1.Checked; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin CheckBox1.Checked:=GLPhongShader1.Enabled; GLSceneViewer1.Invalidate; end; end.
unit Test.Devices.Mercury.ReqCreator; interface uses TestFrameWork, GMGlobals, Classes, SysUtils, Devices.Mercury, Math, Test.Devices.Base.ReqCreator, GMConst, DateUtils, Windows; type TMercury230ReqCreatorForTest = class(TMercury230ReqCreator) protected procedure CheckDevStates; override; function NeedRequestLastArchAddr: bool; override; function CanRequestArchives: bool; override; function NeedRequestMeterInfo: bool; override; end; TMercury230ReqCreatorForTestArch = class(TMercury230ReqCreator) protected procedure CheckDevStates; override; function NeedRequestLastArchAddr: bool; override; function NeedRequestMeterInfo: bool; override; end; TMercury230ReqCreatorTest = class(TDeviceReqCreatorTestBase) private mercuryRecCreator: TMercury230ReqCreatorForTest; mercuryRecCreatorArch: TMercury230ReqCreatorForTestArch; protected procedure SetUp; override; procedure TearDown; override; function GetDevType(): int; override; procedure DoCheckRequests(); override; published procedure OpenChannel; procedure RequestReadings; procedure MeterInfoRequest; procedure LastArchAddrRequest; procedure Archives(); procedure Archives_Utils(); end; implementation { TMercury230ReqCreatorTest } procedure TMercury230ReqCreatorTest.RequestReadings; var buf: ArrayOfByte; s: string; begin buf := mercuryRecCreator.ReadingsRequest(); s := ArrayToString(buf, Length(buf), false, true); Check(s = '31 05 00 00 1E D9'); end; procedure TMercury230ReqCreatorTest.DoCheckRequests; begin CheckReqHexString(0, '1C, 1, 1, 1, 1, 1, 1, 1, 1, EF, 41'); CheckReqHexString(1, '1C, 8, 12, 37, CB'); CheckReqHexString(2, '1C, 5, 0, 0, 17, B5'); CheckReqHexString(3, '$1C, 8, $13, $F6, $B'); end; function TMercury230ReqCreatorTest.GetDevType: int; begin Result := DEVTYPE_MERCURY_230; end; procedure TMercury230ReqCreatorTest.LastArchAddrRequest; var buf: ArrayOfByte; s: string; begin buf := mercuryRecCreator.LastArchAddrRequest(); s := ArrayToString(buf, Length(buf), false, true); Check(s = '31 08 13 66 02'); end; procedure TMercury230ReqCreatorTest.MeterInfoRequest; var buf: ArrayOfByte; s: string; begin buf := mercuryRecCreator.MeterInfoRequest(); s := ArrayToString(buf, Length(buf), false, true); Check(s = '31 08 12 A7 C2'); end; procedure TMercury230ReqCreatorTest.OpenChannel; var buf: ArrayOfByte; s: string; begin buf := mercuryRecCreator.OpenChannelRequest(); s := ArrayToString(buf, Length(buf), false, true); Check(s = '31 01 01 01 01 01 01 01 01 2E 10'); end; procedure TMercury230ReqCreatorTest.SetUp; var RecDetails: TRequestDetails; begin inherited; RecDetails.Init(); RecDetails.DevNumber := 49; mercuryRecCreator := TMercury230ReqCreatorForTest.Create(nil, RecDetails); mercuryRecCreatorArch := TMercury230ReqCreatorForTestArch.Create(ArchRequest, RecDetails); end; procedure TMercury230ReqCreatorTest.TearDown; begin inherited; mercuryRecCreator.Free(); mercuryRecCreatorArch.Free(); end; { TMercury230ReqCreatorForTest } function TMercury230ReqCreatorForTest.CanRequestArchives: bool; begin Result := false; end; procedure TMercury230ReqCreatorForTest.CheckDevStates; begin // ничего не делаем end; function TMercury230ReqCreatorForTest.NeedRequestLastArchAddr: bool; begin Result := true; end; function TMercury230ReqCreatorForTest.NeedRequestMeterInfo: bool; begin Result := true; end; procedure TMercury230ReqCreatorTest.Archives; begin mercuryRecCreatorArch.AddArchiveRequestsToSendBuf(); Check(ReqList.Count = 48 * 20); CheckReqHexString(0, '31, 6, 3, AF, 40, F, CD, 9B'); CheckReqHexString(48 * 20 - 1, '31, 6, 3, EB, 30, F, A8, 4E'); end; procedure TMercury230ReqCreatorTest.Archives_Utils(); begin Check(mercuryRecCreatorArch.ArchRecordAddr(mercuryRecCreatorArch.LastArchUtime) = mercuryRecCreatorArch.LastArchAddr); Check(mercuryRecCreatorArch.ArchRecordAddr(mercuryRecCreatorArch.LastArchUtime - UTC_HOUR) = mercuryRecCreatorArch.LastArchAddr - $20); Check(mercuryRecCreatorArch.ArchRecordAddr(EncodeDateTimeUTC(2001, 01, 01)) = 0); Check(mercuryRecCreatorArch.ArchRecordAddr(EncodeDateTimeUTC(YearOf(Now()) + 1, 01, 01)) = 0); end; { TMercury230ReqCreatorForTestArch } procedure TMercury230ReqCreatorForTestArch.CheckDevStates; begin LastArchAddr := $EB30; LastArchUtime := EncodeDateTimeUTC(YearOf(Now()), MonthOf(Now()), DayOf(Now())) - UTC_HALFHOUR; end; function TMercury230ReqCreatorForTestArch.NeedRequestLastArchAddr: bool; begin Result := false; end; function TMercury230ReqCreatorForTestArch.NeedRequestMeterInfo: bool; begin Result := false; end; initialization RegisterTest('GMIOPSrv/Devices/Mercury230', TMercury230ReqCreatorTest.Suite); end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLSLPostBlurShader <p> A shader that blurs the entire scene.<p> <b>History : </b><font size=-1><ul> <li>22/04/10 - Yar - Fixes after GLState revision < Added GLVectorTypes to uses <li>16/04/07 - DaStr - Shader made ATI compatible <li>05/04/07 - DaStr - Initial version (contributed to GLScene) Previous version history: v1.0 04 November '2006 Creation (based on RenderMonkey demo) v1.1 04 March '2007 IGLPostShader support added v1.2 30 March '2007 TGLCustomGLSLPostBlurShaderSceneObject removed Shader now supports GL_TEXTURE_RECTANGLE_ARB } unit GLSLPostBlurShader; interface {$I GLScene.inc} uses System.Classes, // GLS GLTexture, GLScene, GLVectorGeometry, GLContext, GLSLShader, GLCustomShader, GLRenderContextInfo, GLTextureFormat, GLVectorTypes; type TGLCustomGLSLPostBlurShader = class(TGLCustomGLSLShader, IGLPostShader) private FThreshold: Single; // Implementing IGLPostShader. procedure DoUseTempTexture(const TempTexture: TGLTextureHandle; TextureTarget: TGLTextureTarget); function GetTextureTarget: TGLTextureTarget; function StoreThreshold: Boolean; protected procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override; function DoUnApply(var rci: TRenderContextInfo): Boolean; override; public constructor Create(AOwner: TComponent); override; property Threshold: Single read FThreshold write FThreshold stored StoreThreshold; end; TGLSLPostBlurShader = class(TGLCustomGLSLPostBlurShader) published property Threshold; end; //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- //---------------------------------------------------------------------- //---------------------------------------------------------------------- { TGLCustomGLSLPostBlurShader } constructor TGLCustomGLSLPostBlurShader.Create( AOwner: TComponent); begin inherited; with VertexProgram.Code do begin Add('varying vec2 vTexCoord; '); Add(' '); Add('void main(void) '); Add('{ '); Add(' '); Add(' // Clean up inaccuracies '); Add(' vec2 Position; '); Add(' Position.xy = sign(gl_Vertex.xy); '); Add(' '); Add(' gl_Position = vec4(Position.xy, 0.0, 1.0); '); Add(' vTexCoord = Position.xy *.5 + .5; '); Add(' '); Add('} '); end; with FragmentProgram.Code do begin Add('uniform float threshold; '); Add('uniform vec2 ScreenExtents; '); Add('uniform sampler2DRect Image; '); Add(' '); Add('varying vec2 vTexCoord; '); Add(' '); Add('void main() '); Add('{ '); Add(' '); Add(' vec2 samples[8]; '); Add(' vec2 vTexCoordScr = vTexCoord * ScreenExtents; '); Add(' '); Add(' samples[0] = vTexCoordScr + vec2(-1.0, -1.0); '); Add(' samples[1] = vTexCoordScr + vec2( 0.0, -1.0); '); Add(' samples[2] = vTexCoordScr + vec2( 1.0, -1.0); '); Add(' samples[3] = vTexCoordScr + vec2(-1.0, 0.0); '); Add(' samples[4] = vTexCoordScr + vec2( 1.0, 0.0); '); Add(' samples[5] = vTexCoordScr + vec2(-1.0, 1.0); '); Add(' samples[6] = vTexCoordScr + vec2( 0.0, 1.0); '); Add(' samples[7] = vTexCoordScr + vec2( 1.0, 1.0); '); Add(' '); Add(' vec4 sample = texture2DRect(Image, vTexCoordScr); '); Add(' '); Add(' // Neighborhood average '); Add(' vec4 avg = sample; '); Add(' for (int i = 0; i < 8; i++) '); Add(' { '); Add(' avg += texture2DRect(Image, samples[i]); '); Add(' } '); Add(' '); Add(' '); Add(' avg /= 9.0; '); Add(' '); Add(' // If the difference between the average and the sample is '); Add(' // large, we''ll assume it''s noise. '); Add(' vec4 diff = abs(sample - avg); '); Add(' float sel = float(dot(diff, vec4(0.25)) > threshold); '); Add(' '); Add(' gl_FragColor = mix(sample, avg, sel); '); Add('} '); end; FThreshold := 0.1; end; procedure TGLCustomGLSLPostBlurShader.DoApply( var rci: TRenderContextInfo; Sender: TObject); begin GetGLSLProg.UseProgramObject; GetGLSLProg.Uniform1f['threshold'] := FThreshold; GetGLSLProg.Uniform2f['ScreenExtents'] := Vector2fMake(rci.viewPortSize.cx, rci.viewPortSize.cy); end; function TGLCustomGLSLPostBlurShader.DoUnApply( var rci: TRenderContextInfo): Boolean; begin rci.GLStates.ActiveTexture := 0; GetGLSLProg.EndUseProgramObject; Result := False; end; procedure TGLCustomGLSLPostBlurShader.DoUseTempTexture( const TempTexture: TGLTextureHandle; TextureTarget: TGLTextureTarget); begin Param['Image'].AsCustomTexture[2, TextureTarget] := TempTexture.Handle; end; function TGLCustomGLSLPostBlurShader.GetTextureTarget: TGLTextureTarget; begin Result := ttTextureRect; end; function TGLCustomGLSLPostBlurShader.StoreThreshold: Boolean; begin Result := Abs(FThreshold - 0.1) > 0.00001; end; end.
unit PowerSupplyControl; interface uses Windows, Messages, SysUtils, Classes, forms, UPSH_3610_Const; type TBaudRate = (br9600, br4800, br2400, br1200); TStopBits = (sbOne, sbOne5, sbTwo); TPSState = record Voltage: Real; Current: Real; Power: Real; VoltLim: Integer; CurrLim: Real; PowerLim: Integer; RelayStat: boolean; Overheat: boolean; FineStat: boolean; FineLockStat: boolean; RemStat: boolean; LockStat: boolean; end; TPowerSupplyControl = class(TComponent) {PSP-2010; PSP-405} private FBaudRate: TBaudRate; FParity: boolean; FStopBits: TStopBits; FPortName: String; FByteSize: byte; procedure SetByteSize(NewValue: byte); procedure SetPortName(NewValue: String); procedure SetStopBits(NewValue: TStopBits); procedure SetParity(NewValue: boolean); procedure SetBaudRate(NewValue: TBaudRate); protected PortHandle : Cardinal; FPowerOn : Boolean; FPortReadError : Boolean; // Признак ошибки чтения из COM порта FPortWriteError : Boolean; // Признак ошибки записи из COM порта FWriteTime : Cardinal; // Время затраченное на запись и отклик COM порта FReadTime : Cardinal; // Время затраченное на чтение и отклик COM порта FWTimeAccessPort : Cardinal; procedure ConfigPort; { function ReadPort: String; {} Property PowerOn : Boolean read FPowerOn; Procedure SaveInReestorReadTime; Procedure SaveInReestorWriteTime; Procedure SaveErrorInReestor(Read : Boolean; Write : Boolean; Handle : Boolean; Error : String); Procedure TestPortError; public constructor Create(AOwner: TComponent); override; Destructor Destroy; override; {*************remote control procedures*********************} function SendCommand(Command: String): boolean; function ReadPortOV(bytesR: cardinal): String; procedure SetVoltage(const Voltage: real); procedure IncVoltage; procedure DecVoltage; procedure SetLimVoltage(const Voltage: integer); procedure IncLimVoltage; procedure DecLimVoltage; procedure SetLimCurrent(const Current: real); procedure IncLimCurrent; procedure DecLimCurrent; procedure SetLimPower(const Power: integer); procedure IncLimPower; procedure DecLimPower; procedure SetRelayState(const Stat: boolean); procedure InvertRelay; procedure SetMaxLimVoltage; procedure SetMaxLimCurrent; procedure SetMaxLimPower; procedure SetFineStatus(const Stat: boolean); procedure SaveData; procedure GetFullStatus(var PSInfo: TPSState); procedure GetStatus(var PSInfo: TPSState); function GetVoltage: Real; function GetLimVoltage: Integer; function GetLimCurrent: Real; function GetLimPower: Integer; function GetCurrent: Real; function GetPower: Real; function PowerExist : boolean; Property PortReadError : Boolean read FPortReadError; Property PortWriteError : Boolean read FPortWriteError; Property LastTimePortWrite : Cardinal read FWriteTime; Property LastWTimeAccessPort : Cardinal read FWTimeAccessPort; {***********************************************************} published property BaudRate: TBaudRate read FBaudRate write SetBaudRate; property Parity: Boolean read FParity write SetParity; property StopBits: TStopBits read FStopBits write SetStopBits; property PortName: String read FPortName write SetPortName; property ByteSize: byte read FByteSize write SetByteSize; end; TResTest = record TestTime : Cardinal; Return : String; end; TState = record Value : Real; // Значение измеряемой ведичины Range : Integer; // предел измерения Range_key : String[8]; // Расшифровка предела измерения (для APPA-105N) RangeAuto : Boolean; // если True-авто, False-ручной предел измерения ValueStr : String; // Ответ RS-232 (только для APPA-105N) Mode : String; // Режим измерения ModeType : String; // тип измеряемого сигнала AC,DC,AC+DC KeyStroke : String; // отслеживается удержание (нажатие во время опроса) кнопок end; TPSH_3610Control = class(TComponent) {PSH-3610} private FBaudRate : TBaudRate; FParity : boolean; FByteSize : byte; FStopBits : TStopBits; FPortName : String; procedure SetBaudRate(NewValue: TBaudRate); procedure SetPortName(NewValue: String); protected PortHandle : Cardinal; FPowerOn : Boolean; FPortReadError : Boolean; // Признак ошибки чтения из COM порта FPortWriteError : Boolean; // Признак ошибки записи из COM порта FWriteTime : Cardinal; // Время затраченное на запись и отклик COM порта FReadTime : Cardinal; // Время затраченное на чтение и отклик COM порта FWTimeAccessPort : Cardinal; procedure ConfigPort; public function ReadPort(bytesR : Cardinal) : String; function ReadPortA : String; // Читает данные COM порта до тех пор пока не встретит признак конца строки ($0A) function SendCommand(Command: String) : boolean; {--- ---} procedure OCP_PROTECTION_ON; // установить защиту по току procedure OCP_PROTECTION_OFF; // снять защиту по току procedure ClearRegStatus; // обнуление регистров статуса, в т.ч.снять с экрана Err Procedure SelfTest(Var ResT : TResTest); // самопроверка Procedure ALL_PROTECTION_OFF; function Identification : String; function PowerExist : boolean; procedure SetRelayState(const Stat: boolean); procedure SetVoltage(const Voltage : real); procedure SetCurrent(const Current : real); procedure SetBaseState; function GetVoltage : Real; procedure SetLimVoltage(const Voltage : Real); function GetLimVoltage : Real; function CurrentProtected : Boolean; // возврат лог. признак установки защиты по току function GetCurrent : Real; // возврат установленной величины тока function GetREALCurrent : Real; // возврат величины тока на выходе источника function GetREALVoltage : Real; // возврат величины напряжения на выходе источника {--- ---} constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property PortName : String read FPortName write SetPortName; property BaudRate : TBaudRate read FBaudRate write SetBaudRate; end; TGDM8246Mode = (ACA, DCA, ACDCA, ACV, DCV, ACDCV); TGDM8246 = class (TComponent) {GDM8246} Private sz_Error : String; Exist : Boolean; FPortHandle : Cardinal; FPortName : string; FBaudRate : Cardinal; FWriteTimeDelay : Cardinal; FReadTimeDelay : Cardinal; FCntTryStb : Byte; function GetErrors : string; procedure SetAutoMode(A: Boolean); function GetAutoMode : Boolean; protected Procedure SetPortName(Value : String); Procedure configPort(szCOM: string; BRate: Cardinal; var Error: string); Public function SendCommand(Cmd: string): boolean; function ReadFromPort(BytesR: Word; var ResRead: array of byte): Boolean; constructor Create(szCOM: string; BRate: Cardinal; var Error: string); reintroduce; virtual; destructor Free; procedure Setup(Mode: TGDM8246Mode; Limit: Cardinal; var SetLim, Error: string); function SetInDCV(Limit: Cardinal; var Error: string): Boolean; function SetInACDCV(Limit: Cardinal; var Error: string): Boolean; function SetInDCA(Limit: Cardinal; var Error: string): Boolean;//Предел задаётся в мА function SetInACDCA(Limit: Cardinal; var Error: string): Boolean;//Предел задаётся в мА function GetValueFromMainDisp: string; function GetStabilizedValue(Mcl: Currency): Currency;//В относительная не в процентах function GetValueFromSecondaryDisp: string; function GetValueFromBothDisp: string; function GetMode(var CurrentMode: TGDM8246Mode): Boolean; function Reset: Boolean; function GetID: string; function IsGDM8246: Boolean; function RstToFlt(sz: string): Currency; property PortHandle: Cardinal read FPortHandle; property PortName: string read FPortName write SetPortName; property Auto: Boolean read GetAutoMode write SetAutoMode; property WriteTimeDelay: Cardinal read FWriteTimeDelay write FWriteTimeDelay default 256; property ReadTimeDelay: Cardinal read FReadTimeDelay write FReadTimeDelay default 0; property CountOfTryToStab: Byte read FCntTryStb write FCntTryStb; // function getrange : String; end; TAPPA_105_C_ = Class (TComponent) {APPA-105N} private PortHandle : Cardinal; FPortName : String; FInit : Boolean; protected procedure ConfigPort; Procedure SetPortName(Value : String); function ConfigCommPort(PortName: String; DCB: TDCB;TimeOuts: TCommTimeouts; InQueue,OutQueue: Cardinal): Cardinal; function ReadCommPort(PortHandle: Cardinal; BytesR: Word; var ResRead: array of byte): Boolean; function WriteCommPort(PortHandle: Cardinal; Command: String) : boolean; public property Port_Handle : Cardinal read PortHandle; Procedure RS232_Init; procedure GetCurrentState(var State : TState); constructor Create(AOwner : TComponent); override; destructor Destroy; override; published property PortName : String read FPortName write SetPortName; Property Initialization_ : Boolean read FInit; end; TAPPA_109_C_ = Class (TComponent) {APPA-109N} private PortHandle : Cardinal; FPortName : String; protected procedure ConfigPort; Procedure SetPortName(Value : String); function ConfigCommPort(PortName: String; DCB: TDCB;TimeOuts: TCommTimeouts; InQueue,OutQueue: Cardinal): Cardinal; function ReadCommPort(PortHandle: Cardinal; BytesR: Word; var ResRead: array of byte): Boolean; function WriteCommPort(PortHandle: Cardinal; Command: String) : boolean; public procedure GetCurrentState(var State : TState); constructor Create(AOwner : TComponent); override; destructor Destroy; override; published property PortName : String read FPortName write SetPortName; end; TPowerSupplyType = (PSP405, PSP2010, PSH3610); TPowerSupply = Class (TComponent) private {} FPowerSupplyType : TPowerSupplyType; {} FPSP : TPowerSupplyControl; FPSH : TPSH_3610Control; {} FBaudRate : TBaudRate; FPortName : String; {} procedure SetBaudRate(NewValue: TBaudRate); procedure SetPortName(NewValue: String); {} protected {} procedure ConfigPort; {} public {} constructor Create(AOwner : TComponent); override; destructor Destroy; override; {} procedure SetVoltage(const Voltage : real); procedure OCP_PROTECTION_ON; // установить защиту по току procedure OCP_PROTECTION_OFF; // снять защиту по току procedure ClearRegStatus; // обнуление регистров статуса, в т.ч.снять с экрана Err procedure SetRelayState(const Stat: boolean); function GetREALCurrent : Real; // возврат величины тока на выходе источника function GetREALVoltage : Real; // возврат величины напряжения на выходе источника function GetVoltage : Real; {} published {} property PowerSupplyType : TPowerSupplyType read FPowerSupplyType write FPowerSupplyType; property PortName : String read FPortName write SetPortName; property BaudRate : TBaudRate read FBaudRate write SetBaudRate; {} end; procedure Register; Function INVALIDHandle (Handle : Cardinal) : Boolean; implementation Uses Registry; Const MaxT = 50; Var WaitTimeWrite : Integer = 2500; // Ждать отклик COM порта (для записи) WaitTimeRead : Integer = 650; // Ждать отклик COM порта (для чтения) var T : array[1 .. MaxT] of byte; {--- TPowerSupply ---} constructor TPowerSupply.Create(AOwner : TComponent); begin {} FPSH := TPSH_3610Control.Create(nil); FPSP := TPowerSupplyControl.Create(nil); {} inherited; {} end; destructor TPowerSupply.Destroy; begin {} FPSH.Free; FPSP.Free; Inherited; {} end; procedure TPowerSupply.SetBaudRate; begin {} if PowerSupplyType = PSH3610 then FPSH.SetBaudRate(NewValue) else FPSP.SetBaudRate(NewValue); {} end; Procedure TPowerSupply.SetPortName; begin {} if PowerSupplyType = PSH3610 then FPSH.SetPortName(NewValue) else FPSP.SetPortName(NewValue); {} end; Procedure TPowerSupply.SetVoltage; begin {} if PowerSupplyType = PSH3610 then FPSH.SetVoltage(Voltage) else FPSP.SetVoltage(Voltage); {} end; Procedure TPowerSupply.OCP_PROTECTION_ON; begin {} if PowerSupplyType = PSH3610 then FPSH.OCP_PROTECTION_ON; {} end; Procedure TPowerSupply.OCP_PROTECTION_OFF; begin {} if PowerSupplyType = PSH3610 then FPSH.OCP_PROTECTION_OFF; {} end; Procedure TPowerSupply.ClearRegStatus; begin {} if PowerSupplyType = PSH3610 then FPSH.ClearRegStatus; {} end; procedure TPowerSupply.SetRelayState(const Stat: boolean); begin {} if PowerSupplyType = PSH3610 then FPSH.SetRelayState(Stat) else FPSP.SetRelayState(Stat); {} end; Function TPowerSupply.GetREALCurrent : Real; begin {} if PowerSupplyType = PSH3610 then result := FPSH.GetREALCurrent else result := FPSP.GetCurrent; {} end; Function TPowerSupply.GetREALVoltage : Real; begin {} if PowerSupplyType = PSH3610 then result := FPSH.GetREALVoltage else result := FPSP.GetVoltage; {} end; Function TPowerSupply.GetVoltage : Real; begin {} if PowerSupplyType = PSH3610 then result := FPSH.GetVoltage else result := FPSP.GetVoltage; {} end; Procedure TPowerSupply.ConfigPort; begin {} {} end; {--- TGDM8246 ---} Const NO_ERROR = 'Инициализирован'; INVALID_PORT = 'Неверный порт'; COULD_NOT_SET_TIMEOUT = 'Не удалось задать таймауты для COM порта'; COULD_NOT_SET_BUFFER = 'Не удалось задать буфферы для COM порта'; COULD_NOT_SET_STATE = 'Не удалось сконфигурировать COM порт'; NO_DEVICE = 'Не найден на указанном порте'; function ReadCommPort(PortHandle: Cardinal; BytesR: Word; var ResRead: array of byte): Boolean; var ov: _OVERLAPPED; br: Cardinal; begin FillChar(ResRead,SizeOf(ResRead),0); FillChar(ov,SizeOf(ov),0); ov.hEvent := CreateEvent(nil,true,false,nil); ReadFile(PortHandle,ResRead[0],BytesR,br,@ov); WaitForSingleObject(ov.hEvent,1000); if GetOverlappedResult(PortHandle,ov,br,false) then Result:=True else Result:=False; CloseHandle(ov.hEvent); end; function WriteCommPort(PortHandle: Cardinal; Command: String): boolean; var ov: _OVERLAPPED; bw: Cardinal; begin PurgeComm(PortHandle, PURGE_TXCLEAR + PURGE_RXCLEAR); FillChar(ov,SizeOf(ov),0); ov.hEvent := CreateEvent(nil,true,true,nil); WriteFile(PortHandle,Command[1],Length(Command),bw,@ov); WaitForSingleObject(ov.hEvent , 1000); if GetOverlappedResult(PortHandle,ov,bw,false) then Result:=true else Result:=false; CloseHandle(ov.hEvent); end; function TGDM8246.getrange : String; Var RR : Array [1..100] of Byte; I : Integer; begin result := ''; // SendCommand(':CONFigure:RANGe?'+#10); ReadFromPort(6, RR); For I := 1 to 15 do if RR[I] <> 0 then result := result + CHR(RR[I]); // end; Procedure TGDM8246.configPort(szCOM: string; BRate: Cardinal; var Error: string); var DCB : TDCB; TimeOuts : TCommTimeouts; begin FPortHandle := CreateFile(PChar(szCOM),GENERIC_READ+GENERIC_WRITE, 0, nil,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0); Exist := False; if FPortHandle = INVALID_HANDLE_VALUE then Error := INVALID_PORT else Begin {level1+} FPortName := szCOM; FillChar(TimeOuts,sizeof(TimeOuts),0); if not SetCommTimeouts(FPortHandle, TimeOuts) then Error := COULD_NOT_SET_TIMEOUT else Begin { level2+ } FillChar(DCB,sizeof(DCB),0); with DCB do begin BaudRate := BRate; Parity := NOPARITY; ByteSize := 8; StopBits := ONESTOPBIT; end; DCB.DCBlength := sizeof(DCB); if SetCommState(FPortHandle,DCB) then begin FWriteTimeDelay := 0; FReadTimeDelay := 0; FCntTryStb := 16; Exist := True; if IsGDM8246 then begin Reset; Error := NO_ERROR; end else begin Error := NO_DEVICE; Exist := False; end; end else Error := COULD_NOT_SET_STATE; End;{--- level_2 ---} End;{--- level_1 ----} Error := 'GDM-8246: ' + Error; end; Procedure TGDM8246.SetPortName(Value : String); begin // if Value <> FPortName then begin FPortName := Value; configPort(FPortName, FBaudRate, sz_Error); end; // end; function TGDM8246.SendCommand(Cmd : string): Boolean; begin if Exist then begin Result := WriteCommPort(FPortHandle,Cmd); if not(FWriteTimeDelay=0) then Sleep(FWriteTimeDelay); end else Result:=False; end; function TGDM8246.ReadFromPort(BytesR: Word; var ResRead: array of byte): Boolean; begin if Exist then begin Result:=ReadCommPort(FPortHandle,BytesR,ResRead); if not(FReadTimeDelay=0) then Sleep(FReadTimeDelay); end else Result:=False; end; function TGDM8246.RstToFlt(sz: string): Currency; var n,i: Byte; deg: Longword; begin if Pos('L',sz)=0 then begin n:=Length(sz)-Pos('.',sz); Delete(sz,Pos('.',sz),1); deg:=1; for i:=1 to n do deg:=deg*10; Result:=StrToInt(sz)/deg; end else Result:=922337203685477.5807; end; constructor TGDM8246.Create(szCOM: string; BRate: Cardinal; var Error: string); begin FBaudRate := BRate; configPort(szCOM, BRate, Error); end; destructor TGDM8246.Free; begin {if not((FPortHandle=0)or(FPortHandle=INVALID_HANDLE_VALUE)) then CloseHandle(FPortHandle);} end; function TGDM8246.GetID: string; var Res:array of Byte; i: Byte; begin SendCommand('*IDN?'+#10); SetLength(Res,22);Result:=''; if ReadCommPort(FPortHandle,22,Res) then for i:=0 to High(Res) do Result:=Result+Chr(Res[i]) else Result:='Error'; end; function TGDM8246.IsGDM8246: Boolean; begin Result:=GetID='GW.Inc,GDM-8246,FW1.00'; end; function TGDM8246.GetErrors: string; var SubEr, AllEr: string; ResRead,i,j: Byte; Brk: Boolean; begin //Забираем всю очередь сообщений об ошибках AllEr:=''; repeat SendCommand(':SYST:ERR?'+#10); SubEr:=''; while (ReadFromPort(1,ResRead)xor(ResRead=10)) do SubEr:=SubEr+Chr(ResRead); if SubEr='' then Brk:=true else if SubEr[1]='0' then Brk:=true else Brk:=false; AllEr:=AllEr+SubEr; until Brk; //Выбираем только сообщения об ошибках if AllEr='' then Result:=NO_DEVICE else begin Result:=''; i:=1; while i<Length(AllEr) do begin j:=i; while (not(AllEr[j]=#10))and(j<Length(AllEr)) do j:=j+1; SubEr:=copy(AllEr,i,j-i+1); if not(SubEr[1]='0') then Result:=Result+SubEr; i:=j+1; end; end; end; procedure TGDM8246.Setup(Mode: TGDM8246Mode; Limit: Cardinal; var SetLim, Error: string); var Com: string; ResRead: Byte; begin case Mode of ACA: Com:=':CONF:CURR:AC '+IntToStr(Limit)+#10; DCA: Com:=':CONF:CURR:DC '+IntToStr(Limit)+#10; ACDCA: Com:=':CONF:CURR:ACDC '+IntToStr(Limit)+#10; ACV: Com:=':CONF:VOLT:AC '+IntToStr(Limit)+#10; DCV: Com:=':CONF:VOLT:DC '+IntToStr(Limit)+#10; ACDCV: Com:=':CONF:VOLT:ACDC '+IntToStr(Limit)+#10; else Com:='' end; SetLim:=''; if Com='' then Error:='GDM-8246: Неверно задан режим' else begin SendCommand(Com); //Ошибки Error:=GetErrors; if not(Error='') then Error:='GDM-8246: '+Error; //считывание выставленного диапазона SendCommand(':CONF:RANG?'+#10); while (ReadFromPort(1,ResRead)xor(ResRead=10)) do SetLim:=Setlim+Chr(ResRead); end; end; function TGDM8246.SetInDCV(Limit: Cardinal; var Error: string): Boolean; var szSL: string; begin if Reset then begin Setup(DCV,Limit,szSL,Error); Result:=(Error=''); end else Result:=False; end; function TGDM8246.SetInACDCV(Limit: Cardinal; var Error: string): Boolean; var szSL: string; begin if Reset then begin Setup(ACDCV,Limit,szSL,Error); Result:=(Error=''); end else Result:=False; end; function TGDM8246.SetInDCA(Limit: Cardinal; var Error: string): Boolean; var szSL: string; begin if Reset then begin Setup(DCA,Limit,szSL,Error); Result:=(Error=''); end else Result:=False; end; function TGDM8246.SetInACDCA(Limit: Cardinal; var Error: string): Boolean; var szSL: string; begin if Reset then begin Setup(ACDCA,Limit,szSL,Error); Result:=(Error=''); end else Result:=False; end; function TGDM8246.GetValueFromMainDisp: string; var ResRead:Byte; begin PurgeComm(FPortHandle,PURGE_TXCLEAR+PURGE_RXCLEAR); Result:=''; SendCommand(':VAL?'+#10); while (ReadFromPort(1,ResRead)xor(ResRead=10)) do Result:=Result+Chr(ResRead); end; function TGDM8246.GetStabilizedValue(Mcl: Currency): Currency; var Misc, MW: Currency; Last: array[1..10] of Currency; i, cnt: Byte; Stb: Boolean; begin MW:=0; for i:=1 to 10 do begin Last[i]:=RstToFlt(GetValueFromMainDisp); MW:=MW+0.1*Last[i];//Вычисляем матожидание end; Stb:=True; if MW<0.00001 then Result:=0 else BEGIN for i:=1 to 10 do begin Misc:=Abs(Last[i]-MW)/MW; Stb:=Stb and (Misc<Mcl); end; if Stb then Result:=MW else begin cnt:=0; Repeat for i:=2 to 10 do Last[i-1]:=Last[i]; Last[10]:=RstToFlt(GetValueFromMainDisp); MW:=0; for i:=1 to 10 do MW:=MW+0.1*Last[i]; Stb:=True; if MW<0.00001 then {Result := 0{} else begin for i:=1 to 10 do begin Misc:=Abs(Last[i]-MW)/MW; Stb:=Stb and (Misc<Mcl); end; cnt:=cnt+1; end; Until (Stb)or(cnt>FCntTryStb); Result := Last[10]; end; END; end; function TGDM8246.GetValueFromSecondaryDisp: string; var ResRead:Byte; begin PurgeComm(FPortHandle,PURGE_TXCLEAR+PURGE_RXCLEAR); Result:=''; SendCommand(':READ?'+#10); while (ReadFromPort(1,ResRead)xor(ResRead=10)) do Result:=Result+Chr(ResRead); end; function TGDM8246.GetValueFromBothDisp: string; var ResRead:Byte; begin PurgeComm(FPortHandle,PURGE_TXCLEAR+PURGE_RXCLEAR); Result:=''; SendCommand(':SVAL?'+#10); while (ReadFromPort(1,ResRead)xor(ResRead=10)) do Result:=Result+Chr(ResRead); end; function TGDM8246.GetAutoMode: Boolean; var szAuto: string; ResRead: Byte; begin SendCommand(':CONF:AUT?'+#10); szAuto:=''; while (ReadFromPort(1,ResRead)xor(ResRead=10)) do szAuto:=szAuto+Chr(ResRead); Result:=szAuto='1'; end; procedure TGDM8246.SetAutoMode(A: Boolean); var Com: string; begin if A then Com:=':CONF:AUT 1'+#10 else Com:=':CONF:AUT 0'+#10; SendCommand(Com); end; function TGDM8246.Reset: Boolean; begin Result:=SendCommand('*RST'+#10); end; function TGDM8246.GetMode(var CurrentMode: TGDM8246Mode): Boolean; var ResRead: Byte; szMode: string; begin if SendCommand('CONF:FUNC?'+#10) then begin szMode:=''; while (ReadFromPort(1,ResRead)xor(ResRead=10)) do szMode:=szMode+Chr(ResRead); if szMode='DCV' then begin CurrentMode:=DCV; Result:=True; end else if szMode='ACV' then begin CurrentMode:=ACV; Result:=True; end else if szMode='AC+DCV' then begin CurrentMode:=ACDCV; Result:=True; end else if szMode='DCA' then begin CurrentMode:=DCA; Result:=True; end else if szMode='ACA' then begin CurrentMode:=ACA; Result:=True; end else if szMode='AC+DCA' then begin CurrentMode:=ACDCA; Result:=True; end else begin szMode:=''; Result:=False; end; end else begin szMode:=''; Result:=False; end; end; {------ END GDM-8246 FUNCTION --------} {--- TAPPA_105_C_ ---} Function INVALIDHandle (Handle : Cardinal) : Boolean; begin result := false; if (Handle = 0) or (Handle = INVALID_HANDLE_VALUE) then result := true; end; function TAPPA_105_C_.ConfigCommPort(PortName: String; DCB: TDCB; TimeOuts: TCommTimeouts; InQueue,OutQueue: Cardinal): Cardinal; var PortHandle : Cardinal; DCB2 : TDCB; begin RESULT := 0; PortHandle := CreateFile(PChar(PortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if PortHandle = INVALID_HANDLE_VALUE then begin // MessageBox(0,PChar('Can not open port '+PortName),'Error', // MB_OK or MB_ICONERROR); Exit; end; { if not SetCommTimeouts(PortHandle, TimeOuts) then begin MessageBox(0,PChar('Can not set timeouts to port '+PortName),'Error', MB_OK or MB_ICONERROR); Exit; end; {} // Установка размера входного и выходного буфера // SetupComm(PortHandle, InQueue, OutQueue); // Установка параметров сом-порта {} DCB2 := DCB; DCB2.BaudRate := 2400; DCB2.ByteSize := 7; DCB2.Parity := 01; DCB2.StopBits := 0; DCB2.Flags := $1013; DCB2.XonLim := $000A; DCB2.XoffLim := $000A; {} {} {} DCB.BaudRate := 2400; DCB.ByteSize := 8; DCB.Parity := 0; DCB.StopBits := 0; DCB.Flags := $1011; DCB.XonLim := $0800; DCB.XoffLim := $0200; {} SetCommState(PortHandle , DCB); (**) SetCommState(PortHandle , DCB2); {} // очистка выходных буферов // PurgeComm(PortHandle , PURGE_TXCLEAR); PurgeComm(PortHandle , PURGE_RXCLEAR); Result := PortHandle; Sleep(1000); end; function TAPPA_105_C_.ReadCommPort(PortHandle: Cardinal; BytesR: Word; var ResRead: array of byte): Boolean; var ov : _OVERLAPPED; br : Cardinal; begin {} result := false; if INVALIDHandle(PortHandle) then exit; FillChar(ResRead,SizeOf(ResRead),0); FillChar(ov,SizeOf(ov),0); {} ov.hEvent:=CreateEvent(nil,true,true,nil); ReadFile(PortHandle,ResRead[0],BytesR,br,@ov); WaitForSingleObject(ov.hEvent, 300); if GetOverlappedResult(PortHandle,ov,br,false) then Result:=True else Result:=False; if Result and not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); end; function TAPPA_105_C_.WriteCommPort(PortHandle: Cardinal; Command: String): boolean; var ov: _OVERLAPPED; bw: Cardinal; begin {} result := false; if INVALIDHandle(PortHandle) then exit; FillChar(ov,SizeOf(ov),0); ov.hEvent:=CreateEvent(nil,true,true,nil); {} WriteFile(PortHandle,Command[1],Length(Command),bw,@ov); WaitForSingleObject(ov.hEvent,INFINITE); if GetOverlappedResult(PortHandle,ov,bw,false) or (bw <> 0) then Result:=true else Result:=false; if Result and not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); end; procedure TAPPA_105_C_.ConfigPort; Var DCB : TDCB; TimeOuts : TCommTimeouts; begin if (csDesigning in ComponentState) then exit; FillChar(DCB , SizeOf(TDCB),0); with DCB do begin DCBlength := SizeOf(TDCB); BaudRate := CBR_2400; ByteSize := 8; Parity := NOPARITY; StopBits := ONESTOPBIT; end; with TimeOuts do begin ReadIntervalTimeout := 0; ReadTotalTimeoutMultiplier := 0; ReadTotalTimeoutConstant := 0; WriteTotalTimeoutMultiplier := 0; WriteTotalTimeoutConstant := 0; end; if FPortName <> '' then begin {PortHandle := CreateFile(PChar('\\.\'+PortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); {} PortHandle := ConfigCommPort('\\.\'+FPortName , DCB, TimeOuts, 1024, 1024); //EscapeCommFunction(PortHandle , SETDTR); end; end; procedure TAPPA_105_C_.SetPortName(Value : String); begin if FPortName = Value then exit; FPortName := value; {} if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); {} ConfigPort; end; Procedure TAPPA_105_C_.RS232_Init; Var ResultRead : array of byte; c : Cardinal; ComStat : TComStat; I, K : Integer; begin {} SetLength(ResultRead, 1000); For K := 0 to High(ResultRead) do ResultRead[k] := 0; FInit := false; if not(ReadCommPort(PortHandle ,1 , ResultRead[0])) then begin {} ClearCommBreak(PortHandle); sleep(1); Application.ProcessMessages; ClearCommError(PortHandle, c, @ComStat); sleep(1); Application.ProcessMessages; FlushFileBuffers(PortHandle); sleep(1); Application.ProcessMessages; if ComStat.cbInQue < 36 then ; {} if not (WriteCommPort(PortHandle, 'H')) then begin {} {} end; Sleep(500); {} ClearCommBreak(PortHandle); sleep(1); Application.ProcessMessages; ClearCommError(PortHandle, c, @ComStat); sleep(1); Application.ProcessMessages; FlushFileBuffers(PortHandle); sleep(1); Application.ProcessMessages; if ComStat.cbInQue > 30 then ReadCommPort(PortHandle ,ComStat.cbInQue - 15 , ResultRead[0]); Sleep(500); For I := 0 to 10 do if (ResultRead[I] = 13) or (ResultRead[I] = 10) then begin FInit := true; break; end; {} end else begin {} Sleep(500); ClearCommBreak(PortHandle); sleep(1); Application.ProcessMessages; ClearCommError(PortHandle, c, @ComStat); sleep(1); Application.ProcessMessages; FlushFileBuffers(PortHandle); sleep(1); Application.ProcessMessages; if ComStat.cbInQue > 30 then ReadCommPort(PortHandle ,ComStat.cbInQue - 15 , ResultRead[0]); For I := 0 to 10 do if (ResultRead[I] = 13) or (ResultRead[I] = 10) then begin FInit := true; break; end; {} end; {} sleep(500); {} end; procedure TAPPA_105_C_.GetCurrentState(var State: TState); var k,trr : integer; ResultRead : array of byte; s : string; f88 : Boolean; ComStat : TComStat; c : Cardinal; Range_char : Char; {} TypeVal : String[3]; {} begin {} SetLength(ResultRead, 1000); trr := 0; ZeroMemory(@State , SizeOf(State)); {} if not FInit then exit; {} For K := 0 to High(ResultRead) do ResultRead[k] := 0; s := ''; k:=0; f88 := false; {} ClearCommBreak(PortHandle); sleep(1); Application.ProcessMessages; ClearCommError(PortHandle, c, @ComStat); sleep(1); Application.ProcessMessages; FlushFileBuffers(PortHandle); sleep(1); Application.ProcessMessages; if ComStat.cbInQue > 30 then ReadCommPort(PortHandle ,ComStat.cbInQue - 15 , ResultRead[0]); sleep(1); {} repeat {} if not(ReadCommPort(PortHandle ,1 , ResultRead[k])) then begin // break; Sleep(1); end else K := K + 1; {} trr := trr + 1; if Trr >= 20 then break; {} // проверка наличия установочных битов if ((ResultRead[k-1] = 13) or (ResultRead[k-1] = 10)) and f88 then break else if ((ResultRead[k-1] = 13) or (ResultRead[k-1] = 10)) then begin {} if (ResultRead[k-1] = 13) then if not(ReadCommPort(PortHandle ,1 , ResultRead[k-1])) then ; sleep(5); {} f88 := true; S := ''; k := 0; continue; {} end else s := s + chr(ResultRead[k-1]); {} until false; {} if S = '' then ; State.ValueStr := S; {} State.Value := StrToIntDef(Copy(S, 2, 4), 0); {} Range_char := #0; TypeVal := Range_char; if (Length(S) > 8) then begin {} Range_char := S[1]; {} if S[6] = ';' then TypeVal := 'V'; if S[6] = '3' then TypeVal := 'R'; // Режим прозвонки, изм сопротивл, проверки диодов {} if S[6] = '9' then TypeVal := 'mA'; {} {} if TypeVal = 'R' then begin {} State.RangeAuto := false; if S[9] = '2' then State.RangeAuto := true; {} end else if TypeVal = 'mA' then begin {} State.RangeAuto := false; if (S[9] = ':') or (S[9] = '6') then State.RangeAuto := true; {} end; {} if (S[9] = '6') or (S[9] = '4') then State.ModeType := 'AC' else if (not (Ord(S[9]) in [Ord('0')..ord('9')])) or (Ord(S[9]) = Ord('8')) then State.ModeType := 'DC' else State.ModeType := ''; {} end; {} State.Mode := TypeVal; if (Length(State.ValueStr) > 2) and (State.Mode='V') then begin if State.ValueStr[1]='1' then State.Value := State.Value/1000; if State.ValueStr[1]='2' then State.Value := State.Value/100; if State.ValueStr[1]='3' then State.Value := State.Value/10; end; {} if TypeVal = 'mA' then begin if Range_char = '0' then begin State.Value := (State.Value * 0.01)/1; State.Mode := 'мА'; State.Range := 40; State.Range_key := 'mA'; end; if Range_char = '1' then begin State.Value := (State.Value * 0.1)/1; State.Mode := 'мА'; State.Range := 400; State.Range_key := 'mA'; end; end; if TypeVal = 'R' then begin if Range_char = '0' then begin State.Value := (State.Value * 0.1)/1; State.Mode := 'Ом'; State.Range := 400; State.Range_key := 'Оhm'; end; if Range_char = '1' then begin State.Value := (State.Value * 1)/1; State.Mode := 'Ом'; State.Range := 4000; State.Range_key := 'Оhm'; end; if Range_char = '2' then begin State.Value := (State.Value * 10)/1000; State.Mode := 'КОм'; State.Range := 40; State.Range_key := 'Kohm'; end; if Range_char = '3' then begin State.Value := (State.Value * 100)/1000; State.Mode := 'КОм'; State.Range := 400; State.Range_key := 'Kohm'; end; if Range_char = '4' then begin State.Value := (State.Value * 1000)/1000000; State.Mode := 'MОм'; State.Range := 4; State.Range_key := 'Mohm'; end; if Range_char = '5' then begin State.Value := (State.Value * 10000)/1000000; State.Mode := 'MОм'; State.Range := 40; State.Range_key := 'Mohm'; end; end; {} exit; {} with State do begin //Режим измерения case ResultRead[k-3] of 01: Mode:='V'; 02: Mode:='mV'; 03: Mode:='Ом'; 04: Mode:='ДИОД'; 05: Mode:='mA'; 06: Mode:='A'; 07: Mode:='Емкость'; 08: Mode:='Hz'; 09: Mode:='Температура'; end; //Вид измеряемого сигнала case ResultRead[5] of 00: ModeType:='AC'; 01: ModeType:='DC'; 02: ModeType:='AC+DC'; end; //отслеживание нажатой кнопки case ResultRead[6] of 00: KeyStroke:=''; 01: KeyStroke:='Желтая'; 02: KeyStroke:='BAR'; 03: KeyStroke:='PEAK'; 04: KeyStroke:='RANGE'; 05: KeyStroke:='Синяя'; 06: KeyStroke:='M/M/A'; 07: KeyStroke:='REL'; 08: KeyStroke:='AUTO'; end; //определяем предел измерения if ResultRead[7]<10 then RangeAuto:=True else RangeAuto:=False; case ResultRead[4] of 01: begin case ResultRead[7] of 00,128: Range:=2; 01,129: Range:=20; 02,130: Range:=200; 03,131: Range:=1000; end; end; 05: begin case ResultRead[7] of 00,128: Range:=20; 01,129: Range:=200; end; end; 06: begin case ResultRead[7] of 00,128: Range:=2; 01,129: Range:=20; end; end; end; // Опрделяем результат измерния if ResultRead[10]=$FF then Value:=-(65536-(ResultRead[9]*256+ResultRead[8])) else Value:=ResultRead[9]*256+ResultRead[8]; case Range of 2: Value := Value/10000; 20: Value := Value/1000; 200: Value := Value/100; 1000: Value := Value/10; end; if ResultRead[10] = $4E then Value:=9999; // на экране prob case ResultRead[11] of 00: Range:=0; end; end; end; constructor TAPPA_105_C_.Create(AOwner: TComponent); begin FInit := false; ConfigPort; inherited Create(AOwner); end; destructor TAPPA_105_C_.Destroy; begin if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); inherited Destroy; end; {--- TAPPA_109_C_ ---} function TAPPA_109_C_.ConfigCommPort(PortName: String; DCB: TDCB; TimeOuts: TCommTimeouts; InQueue,OutQueue: Cardinal): Cardinal; var PortHandle : Cardinal; begin RESULT := 0; PortHandle := CreateFile(PChar(PortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if PortHandle = INVALID_HANDLE_VALUE then begin // MessageBox(0,PChar('Can not open port '+PortName),'Error', // MB_OK or MB_ICONERROR); Exit; end; if not SetCommTimeouts(PortHandle, TimeOuts) then begin MessageBox(0,PChar('Can not set timeouts to port '+PortName),'Error', MB_OK or MB_ICONERROR); Exit; end; // Установка размера входного и выходного буфера SetupComm(PortHandle, InQueue, OutQueue); // Установка параметров сом-порта SetCommState(PortHandle , DCB); // очистка выходных буферов PurgeComm(PortHandle , PURGE_TXCLEAR); PurgeComm(PortHandle , PURGE_RXCLEAR); Result := PortHandle; Sleep(1000); end; function TAPPA_109_C_.ReadCommPort(PortHandle: Cardinal; BytesR: Word; var ResRead: array of byte): Boolean; var ov : _OVERLAPPED; br : Cardinal; begin FillChar(ResRead,SizeOf(ResRead),0); FillChar(ov,SizeOf(ov),0); ov.hEvent:=CreateEvent(nil,true,true,nil); ReadFile(PortHandle,ResRead[0],BytesR,br,@ov); WaitForSingleObject(ov.hEvent,100); if GetOverlappedResult(PortHandle,ov,br,false) then Result:=True else Result:=False; if Result and not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); end; function TAPPA_109_C_.WriteCommPort(PortHandle: Cardinal; Command: String): boolean; var ov: _OVERLAPPED; bw: Cardinal; begin FillChar(ov,SizeOf(ov),0); ov.hEvent:=CreateEvent(nil,true,true,nil); WriteFile(PortHandle,Command[1],Length(Command),bw,@ov); WaitForSingleObject(ov.hEvent,INFINITE); if GetOverlappedResult(PortHandle,ov,bw,false) then Result:=true else Result:=false; if Result and not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); end; procedure TAPPA_109_C_.ConfigPort; Var DCB : TDCB; TimeOuts : TCommTimeouts; begin if (csDesigning in ComponentState) then exit; FillChar(DCB , SizeOf(TDCB),0); with DCB do begin DCBlength := SizeOf(TDCB); BaudRate := CBR_9600; ByteSize := 8; Parity := NOPARITY; StopBits := ONESTOPBIT; end; with TimeOuts do begin ReadIntervalTimeout := 0; ReadTotalTimeoutMultiplier := 0; ReadTotalTimeoutConstant := 0; WriteTotalTimeoutMultiplier := 0; WriteTotalTimeoutConstant := 0; end; if FPortName <> '' then begin {PortHandle := CreateFile(PChar(PortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); {} PortHandle := ConfigCommPort('\\.\'+FPortName , DCB, TimeOuts, 1024, 1024); EscapeCommFunction(PortHandle , SETDTR); end; end; procedure TAPPA_109_C_.SetPortName(Value : String); begin if FPortName = Value then exit; {} if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); {} FPortName := value; ConfigPort; end; procedure TAPPA_109_C_.GetCurrentState(var State: TState); var i, k,t : integer; ResultRead : array of byte; s : string; begin SetLength(ResultRead, 1000); t := 0; I := 1; ZeroMemory(@State , SizeOf(State)); repeat if not (WriteCommPort(PortHandle,#85+#85+#00+#00+#170)) then begin // MessageDlg('Ошибка записи в порт',mtError,mbOKCancel,0); exit; end; if not(ReadCommPort(PortHandle ,19+(i-1) , ResultRead)) then begin // MessageDlg('Ошибка чтения из порта',mtError,mbOKCancel,0); exit; end; // проверка наличия установочных битов s := ''; for k:=0 to (18+i) do s := s + chr(ResultRead[k]); i := Pos(#85+#85+#00+#14 , s); inc(t) until ((i=1) and (Length(s)=19)) or (t=10); with State do begin //Режим измерения case ResultRead[4] of 01: Mode:='V'; 02: Mode:='mV'; 03: Mode:='Ом'; 04: Mode:='ДИОД'; 05: Mode:='mA'; 06: Mode:='A'; 07: Mode:='Емкость'; 08: Mode:='Hz'; 09: Mode:='Температура'; end; //Вид измеряемого сигнала case ResultRead[5] of 00: ModeType:='AC'; 01: ModeType:='DC'; 02: ModeType:='AC+DC'; end; //отслеживание нажатой кнопки case ResultRead[6] of 00: KeyStroke:=''; 01: KeyStroke:='Желтая'; 02: KeyStroke:='BAR'; 03: KeyStroke:='PEAK'; 04: KeyStroke:='RANGE'; 05: KeyStroke:='Синяя'; 06: KeyStroke:='M/M/A'; 07: KeyStroke:='REL'; 08: KeyStroke:='AUTO'; end; //определяем предел измерения if ResultRead[7]<10 then RangeAuto:=True else RangeAuto:=False; case ResultRead[4] of 01: begin case ResultRead[7] of 00,128: Range:=2; 01,129: Range:=20; 02,130: Range:=200; 03,131: Range:=1000; end; end; 05: begin case ResultRead[7] of 00,128: Range:=20; 01,129: Range:=200; end; end; 06: begin case ResultRead[7] of 00,128: Range:=2; 01,129: Range:=20; end; end; end; // Опрделяем результат измерния if ResultRead[10]=$FF then Value:=-(65536-(ResultRead[9]*256+ResultRead[8])) else Value:=ResultRead[9]*256+ResultRead[8]; case Range of 2: Value := Value/10000; 20: Value := Value/1000; 200: Value := Value/100; 1000: Value := Value/10; end; if ResultRead[10] = $4E then Value:=9999; // на экране prob case ResultRead[11] of 00: Range:=0; end; end; end; constructor TAPPA_109_C_.Create(AOwner: TComponent); begin ConfigPort; inherited Create(AOwner); end; destructor TAPPA_109_C_.Destroy; begin if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); inherited Destroy; end; {--- TPSH_3610Control ---} constructor TPSH_3610Control.Create(AOwner: TComponent); begin PortHandle := 0; FPortName := ''; FPowerOn := False; {--- ---} FPortReadError := False; FPortWriteError := False; FWTimeAccessPort := 0; FWriteTime := 0; FReadTime := 0; {--- ---} FBaudRate := br4800; FParity := false; FStopBits := sbOne; // sbTwo FByteSize := 8; inherited Create(AOwner); end; destructor TPSH_3610Control.Destroy; Var lpErrors : Cardinal; begin lpErrors := 0; ClearCommBreak(PortHandle); ClearCommError(PortHandle , lpErrors , nil); if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); Inherited; end; procedure TPSH_3610Control.ConfigPort; var DCB: TDCB; TimeOuts: TCommTimeouts; tw: Cardinal; begin tw:=0; if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); FillChar(DCB,SizeOf(TDCB),0); DCB.DCBlength:=SizeOf(TDCB); case FBaudRate of br9600: tw:=CBR_9600; br4800: tw:=CBR_4800; br2400: tw:=CBR_2400; br1200: tw:=CBR_1200; end; DCB.BaudRate := tw; DCB.ByteSize := FByteSize; if not FParity then DCB.Parity:=NOPARITY else DCB.Parity:=ODDPARITY; case FStopBits of sbOne : DCB.StopBits := ONESTOPBIT; sbOne5: DCB.StopBits := ONE5STOPBITS; sbTwo : DCB.StopBits := TWOSTOPBITS; end; PortHandle:=CreateFile(PChar(FPortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if INVALIDHandle(PortHandle) then begin { MessageBox(0,PChar('Can not open port '+FPortName),'Error', MB_OK or MB_ICONERROR); {} // SaveErrorInReestor(FPortReadError,FPortWriteError,true,DateToStr(Date)+' '+TimeToStr(Time)); Exit; end else begin FPortReadError := False; FPortWriteError := False; end; with TimeOuts do begin ReadIntervalTimeout := MAXWORD; ReadTotalTimeoutMultiplier := 0; ReadTotalTimeoutConstant := 0; WriteTotalTimeoutMultiplier := 0; WriteTotalTimeoutConstant := 0; end; if not SetCommTimeouts(PortHandle, TimeOuts) then begin MessageBox(0,PChar('Can not set timeouts to port '+FPortName),'Error', MB_OK or MB_ICONERROR); Exit; end; if not INVALIDHandle(PortHandle) then SetCommState(PortHandle , DCB); if not INVALIDHandle(PortHandle) then EscapeCommFunction(PortHandle , SETDTR); {} end; procedure TPSH_3610Control.SetBaudRate(NewValue : TBaudRate); begin if FBaudRate = NewValue then Exit; FBaudRate := NewValue; if not (csDesigning in ComponentState) then ConfigPort; end; procedure TPSH_3610Control.SetPortName(NewValue : String); begin if FPortName = NewValue then Exit; FPortName := NewValue; if not (csDesigning in ComponentState) then ConfigPort; end; procedure TPSH_3610Control.SelfTest(Var ResT : TResTest); Var Com : String; begin // TestPortError; Com := MC_TST + Chr($0A); SendCommand(Com); Sleep(500); Rest.TestTime := GetTickCount - 500; COM := ReadPortA; Rest.TestTime := GetTickCount - Rest.TestTime; Rest.Return := COM; end; procedure TPSH_3610Control.ClearRegStatus; Var Com : String; begin // TestPortError; Com := SC_CLS + Chr($0A); SendCommand(Com); Sleep(5); end; procedure TPSH_3610Control.OCP_PROTECTION_ON; Var Com : String; begin // TestPortError; Com := GS_OCP_PROTECTION_ON + Chr($0A); SendCommand(Com); Sleep(5); end; procedure TPSH_3610Control.OCP_PROTECTION_OFF; Var Com : String; begin // TestPortError; Com := GS_OCP_PROTECTION_OFF + Chr($0A); SendCommand(Com); sleep(5); end; procedure TPSH_3610Control.SetBaseState; Var Com : String; begin // TestPortError; Com := MC_RESET + Chr($0A); SendCommand(Com); sleep(5); end; function TPSH_3610Control.PowerExist : boolean; Var COM , R : String; begin // ConfigPort; Result := false; Com := GS_GET_OUTPUT_STATE; Com := COM + Chr($0A); SendCommand(Com); sleep(5); COM := ''; R := ReadPort(1); While (R <> 'ERROR') and (POS(CHR($0A),R) = 0) do begin Com := COM + R; R := ReadPort(1); end; if POS(CHR($0A),R) <> 0 then begin Delete(R, POS(CHR($0A),R), 1); COM := COM + R; end; {} if COM = '1' then RESULT := TRUE; end; procedure TPSH_3610Control.SetRelayState(const Stat: boolean); Var Com : String; begin // TestPortError; If Stat then Com := GS_OUTPUT_ON else Com := GS_OUTPUT_OFF; Com := COM + Chr($0A); SendCommand(Com); sleep(5); end; procedure TPSH_3610Control.SetVoltage(const Voltage : real); var Com : String; begin if Voltage < 10 then Com := GS_SET_VOLTAGE + ''+ FloatToStrF(Voltage,ffFixed,3,2)+#10 else Com := GS_SET_VOLTAGE + FloatToStrF(Voltage,ffFixed,4,2)+#10; if Voltage >= 36.00 then Com := GS_SET_VOLTAGE + '36.00' + #10; if Pos(',',Com) <> 0 then begin Insert('.',Com,Pos(',',Com)); Delete(Com,Pos(',',Com),1); end; SendCommand(Com); sleep(5); end; procedure TPSH_3610Control.SetCurrent(const Current : real); var Com : String; begin Com := ''; if Current < 10.10 then Com := GS_SET_CURRENT + ''+ FloatToStrF(Current,ffFixed,4,2)+#10; if Pos(',',Com) <> 0 then begin Insert('.',Com,Pos(',',Com)); Delete(Com,Pos(',',Com),1); end; SendCommand(Com); sleep(5); end; function TPSH_3610Control.GetVoltage : Real; Var TS : String; Com : String; Leng : Integer; bw : Integer; begin Result := 0.0; ConfigPort; // TestPortError; TS := ''; Com := GS_GET_VOLTAGE + #10; SendCommand(Com); sleep(5); Com := ReadPort(5); If Com = 'ERROR' then begin // SaveErrorInReestor(false, false, false, ''); Exit; end; Leng := Length(Com); for bw := 1 to 6 do begin if bw <= Leng then if ORD(Com[bw]) = $0A then break else if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; end; Result := StrToFloatDef(TS , 0.0); {} sleep(5); end; procedure TPSH_3610Control.SetLimVoltage(const Voltage : Real); var Com : String; Volt : Real; begin Volt := abs(Voltage); FillChar(t,SizeOf(t),0); if Volt > 36 then Com := GS_SET_OVP_VALUE+'36'+#10 else if Volt < 10 then Com := GS_SET_OVP_VALUE + '0' + FloatToStrF(Volt,ffFixed,4,2)+#10 else Com:=GS_SET_OVP_VALUE + FloatToStrF(Volt,ffFixed,4,2)+#10; if Pos(',',Com) <> 0 then begin Insert('.',Com,Pos(',',Com)); Delete(Com,Pos(',',Com),1); end; SendCommand(Com); sleep(5); end; function TPSH_3610Control.GetLimVoltage : Real; Var TS : String; Com : String; Leng : Integer; bw : Integer; begin Result := 0; // TestPortError; TS := ''; Com := GS_GET_OVP_VALUE + Chr($0A); SendCommand(Com); sleep(5); Com := ReadPort(5); If Com = 'ERROR' then begin // SaveErrorInReestor(false, false, false, ''); Exit; end; Leng := Length(Com); for bw := 1 to 6 do begin if bw <= Leng then if ORD(Com[bw]) = $0A then break else if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; end; Result := StrToFloatDef(TS , 0); sleep(5); end; function TPSH_3610Control.CurrentProtected : Boolean; Var TS : String; R : String; Com : String; begin Result := false; // TestPortError; TS := ''; Com := GS_GET_OCP_PROTECTION_STATUS + Chr($0A); SendCommand(Com); sleep(5); COM := ''; R := ReadPort(1); While (R <> 'ERROR') and (POS(CHR($0A),R) = 0) do begin Com := COM + R; R := ReadPort(1); end; if POS(CHR($0A),R) <> 0 then begin Delete(R, POS(CHR($0A),R), 1); COM := COM + R; end; {} if COM = '1' then Result := true; sleep(5); end; procedure TPSH_3610Control.ALL_PROTECTION_OFF; Var Com : String; begin // TestPortError; Com := GS_ALL_PROTECTION_OFF + Chr($0A); SendCommand(Com); sleep(5); end; function TPSH_3610Control.GetCurrent : Real; Var TS : String; Com : String; Leng : Integer; bw : Integer; begin Result := 0.0; // TestPortError; TS := ''; Com := GS_GET_CURRENT + Chr($0A); SendCommand(Com); sleep(5); Com := ReadPort(5); If Com = 'ERROR' then begin // SaveErrorInReestor(false, false, false, ''); Exit; end; Leng := Length(Com); for bw := 1 to 6 do begin if bw <= Leng then if ORD(Com[bw]) = $0A then break else if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; end; Result := StrToFloatDef(TS , 0.0); sleep(5); end; Function TPSH_3610Control.GetRealCurrent : Real; Var TS : String; Com : String; Leng : Integer; bw : Integer; begin Result := 0.0; // TestPortError; TS := ''; Com := GS_GET_REAL_CURRENT + Chr($0A); SendCommand(Com); sleep(5); Com := ReadPort(5); If Com = 'ERROR' then begin // SaveErrorInReestor(false, false, false, ''); Exit; end; Leng := Length(Com); for bw := 1 to 6 do begin if bw <= Leng then if ORD(Com[bw]) = $0A then break else if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; end; Result := StrToFloatDef(TS , 0.0); sleep(5); end; Function TPSH_3610Control.GetREALVoltage : Real; Var TS : String; Com : String; Leng : Integer; bw : Integer; begin Result := 0.0; ConfigPort; // TestPortError; TS := ''; Com := GS_GET_REAL_VOLTAGE + Chr($0A); SendCommand(Com); sleep(5); Com := ReadPort(5); If Com = 'ERROR' then begin // SaveErrorInReestor(false, false, false, ''); Exit; end; Leng := Length(Com); for bw := 1 to 6 do begin if bw <= Leng then if ORD(Com[bw]) = $0A then break else if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; end; Result := StrToFloatDef(TS , 0.0); sleep(5); end; function TPSH_3610Control.Identification : String; Var Com : String; begin // TestPortError; Com := MC_IDN + #10; SendCommand(Com); Sleep(100); COM := ReadPortA; If Com = 'ERROR' then begin // SaveErrorInReestor(false, false, false, ''); Exit; end; Result := Com; Sleep(50); end; function TPSH_3610Control.ReadPortA : String; Var COM : String; R : String; begin COM := ''; R := ReadPort(1); While (R <> 'ERROR') and (POS(CHR($0A),R) = 0) do begin Com := COM + R; R := ReadPort(1); end; if POS(CHR($0A),R) <> 0 then begin Delete(R, POS(CHR($0A),R), 1); COM := COM + R; end; {} If R = 'ERROR' then begin // SaveErrorInReestor(false, false, false, ''); Exit; end; Result := Com; Sleep(50); end; function TPSH_3610Control.ReadPort(bytesR : Cardinal): String; var ov: _OVERLAPPED; br: Cardinal; tw: String; t: array [1..255] of byte; i: byte; CheckRange : Boolean; t1 : Cardinal; t2 : Cardinal; begin t1 := GetTickCount; FReadTime := 0; {-------------------} if INVALIDHandle(PortHandle) then FPortReadError := true; FWTimeAccessPort := 0; If FPortReadError or FPortWriteError then begin // SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := 'ERROR'; t1 := GetTickCount; ConfigPort; t2 := GetTickCount - t1; FWTimeAccessPort := t2; Exit; end; FillChar(t, SizeOf(t) , 0); FillChar(ov,SizeOf(ov), 0); ov.hEvent:=CreateEvent(nil, true, true, nil); CheckRange:=(BytesR + 1 <= 255) and (BytesR + 1 > 0); If not CheckRange then // Если последний индекс begin // не в границах диапазона массива Result := 'ERROR'; if not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); Exit; end; ReadFile(PortHandle, t[1], bytesR+1, br, @ov); // if not INVALIDHandle(ov.hEvent) then WaitForSingleObject(ov.hEvent, WaitTimeRead); tw:=''; if not INVALIDHandle(PortHandle) then if GetOverlappedResult(PortHandle, ov, br, false) then begin for i:=1 to bytesR + 1 do tw := tw + Chr(T[i]); Result := tw; end else Result := 'ERROR' else Result := 'ERROR'; FPortReadError := False; If Result = 'ERROR' then FPortReadError := True; if not INVALIDHandle(ov.hEvent) then if ResetEvent(ov.hEvent) and (Result <> 'ERROR') then CloseHandle(ov.hEvent); FWTimeAccessPort := 0; If FPortReadError or FPortWriteError then begin // SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := 'ERROR'; t1 := GetTickCount; ConfigPort; t2 := GetTickCount - t1; FWTimeAccessPort := t2; Exit; end; t2 := GetTickCount - t1; FReadTime := t2; // SaveInReestorReadTime; end; (**) function TPSH_3610Control.SendCommand(Command: String): boolean; var ov : _OVERLAPPED; bw : Cardinal; // Кол - во записанных в порт байт t1 : Cardinal; t2 : Cardinal; begin t1 := GetTickCount; FWriteTime := 0; {-----------------------} if INVALIDHandle(PortHandle) then FPortWriteError := true; IF FPortWriteError or FPortReadError then begin // SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := False; Exit; end; FillChar(ov,SizeOf(ov),0); // Обнуление ("очистка") структуры - ov ov.hEvent:=CreateEvent(nil, true, true, nil); // Создание события If Command = '' then begin if not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); // Уничтожаем событие Result:=False; Exit; end; if (not INVALIDHandle(PortHandle)) and (not INVALIDHandle(ov.hEvent)) then WriteFile(PortHandle, Command[1], Length(Command), bw, @ov); if not INVALIDHandle(ov.hEvent) then WaitForSingleObject(ov.hEvent, WaitTimeWrite); if INVALIDHandle(PortHandle) then FPortWriteError := true; IF FPortWriteError then begin // SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := False; Exit; end; Result := false; if (not INVALIDHandle(PortHandle)) and (not INVALIDHandle(ov.hEvent)) then if GetOverlappedResult(PortHandle, ov, bw, false) then Result:=true; FPortWriteError := not Result; if not INVALIDHandle(ov.hEvent) then if ResetEvent(ov.hEvent) and Result then CloseHandle(ov.hEvent); {-----------------------} t2 := GetTickCount - t1; FWriteTime := t2; // SaveInReestorWriteTime; end; {--- TPowerSupplyControl ---} procedure Register; begin RegisterComponents('Samples', [TPowerSupplyControl , TPSH_3610Control, TAPPA_105_C_, TAPPA_109_C_, TPowerSupply]); end; constructor TPowerSupplyControl.Create(AOwner: TComponent); begin Inherited; PortHandle := 0; FPowerOn := False; FPortReadError := False; FPortWriteError := False; FWTimeAccessPort := 0; FWriteTime := 0; FReadTime := 0; FBaudRate := br2400; FParity := false; FStopBits := sbOne; FPortName := ''; // COM1 FByteSize := 8; {if not (csDesigning in ComponentState) then begin // ConfigPort; end; {} end; destructor TPowerSupplyControl.Destroy; Var lpErrors : Cardinal; begin lpErrors := 0; ClearCommBreak(PortHandle); ClearCommError(PortHandle , lpErrors , nil); if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); Inherited; end; Procedure TPowerSupplyControl.SaveErrorInReestor(Read : Boolean; Write : Boolean; Handle : Boolean; Error : String); Var Reestor : TRegistry; begin Reestor := TRegistry.Create; Reestor.RootKey := HKEY_LOCAL_MACHINE; Reestor.OpenKey('Software\PowerSupplyControl\'+Name,true); If Read then Reestor.WriteString('ReadError '+Pchar(FPortName)+' : ' , Error); If Write then Reestor.WriteString('WriteError '+Pchar(FPortName)+' : ', Error); If Handle then Reestor.WriteString('HandleError '+Pchar(FPortName)+' : ', Error); Reestor.CloseKey; end; Procedure TPowerSupplyControl.SaveInReestorWriteTime; Var Reestor : TRegistry; begin Reestor := TRegistry.Create; Reestor.RootKey := HKEY_LOCAL_MACHINE; Reestor.OpenKey('Software\PowerSupplyControl\'+Name,true); Reestor.WriteString('WaitWrite'+Pchar(FPortName)+' : ',IntToStr(FWriteTime)); Reestor.CloseKey; end; Procedure TPowerSupplyControl.SaveInReestorReadTime; Var Reestor : TRegistry; begin Reestor := TRegistry.Create; Reestor.RootKey := HKEY_LOCAL_MACHINE; Reestor.OpenKey('Software\PowerSupplyControl\'+Name,true); Reestor.WriteString('WaitRead'+Pchar(FPortName)+' : ',IntToStr(FReadTime)); Reestor.CloseKey; end; procedure TPowerSupplyControl.ConfigPort; var DCB: TDCB; TimeOuts: TCommTimeouts; tw: Cardinal; begin tw:=0; if not INVALIDHandle(PortHandle) then CloseHandle(PortHandle); FillChar(DCB,SizeOf(TDCB),0); DCB.DCBlength:=SizeOf(TDCB); case FBaudRate of br9600: tw:=CBR_9600; br4800: tw:=CBR_4800; br2400: tw:=CBR_2400; br1200: tw:=CBR_1200; end; DCB.BaudRate:=tw; DCB.ByteSize:=FByteSize; if not FParity then DCB.Parity:=NOPARITY else DCB.Parity:=ODDPARITY; case FStopBits of sbOne : DCB.StopBits:=ONESTOPBIT; sbOne5: DCB.StopBits:=ONE5STOPBITS; sbTwo : DCB.StopBits:=TWOSTOPBITS; end; PortHandle := CreateFile(PChar(FPortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if INVALIDHandle(PortHandle) then begin { MessageBox(0,PChar('Can not open port '+FPortName),'Error', MB_OK or MB_ICONERROR); {} // SaveErrorInReestor(FPortReadError,FPortWriteError,true,DateToStr(Date)+' '+TimeToStr(Time)); Exit; end else begin FPortReadError := False; FPortWriteError := False; end; with TimeOuts do begin ReadIntervalTimeout:=MAXWORD; ReadTotalTimeoutMultiplier:=0; ReadTotalTimeoutConstant:=0; WriteTotalTimeoutMultiplier:=0; WriteTotalTimeoutConstant:=0; end; if not SetCommTimeouts(PortHandle, TimeOuts) then begin MessageBox(0,PChar('Can not set timeouts to port '+FPortName),'Error', MB_OK or MB_ICONERROR); Exit; end; if not INVALIDHandle(PortHandle) then SetCommState(PortHandle,DCB); if not INVALIDHandle(PortHandle) then EscapeCommFunction(PortHandle,SETDTR); end; procedure TPowerSupplyControl.SetByteSize(NewValue: byte); begin if FByteSize = NewValue then Exit; FByteSize:=NewValue; if not (csDesigning in ComponentState) then ConfigPort; end; procedure TPowerSupplyControl.SetPortName(NewValue: String); begin if FPortName = NewValue then Exit; FPortName:=NewValue; if not (csDesigning in ComponentState) then ConfigPort; end; procedure TPowerSupplyControl.SetStopBits(NewValue: TStopBits); begin if FStopBits = NewValue then Exit; FStopBits:=NewValue; if not (csDesigning in ComponentState) then ConfigPort; end; procedure TPowerSupplyControl.SetParity(NewValue: boolean); begin if FParity = NewValue then Exit; FParity:=NewValue; if not (csDesigning in ComponentState) then ConfigPort; end; procedure TPowerSupplyControl.SetBaudRate(NewValue: TBaudRate); begin if FBaudRate = NewValue then Exit; FBaudRate:=NewValue; if not (csDesigning in ComponentState) then ConfigPort; end; procedure TPowerSupplyControl.SetVoltage(const Voltage: Real); var Com : String; begin if Voltage < 10 then Com:='SV 0'+FloatToStrF(Voltage,ffFixed,3,2)+#13 else Com:='SV '+FloatToStrF(Voltage,ffFixed,4,2)+#13; if Voltage >= 40.00 then Com:='SV 40.00'+#13; if Pos(',',Com) <> 0 then begin Insert('.',Com,Pos(',',Com)); Delete(Com,Pos(',',Com),1); end; SendCommand(Com); end; procedure TPowerSupplyControl.IncVoltage; var Com: String; begin Com:='SV+'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.DecVoltage; var Com: String; begin Com:='SV-'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetLimVoltage(const Voltage: integer); var Com: String; begin FillChar(t,SizeOf(t),0); if Voltage > 40 then Com:='SU 40'+#13 else if Voltage < 10 then Com:='SU 0'+IntToStr(Voltage)+#13 else Com:='SU '+IntToStr(Voltage)+#13; SendCommand(Com); end; procedure TPowerSupplyControl.IncLimVoltage; var Com: String; begin Com:='SU+'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.DecLimVoltage; var Com: String; begin Com:='SU-'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetLimCurrent(const Current: Real); var Com: String; begin Com:='SI '+FloatToStrF(Current,ffFixed,3,2)+#13; if Pos(',',Com) <> 0 then begin Insert('.',Com,Pos(',',Com)); Delete(Com,Pos(',',Com),1); end; SendCommand(Com); end; procedure TPowerSupplyControl.IncLimCurrent; var Com: String; begin Com:='SI+'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.DecLimCurrent; var Com: String; begin Com:='SI-'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetLimPower(const Power: Integer); var Com: String; begin if Power < 10 then Com:='SP 00'+IntToStr(Power) + #13; if (Power >= 10) and (Power < 100) then Com:='SP 0'+IntToStr(Power) + #13; if Power >= 100 then Com:='SP '+IntToStr(Power) + #13; SendCommand(Com); end; procedure TPowerSupplyControl.IncLimPower; var Com: String; begin Com:='SP+'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.DecLimPower; var Com: String; begin Com:='SP-'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetRelayState(const Stat: Boolean); var Com : String; begin TestPortError; If Stat then begin Com:='KOE'+#13; FPowerOn := True; end else begin Com:='KOD'+#13; FPowerOn := False; end; SendCommand(Com); end; procedure TPowerSupplyControl.InvertRelay; var Com: String; begin Com:='KO'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetMaxLimVoltage; var Com: String; begin Com:='SUM'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetMaxLimCurrent; var Com: String; begin Com:='SIM'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetMaxLimPower; var Com: String; begin Com:='SPM'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.SetFineStatus(const Stat: boolean); var Com: String; begin if Stat then Com:='KF'+#13 else Com:='KN'+#13; SendCommand(Com); end; procedure TPowerSupplyControl.GetFullStatus(var PSInfo: TPSState); var Com, TS: String; begin ZeroMemory(@PSInfo,SizeOf(PSInfo)); TS:=''; TestPortError; Com:='L'+#13; SendCommand(Com); Com:=ReadPortOV(39); If Com = 'ERROR' then Exit; TS:=Copy(Com,2,5); if Pos('.',TS) <> 0 then begin Insert(',',TS,Pos('.',TS)); Delete(TS,Pos('.',TS),1); PSInfo.Voltage:=StrToFloatDef(TS, 0.0); end; TS:=Copy(Com,8,5); if Pos('.',TS) <> 0 then begin Insert(',',TS,Pos('.',TS)); Delete(TS,Pos('.',TS),1); PSInfo.Current:=StrToFloatDef(TS, 0.0); end; TS:=Copy(Com,14,5); if Pos('.',TS) <> 0 then begin Insert(',',TS,Pos('.',TS)); Delete(TS,Pos('.',TS),1); PSInfo.Power:=StrToFloatDef(TS, 0.0); end; TS:=Copy(Com,20,2); PSInfo.VoltLim:=StrToInt(TS); TS:=Copy(Com,23,4); if Pos('.',TS) <> 0 then begin Insert(',',TS,Pos('.',TS)); Delete(TS,Pos('.',TS),1); PSInfo.CurrLim:=StrToFloatDef(TS, 0.0); end; TS:=Copy(Com,28,3); PSInfo.PowerLim:=StrToInt(TS); PSInfo.RelayStat:=Com[32] = '1'; PSInfo.Overheat:=Com[33] = '1'; PSInfo.FineStat:=Com[34] = '1'; PSInfo.FineLockStat:=Com[35] = '0'; PSInfo.RemStat:=Com[36] = '1'; PSInfo.LockStat:=Com[37] = '1'; end; procedure TPowerSupplyControl.GetStatus(var PSInfo: TPSState); var Com , TS : String; begin FillChar(t,SizeOf(t),0); ZeroMemory(@PSInfo,SizeOf(PSInfo)); TS:=''; TestPortError; Com:='F'+#13; SendCommand(Com); Com:=ReadPortOV(9); If Com = 'ERROR' then Exit; PSInfo.RelayStat:=Com[2] = '1'; PSInfo.Overheat:=Com[3] = '1'; PSInfo.FineStat:=Com[4] = '1'; PSInfo.FineLockStat:=Com[5] = '0'; PSInfo.RemStat:=Com[6] = '1'; PSInfo.LockStat:=Com[7] = '1'; end; function TPowerSupplyControl.GetVoltage: Real; var BW : Integer; Com, TS : String; Leng : Integer; begin Result := 0.0; TestPortError; TS:=''; Com:='V'+Chr($0D); SendCommand(Com); Sleep(50); Com := ReadPortOV(8); If Com = 'ERROR' then begin SaveErrorInReestor(false, false, false, ''); Exit; end; Leng := Length(Com); if Leng < 2 then exit; for bw := 2 to 6 do begin if bw <= Leng then if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; end; Result := StrToFloatDef(TS , 0.0); Sleep(50); end; function TPowerSupplyControl.GetLimVoltage: Integer; var Com, TS: String; begin Result:=0; FillChar(t,SizeOf(t),0); TS:=''; Com:='U'+#13; SendCommand(Com); Com:=ReadPortOV(5); If Com = 'ERROR' then Exit; TS:=Com[2] + Com[3]; Result:=StrToInt(TS); end; function TPowerSupplyControl.GetLimCurrent: Real; var BW: Cardinal; Com, TS: String; begin Result := 0.0; TestPortError; FillChar(t,SizeOf(t),0); TS:=''; Com:='I'+#13; SendCommand(Com); Com:=ReadPortOV(7); If Com = 'ERROR' then Exit; for bw:=2 to 5 do if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; Result:=StrToFloatdef(TS, 0.0); end; function TPowerSupplyControl.GetLimPower: Integer; var Com, TS: String; begin Result:=0; FillChar(t,SizeOf(t),0); TS:=''; Com:='P'+#13; SendCommand(Com); Com:=ReadPortOV(6); If Com = 'ERROR' then Exit; TS:=Com[2] + Com[3] + Com[4]; Result:=StrToInt(TS); end; function TPowerSupplyControl.GetCurrent: Real; var BW: Cardinal; Com, TS: String; begin Result := 0.0; TestPortError; FillChar(t,SizeOf(t),0); TS:=''; Com:='A'+#13; SendCommand(Com); Sleep(50); Com:=ReadPortOV(8); If Com = 'ERROR' then Exit; for bw:=2 to 6 do if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; Result:=StrToFloatDef(TS , 0.0); Sleep(50); end; function TPowerSupplyControl.GetPower: Real; var BW: Cardinal; Com, TS: String; begin Result := 0.0; TestPortError; FillChar(t,SizeOf(t),0); TS:=''; Com:='W'+#13; SendCommand(Com); Com:=ReadPortOV(8); If Com = 'ERROR' then Exit; for bw:=2 to 6 do if Com[bw] <> '.' then TS:=TS + Com[bw] else TS:=TS + ','; Result := StrToFloatDef(TS, 0.0); end; procedure TPowerSupplyControl.SaveData; var Com: String; begin Com:='EEP'+#13; SendCommand(Com); end; function TPowerSupplyControl.SendCommand(Command: String): boolean; var ov : _OVERLAPPED; bw : Cardinal; // Кол - во записанных в порт байт t1 : Cardinal; t2 : Cardinal; begin t1 := GetTickCount; FWriteTime := 0; {-----------------------} if INVALIDHandle(PortHandle) then FPortWriteError := true; IF FPortWriteError or FPortReadError then begin SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := False; Exit; end; FillChar(ov,SizeOf(ov),0); // Обнуление ("очистка") структуры - ov ov.hEvent:=CreateEvent(nil, true, true, nil); // Создание события If Command = '' then begin if not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); // Уничтожаем событие Result:=False; Exit; end; if (not INVALIDHandle(PortHandle)) and (not INVALIDHandle(ov.hEvent)) then WriteFile(PortHandle, Command[1], Length(Command), bw, @ov); if not INVALIDHandle(ov.hEvent) then WaitForSingleObject(ov.hEvent, WaitTimeWrite); if INVALIDHandle(PortHandle) then FPortWriteError := true; IF FPortWriteError then begin SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := False; Exit; end; Result := false; if (not INVALIDHandle(PortHandle)) and (not INVALIDHandle(ov.hEvent)) then if GetOverlappedResult(PortHandle, ov, bw, false) then Result:=true; FPortWriteError := not Result; if not INVALIDHandle(ov.hEvent) then if ResetEvent(ov.hEvent) and Result then CloseHandle(ov.hEvent); {-----------------------} t2 := GetTickCount - t1; FWriteTime := t2; SaveInReestorWriteTime; end; function TPowerSupplyControl.ReadPortOV(bytesR: Cardinal): String; var ov: _OVERLAPPED; br: Cardinal; tw: String; t: array [1..255] of byte; i: byte; CheckRange : Boolean; t1 : Cardinal; t2 : Cardinal; begin t1 := GetTickCount; FReadTime := 0; {-------------------} if INVALIDHandle(PortHandle) then FPortReadError := true; FWTimeAccessPort := 0; If FPortReadError or FPortWriteError then begin SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := 'ERROR'; t1 := GetTickCount; ConfigPort; t2 := GetTickCount - t1; FWTimeAccessPort := t2; Exit; end; FillChar(t, SizeOf(t) , 0); FillChar(ov,SizeOf(ov), 0); ov.hEvent:=CreateEvent(nil, true, true, nil); CheckRange:=(BytesR + 1 <= 255) and (BytesR + 1 > 0); If not CheckRange then // Если последний индекс begin // не в границах диапазона массива Result := 'ERROR'; if not INVALIDHandle(ov.hEvent) then CloseHandle(ov.hEvent); Exit; end; ReadFile(PortHandle, t[1], bytesR+1, br, @ov); if not INVALIDHandle(ov.hEvent) then WaitForSingleObject(ov.hEvent, WaitTimeRead); tw:=''; if not INVALIDHandle(PortHandle) then if GetOverlappedResult(PortHandle, ov, br, false) then begin for i:=1 to bytesR + 1 do tw := tw + Chr(T[i]); Result := tw; end else Result := 'ERROR' else Result := 'ERROR'; FPortReadError := False; If Result = 'ERROR' then FPortReadError := True; if not INVALIDHandle(ov.hEvent) then if ResetEvent(ov.hEvent) and (Result <> 'ERROR') then ; // CloseHandle(ov.hEvent); FWTimeAccessPort := 0; If FPortReadError or FPortWriteError then begin SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); Result := 'ERROR'; t1 := GetTickCount; ConfigPort; t2 := GetTickCount - t1; FWTimeAccessPort := t2; Exit; end; t2 := GetTickCount - t1; FReadTime := t2; SaveInReestorReadTime; end; Procedure TPowerSupplyControl.TestPortError; begin If FPortReadError or FPortWriteError then begin SaveErrorInReestor(FPortReadError, FPortWriteError, false,DateToStr(Date)+' '+TimeToStr(Time)); ConfigPort; Sleep(300); end; end; function TPowerSupplyControl.PowerExist: boolean; var Com: String; begin Result := false; TestPortError; Com:='V'+Chr($0D); SendCommand(Com); Com:=ReadPortOV(8); if (Com <> '') and (Com <> 'ERROR') then Result := true; FPowerOn := Result; end; { asm and al , $00 out 21h , al out $A1 , al end; {-- размаскировать все вектора прерываний --} end.
{ Bipartite Maximum Independent Set Matching Method O(N3) Input: G: UnDirected Simple Bipartite Graph M, N: Number of vertices Output: I1[I]: Vertex I from first part is in the set I2[I]: Vertex I from second part is in the set IndSize: Size of independent set Reference: West By Behdad } program BipartiteMaximumIndependentSet; const MaxNum = 100 + 2; var M, N: Integer; G: array [1 .. MaxNum, 1 .. MaxNum] of Integer; Mark: array [1 .. MaxNum] of Boolean; M1, M2, I1, I2: array [1 .. MaxNum] of Integer; IndSize: Integer; function ADfs (V : Integer) : Boolean; var I : Integer; begin Mark[V] := True; for I := 1 to N do if (G[V, I] <> 0) and ((M2[I] = 0) or not Mark[M2[I]] and ADfs(M2[I])) then begin M2[I] := V; M1[V] := I; ADfs := True; Exit; end; ADfs := False; end; procedure BDfs (V : Integer); var I : Integer; begin Mark[V] := True; for I := 1 to N do if (G[V, I] = 1) and (I2[I] = 1) then begin I2[I] := 0; I1[M2[I]] := 1; BDfs(M2[I]); end; end; procedure BipIndependent; var I: Integer; Fl: Boolean; begin IndSize := M + N; FillChar(Mark, SizeOf(Mark), 0); repeat Fl := True; FillChar(Mark, SizeOf(Mark), 0); for I := 1 to M do if not Mark[I] and (M1[I] = 0) and ADfs(I) then begin Dec(IndSize); Fl := False; end; until Fl; FillChar(I1, SizeOf(I1), 0); FillChar(I2, SizeOf(I2), 0); FillChar(Mark, SizeOf(Mark), 0); for I := 1 to M do if M1[I] = 0 then I1[I] := 1; for I := 1 to N do I2[I] := 1; for I := 1 to M do if M1[I] = 0 then BDfs(I); end; begin BipIndependent; end.
{Implementation of Buffer with capacity = 2 and without priority} Unit Buffer; Interface type p_Buffer = ^BufferObj; BufferObj = object private {capacity of Buffer} capacity : longint; {length Of Buffer} indBuf : longint; {massive number and time of Source in Buffer according} masBufN : array[1..2] of longint; masBufT : array[1..2] of real; public {initialization the field} constructor Init(capacity_ : longint); {return quantity elemnts in Buffer} function getQuantity : longint; {check for emptiness and fullness of the buffer according} function Empty : boolean; function Full : boolean; {setter and getter of Request for Buffer according} procedure setRequest(bufN : longint; bufT : real); procedure getRequest(var bufN : longint; var bufT : real); {clear all buffer} procedure clearBuffer; end; Implementation constructor BufferObj.Init; begin capacity := capacity_; indBuf := 0; end; function BufferObj.Empty; begin Empty := (indBuf = 0); end; function BufferObj.Full; begin Full := (indBuf = CAPACITY); end; procedure BufferObj.setRequest; begin inc(indBuf); masBufN[indBuf] := bufN; masBufT[indBuf] := bufT; end; procedure BufferObj.getRequest ; begin dec(indBuf); bufN := masBufN[1]; bufT := masBufT[1]; masBufN[1] := masBufN[2]; masBufT[1] := masBufT[2]; end; procedure BufferObj.clearBuffer; var i : longint; begin for i := 1 to capacity do begin masBufN[i] := 0; masBufT[i] := 0; end; indBuf := 0; end; function BufferObj.getQuantity; begin getQuantity := indBuf; end; BEGIN END.
{----------------------------------------------------------------------------- The contents of this file are subject to the GNU General Public 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.gnu.org/copyleft/gpl.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. $Id$ You may retrieve the latest version of this file at the Corporeal Website, located at http://www.elsdoerfer.info/corporeal Known Issues: -----------------------------------------------------------------------------} // from http://www.installationexcellence.com/articles/VistaWithDelphi/Index.html unit VistaCompat; interface uses Forms, Windows, Graphics; function IsWindowsVista: Boolean; procedure SetVistaFonts(const AForm: TCustomForm); procedure SetVistaContentFonts(const AFont: TFont); procedure SetDesktopIconFonts(const AFont: TFont); const VistaFont = 'Segoe UI'; VistaContentFont = 'Calibri'; XPContentFont = 'Verdana'; XPFont = 'Tahoma'; var CheckOSVerForFonts: Boolean = True; implementation uses SysUtils, Dialogs, Controls, UxTheme; procedure SetVistaTreeView(const AHandle: THandle); begin if IsWindowsVista then SetWindowTheme(AHandle, 'explorer', nil); end; procedure SetVistaFonts(const AForm: TCustomForm); begin if (IsWindowsVista or not CheckOSVerForFonts) and not SameText(AForm.Font.Name, VistaFont) and (Screen.Fonts.IndexOf(VistaFont) >= 0) then begin AForm.Font.Size := AForm.Font.Size + 1; AForm.Font.Name := VistaFont; end; end; procedure SetVistaContentFonts(const AFont: TFont); begin if (IsWindowsVista or not CheckOSVerForFonts) and not SameText(AFont.Name, VistaContentFont) and (Screen.Fonts.IndexOf(VistaContentFont) >= 0) then begin AFont.Size := AFont.Size + 2; AFont.Name := VistaContentFont; end; end; procedure SetDefaultFonts(const AFont: TFont); begin AFont.Handle := GetStockObject(DEFAULT_GUI_FONT); end; procedure SetDesktopIconFonts(const AFont: TFont); var LogFont: TLogFont; begin if SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont), @LogFont, 0) then AFont.Handle := CreateFontIndirect(LogFont) else SetDefaultFonts(AFont); end; function IsWindowsVista: Boolean; var VerInfo: TOSVersioninfo; begin VerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); GetVersionEx(VerInfo); Result := VerInfo.dwMajorVersion >= 6; end; end.
unit uLogs; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls; type TfLogs = class(TForm) TorLogs: TMemo; BypasserLogs: TMemo; Splitter1: TSplitter; Label1: TLabel; Label2: TLabel; procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var fLogs: TfLogs; implementation {$R *.dfm} uses uSettings; function AttachConsole(dwProcessId: DWORD): BOOL; stdcall; external 'kernel32.dll' name 'AttachConsole'; function ReadConsole(PID: Cardinal): TStringList; var BufferInfo: _CONSOLE_SCREEN_BUFFER_INFO; BufferSize, BufferCoord: _COORD; ReadRegion: _SMALL_RECT; Buffer: array of _CHAR_INFO; I, J: Integer; Line: AnsiString; ConsoleHandle: DWORD; begin try if AttachConsole(PID) then ConsoleHandle := GetStdHandle(STD_OUTPUT_HANDLE); Result := TStringList.Create; ZeroMemory(@BufferInfo, SizeOf(BufferInfo)); if not GetConsoleScreenBufferInfo(ConsoleHandle, BufferInfo) then // raise Exception.Create('GetConsoleScreenBufferInfo error: ' + IntToStr(GetLastError)); Sleep(1); SetLength(Buffer, BufferInfo.dwSize.X * BufferInfo.dwSize.Y); BufferSize.X := BufferInfo.dwSize.X; BufferSize.Y := BufferInfo.dwSize.Y; BufferCoord.X := 0; BufferCoord.Y := 0; ReadRegion.Left := 0; ReadRegion.Top := 0; ReadRegion.Right := BufferInfo.dwSize.X; ReadRegion.Bottom := BufferInfo.dwSize.Y; if ReadConsoleOutput(ConsoleHandle, Pointer(Buffer), BufferSize, BufferCoord, ReadRegion) then begin for I := 0 to BufferInfo.dwSize.Y - 1 do begin Line := ''; for J := 0 to BufferInfo.dwSize.X - 1 do Line := Line + Buffer[I * BufferInfo.dwSize.X + J].AsciiChar; if Trim(Line) <> '' then Result.Add(Trim(Line)); end end //else // raise Exception.Create('ReadConsoleOutput error: ' + IntToStr(GetLastError)); finally FreeConsole; end; end; procedure TfLogs.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F5 then begin TorLogs.Text := ReadConsole(dwTorPID).Text; SendMessage(TorLogs.Handle, WM_VSCROLL, SB_BOTTOM, 0); BypasserLogs.Text := ReadConsole(dwRKNPID).Text; SendMessage(BypasserLogs.Handle, WM_VSCROLL, SB_BOTTOM, 0); end; end; procedure TfLogs.FormShow(Sender: TObject); begin ShowWindow(Application.Handle, SW_HIDE); CenteringWindow(Handle, GetDesktopWindow); TorLogs.Text := ReadConsole(dwTorPID).Text; SendMessage(TorLogs.Handle, WM_VSCROLL, SB_BOTTOM, 0); BypasserLogs.Text := ReadConsole(dwRKNPID).Text; SendMessage(BypasserLogs.Handle, WM_VSCROLL, SB_BOTTOM, 0); end; end.
unit Unit1; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, //GLS GLScene, GLObjects, GLVectorGeometry, GLCadencer, GLBehaviours, GLGraph, GLMovement, GLWin32Viewer, GLCrossPlatform, GLCoordinates, GLBaseClasses, GLUtils, GLSimpleNavigation; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; Cube2: TGLCube; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; DummyCube1: TGLDummyCube; GLCadencer1: TGLCadencer; MoveBtn: TBitBtn; Sphere1: TGLSphere; GLSimpleNavigation1: TGLSimpleNavigation; procedure FormActivate(Sender: TObject); procedure MoveBtnClick(Sender: TObject); private procedure PathTravelStop(Sender: TObject; Path: TGLMovementPath; var Looped: Boolean); procedure PathAllTravelledOver(Sender: TObject); public end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormActivate(Sender: TObject); var Movement: TGLMovement; Path: TGLMovementPath; Node: TGLPathNode; begin // Create a movement, a path and the first node of the path. Movement := GetOrCreateMovement(Cube2); Movement.OnPathTravelStop := PathTravelStop; Movement.OnAllPathTravelledOver := PathAllTravelledOver; Path := Movement.AddPath; Path.ShowPath := True; // Path.StartTime := 2; // Path.Looped := True; Node := Path.AddNodeFromObject(Cube2); Node.Speed := 4.0; // Add a node. Node := Path.AddNode; Node.Speed := 4.0; Node.PositionAsVector := VectorMake(-10, 0, 0, 1); Node.RotationAsVector := VectorMake(0, 0, 0); // Add a node. Node := Path.AddNode; Node.Speed := 4.0; Node.PositionAsVector := VectorMake(0, 5, - 5); Node.RotationAsVector := VectorMake(0, 90, 0); // Add a node. Node := Path.AddNode; Node.Speed := 4.0; Node.PositionAsVector := VectorMake(6, - 5, 2); Node.RotationAsVector := VectorMake(0, 180, 0); // Add a node. Node := Path.AddNode; Node.Speed := 4.0; Node.PositionAsVector := VectorMake(-6, 0, 0); Node.RotationAsVector := VectorMake(0, 259, 0); // Activatived the current path. Movement.ActivePathIndex := 0; end; procedure TForm1.MoveBtnClick(Sender: TObject); var Movement: TGLMovement; begin Movement := GetMovement(Cube2); if Assigned(Movement) then begin Movement.StartPathTravel; GLCadencer1.Enabled := True; end; end; procedure TForm1.PathTravelStop(Sender: TObject; Path: TGLMovementPath; var Looped: Boolean); begin if not Application.Terminated then InformationDlg('Path Travel Stopped'); end; procedure TForm1.PathAllTravelledOver(Sender: TObject); begin if not Application.Terminated then InformationDlg('All Path(es) Traveled Over'); end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Datasnap.DSProxyDispatcher; interface uses Datasnap.DSClientMetadata, System.Classes, System.Generics.Collections, Web.HTTPApp; type /// <summary> /// The proxy dispatcher for WebBroker based datasnap servers /// </summary> TDSProxyDispatcher = class(TCustomWebFileDispatcher) strict private FAvailableProxies: TDictionary<string, string>; FDSProxyGenerator: TDSProxyGenerator; procedure OnBeforeDispatch(Sender: TObject; const AFileName: string; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure BuildAvailableProxies; procedure SetDSProxyGenerator(const Value: TDSProxyGenerator); function GetLanguage(const AFileName: String): String; private FRequiredProxyFilesPath: String; // IWebDispatch {$HINTS OFF} function DispatchMethodType: TMethodType; {$HINTS ON} procedure SetRequiredProxyFilesPath(const Value: String); protected procedure CreateZipFile(LanguageRequiredFiles, Filename: String); function isSupportedProxy(const Language: String; out WriterID: String): Boolean; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AfterDispatch; /// <summary> /// Represents the full path where are the required proxy files /// </summary> property RequiredProxyFilesPath: String read FRequiredProxyFilesPath write SetRequiredProxyFilesPath; /// <summary> /// The TDSProxyGenerator instance to use /// </summary> property DSProxyGenerator: TDSProxyGenerator read FDSProxyGenerator write SetDSProxyGenerator; end; implementation uses Datasnap.DSProxyWriter, Datasnap.DSProxyUtils, System.StrUtils, System.SysUtils, System.Types, Web.WebFileDispatcher; { TDSProxyDipatcher } procedure TDSProxyDispatcher.BuildAvailableProxies; var writer: String; WriterProxy: TDSProxyWriter; begin if not assigned(FAvailableProxies) then begin FAvailableProxies := TDictionary<string, string>.Create; for writer in TDSProxyWriterFactory.RegisteredWritersList do begin WriterProxy := TDSProxyWriterFactory.GetWriter(writer); try if not FAvailableProxies.ContainsKey(WriterProxy.Properties.Language) then FAvailableProxies.Add(WriterProxy.Properties.Language, writer); finally WriterProxy.Free; end; end; end; end; constructor TDSProxyDispatcher.Create(AOwner: TComponent); begin inherited Create(AOwner); RootDirectory := '.'; WebDirectories.Clear; WebFileExtensions.Clear; TWebDirectoryItem.Create(WebDirectories, dirInclude, '\proxy\*'); TWebDirectoryItem.Create(WebDirectories, dirExclude, '\proxy\*\*'); RequiredProxyFilesPath := 'proxy'; TWebFileExtensionItem.Create(WebFileExtensions, 'application/x-zip-compressed', 'zip'); BeforeDispatch := OnBeforeDispatch; end; procedure TDSProxyDispatcher.CreateZipFile(LanguageRequiredFiles, Filename: String); begin TDSProxyUtils.CompressDirectory(LanguageRequiredFiles, Filename); end; destructor TDSProxyDispatcher.Destroy; begin FreeAndNil(FAvailableProxies); inherited; end; function TDSProxyDispatcher.DispatchMethodType: TMethodType; begin Result := mtGet; end; function TDSProxyDispatcher.GetLanguage(const AFileName: String): String; var a: TStringDynArray; begin a := SplitString(LowerCase(AFileName), '.'); Result := a[0]; end; function TDSProxyDispatcher.isSupportedProxy(const Language: String; out WriterID: String): Boolean; begin BuildAvailableProxies; Result := FAvailableProxies.TryGetValue(Language, WriterID); end; procedure TDSProxyDispatcher.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FDSProxyGenerator) then FDSProxyGenerator := nil; end; procedure TDSProxyDispatcher.OnBeforeDispatch(Sender: TObject; const AFileName: string; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var D1, D2: TDateTime; Language, WriterID: String; Filename, LanguageRequiredFiles, OutputProxyDir: String; MustGenerateProxy: Boolean; begin Handled := False; try Filename := WebApplicationDirectory + RequiredProxyFilesPath + '\' + ExtractFileName(AFileName); if assigned(FDSProxyGenerator) then begin Language := GetLanguage(ExtractFileName(Filename)); if isSupportedProxy(Language, WriterID) then begin MustGenerateProxy := False; if not FileExists(Filename) then MustGenerateProxy := True; if not MustGenerateProxy then // the file exists // check for older generated proxy MustGenerateProxy := FileAge(Filename, D1) and FileAge(WebApplicationFileName, D2) and (D1 < D2); if MustGenerateProxy then begin FDSProxyGenerator.writer := WriterID; if DirectoryExists(FRequiredProxyFilesPath) then // full path LanguageRequiredFiles := IncludeTrailingPathDelimiter (FRequiredProxyFilesPath) + Language else // try with a relative path LanguageRequiredFiles := WebApplicationDirectory + FRequiredProxyFilesPath + '\' + Language; OutputProxyDir := LanguageRequiredFiles + '\' + FDSProxyGenerator.WriterProperties.Comment; FDSProxyGenerator.TargetDirectory := OutputProxyDir; FDSProxyGenerator.TargetUnitName := 'DSProxy' + FDSProxyGenerator.FileDescriptions[0].DefaultFileExt; FDSProxyGenerator.Write; DeleteFile(Filename); CreateZipFile(LanguageRequiredFiles, Filename); end; end; end; except on E: Exception do raise; end; end; procedure TDSProxyDispatcher.SetDSProxyGenerator(const Value : TDSProxyGenerator); begin FDSProxyGenerator := Value; FreeAndNil(FAvailableProxies); end; procedure TDSProxyDispatcher.SetRequiredProxyFilesPath(const Value: String); begin FRequiredProxyFilesPath := Value; end; end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit OriUtils_TChart; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, TAGraph, TASeries, TACustomSeries, OriIniFile; type TChartHelper = class helper for TChart public function HasSeries(ASeries: TBasicChartSeries): Boolean; procedure BeginUpdate; procedure EndUpdate; end; TChartSeriesHelper = class helper for TChartSeries public procedure SetXY(Index: Integer; const X, Y: Double); inline; end; TCopyImageFormat = (cifWmf, cifEmf, cifBmp); TChartPenSettings = record Visible: Boolean; Color: TColor; Style: TPenStyle; SmallDots: Boolean; Width: Integer; end; procedure ChooseSeriesColor(Series: TLineSeries); function GetLineSeriesColor(Chart: TChart): TColor; function GetRandomLineSeriesColor(Chart: TChart): TColor; function GetRandomSeriesColor: TColor; procedure SetChartPen(var Pen: TChartPenSettings; Visible: Boolean; Color: TColor; Style: TPenStyle; SmallDots: Boolean; Width: Integer); inline; overload; procedure WriteChartPen(Ini: TOriIniFile; const Key: String; var Pen: TChartPenSettings); procedure ReadChartPen(Ini: TOriIniFile; const Key: String; var Pen: TChartPenSettings); implementation uses OriGraphics, OriStrings; {%region TChartHelper} function TChartHelper.HasSeries(ASeries: TBasicChartSeries): Boolean; var I: Integer; begin Result := False; for I := 0 to Self.Series.Count-1 do if Self.Series[I] = ASeries then begin Result := True; exit; end; end; procedure TChartHelper.BeginUpdate; var I: Integer; begin for I := 0 to Series.Count-1 do if Series[I] is TLineSeries then TLineSeries(Series[I]).BeginUpdate; end; procedure TChartHelper.EndUpdate; var I: Integer; begin for I := 0 to Series.Count-1 do if Series[I] is TLineSeries then TLineSeries(Series[I]).EndUpdate; end; {%endregion} {%region TChartSeriesHelper} procedure TChartSeriesHelper.SetXY(Index: Integer; const X, Y: Double); begin SetXValue(Index, X); SetYValue(Index, Y); end; {%endregion} {%region Series Colors} const SeriesColors: array[0..50] of TColor = (clRed, clGreen, clBlue, clBlack, clMaroon, clNavy, clOlive, clPurple, clTeal, clGray, clLime, clFuchsia, clAqua, clMediumVioletRed, clDarkRed, clBrown, clDarkGreen, clDarkCyan, clMidnightBlue, clDarkSlateGray, clDarkSlateBlue, clDarkOrange, clFireBrick, clDarkKhaki, clSienna, clPaleVioletRed, clSeaGreen, clCadetBlue, clRoyalBlue, clSlateBlue, clSlateGray, clDeepPink, clCrimson, clSaddleBrown, clDarkOliveGreen, clLightSeaGreen, clSteelBlue, clOrangeRed, clIndigo, clDimGray, clIndianRed, clDarkGoldenrod, clDarkSeaGreen, clTurquoise, clDodgerBlue, clDarkViolet, clDarkSalmon, clRosyBrown, clMediumSpringGreen, clMediumAquamarine, clViolet); procedure ChooseSeriesColor(Series: TLineSeries); begin if Assigned(Series.Owner) and (Series.Owner is TChart) then Series.LinePen.Color := GetLineSeriesColor(TChart(Series.Owner)) else Series.LinePen.Color := GetRandomSeriesColor; end; function LineSeriesColorExists(Chart: TChart; Color: TColor): Boolean; var I: Integer; begin for I := 0 to Chart.Series.Count-1 do if Chart.Series[I] is TLineSeries then if TLineSeries(Chart.Series[I]).SeriesColor = Color then begin Result := True; exit; end; Result := False; end; function GetLineSeriesColor(Chart: TChart): TColor; var I: Integer; begin for I := Low(SeriesColors) to High(SeriesColors) do if not LineSeriesColorExists(Chart, SeriesColors[I]) then begin Result := SeriesColors[I]; exit; end; Result := SeriesColors[Random(Length(SeriesColors))]; end; function GetRandomLineSeriesColor(Chart: TChart): TColor; var I, Start: Integer; begin Start := Random(Length(SeriesColors)); for I := Start to High(SeriesColors) do if not LineSeriesColorExists(Chart, SeriesColors[I]) then begin Result := SeriesColors[I]; exit; end; for I := Low(SeriesColors) to Start-1 do if not LineSeriesColorExists(Chart, SeriesColors[I]) then begin Result := SeriesColors[I]; exit; end; Result := SeriesColors[Start]; end; function GetRandomSeriesColor: TColor; begin Result := SeriesColors[Random(Length(SeriesColors))]; end; {%endregion} {%region Storage} procedure SetChartPen(var Pen: TChartPenSettings; Visible: Boolean; Color: TColor; Style: TPenStyle; SmallDots: Boolean; Width: Integer); begin Pen.Visible := Visible; Pen.Color := Color; Pen.Style := Style; Pen.SmallDots := SmallDots; Pen.Width := Width; end; procedure WriteChartPen(Ini: TOriIniFile; const Key: String; var Pen: TChartPenSettings); begin with Pen do Ini.WriteString(Key, Format('%d;%d;%d;$%s;%d', [Ord(Visible), Ord(Style), Width, IntToHex(Color, 8), Ord(SmallDots)])); end; procedure ReadChartPen(Ini: TOriIniFile; const Key: String; var Pen: TChartPenSettings); var Parts: TStringArray; begin SplitStr(Ini.ReadString(Key, ''), ';', Parts); if Length(Parts) > 4 then with Pen do begin Visible := StrToBoolDef(Parts[0], Visible); Style := TPenStyle(StrToIntDef(Parts[1], Ord(Style))); Width := StrToIntDef(Parts[2], Width); Color := StrToIntDef(Parts[3], Color); SmallDots := StrToBoolDef(Parts[4], Visible); end; end; {%endregion} end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------} unit untEasyPlateManager; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, untEasyPlateDBBaseForm, StdCtrls, untEasyLabel, untEasyDBConnection, untEasyPageControl, ExtCtrls, untEasyGroupBox, untEasyProgressBar, untEasyEdit, untEasyEditExt, untEasyButtons, Grids, untEasyBaseGrid, untEasyGrid, ComCtrls, untEasyTreeView, untEasyMemo, DB, DBClient, Provider, ImgList, Menus, untEasyMenus, untEasyMenuStylers; //插件导出函数 function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm; type TEasyRefreshType = (ertSaveRefresh, ertNoSaveRefresh); TfrmEasyPlateManage = class(TfrmEasyPlateDBBaseForm) cdsDirManager: TClientDataSet; tvNavPP: TEasyPopupMenu; N6: TMenuItem; N7: TMenuItem; N10: TMenuItem; ppTVRefresh: TMenuItem; EasyMenuOfficeStyler1: TEasyMenuOfficeStyler; imglv: TImageList; imglvDel: TImageList; EasyPanel11: TEasyPanel; Splitter2: TSplitter; EasyPanel12: TEasyPanel; tvSysDirectory: TEasyTreeView; EasyPanel13: TEasyPanel; btnAdd: TEasyBitButton; btnEdit: TEasyBitButton; btnRefresh: TEasyBitButton; btnDelete: TEasyBitButton; pgcDirOperate: TEasyPageControl; EasyTabSheet3: TEasyTabSheet; EasyLabel4: TEasyLabel; EasyLabel6: TEasyLabel; lvParamers: TListView; btnParamAdd: TEasyBitButton; btnParamEdit: TEasyBitButton; btnParamDelete: TEasyBitButton; lvDeleted: TListView; btnSave: TEasyBitButton; btnCancel: TEasyBitButton; btnExit: TEasyBitButton; cdsParam: TClientDataSet; imgtv: TImageList; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; procedure FormCreate(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnEditClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure tvSysDirectoryExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); procedure tvSysDirectoryDragDrop(Sender, Source: TObject; X, Y: Integer); procedure tvSysDirectoryMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure tvSysDirectoryDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure N6Click(Sender: TObject); procedure N7Click(Sender: TObject); procedure ppTVRefreshClick(Sender: TObject); procedure btnParamEditClick(Sender: TObject); procedure btnParamDeleteClick(Sender: TObject); procedure btnParamAddClick(Sender: TObject); procedure btnExitClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure tvSysDirectoryChange(Sender: TObject; Node: TTreeNode); procedure N2Click(Sender: TObject); procedure N3Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } //初始化树,只生成第一层节点 procedure GenerateTreeView(ATreeView: TEasyTreeView; var AData: TList; RootFlag: string); //加载子节点 procedure LoadChildTreeNodes(ATreeView: TEasyTreeView; var AData: TList; ParentNode: TTreeNode); //刷新树 procedure RefreshDirectoryTreeView(AEasyRefreshType: TEasyRefreshType); procedure InitDirectoryData; public { Public declarations } end; var frmEasyPlateManage: TfrmEasyPlateManage; implementation {$R *.dfm} uses untTvDirectoryOper, ActiveX, untEasyUtilDLL, untPlugParamsOP, untEasyClassPluginDirectory, untEasyUtilMethod; var //操作对应的三种标志 增加 修改 删除 Easy_Add :string= 'Add'; Easy_Edit :string= 'Edit'; Easy_Del :string= 'Del'; ParentNodeFlag :string = '{00000000-0000-0000-0000-000000000000}'; APluginParamsList, APluginDirectoryList: TList; //引出函数实现 function ShowBplForm(AParamList: TStrings): TForm; begin frmEasyPlateManage := TfrmEasyPlateManage.Create(Application); Application.Handle := frmEasyPlateManage.EasyApplicationHandle; if frmEasyPlateManage.FormStyle <> fsMDIChild then frmEasyPlateManage.FormStyle := fsMDIChild; if frmEasyPlateManage.WindowState <> wsMaximized then frmEasyPlateManage.WindowState := wsMaximized; frmEasyPlateManage.FormId := '{AC8E0BB3-2578-4D2A-8869-850891B8E5E8}'; Result := frmEasyPlateManage; end; procedure TfrmEasyPlateManage.FormCreate(Sender: TObject); begin inherited; //在初始 imgtv.Clear; imgtv.Assign(DMEasyDBConnection.img16); //插件目录类容器 APluginDirectoryList := TList.Create; APluginParamsList := TList.Create; //初始化分页显示页面 pgcDirOperate.ActivePageIndex := 0; //初始化数据 InitDirectoryData; //生成目录树 GenerateTreeView(tvSysDirectory, APluginDirectoryList, ParentNodeFlag); //目录树只读 tvSysDirectory.ReadOnly := True; end; procedure TfrmEasyPlateManage.GenerateTreeView(ATreeView: TEasyTreeView; var AData: TList; RootFlag: string); var I : Integer; ATmpNode: TTreeNode; begin ATreeView.Items.BeginUpdate; try ATreeView.Items.Clear; with ATreeView do begin for I := 0 to AData.Count - 1 do begin with TEasysysPluginsDirectory(AData[I]) do begin if (ParentPluginGUID = RootFlag) and (PluginCName <> '') then begin ATmpNode := ATreeView.Items.AddChildObject(nil, PluginCName, AData[I]); ATmpNode.ImageIndex := ImageIndex; ATmpNode.SelectedIndex := SelectedImageIndex; //生成临时节点 只有目录 if IsDirectory then ATreeView.Items.AddChildFirst(ATmpNode, 'TempChildNode'); end; end; end; end; if ATreeView.Items.Count = 0 then begin Application.MessageBox('暂无目录结构数据!', '提示', MB_OK + MB_ICONWARNING); Exit; end; // ATreeView.Items.AddChild(nil, '暂无目录结构'); finally ATreeView.Items.EndUpdate; end; end; procedure TfrmEasyPlateManage.btnAddClick(Sender: TObject); var AEasysysPluginsDirectory: TEasysysPluginsDirectory; AParentNodeName: string; ATmpNode: TTreeNode; begin inherited; AEasysysPluginsDirectory := TEasysysPluginsDirectory.Create; if tvSysDirectory.Selected <> nil then begin //如果是模块则不能增加子节点 if not TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).IsDirectory then Exit; AEasysysPluginsDirectory.ParentPluginGUID := TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).PluginGUID; AParentNodeName := TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).PluginCName; ShowfrmTvDirectoryOper(AEasysysPluginsDirectory, Easy_Add, AParentNodeName); end else begin AEasysysPluginsDirectory.ParentPluginGUID := ParentNodeFlag; ShowfrmTvDirectoryOper(AEasysysPluginsDirectory, Easy_Add); end; //确定新增 if AEasysysPluginsDirectory.PluginGUID <> '' then begin ATmpNode := tvSysDirectory.Items.AddChildObject(tvSysDirectory.Selected, AEasysysPluginsDirectory.PluginCName, AEasysysPluginsDirectory); ATmpNode.ImageIndex := AEasysysPluginsDirectory.ImageIndex; ATmpNode.SelectedIndex := AEasysysPluginsDirectory.SelectedImageIndex; TEasysysPluginsDirectory.AppendClientDataSet(cdsDirManager, AEasysysPluginsDirectory, APluginDirectoryList); end else AEasysysPluginsDirectory.Free; end; procedure TfrmEasyPlateManage.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; EasyFreeAndNilList(APluginDirectoryList); EasyFreeAndNilList(APluginParamsList); end; procedure TfrmEasyPlateManage.btnEditClick(Sender: TObject); var ASelectedNode: TTreeNode; TmpData : TEasysysPluginsDirectory; begin inherited; ASelectedNode := tvSysDirectory.Selected; if ASelectedNode = nil then begin Application.MessageBox('请选择一个要修改的节点!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; TmpData := TEasysysPluginsDirectory(ASelectedNode.Data); ShowfrmTvDirectoryOper(TmpData, Easy_Edit); //修改 ASelectedNode.Text := TmpData.PluginCName; TEasysysPluginsDirectory.EditClientDataSet(cdsDirManager, TmpData); end; procedure TfrmEasyPlateManage.btnDeleteClick(Sender: TObject); var ASelectedNode: TTreeNode; TmpListItem : TListItem; begin inherited; ASelectedNode := tvSysDirectory.Selected; if ASelectedNode = nil then begin Application.MessageBox('请选择要删除的节点!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; if ASelectedNode.HasChildren then begin tvSysDirectory.Selected.Expand(True); if ASelectedNode.getFirstChild.Text <> 'TempChildNode' then begin Application.MessageBox('存在子节点,不能进行删除操作!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; end; if Application.MessageBox(PChar('确定要删除节点【' + TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).PluginCName +'】吗?'), '提示', MB_OKCANCEL + MB_ICONQUESTION) <> IDOK then Exit; TmpListItem := lvDeleted.Items.Add; //删除 tvSysDirectory.Items.Delete(ASelectedNode); TmpListItem.Caption := TEasysysPluginsDirectory(ASelectedNode.Data).PluginCName; TEasysysPluginsDirectory.DeleteClientDataSet(cdsDirManager, TEasysysPluginsDirectory(ASelectedNode.Data), APluginDirectoryList); end; procedure TfrmEasyPlateManage.btnRefreshClick(Sender: TObject); begin inherited; if cdsDirManager.ChangeCount > 0 then begin case Application.MessageBox(PChar('目录结构已发生更改,是否保存?'), PChar('提示'), MB_YESNOCANCEL + MB_ICONQUESTION) of IDYES: begin //保存并刷新树 frmEasyPlateManage.RefreshDirectoryTreeView(ertSaveRefresh); end; IDNO: begin //取消更新并刷新树 frmEasyPlateManage.RefreshDirectoryTreeView(ertNoSaveRefresh); end; end; end else RefreshDirectoryTreeView(ertNoSaveRefresh); end; procedure TfrmEasyPlateManage.btnCancelClick(Sender: TObject); begin inherited; if (cdsDirManager.ChangeCount = 0) and (cdsParam.ChangeCount = 0) then begin Application.MessageBox('数据未发生变更,操作无效!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; lvParamers.Items.Clear; lvDeleted.Items.Clear; if cdsDirManager.ChangeCount > 0 then cdsDirManager.CancelUpdates; if cdsParam.ChangeCount > 0 then cdsParam.CancelUpdates; RefreshDirectoryTreeView(ertNoSaveRefresh); end; procedure TfrmEasyPlateManage.InitDirectoryData; var ATmpData, ATmpDataParam: OleVariant; begin if cdsDirManager.Active then cdsDirManager.Close; //初始化系统目录数组 cdsDirManager.Data := EasyRDMDisp.EasyGetRDMData('SELECT * FROM vwSysPluginsDirectory ORDER BY ParentPluginGUID, iOrder'); ATmpData := cdsDirManager.Data; TEasysysPluginsDirectory.GeneratePluginDirectoryList(ATmpData, APluginDirectoryList); //同进也提取参数数据集 cdsParam.Data := EasyRDMDisp.EasyGetRDMData('SELECT * FROM vwSysPluginParams ORDER BY ParamName'); ATmpDataParam := cdsParam.Data; TEasysysPluginParam.GeneratePluginParamList(ATmpDataParam, APluginParamsList); end; procedure TfrmEasyPlateManage.LoadChildTreeNodes(ATreeView: TEasyTreeView; var AData: TList; ParentNode: TTreeNode); var I : Integer; ATmpNode: TTreeNode; begin with ATreeView do begin for I := 0 to AData.Count - 1 do begin with TEasysysPluginsDirectory(AData[I]) do begin if ParentPluginGUID = TEasysysPluginsDirectory(ParentNode.Data).PluginGUID then begin ATmpNode := ATreeView.Items.AddChildObject(ParentNode, PluginCName, AData[I]); ATmpNode.ImageIndex := ImageIndex; ATmpNode.SelectedIndex := SelectedImageIndex; //生成临时节点 只有目录 if IsDirectory then ATreeView.Items.AddChildFirst(ATmpNode, 'TempChildNode'); end; end; end; end; end; procedure TfrmEasyPlateManage.tvSysDirectoryExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); begin inherited; if Node.HasChildren then begin if Node.Item[0].Text = 'TempChildNode' then begin Node.Item[0].Delete; LoadChildTreeNodes(tvSysDirectory, APluginDirectoryList, Node); end; end; end; procedure TfrmEasyPlateManage.tvSysDirectoryDragDrop(Sender, Source: TObject; X, Y: Integer); var AnItem : TTreeNode; //目标节点 AttachMode: TNodeAttachMode; HT : THitTests; SelectedPluginGUID, NewParentGUID: string; begin if tvSysDirectory.Selected = nil then Exit; AttachMode := naAdd; HT := tvSysDirectory.GetHitTestInfoAt(X, Y); AnItem := tvSysDirectory.GetNodeAt(X, Y); if (HT - [htOnItem, htOnIcon, htNowhere, htOnIndent] <> HT) then begin if (htOnItem in HT) or (htOnIcon in HT) then AttachMode := naAddChild else if htNowhere in HT then AttachMode := naAdd else if htOnIndent in HT then AttachMode := naInsert; tvSysDirectory.Selected.MoveTo(AnItem, AttachMode); SelectedPluginGUID := TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).PluginGUID; //更改移动节点的上级节点 并设置更新状态 if AnItem = nil then //上级节点为空,将选中节点设置为根节点 begin //更新对象的同时更新数据集 TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).ParentPluginGUID := ParentNodeFlag; with cdsDirManager do begin if Locate('PluginGUID', VarArrayOf([SelectedPluginGUID]), [loCaseInsensitive]) then begin Edit; FieldByName('ParentPluginGUID').AsString := ParentNodeFlag; Post; end; end; end else //上级节点不为空,将选中节点设置为子节点 begin //新上级节点GUDI NewParentGUID := TEasysysPluginsDirectory(AnItem.Data).PluginGUID; //更新对象的同时更新数据集 TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).ParentPluginGUID := NewParentGUID; with cdsDirManager do begin if Locate('PluginGUID', VarArrayOf([SelectedPluginGUID]), [loCaseInsensitive]) then begin Edit; FieldByName('ParentPluginGUID').AsString := NewParentGUID; Post; end; end; end; end; end; procedure TfrmEasyPlateManage.tvSysDirectoryMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; //判断左键按下并且鼠标点在一个结点上开始实现拖拽} if (Button = mbLeft) and (htOnItem in tvSysDirectory.GetHitTestInfoAt(X, Y)) then tvSysDirectory.BeginDrag(False); end; procedure TfrmEasyPlateManage.tvSysDirectoryDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Node: TTreeNode; begin if Source = tvSysDirectory then begin Node := tvSysDirectory.GetNodeAt(X, Y); {取当前结点} if Node <> nil then {当前结点不为空才能实现拖拽,accept:=true} Accept := True; end; end; procedure TfrmEasyPlateManage.N6Click(Sender: TObject); begin inherited; tvSysDirectory.FullExpand; end; procedure TfrmEasyPlateManage.N7Click(Sender: TObject); begin inherited; tvSysDirectory.FullCollapse; end; procedure TfrmEasyPlateManage.ppTVRefreshClick(Sender: TObject); begin inherited; btnRefreshClick(Sender); end; procedure TfrmEasyPlateManage.btnParamEditClick(Sender: TObject); var ATmpParamData: TEasysysPluginParam; begin inherited; if lvParamers.Selected <> nil then begin ATmpParamData := TEasysysPluginParam(lvParamers.Selected.Data); if ATmpParamData <> nil then ShowfrmPlugParamsOP(ATmpParamData, Easy_Edit); end else begin Application.MessageBox('请选择要【编辑】的参数!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; TEasysysPluginParam.EditClientDataSet(cdsParam, ATmpParamData); lvParamers.Selected.Caption := ATmpParamData.ParamName; lvParamers.Selected.SubItems[0] := ATmpParamData.Value; end; procedure TfrmEasyPlateManage.btnParamDeleteClick(Sender: TObject); var ATmpParamData: TEasysysPluginParam; begin inherited; if lvParamers.Selected <> nil then begin if Application.MessageBox(PChar('确定要删除【' + lvParamers.Selected.Caption + '】参数吗?'), '提示', MB_OKCANCEL + MB_ICONQUESTION) = IDOK then begin ATmpParamData := TEasysysPluginParam(lvParamers.Selected.Data); TEasysysPluginParam.DeleteClientDataSet(cdsParam, ATmpParamData, APluginParamsList); lvParamers.DeleteSelected; end; end else begin Application.MessageBox('请选择要【删除】的参数!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; end; procedure TfrmEasyPlateManage.btnParamAddClick(Sender: TObject); var ATmpParamData: TEasysysPluginParam; TmpListItem: TListItem; begin inherited; if tvSysDirectory.Selected <> nil then begin if not TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).IsDirectory then begin ATmpParamData := TEasysysPluginParam.Create; //新增时初始化 ATmpParamData.PluginParamGUID := GenerateGUID; ATmpParamData.PluginGUID := TEasysysPluginsDirectory(tvSysDirectory.Selected.Data).PluginGUID; ShowfrmPlugParamsOP(ATmpParamData, Easy_Add); end else begin Application.MessageBox('只能对【插件】文件添加参数!', '提示', MB_OK + MB_ICONWARNING); Exit; end; end else begin Application.MessageBox('请选择要添加参数的【插件】文件!', '提示', MB_OK + MB_ICONWARNING); Exit; end; //执行保存 if ATmpParamData.ParamName <> '' then begin TmpListItem := lvParamers.Items.Add; TEasysysPluginParam.AppendClientDataSet(cdsParam, ATmpParamData, APluginParamsList); //列表指向对应 TmpListItem.Data := ATmpParamData; TmpListItem.Caption := ATmpParamData.ParamName; TmpListItem.SubItems.Add(ATmpParamData.Value); end else ATmpParamData.Free; end; procedure TfrmEasyPlateManage.RefreshDirectoryTreeView(AEasyRefreshType: TEasyRefreshType); var ATmpData: OleVariant; begin //清空树 tvSysDirectory.Items.Clear; //如果已加载插件容器必须先释放 while (APluginDirectoryList.Count > 0) do begin TEasysysPluginsDirectory(APluginDirectoryList[0]).Free; APluginDirectoryList.Delete(0); end; //先保存 初始化数据 if AEasyRefreshType = ertSaveRefresh then begin //sysPluginsDirectory btnSaveClick(nil); end else if AEasyRefreshType = ertNoSaveRefresh then begin //取消更新,重新生成对象 frmEasyPlateManage.cdsDirManager.CancelUpdates; ATmpData := frmEasyPlateManage.cdsDirManager.Data; TEasysysPluginsDirectory.GeneratePluginDirectoryList(ATmpData, APluginDirectoryList); end; //生成目录树 GenerateTreeView(tvSysDirectory, APluginDirectoryList, ParentNodeFlag); //2010-10-31 18:30:41 + //清空已删除的参数树 lvParamers.Items.Clear; //清空已删除的列表 lvDeleted.Items.Clear; end; procedure TfrmEasyPlateManage.btnExitClick(Sender: TObject); begin inherited; if (cdsDirManager.ChangeCount > 0) or (cdsParam.ChangeCount > 0) then begin Application.MessageBox('数据已发生变更,请先进行保存或取消操作以后,再关闭本窗口!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end else Close; end; procedure TfrmEasyPlateManage.btnSaveClick(Sender: TObject); var IAErrorCode, I: Integer; AErrorCode, TableNameOle, KeyFieldOle, DeltaOle, ReturnOle : OleVariant; cdsError : TClientDataSet; __Error : Boolean; begin inherited; __Error := False; if (cdsDirManager.ChangeCount = 0) and (cdsParam.ChangeCount = 0) then begin Application.MessageBox('数据未发生变更,操作无效!', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; try if (cdsDirManager.ChangeCount > 0) and (cdsParam.ChangeCount = 0) then ReturnOle := EasyRDMDisp.EasySaveRDMData('sysPluginsDirectory', cdsDirManager.Delta, 'PluginGUID', IAErrorCode) else if (cdsDirManager.ChangeCount = 0) and (cdsParam.ChangeCount > 0) then ReturnOle := EasyRDMDisp.EasySaveRDMData('sysPluginParams', cdsParam.Delta, 'PluginParamGUID', IAErrorCode) else if (cdsDirManager.ChangeCount > 0) and (cdsParam.ChangeCount > 0) then begin AErrorCode := 0; TableNameOle := VarArrayCreate([0, 1], varVariant); TableNameOle[0] := 'sysPluginsDirectory'; TableNameOle[1] := 'sysPluginParams'; KeyFieldOle := VarArrayCreate([0, 1], varVariant); KeyFieldOle[0] := 'PluginGUID'; KeyFieldOle[1] := 'PluginParamGUID'; DeltaOle := VarArrayCreate([0, 1], varVariant); DeltaOle[0] := cdsDirManager.Delta; DeltaOle[1] := cdsParam.Delta; AErrorCode := VarArrayCreate([0, 1], varVariant); ReturnOle := EasyRDMDisp.EasySaveRDMDatas(TableNameOle, DeltaOle, KeyFieldOle, AErrorCode); //如果 ACodeErrorOle > 0 即发生错误 for I := VarArrayLowBound(AErrorCode, 1) to VarArrayHighBound(AErrorCode, 1) do begin if AErrorCode[I] <> 0 then begin __Error := True; Break; end; end; end; if (IAErrorCode <> 0) or __Error then begin cdsError := TClientDataSet.Create(Self); try cdsError.Data := ReturnOle; Application.MessageBox(PChar('保存出错,原因:' + #13 + cdsError.fieldbyname('ERROR_MESSAGE').AsString), '提示', MB_OK + MB_ICONERROR); finally cdsError.Free; end; end else begin Application.MessageBox('保存成功!', '提示', MB_OK + MB_ICONINFORMATION); if cdsDirManager.ChangeCount > 0 then cdsDirManager.MergeChangeLog; if cdsParam.ChangeCount > 0 then cdsParam.MergeChangeLog; lvDeleted.Clear; // btnRefreshClick(Sender); end; except on E: Exception do Application.MessageBox(PChar('保存出错,原因:' + E.message), '提示', MB_OK + MB_ICONERROR); end; end; procedure TfrmEasyPlateManage.tvSysDirectoryChange(Sender: TObject; Node: TTreeNode); var I: Integer; TmpListItem: TListItem; begin inherited; lvParamers.Items.Clear; if not TEasysysPluginsDirectory(Node.Data).IsDirectory then begin for I := 0 to APluginParamsList.Count - 1 do begin if TEasysysPluginParam(APluginParamsList[I]).PluginGUID = TEasysysPluginsDirectory(Node.Data).PluginGUID then begin TmpListItem := lvParamers.Items.Add; TmpListItem.Data := TEasysysPluginParam(APluginParamsList[I]); //2010-10-31 18:29:46 参数改为显示英文名称 TmpListItem.Caption := TEasysysPluginParam(APluginParamsList[I]).ParamName; TmpListItem.SubItems.Add(TEasysysPluginParam(APluginParamsList[I]).Value); end; end; end; end; procedure TfrmEasyPlateManage.N2Click(Sender: TObject); begin inherited; if tvSysDirectory.Selected <> nil then tvSysDirectory.Selected.Expanded := True; end; procedure TfrmEasyPlateManage.N3Click(Sender: TObject); begin inherited; if tvSysDirectory.Selected <> nil then tvSysDirectory.Selected.Collapse(True); end; procedure TfrmEasyPlateManage.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; //KeyPreview TRUE if (ssCtrl in Shift) and (Key = ord('N')) then //Ctrl + N btnAddClick(Sender) else if (ssCtrl in Shift) and (Key = ord('E')) then //Ctrl + E btnEditClick(Sender) else if (ssCtrl in Shift) and (Key = ord('D')) then //Ctrl + D btnDeleteClick(Sender) else if (ssCtrl in Shift) and (Key = ord('S')) then //Ctrl + S btnSaveClick(Sender) else if (ssCtrl in Shift) and (Key = ord('Z')) then //Ctrl + Z btnCancelClick(Sender) else if (ssAlt in Shift) and (Key = ord('F')) then //Alt + F btnRefreshClick(Sender); end; end.
object frmGeneratorEditor: TfrmGeneratorEditor Left = 365 Top = 225 BorderStyle = bsDialog Caption = 'frmGeneratorEditor' ClientHeight = 212 ClientWidth = 274 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Scaled = False PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 10 Top = 13 Width = 79 Height = 13 Alignment = taRightJustify AutoSize = False Caption = '&Generator' FocusControl = cbxGenerators end object Label2: TLabel Left = 10 Top = 41 Width = 79 Height = 13 Alignment = taRightJustify AutoSize = False Caption = '&Field' FocusControl = cbxFields end object Label3: TLabel Left = 27 Top = 68 Width = 62 Height = 13 Alignment = taRightJustify Caption = 'Increment By' end object OKBtn: TButton Left = 10 Top = 182 Width = 61 Height = 24 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 0 end object CancelBtn: TButton Left = 81 Top = 182 Width = 61 Height = 24 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 1 end object cbxGenerators: TComboBox Left = 94 Top = 10 Width = 170 Height = 21 ItemHeight = 13 Sorted = True TabOrder = 2 Text = 'cbxGenerators' end object cbxFields: TComboBox Left = 94 Top = 37 Width = 170 Height = 21 ItemHeight = 13 Sorted = True TabOrder = 3 Text = 'cbxFields' end object grpApplyEvent: TRadioGroup Left = 10 Top = 92 Width = 254 Height = 79 Caption = '&Apply Event' ItemIndex = 0 Items.Strings = ( 'On New Record' 'On Post' 'On Server') TabOrder = 4 end object HelpBtn: TButton Left = 202 Top = 182 Width = 61 Height = 24 Caption = 'Help' TabOrder = 5 Visible = False end object edtIncrement: TEdit Left = 96 Top = 64 Width = 165 Height = 21 TabOrder = 6 Text = '1' end end
unit IdStack; interface uses Classes, IdException, IdStackConsts, IdGlobal; type TIdServeFile = function(ASocket: TIdStackSocketHandle; AFileName: string): cardinal; TIdStackVersion = class protected FMaxUdpDg: Cardinal; FMaxSockets: Cardinal; FVersion: Word; FLowVersion: Word; FDescription: string; FVendorInfo: string; FSystemStatus: string; FName: string; constructor Create(InfoStruct: Pointer); virtual; abstract; published property Name: string read FName; property Version: Word read FVersion; property LowVersion: Word read FLowVersion; property Description: string read FDescription; property SystemStatus: string read FSystemStatus; property MaxSockets: Cardinal read FMaxSockets; property MaxUdpDg: Cardinal read FMaxUdpDg; property VendorInfo: string read FVendorInfo; end; TIdSunB = packed record s_b1, s_b2, s_b3, s_b4: byte; end; TIdSunW = packed record s_w1, s_w2: word; end; PIdInAddr = ^TIdInAddr; TIdInAddr = record case integer of 0: (S_un_b: TIdSunB); 1: (S_un_w: TIdSunW); 2: (S_addr: longword); end; TIdStack = class protected FStackVersion: TIdStackVersion; FLocalAddress: string; FLocalAddresses: TStrings; procedure PopulateLocalAddresses; virtual; abstract; function WSGetLocalAddress: string; virtual; abstract; function WSGetLocalAddresses: TStrings; virtual; abstract; public function CheckForSocketError(const AResult: integer = Id_SOCKET_ERROR): boolean; overload; function CheckForSocketError(const AResult: integer; const AIgnore: array of integer) : boolean; overload; constructor Create; reintroduce; virtual; destructor Destroy; override; class function CreateStack: TIdStack; function CreateSocketHandle(const ASocketType: Integer; const AProtocol: Integer = Id_IPPROTO_IP): TIdStackSocketHandle; function IsIP(AIP: string): boolean; procedure RaiseSocketError(const AErr: integer); function ResolveHost(const AHost: string): string; function WSAccept(ASocket: TIdStackSocketHandle; var VIP: string; var VPort: Integer) : TIdStackSocketHandle; virtual; abstract; function WSBind(ASocket: TIdStackSocketHandle; const AFamily: Integer; const AIP: string; const APort: Integer): Integer; virtual; abstract; function WSCloseSocket(ASocket: TIdStackSocketHandle): Integer; virtual; abstract; function WSConnect(const ASocket: TIdStackSocketHandle; const AFamily: Integer; const AIP: string; const APort: Integer): Integer; virtual; abstract; function WSGetHostByName(const AHostName: string): string; virtual; abstract; function WSGetHostName: string; virtual; abstract; function WSGetHostByAddr(const AAddress: string): string; virtual; abstract; function WSGetServByName(const AServiceName: string): Integer; virtual; abstract; function WSGetServByPort(const APortNumber: Integer): TStrings; virtual; abstract; function WSHToNs(AHostShort: Word): Word; virtual; abstract; function WSListen(ASocket: TIdStackSocketHandle; ABackLog: Integer): Integer; virtual; abstract; function WSNToHs(ANetShort: Word): Word; virtual; abstract; function WSHToNL(AHostLong: LongWord): LongWord; virtual; abstract; function WSNToHL(ANetLong: LongWord): LongWord; virtual; abstract; function WSRecv(ASocket: TIdStackSocketHandle; var ABuffer; ABufferLength, AFlags: Integer) : Integer; virtual; abstract; function WSRecvFrom(const ASocket: TIdStackSocketHandle; var ABuffer; const ALength, AFlags: Integer; var VIP: string; var VPort: Integer): Integer; virtual; abstract; function WSSelect(ARead, AWrite, AErrors: TList; ATimeout: Integer): Integer; virtual; abstract; function WSSend(ASocket: TIdStackSocketHandle; var ABuffer; const ABufferLength, AFlags: Integer): Integer; virtual; abstract; function WSSendTo(ASocket: TIdStackSocketHandle; var ABuffer; const ABufferLength, AFlags: Integer; const AIP: string; const APort: integer): Integer; virtual; abstract; function WSSetSockOpt(ASocket: TIdStackSocketHandle; ALevel, AOptName: Integer; AOptVal: PChar; AOptLen: Integer): Integer; virtual; abstract; function WSSocket(AFamily, AStruct, AProtocol: Integer): TIdStackSocketHandle; virtual; abstract; function WSShutdown(ASocket: TIdStackSocketHandle; AHow: Integer): Integer; virtual; abstract; function WSTranslateSocketErrorMsg(const AErr: integer): string; virtual; function WSGetLastError: Integer; virtual; abstract; procedure WSGetPeerName(ASocket: TIdStackSocketHandle; var AFamily: Integer; var AIP: string; var APort: Integer); virtual; abstract; procedure WSGetSockName(ASocket: TIdStackSocketHandle; var AFamily: Integer; var AIP: string; var APort: Integer); virtual; abstract; function StringToTInAddr(AIP: string): TIdInAddr; function TInAddrToString(var AInAddr): string; virtual; abstract; procedure TranslateStringToTInAddr(AIP: string; var AInAddr); virtual; abstract; property LocalAddress: string read WSGetLocalAddress; property LocalAddresses: TStrings read WSGetLocalAddresses; property StackVersion: TIdStackVersion read FStackVersion; end; EIdStackError = class(EIdException); EIdStackInitializationFailed = class(EIdStackError); EIdStackSetSizeExceeded = class(EIdStackError); var GStack: TIdStack = nil; GServeFileProc: TIdServeFile = nil; implementation uses {$IFDEF LINUX} IdStackLinux, {$ELSE} IdStackWinsock, {$ENDIF} IdResourceStrings, SysUtils; function TIdStack.CheckForSocketError(const AResult: integer): boolean; begin result := CheckForSocketError(AResult, []); end; function TIdStack.CheckForSocketError(const AResult: integer; const AIgnore: array of integer): boolean; var i, nErr: integer; begin Result := false; if AResult = Id_SOCKET_ERROR then begin nErr := WSGetLastError; for i := Low(AIgnore) to High(AIgnore) do begin if nErr = AIgnore[i] then begin Result := True; exit; end; end; RaiseSocketError(nErr); end; end; function TIdStack.CreateSocketHandle(const ASocketType: Integer; const AProtocol: Integer = Id_IPPROTO_IP): TIdStackSocketHandle; begin result := WSSocket(Id_PF_INET, ASocketType, AProtocol); if result = Id_INVALID_SOCKET then begin raise EIdInvalidSocket.Create(RSCannotAllocateSocket); end; end; procedure TIdStack.RaiseSocketError(const AErr: integer); begin (* RRRRR EEEEEE AAAA DDDDD MM MM EEEEEE !! !! !! RR RR EE AA AA DD DD MMMM MMMM EE !! !! !! RRRRR EEEE AAAAAA DD DD MM MMM MM EEEE !! !! !! RR RR EE AA AA DD DD MM MM EE RR RR EEEEEE AA AA DDDDD MM MM EEEEEE .. .. .. Please read the note in the next comment. *) raise EIdSocketError.CreateError(AErr, WSTranslateSocketErrorMsg(AErr)); (* It is normal to receive a 10038 exception (10038, NOT others!) here when *shutting down* (NOT at other times!) servers (NOT clients!). If you receive a 10038 exception here please see the FAQ at: http://www.nevrona.com/Indy/FAQ.html If you get a 10038 exception here, and HAVE NOT read the FAQ and ask about this in the public forums you will be publicly flogged, tarred and feathered and your name added to every chain letter in existence today. If you insist upon requesting help via our email boxes on the 10038 error that is already answered in the FAQ and you are simply too slothful to search for your answer and ask your question in the public forums you may be publicly flogged, tarred and feathered and your name may be added to every chain letter / EMail in existence today." Otherwise, if you DID read the FAQ and have further questions, please feel free to ask using one of the methods (Carefullly note that these methods do not list email) listed on the Tech Support link at http://www.nevrona.com/Indy/ RRRRR EEEEEE AAAA DDDDD MM MM EEEEEE !! !! !! RR RR EE AA AA DD DD MMMM MMMM EE !! !! !! RRRRR EEEE AAAAAA DD DD MM MMM MM EEEE !! !! !! RR RR EE AA AA DD DD MM MM EE RR RR EEEEEE AA AA DDDDD MM MM EEEEEE .. .. .. *) end; constructor TIdStack.Create; begin end; class function TIdStack.CreateStack: TIdStack; begin {$IFDEF LINUX} result := TIdStackLinux.Create; {$ELSE} result := TIdStackWinsock.Create; {$ENDIF} end; function TIdStack.ResolveHost(const AHost: string): string; begin if AnsiSameText(AHost, 'LOCALHOST') then begin result := '127.0.0.1'; end else if IsIP(AHost) then begin result := AHost; end else begin result := WSGetHostByName(AHost); end; end; function TIdStack.WSTranslateSocketErrorMsg(const AErr: integer): string; begin Result := ''; case AErr of Id_WSAEINTR: Result := RSStackEINTR; Id_WSAEBADF: Result := RSStackEBADF; Id_WSAEACCES: Result := RSStackEACCES; Id_WSAEFAULT: Result := RSStackEFAULT; Id_WSAEINVAL: Result := RSStackEINVAL; Id_WSAEMFILE: Result := RSStackEMFILE; Id_WSAEWOULDBLOCK: Result := RSStackEWOULDBLOCK; Id_WSAEINPROGRESS: Result := RSStackEINPROGRESS; Id_WSAEALREADY: Result := RSStackEALREADY; Id_WSAENOTSOCK: Result := RSStackENOTSOCK; Id_WSAEDESTADDRREQ: Result := RSStackEDESTADDRREQ; Id_WSAEMSGSIZE: Result := RSStackEMSGSIZE; Id_WSAEPROTOTYPE: Result := RSStackEPROTOTYPE; Id_WSAENOPROTOOPT: Result := RSStackENOPROTOOPT; Id_WSAEPROTONOSUPPORT: Result := RSStackEPROTONOSUPPORT; Id_WSAESOCKTNOSUPPORT: Result := RSStackESOCKTNOSUPPORT; Id_WSAEOPNOTSUPP: Result := RSStackEOPNOTSUPP; Id_WSAEPFNOSUPPORT: Result := RSStackEPFNOSUPPORT; Id_WSAEAFNOSUPPORT: Result := RSStackEAFNOSUPPORT; Id_WSAEADDRINUSE: Result := RSStackEADDRINUSE; Id_WSAEADDRNOTAVAIL: Result := RSStackEADDRNOTAVAIL; Id_WSAENETDOWN: Result := RSStackENETDOWN; Id_WSAENETUNREACH: Result := RSStackENETUNREACH; Id_WSAENETRESET: Result := RSStackENETRESET; Id_WSAECONNABORTED: Result := RSStackECONNABORTED; Id_WSAECONNRESET: Result := RSStackECONNRESET; Id_WSAENOBUFS: Result := RSStackENOBUFS; Id_WSAEISCONN: Result := RSStackEISCONN; Id_WSAENOTCONN: Result := RSStackENOTCONN; Id_WSAESHUTDOWN: Result := RSStackESHUTDOWN; Id_WSAETOOMANYREFS: Result := RSStackETOOMANYREFS; Id_WSAETIMEDOUT: Result := RSStackETIMEDOUT; Id_WSAECONNREFUSED: Result := RSStackECONNREFUSED; Id_WSAELOOP: Result := RSStackELOOP; Id_WSAENAMETOOLONG: Result := RSStackENAMETOOLONG; Id_WSAEHOSTDOWN: Result := RSStackEHOSTDOWN; Id_WSAEHOSTUNREACH: Result := RSStackEHOSTUNREACH; Id_WSAENOTEMPTY: Result := RSStackENOTEMPTY; end; Result := Format(RSStackError, [AErr, Result]); end; function TIdStack.IsIP(AIP: string): boolean; var s1, s2, s3, s4: string; function ByteIsOk(const AByte: string): boolean; begin result := (StrToIntDef(AByte, -1) > -1) and (StrToIntDef(AByte, 256) < 256); end; begin s1 := Fetch(AIP, '.'); s2 := Fetch(AIP, '.'); s3 := Fetch(AIP, '.'); s4 := AIP; result := ByteIsOk(s1) and ByteIsOk(s2) and ByteIsOk(s3) and ByteIsOk(s4); end; destructor TIdStack.Destroy; begin FLocalAddresses.Free; inherited; end; function TIdStack.StringToTInAddr(AIP: string): TIdInAddr; begin TranslateStringToTInAddr(AIP, result); end; end.
{ Embarcadero Delphi Visual Component Library } { InterBase Express core components } { } { Copyright (c) 1998-2017 Embarcadero Technologies, Inc.} { All rights reserved } { } { Additional code created by Jeff Overcash and used } { with permission. } {*************************************************************} unit IBX.IBFieldHelper; interface uses Data.DB, IBX.IBSql; type TIBFieldHelper = class helper for TField public function ChangeState : TIBChangeState; end; implementation uses IBX.IBCustomDataSet; { TIBFieldHelper } /// <summary> Returns the change state for the field for InterBase subscriptions /// </summary> /// <remarks> /// This is the same as calling The TField version in IBCustomDataset. /// Caluculated fields and fields not part of the dataset always return csSame. /// </remarks> /// <returns>The IBX.TIBChangeState for the associated TField. /// </returns> function TIBFieldHelper.ChangeState: TIBChangeState; begin Result := (DataSet as TIBCustomDataset).ChangeState(Self); end; end.
program yeehaacli; {$mode objfpc}{$H+} uses cthreads, SysUtils, fpjson, fgl, Yeehaa; const ListenPort = 9999; type TBulbInfos = specialize TFPGMap<String,TBulbInfo>; { THandler } THandler = class FBulbInfos: TBulbInfos; FConn: TYeeConn; private procedure DisplayConnectionError(const AMsg: String); procedure HandleBulbFound(const ANewBulb: TBulbInfo); procedure DisplayResult(const AID: Integer; AResult, AError: TJSONData); public constructor Create(const AListenPort: Word); destructor Destroy; override; procedure PrintBulbs; procedure TogglePower(const AIndex: Integer); end; { TEventHandler } procedure THandler.DisplayConnectionError(const AMsg: String); begin WriteLn('Connection error: ' + AMsg); end; procedure THandler.HandleBulbFound(const ANewBulb: TBulbInfo); begin FBulbInfos[ANewBulb.ID] := ANewBulb; end; procedure THandler.DisplayResult(const AID: Integer; AResult, AError: TJSONData ); begin Write('Command ',AID,': '); if Assigned(AResult) then Write('Result = ',AResult.AsJSON); if Assigned(AError) then Write('Error = ',AError.AsJSON); end; constructor THandler.Create(const AListenPort: Word); begin FBulbInfos := TBulbInfos.Create; FConn := TYeeConn.Create(AListenPort); with FConn do begin OnBulbFound := @HandleBulbFound; OnCommandResult := @DisplayResult; OnConnectionError := @DisplayConnectionError; end; end; destructor THandler.Destroy; begin FConn.Free; FBulbInfos.Free; inherited Destroy; end; procedure THandler.PrintBulbs; var i: Integer; LBulbInfo: TBulbInfo; begin for i := 0 to FBulbInfos.Count - 1 do begin LBulbInfo := FBulbInfos.Data[i]; WriteLn( i + 1, ': ip='+LBulbInfo.IP+ ',model='+LBulbInfo.Model+ ',power=',LBulbInfo.PoweredOn, ',brightness=',LBulbInfo.BrightnessPercentage, ',rgb=',LBulbInfo.RGB ); end; end; procedure THandler.TogglePower(const AIndex: Integer); var LBulbInfo: TBulbInfo; begin if (0 <= AIndex) and (AIndex < FBulbInfos.Count) then begin LBulbInfo := FBulbInfos.Data[AIndex]; FConn.SetPower(LBulbInfo.IP,not LBulbInfo.PoweredOn,teSmooth,500); end else WriteLn('Invalid bulb index, print first to look for valid ones') end; var Quit: Boolean; Cmd: string; begin with THandler.Create(ListenPort) do try Quit := false; repeat WriteLn('[P]rint bulbs'); WriteLn('[T]oggle power'); WriteLn('[Q]uit'); Write('Cmd: ');ReadLn(Cmd); if Length(Cmd) > 0 then case UpCase(Cmd[1]) of 'P': PrintBulbs; 'T': begin Write('Bulb index: ');ReadLn(Cmd); TogglePower(StrToIntDef(Cmd,-1)); end; 'Q': Quit := true; else WriteLn(StdErr,'Command not understood: ' + Cmd); end; WriteLn; until Quit; finally Free; end; end.
{ This unit is part of the Lua4Delphi Source Code Copyright (C) 2009-2012, LaKraven Studios Ltd. Copyright Protection Packet(s): L4D014 www.Lua4Delphi.com www.LaKraven.com -------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. -------------------------------------------------------------------- Unit: L4D.Lua.Intf.pas Released: 5th February 2012 Changelog: 5th February 2012: - Released } unit L4D.Lua.Intf; interface {$I Lua4Delphi.inc} const {$REGION 'Lua Constants'} // From the Lua Headers... LUA_IDSIZE = 60; // gives the maximum size for the description of the source of a function in debug information. CHANGE it if you want a different size. LUAL_BUFFERSIZE = 1024; // the buffer size used by the lauxlib buffer system. LUA_SIGNATURE = #27'Lua'; // mark for precompiled code (`<esc>Lua') LUA_MULTRET = -1; // option for multiple returns in `lua_pcall' and `lua_call' // Basic Lua Type IDs LUA_TNONE = -1; LUA_TNIL = 0; LUA_TBOOLEAN = 1; LUA_TLIGHTUSERDATA = 2; LUA_TNUMBER = 3; LUA_TSTRING = 4; LUA_TTABLE = 5; LUA_TFUNCTION = 6; LUA_TUSERDATA = 7; LUA_TTHREAD = 8; // Pseduo Indices LUA_REGISTRYINDEX = -10000; LUA_ENVIRONINDEX = -10001; LUA_GLOBALSINDEX = -10002; // Thread State LUA_OK = 0; LUA_YIELD_ = 1; // Note: the underscore suffix is needed in Pascal LUA_ERRRUN = 2; LUA_ERRSYNTAX = 3; LUA_ERRMEM = 4; // LUA_MINSTACK = 20; // Minimum Lua Stack available to a C (Delphi) Function // Garbage Collection State IDs LUA_GCSTOP = 0; LUA_GCRESTART = 1; LUA_GCCOLLECT = 2; LUA_GCCOUNT = 3; LUA_GCCOUNTB = 4; LUA_GCSTEP = 5; LUA_GCSETPAUSE = 6; LUA_GCSETSTEPMUL = 7; // Comparison functions LUA_OPEQ = 0; LUA_OPLT = 1; LUA_OPLE = 2; // Event codes LUA_HOOKCALL = 0; LUA_HOOKRET = 1; LUA_HOOKLINE = 2; LUA_HOOKCOUNT = 3; LUA_HOOKTAILRET = 4; // Event masks LUA_MASKCALL = 1 shl LUA_HOOKCALL; LUA_MASKRET = 1 shl LUA_HOOKRET; LUA_MASKLINE = 1 shl LUA_HOOKLINE; LUA_MASKCOUNT = 1 shl LUA_HOOKCOUNT; // Key to file-handle type LUA_FILEHANDLE = 'FILE*'; // Lua Library Names LUA_COLIBNAME = 'coroutine'; LUA_TABLIBNAME = 'table'; LUA_IOLIBNAME = 'io'; LUA_OSLIBNAME = 'os'; LUA_STRLIBNAME = 'string'; LUA_MATHLIBNAME = 'math'; LUA_DBLIBNAME = 'debug'; LUA_LOADLIBNAME = 'package'; // Pre-defined references LUA_NOREF = -2; LUA_REFNIL = -1; {$ENDREGION} type {$REGION 'Lua Types'} { Pointer Types } PLuaState = Pointer; PLuaDebug = ^TLuaDebug; PluaLReg = ^TluaLReg; PLuaLBuffer = ^TLuaLBuffer; { Standard Typedefs } TLuaInteger = type Integer; TLuaNumber = type Double; PLuaNumber = ^TLuaNumber; { TLuaDebug } TLuaDebug = packed record event: Integer; name: PAnsiChar; (* (n) *) namewhat: PAnsiChar; (* (n) `global', `local', `field', `method' *) what: PAnsiChar; (* (S) `Lua', `C', `main', `tail' *) source: PAnsiChar; (* (S) *) currentline: Integer; (* (l) *) nups: Integer; (* (u) number of upvalues *) linedefined: Integer; (* (S) *) short_src: array [0..LUA_IDSIZE-1] of Char; (* (S) *) (* private part *) i_ci: Integer; (* active function *) end; { Method Types } TLuaDelphiFunction = function(ALuaState: PLuaState) : Integer; cdecl; TLuaAllocFunction = function (AUserData, APtr: Pointer; AOSize, ANSize: Cardinal): Pointer; cdecl; TLuaReaderFunction = function (ALuaState: PLuaState; AUserData: Pointer; ASize: PCardinal): PAnsiChar; cdecl; TLuaWriterFunction = function (ALuaState: PLuaState; const APtr: Pointer; ASize: Cardinal; AUserData: Pointer): Integer; cdecl; TLuaHookFunction = procedure (L: PluaState; ar: PLuaDebug); cdecl; { TluaLReg } TluaLReg = packed record name: PAnsiChar; func: TLuaDelphiFunction; end; { TLuaLBuffer } TLuaLBuffer = packed record p: PAnsiChar; (* current position in buffer *) lvl: Integer; (* number of strings in the stack (level) *) L: PluaState; buffer: Array [0..LUAL_BUFFERSIZE-1] of Char; end; {$ENDREGION} { ILuaLibCommonMacros - Provides a common interface for Lua Macros (5.1 and 5.2) } {$REGION 'Lua Common Macros Interface'} ILuaLibCommonMacros = interface ['{834959B0-6150-480F-BC3C-092ACEBF396C}'] function lua_isboolean(L: PLuaState; idx: Integer): LongBool; function lua_isfunction(L: PLuaState; idx: Integer): LongBool; function lua_islightuserdata(L: PLuaState; idx: Integer): LongBool; function lua_isnil(L: PLuaState; idx: Integer): LongBool; function lua_isnone(L: PLuaState; idx: Integer): LongBool; function lua_isnoneornil(L: PLuaState; idx: Integer): LongBool; function lua_istable(L: PLuaState; idx: Integer): LongBool; function lua_isthread(L: PLuaState; idx: Integer): LongBool; procedure lua_newtable(L: PLuaState); procedure lua_pop(L: PLuaState; n: Integer); procedure lua_pushcfunction(L: PLuaState; f: TLuaDelphiFunction); function lua_pushliteral(L: PLuaState; s: PAnsiChar): PAnsiChar; function lua_pushlstring(L: PLuaState; const s: PAnsiChar; ls: Cardinal): PAnsiChar; procedure lua_register(L: PLuaState; name: PAnsiChar; f: TLuaDelphiFunction); function lua_tostring(L: PLuaState; idx: Integer): PAnsiChar; end; {$ENDREGION} { ILuaLibCommonMacrosLocal - Provides a common interface for Lua Macros (5.1 and 5.2) (LOCALIZED) } {$REGION 'Lua Common Macros Localized Interface'} ILuaLibCommonMacrosLocal = interface(ILuaLibCommonMacros) ['{DE490F66-1489-4A30-8A83-29591E84E5BA}'] function lua_isboolean(idx: Integer): LongBool; function lua_isfunction(idx: Integer): LongBool; function lua_islightuserdata(idx: Integer): LongBool; function lua_isnil(idx: Integer): LongBool; function lua_isnone(idx: Integer): LongBool; function lua_isnoneornil(idx: Integer): LongBool; function lua_istable(idx: Integer): LongBool; function lua_isthread(idx: Integer): LongBool; procedure lua_newtable; procedure lua_pop(n: Integer); procedure lua_pushcfunction(f: TLuaDelphiFunction); function lua_pushliteral(s: PAnsiChar): PAnsiChar; function lua_pushlstring(const s: PAnsiChar; ls: Cardinal): PAnsiChar; procedure lua_register(name: PAnsiChar; f: TLuaDelphiFunction); function lua_tostring(idx: Integer): PAnsiChar; end; {$ENDREGION} { ILuaAuxCommonMacros - Provides a common interface for Lua Auxiliary Macros (5.1 and 5.2) } {$REGION 'Lua Auxiliary Macros Interface'} ILuaAuxCommonMacros = interface ['{A66E5F38-D89F-47C4-96ED-AEF1CEDA7B2D}'] function luaL_checkint(L: PLuaState; narg: Integer): Integer; overload; function luaL_checklong(L: PLuaState; narg: Cardinal): Cardinal; overload; function luaL_checkstring(L: PLuaState; narg: Integer): PAnsiChar; overload; function luaL_dofile(L: PLuaState; filename: PAnsiChar): Integer; overload; function luaL_dostring(L: PLuaState; str: PAnsiChar): Integer; overload; procedure luaL_getmetatable(L: PLuaState; tname: PAnsiChar); overload; function luaL_optint(L: PLuaState; narg, d: Integer): Integer; overload; function luaL_optlong(L: PLuaState; narg: Integer; d: Cardinal): Cardinal; overload; function luaL_optstring(L: PLuaState; narg: Integer; d: PAnsiChar): PAnsiChar; overload; function luaL_typename(L: PLuaState; index: Integer): PAnsiChar; overload; end; {$ENDREGION} { ILuaAuxCommonMacrosLocal - Provides a common interface for Lua Auxiliary Macros (5.1 and 5.2) (LOCALIZED) } {$REGION 'Lua Auxiliary Macros Localized Interface'} ILuaAuxCommonMacrosLocal = interface ['{3764DEA4-AAC3-4FE3-9D59-8B2A0B0448D8}'] function luaL_checkint(narg: Integer): Integer; overload; function luaL_checklong(narg: Cardinal): Cardinal; overload; function luaL_checkstring(narg: Integer): PAnsiChar; overload; function luaL_dofile(filename: PAnsiChar): Integer; overload; function luaL_dostring(str: PAnsiChar): Integer; overload; procedure luaL_getmetatable(tname: PAnsiChar); overload; function luaL_optint(narg, d: Integer): Integer; overload; function luaL_optlong(narg: Integer; d: Cardinal): Cardinal; overload; function luaL_optstring(narg: Integer; d: PAnsiChar): PAnsiChar; overload; function luaL_typename(index: Integer): PAnsiChar; overload; end; {$ENDREGION} { ILuaLibInterchange - Provides a common interface for normally version-specific Lua methods } {$REGION 'Lua Lib Interchange Interface'} ILuaLibInterchange = interface ['{428860B0-0569-4A30-AF36-EB25734E1CD7}'] procedure lua_call(L: PLuaState; nargs, nresults: Integer); // External "lua_call" in 5.1, External "lua_callk" in 5.2 procedure lua_callk(L: PLuaState; nargs, nresults, ctx: Integer; k: TLuaDelphiFunction); // External "lua_call" in 5.1, External "lua_callk" in 5.2 function lua_compare(L: PLuaState; idx1, idx2, op: Integer): LongBool; // "lua_equal" OR "lua_lessthan" in 5.1, External in 5.2 function lua_cpcall(L: PLuaState; func: TLuaDelphiFunction; ud: Pointer): Integer; // External in 5.1, "lua_pcall" in 5.2 function lua_equal(L: PLuaState; idx1, idx2: Integer): LongBool; // External in 5.1, "lua_compare" in 5.2 procedure lua_getfenv(L: PLuaState; idx: Integer); // External in 5.1, "lua_getuservalue" in 5.2 procedure lua_getglobal(L: PLuaState; name: PAnsiChar); // "lua_getfield" in 5.1, External in 5.2 procedure lua_getuservalue(L: PLuaState; idx: Integer); // "lua_getfenv" in 5.1, External in 5.2 function lua_lessthan(L: PLuaState; idx1, idx2: Integer): LongBool; // External in 5.1, "lua_compare" in 5.2 function lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer; overload; // Extra parameter in 5.2 (mode)... 5.1 to pass "nil" to operate normally function lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; Source, Mode: PAnsiChar): Integer; overload; // Extra parameter in 5.2 (mode)... 5.1 to pass "nil" to operate normally function lua_objlen(L: PLuaState; idx: Integer): Cardinal; // External in 5.1, "lua_rawlen" in 5.2 function lua_pcall(L: PLuaState; nargs, nresults, errfunc: Integer): Integer; // External in 5.1, "lua_pcallk" in 5.2 function lua_pcallk(L: PLuaState; nargs, nresults, arrfunc, ctx: Integer; k: TLuaDelphiFunction): Integer; // External in 5.1, "lua_pcallk" in 5.2 function lua_rawlen(L: PLuaState; idx: Integer): Cardinal; // "lua_objlen" in 5.1, External in 5.2 function lua_resume(L: PLuaState; narg: Integer): Integer; // 5.1 version // Commonized Externals function lua_setfenv(L: PLuaState; idx: Integer): LongBool; // External in 5.1, "lua_setuservalue" in 5.2 procedure lua_setglobal(L: PLuaState; name: PAnsiChar); // "lua_setfield" in 5.1, External in 5.2 function lua_setmetatable(L: PLuaState; objindex: Integer): LongBool; // Function in 5.1, Procedure in 5.2... using a Function for both (saves hardship) procedure lua_setuservalue(L: PLuaState; idx: Integer); // "lua_getfenv" & "lua_setfenv" in 5.1, External in 5.2 function lua_tointeger(L: PLuaState; idx: Integer): Integer; // In 5.1 function lua_tointegerx(L: PLuaState; idx: Integer; isnum: PInteger): Integer; // In 5.2 function lua_tonumber(L: PLuaState; idx: Integer): Double; // In 5.1 function lua_tonumberx(L: PLuaState; idx: Integer; isnum: PInteger): Double; // In 5.2 function lua_yield(L: PLuaState; nresults: Integer): Integer; // "lua_yield" in 5.1, "lua_yieldk" in 5.2 function lua_yieldk(L: PLuaState; nresults, ctx: Integer; k: TLuaDelphiFunction): Integer; // "lua_yield" in 5.1, "lua_yieldk" in 5.2 end; {$ENDREGION} { ILuaLibInterchangeLocal - Provides a common interface for normally version-specific Lua methods (LOCALIZED) } {$REGION 'Lua Lib Interchange Localized Interface'} ILuaLibInterchangeLocal = interface(ILuaLibInterchange) ['{F92CB292-4EF6-4B68-8AE7-5040AD907761}'] procedure lua_call(nargs, nresults: Integer); procedure lua_callk(nargs, nresults, ctx: Integer; k: TLuaDelphiFunction); function lua_compare(idx1, idx2, op: Integer): LongBool; function lua_cpcall(func: TLuaDelphiFunction; ud: Pointer): Integer; function lua_equal(idx1, idx2: Integer): LongBool; procedure lua_getfenv(idx: Integer); procedure lua_getglobal(name: PAnsiChar); procedure lua_getuservalue(idx: Integer); function lua_lessthan(idx1, idx2: Integer): LongBool; function lua_load(reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer; overload; // 5.1 version function lua_load(reader: TLuaReaderFunction; dt: Pointer; Source, Mode: PAnsiChar): Integer; overload; // 5.2 version function lua_objlen(idx: Integer): Cardinal; function lua_pcall(nargs, nresults, errfunc: Integer): Integer; function lua_pcallk(nargs, nresults, arrfunc, ctx: Integer; k: TLuaDelphiFunction): Integer; function lua_rawlen(idx: Integer): Cardinal; function lua_resume(narg: Integer): Integer; // 5.1 version function lua_setfenv(idx: Integer): LongBool; procedure lua_setglobal(name: PAnsiChar); function lua_setmetatable(objindex: Integer): LongBool; procedure lua_setuservalue(idx: Integer); function lua_tointeger(idx: Integer): Integer; function lua_tointegerx(idx: Integer; isnum: PInteger): Integer; function lua_tonumber(idx: Integer): Double; function lua_tonumberx(idx: Integer; isnum: PInteger): Double; function lua_yield(nresults: Integer): Integer; function lua_yieldk(nresults, ctx: Integer; k: TLuaDelphiFunction): Integer; end; {$ENDREGION} { ILuaAuxInterchange - Provides a common interface for normally version-specific Lua Aux methods } {$REGION 'Lua Auxiliary Interchange Interface'} ILuaAuxInterchange = interface ['{6E7D4871-291F-4563-AA84-B032414A3BCA}'] function luaL_loadbuffer(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer; overload; function luaL_loadbufferx(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer; overload; function luaL_loadfile(L: PLuaState; filename: PAnsiChar): Integer; overload; function luaL_loadfilex(L: PLuaState; filename, mode: PAnsiChar): Integer; overload; function luaL_prepbuffer(B: TLuaLBuffer): PAnsiChar; overload; function luaL_prepbuffsize(B: TLuaLBuffer; sz: Cardinal): PAnsiChar; overload; procedure luaL_register(L: PLuaState; libname: PAnsiChar; lib: PluaLReg); overload; end; {$ENDREGION} { ILuaAuxInterchangeLocal - Provides a common interface for normally version-specific Lua Aux methods (LOCALIZED) } {$REGION 'Lua Auxiliary Interchange Localized Interface'} ILuaAuxInterchangeLocal = interface(ILuaAuxInterchange) ['{94033932-FB59-499C-B14D-515A56130846}'] function luaL_loadbuffer(buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer; overload; function luaL_loadbufferx(buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer; overload; function luaL_loadfile(filename: PAnsiChar): Integer; overload; function luaL_loadfilex(filename, mode: PAnsiChar): Integer; overload; procedure luaL_register(libname: PAnsiChar; lib: PluaLReg); overload; end; {$ENDREGION} { ILuaLibCommon - Provides a common interface for core Lua 5.1 and 5.2 methods } {$REGION 'Lua Common Lib Interface'} ILuaLibCommon = interface ['{9734B0E4-9D9E-46FF-83BE-2AE1A2A9E916}'] function lua_atpanic(L: PLuaState; panicf: TLuaDelphiFunction): TLuaDelphiFunction; function lua_checkstack(L: PLuaState; sz: Integer): LongBool; procedure lua_close(L: PLuaState); procedure lua_concat(L: PLuaState; n: Integer); procedure lua_createtable(L: PLuaState; narr, nrec: Integer); function lua_dump(L: PLuaState; writer: TLuaWriterFunction; data: Pointer): Integer; function lua_error(L: PLuaState): Integer; function lua_gc(L: PLuaState; what, data: Integer): Integer; function lua_getallocf(L: PLuaState; ud: PPointer): TLuaAllocFunction; procedure lua_getfield(L: PLuaState; idx: Integer; k: PAnsiChar); function lua_gethook(L: PLuaState): TLuaHookFunction; function lua_gethookcount(L: PLuaState): Integer; function lua_gethookmask(L: PLuaState): Integer; function lua_getinfo(L: PLuaState; const what: PAnsiChar; ar: PLuaDebug): Integer; function lua_getlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; function lua_getmetatable(L: PLuaState; objindex: Integer): LongBool; function lua_getstack(L: PLuaState; level: Integer; ar: PLuaDebug): Integer; procedure lua_gettable(L: PLuaState ; idx: Integer); function lua_gettop(L: PLuaState): Integer; function lua_getupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; procedure lua_insert(L: PLuaState; idx: Integer); function lua_iscfunction(L: PLuaState; idx: Integer): LongBool; function lua_isnumber(L: PLuaState; idx: Integer): LongBool; function lua_isstring(L: PLuaState; idx: Integer): LongBool; function lua_isuserdata(L: PLuaState; idx: Integer): LongBool; function lua_newthread(L: PLuaState): PLuaState; function lua_newstate(f: TLuaAllocFunction; ud: Pointer): PLuaState; function lua_newuserdata(L: PLuaState; sz: Cardinal): Pointer; function lua_next(L: PLuaState; idx: Integer): Integer; procedure lua_pushboolean(L: PLuaState; b: LongBool); procedure lua_pushcclosure(L: PLuaState; fn: TLuaDelphiFunction; n: Integer); function lua_pushfstring(L: PLuaState; const fmt: PAnsiChar): PAnsiChar; {varargs;} procedure lua_pushinteger(L: PLuaState; n: Integer); procedure lua_pushlightuserdata(L: PLuaState; p: Pointer); procedure lua_pushnil(L: PLuaState); procedure lua_pushnumber(L: PLuaState; n: Double); function lua_pushstring(L: PLuaState; const s: PAnsiChar): PAnsiChar; function lua_pushthread(L: PLuaState): LongBool; procedure lua_pushvalue(L: PLuaState; idx: Integer); function lua_pushvfstring(L: PLuaState; const fmt: PAnsiChar; argp: Pointer): PAnsiChar; function lua_rawequal(L: PLuaState; idx1, idx2: Integer): LongBool; procedure lua_rawget(L: PLuaState; idx: Integer); procedure lua_rawgeti(L: PLuaState; idx, n: Integer); procedure lua_rawset(L: PLuaState; idx: Integer); procedure lua_rawseti(L: PLuaState; idx , n: Integer); procedure lua_remove(L: PLuaState; idx: Integer); procedure lua_replace(L: PLuaState; idx: Integer); procedure lua_setallocf(L: PLuaState; f: TLuaAllocFunction; ud: Pointer); procedure lua_setfield(L: PLuaState; idx: Integer; const k: PAnsiChar); function lua_sethook(L: PLuaState; func: TLuaHookFunction; mask, count: Integer): Integer; function lua_setlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; procedure lua_settable(L: PLuaState; idx: Integer); procedure lua_settop(L: PLuaState; idx: Integer); function lua_setupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; function lua_status(L: PLuaState): Integer; function lua_toboolean(L: PLuaState; idx: Integer): LongBool; function lua_tocfunction(L: PLuaState; idx: Integer): TLuaDelphiFunction; function lua_tolstring(L: PLuaState; idx: Integer; len: PCardinal): PAnsiChar; function lua_topointer(L: PLuaState; idx: Integer): Pointer; function lua_tothread(L: PLuaState; idx: Integer): PLuaState; function lua_touserdata(L: PLuaState; idx: Integer): Pointer; function lua_type(L: PLuaState; idx: Integer): Integer; function lua_typename(L: PLuaState; tp: Integer): PAnsiChar; procedure lua_xmove(src, dest: PLuaState; n: Integer); function luaopen_base(L: PLuaState): Integer; function luaopen_debug(L: PLuaState): Integer; function luaopen_io(L: PLuaState): Integer; function luaopen_math(L: PLuaState): Integer; function luaopen_os(L: PLuaState): Integer; function luaopen_package(L: PLuaState): Integer; function luaopen_string(L: PLuaState): Integer; function luaopen_table(L: PLuaState): Integer; end; {$ENDREGION} { ILuaLibCommonLocal - A common interface for Lua LOCALIZED } {$REGION 'Lua Common Lib Localized Interface'} ILuaLibCommonLocal = interface(ILuaLibCommon) ['{03D3A047-007B-4678-B013-CEA6B8986079}'] function lua_atpanic(panicf: TLuaDelphiFunction): TLuaDelphiFunction; function lua_checkstack(sz: Integer): LongBool; procedure lua_close; procedure lua_concat(n: Integer); procedure lua_createtable(narr, nrec: Integer); function lua_dump(writer: TLuaWriterFunction; data: Pointer): Integer; function lua_error: Integer; function lua_gc(what, data: Integer): Integer; function lua_getallocf(ud: PPointer): TLuaAllocFunction; procedure lua_getfield(idx: Integer; k: PAnsiChar); function lua_gethook: TLuaHookFunction; function lua_gethookcount: Integer; function lua_gethookmask: Integer; function lua_getinfo(const what: PAnsiChar; ar: PLuaDebug): Integer; function lua_getlocal(ar: PLuaDebug; n: Integer): PAnsiChar; function lua_getmetatable(objindex: Integer): LongBool; function lua_getstack(level: Integer; ar: PLuaDebug): Integer; procedure lua_gettable( idx: Integer); function lua_gettop: Integer; function lua_getupvalue(funcindex, n: Integer): PAnsiChar; procedure lua_insert(idx: Integer); function lua_iscfunction(idx: Integer): LongBool; function lua_isnumber(idx: Integer): LongBool; function lua_isstring(idx: Integer): LongBool; function lua_isuserdata(idx: Integer): LongBool; function lua_newthread: PLuaState; function lua_newuserdata(sz: Cardinal): Pointer; function lua_next(idx: Integer): Integer; procedure lua_pushboolean(b: LongBool); procedure lua_pushcclosure(fn: TLuaDelphiFunction; n: Integer); function lua_pushfstring(const fmt: PAnsiChar): PAnsiChar; {varargs;} procedure lua_pushinteger(n: Integer); procedure lua_pushlightuserdata(p: Pointer); procedure lua_pushnil; procedure lua_pushnumber(n: Double); function lua_pushstring(const s: PAnsiChar): PAnsiChar; function lua_pushthread: LongBool; procedure lua_pushvalue(idx: Integer); function lua_pushvfstring(const fmt: PAnsiChar; argp: Pointer): PAnsiChar; function lua_rawequal(idx1, idx2: Integer): LongBool; procedure lua_rawget(idx: Integer); procedure lua_rawgeti(idx, n: Integer); procedure lua_rawset(idx: Integer); procedure lua_rawseti(idx , n: Integer); procedure lua_remove(idx: Integer); procedure lua_replace(idx: Integer); procedure lua_setallocf(f: TLuaAllocFunction; ud: Pointer); procedure lua_setfield(idx: Integer; const k: PAnsiChar); function lua_sethook(func: TLuaHookFunction; mask, count: Integer): Integer; function lua_setlocal(ar: PLuaDebug; n: Integer): PAnsiChar; procedure lua_settable(idx: Integer); procedure lua_settop(idx: Integer); function lua_setupvalue(funcindex, n: Integer): PAnsiChar; function lua_status: Integer; function lua_toboolean(idx: Integer): LongBool; function lua_tocfunction(idx: Integer): TLuaDelphiFunction; function lua_tolstring(idx: Integer; len: PCardinal): PAnsiChar; function lua_topointer(idx: Integer): Pointer; function lua_tothread(idx: Integer): PLuaState; function lua_touserdata(idx: Integer): Pointer; function lua_type(idx: Integer): Integer; function lua_typename(tp: Integer): PAnsiChar; procedure lua_xmove(dest: PLuaState; n: Integer); function luaopen_base: Integer; function luaopen_debug: Integer; function luaopen_io: Integer; function luaopen_math: Integer; function luaopen_os: Integer; function luaopen_package: Integer; function luaopen_string: Integer; function luaopen_table: Integer; end; {$ENDREGION} { ILuaAuxCommon - Provides a common interface between Lua 5.1 and Lua 5.2 for the Auxiliary Library } {$REGION 'Lua Auxiliary Common Interface'} ILuaAuxCommon = interface ['{3B3FA3F4-25D2-4C4C-82FF-A61F9A4BFA53}'] procedure luaL_addlstring(B: PLuaLBuffer; const s: PAnsiChar; ls: Cardinal); procedure luaL_addstring(B: PLuaLBuffer; const s: PAnsiChar); procedure luaL_addvalue(B: PLuaLBuffer); function luaL_argerror(L: PLuaState; numarg: Integer; const extramsg: PAnsiChar): Integer; procedure luaL_buffinit(L: PLuaState; B: PLuaLBuffer); function luaL_callmeta(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; procedure luaL_checkany(L: PLuaState; narg: Integer); function luaL_checkinteger(L: PLuaState; numArg: Integer): Integer; function luaL_checklstring(L: PLuaState; numArg: Integer; ls: PCardinal): PAnsiChar; function luaL_checknumber(L: PLuaState; numArg: Integer): Double; function luaL_checkoption(L: PLuaState; narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer; procedure luaL_checkstack(L: PLuaState; sz: Integer; const msg: PAnsiChar); procedure luaL_checktype(L: PLuaState; narg, t: Integer); function luaL_checkudata(L: PLuaState; ud: Integer; const tname: PAnsiChar): Pointer; function luaL_error(L: PLuaState; const fmt: PAnsiChar): Integer; {varargs;} function luaL_getmetafield(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; function luaL_gsub(L: PLuaState; const s, p, r: PAnsiChar): PAnsiChar; function luaL_loadstring(L: PLuaState; const s: PAnsiChar): Integer; function luaL_newmetatable(L: PLuaState; const tname: PAnsiChar): Integer; function luaL_newstate: PLuaState; procedure luaL_openlibs(L: PLuaState); function luaL_optinteger(L: PLuaState; nArg: Integer; def: Integer): Integer; function luaL_optlstring(L: PLuaState; numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar; function luaL_optnumber(L: PLuaState; nArg: Integer; def: Double): Double; procedure luaL_pushresult(B: PLuaLBuffer); function luaL_ref(L: PLuaState; t: Integer): Integer; procedure luaL_unref(L: PLuaState; t, ref: Integer); procedure luaL_where(L: PLuaState; lvl: Integer); end; {$ENDREGION} { ILuaAuxCommonLocal - A common interface for Lua LOCALIZED } {$REGION 'Lua Auxiliary Common Localized Interface'} ILuaCommonAuxLocal = interface(ILuaAuxCommon) function luaL_argerror(numarg: Integer; const extramsg: PAnsiChar): Integer; procedure luaL_buffinit(B: PLuaLBuffer); function luaL_callmeta(obj: Integer; const e: PAnsiChar): Integer; procedure luaL_checkany(narg: Integer); function luaL_checkinteger(numArg: Integer): Integer; function luaL_checklstring(numArg: Integer; ls: PCardinal): PAnsiChar; function luaL_checknumber(numArg: Integer): Double; function luaL_checkoption(narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer; procedure luaL_checkstack(sz: Integer; const msg: PAnsiChar); procedure luaL_checktype(narg, t: Integer); function luaL_checkudata(ud: Integer; const tname: PAnsiChar): Pointer; function luaL_error(const fmt: PAnsiChar): Integer; {varargs;} function luaL_getmetafield(obj: Integer; const e: PAnsiChar): Integer; function luaL_gsub(const s, p, r: PAnsiChar): PAnsiChar; function luaL_loadstring(const s: PAnsiChar): Integer; function luaL_newmetatable(const tname: PAnsiChar): Integer; procedure luaL_openlibs; function luaL_optinteger(nArg: Integer; def: Integer): Integer; function luaL_optnumber(nArg: Integer; def: Double): Double; function luaL_optlstring(numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar; function luaL_ref(t: Integer): Integer; procedure luaL_unref(t, ref: Integer); procedure luaL_where(lvl: Integer); end; {$ENDREGION} { ILua51Lib - Interface for Lua 5.1 specific methods } {$REGION 'Lua 5.1 Interface'} ILua51Lib = interface ['{30DF6960-F4AF-47ED-AC27-78146F0F419F}'] end; {$ENDREGION} { ILua51LibLocal - Interface for Lua 5.1 specific methods (LOCALIZED) } {$REGION 'Lua 5.1 Localized Interface'} ILua51LibLocal = interface(ILua51Lib) ['{690B5B7D-FDEE-4FCC-BE86-5592CAFD765D}'] end; {$ENDREGION} { ILua51Aux - Interface for Lua 5.1 Auxiliary specific methods } {$REGION 'Lua 5.1 Auxiliary Interface'} ILua51Aux = interface ['{C05C9794-AD51-4FC4-B01C-97B38E2710EB}'] function luaL_findtable(L: PLuaState; idx: Integer; const fname: PAnsiChar; szhint: Integer): PAnsiChar; procedure luaL_openlib(L: PLuaState; const libname: PAnsiChar; const lr: PLuaLReg; nup: Integer); function luaL_typerror(L: PLuaState; narg: Integer; const tname: PAnsiChar): Integer; end; {$ENDREGION} { ILua51AuxLocal - Interface for Lua 5.1 specific Auxiliary methods (LOCALIZED) } {$REGION 'Lua 5.1 Auxiliary Interface ((LOCALIZED)'} ILua51AuxLocal = interface(ILua51Aux) ['{9B1CDACF-BCE0-4A8C-BE4F-53C4276B884F}'] function luaL_findtable(idx: Integer; const fname: PAnsiChar; szhint: Integer): PAnsiChar; procedure luaL_openlib(const libname: PAnsiChar; const lr: PLuaLReg; nup: Integer); function luaL_typerror(narg: Integer; const tname: PAnsiChar): Integer; end; {$ENDREGION} { ILua52Lib - Interface for Lua 5.2 specific methods } {$REGION 'Lua 5.2 Interface'} ILua52Lib = interface ['{801F2000-D8E0-4DB5-9392-514DAE48411F}'] function lua_absindex(L: PLuaState; idx: Integer): Integer; function lua_arith(L: PLuaState; op: Integer): Integer; procedure lua_copy(L: PLuaState; fromidx, toidx: Integer); function lua_getctx(L: PLuaState; ctx: PInteger): Integer; procedure lua_len(L: PLuaState; idx: Integer); procedure lua_pushunsigned(L: PLuaState; u: Cardinal); procedure lua_rawgetp(L: PLuaState; idx: Integer; p: Pointer); procedure lua_rawsetp(L: PLuaState; idx: Integer; p: Pointer); function lua_resume(L, from: PLuaState; narg: Integer): Integer; // 5.2 version function lua_tounsignedx(L: PLuaState; idx: Integer; isnum: PInteger): Cardinal; function lua_upvalueid(L: PLuaState; funcidx, n: Integer): Pointer; procedure lua_upvaluejoin(L: PLuaState; fidx1, n1, fidx2, n2: Integer); function lua_version(L: PLuaState): PInteger; function luaopen_bit32(L: PLuaState): Integer; function luaopen_coroutine(L: PLuaState): Integer; end; {$ENDREGION} { ILua52LibLocal - Interface for Lua 5.2 specific methods (LOCALIZED) } {$REGION 'Lua 5.2 Localized Interface'} ILua52LibLocal = interface(ILua52Lib) ['{01288353-6B86-4754-B5AA-449C308E32D2}'] function lua_absindex(idx: Integer): Integer; function lua_arith(op: Integer): Integer; procedure lua_copy(fromidx, toidx: Integer); function lua_getctx(ctx: PInteger): Integer; procedure lua_len(idx: Integer); procedure lua_pushunsigned(u: Cardinal); procedure lua_rawgetp(idx: Integer; p: Pointer); procedure lua_rawsetp(idx: Integer; p: Pointer); function lua_resume(from: PLuaState; narg: Integer; const UNUSED_PROPERTY: Boolean = True): Integer; // 5.2 version function lua_tounsignedx(idx: Integer; isnum: PInteger): Cardinal; function lua_upvalueid(funcidx, n: Integer): Pointer; procedure lua_upvaluejoin(fidx1, n1, fidx2, n2: Integer); function lua_version: PInteger; function luaopen_bit32: Integer; function luaopen_coroutine: Integer; end; {$ENDREGION} { ILua52Lib - Interface for Lua 5.2 specific methods } {$REGION 'Lua 5.2 Auxiliary Interface'} ILua52Aux = interface ['{1066BF7A-2BDC-4851-946E-0DF000AAB560}'] function luaL_checkunsigned(L: PLuaState; narg: Integer): Cardinal; procedure luaL_checkversion(L: PLuaState); function luaL_execresult(L: PLuaState; stat: Integer): Integer; function luaL_fileresult(L: PLuaState; stat: Integer; fname: PAnsiChar): Integer; function luaL_getsubtable(L: PLuaState; idx: Integer; fname: PAnsiChar): Integer; function luaL_len(L: PLuaState; idx: Integer): Integer; function luaL_optunsigned(L: PLuaState; narg: Integer; u: Cardinal): Cardinal; function luaL_buffinitsize(L: PLuaState; B: PLuaLBuffer; sz: Cardinal): PAnsiChar; procedure luaL_requiref(L: PLuaState; modname: PansiChar; openf: TLuaDelphiFunction; glb: Integer); procedure luaL_setfuncs(L: PLuaState; lreg: PluaLReg; nup: Integer); procedure luaL_setmetatable(L: PluaState; tname: PAnsiChar); // 5.2 version function luaL_testudata(L: PLuaState; narg: Integer; tname: PAnsiChar): Pointer; procedure luaL_traceback(L, L1: PLuaState; msg: PAnsiChar; level: Integer); end; {$ENDREGION} { ILua52LibLocal - Interface for Lua 5.2 specific methods (LOCALIZED) } {$REGION 'Lua 5.2 Auxiliary Localized Interface'} ILua52AuxLocal = interface(ILua52Aux) ['{12F3D79C-339A-4135-92D6-53E9D81A5441}'] function luaL_checkunsigned(narg: Integer): Cardinal; procedure luaL_checkversion; function luaL_execresult(stat: Integer): Integer; function luaL_fileresult(stat: Integer; fname: PAnsiChar): Integer; function luaL_getsubtable(idx: Integer; fname: PAnsiChar): Integer; function luaL_len(idx: Integer): Integer; function luaL_optunsigned(narg: Integer; u: Cardinal): Cardinal; function luaL_buffinitsize(B: PLuaLBuffer; sz: Cardinal): PAnsiChar; function luaL_prepbuffsize(B: PLuaLBuffer; sz: Cardinal): PAnsiChar; procedure luaL_pushresultsize(B: PLuaLBuffer; sz: Cardinal); procedure luaL_requiref(modname: PansiChar; openf: TLuaDelphiFunction; glb: Integer); procedure luaL_setfuncs(lreg: PluaLReg; nup: Integer); procedure luaL_setmetatable(tname: PAnsiChar); function luaL_testudata(narg: Integer; tname: PAnsiChar): Pointer; procedure luaL_traceback(L1: PLuaState; msg: PAnsiChar; level: Integer); end; {$ENDREGION} implementation end.
unit SSHCommand; { unit : SSHCommand.pas Author : tmaxeiner <tmaxeiner@maxeiner-computing.de> License : MIT, see License file Version : 0.1 } interface uses System.SysUtils, shellapi, Winapi.Windows; type TSSHCommand = record strict private FSSHClient : string; FHostName : string; FPortNum : integer; FUserName : string; FKeyFile : string; FCommand : string; FCommandParameter : string; FSource : string; FDestination : string; FSCPParameterLine : string; function GetPortNum : integer; procedure SetHostName( const Value : string ); procedure SetKeyFile( const Value : string ); procedure SetPortNum( const Value : integer ); procedure SetSSHClient( const Value : string ); procedure SetUserName( const Value : string ); private procedure SetCommand(const Value: string); procedure SetCommandParameter(const Value: string); procedure SetDestination(const Value: string); procedure SetSource(const Value: string); public /// <summary> /// Set a ssh client exe. Can be in application directory. /// Don't use original path in windows wich is /// c:\windows\system32\Openssh because it won't work with this wrapper! /// Leave blank if ssh.exe is in your application directory or in other searchpath. /// </summary> property SSHClient : string read FSSHClient write SetSSHClient; /// <summary> /// Hostname like www.excample.com or IP address. /// </summary> property HostName : string read FHostName write SetHostName; /// <summary> /// Leave blank if you use standard port 22. /// </summary> property PortNum : integer read GetPortNum write SetPortNum; /// <summary> /// Username on remote host. Needs login access rights. /// </summary> property UserName : string read FUserName write SetUserName; /// <summary> /// Full path of your private key file. /// </summary> property KeyFile : string read FKeyFile write SetKeyFile; /// <summary> /// Command to be run on remote host. /// </summary> property Command : string read FCommand write SetCommand; /// <summary> /// Command line parameter fpr the command to be run on remote host. /// </summary> property CommandParameter : string read FCommandParameter write SetCommandParameter; /// <summary> /// Destination for scp. /// This property is there for testing purpose. /// </summary> property Source : string read FSource write SetSource; /// <summary> /// Destination for scp. /// This property is there for testing purpose. /// </summary> property Destination : string read FDestination write SetDestination; /// <summary> /// Gives the parameter line for command execution. /// Can be used for testing. /// Set properties Source and Destionation first. /// </summary> function GetCommandParameterLine : string; /// <summary> /// Gives the parameter line for copy from remote action. /// Set properties Source and Destionation first. /// Can be used for testing. /// </summary> function GetSCPToRemoteParameterLine : string; /// <summary> /// Gives the parameter line for copy to remote action. /// Set properties Source and Destionation first. /// Can be used for testing. /// </summary> function GetSCPFromRemoteParameterLine : string; /// <summary> /// Send ACommand with AParameter to the remote host. /// All remote settings need to be set first. /// </summary> function SendCommand( const ACommand : string; const AParameter : string) : integer; /// <summary> /// Copy a local ASource to the remote host to ADestination. /// Uses scp. All remote settings need to be set first. /// If ADestination has trailing / then last part is a directory und filename of sourceparameter will copy into it. /// If ADestination has no trailing / then last part will be the new filename as copy destination. /// ASource can contain wildcards. Then give a trailing / as ADestination. /// </summary> function SCPToRemote( const ASource : string; const ADestination : string) : integer; /// <summary> /// Copy from ASource at remote host to a local ADestination /// All remote settings need to be set first. /// If ADestination has trailing / then last part is a directory und filename of sourceparameter will copy into it. /// If ADestination has no trailing / then last part will be the new filename as copy destination. /// ASource can contain wildcards. Then give a trailing / as ADestination. /// </summary> function SCPFromRemote( const ASource : string; const ADestination : string) : integer; end; implementation { TSSHCommand } {################################################################################################} function TSSHCommand.GetPortNum : integer; begin result := FPortNum; end; {################################################################################################} function TSSHCommand.GetSCPFromRemoteParameterLine: string; begin if FPortNum = 0 then FPortNum := 22; // scp -P 12322 -i keyfile user@remotehost:/home/user/file1.csv c:\tools\ result := '-P ' + FPortNum.ToString + ' -i ' + FKeyFile + ' ' + FUserName + '@' + FHostName + ':' + FSource + ' ' + FDestination; end; {################################################################################################} function TSSHCommand.GetSCPToRemoteParameterLine: string; begin if FPortNum = 0 then FPortNum := 22; // scp -P 12322 -i keyfile ASource user@remotehost:ADestination result := '-P ' + FPortNum.ToString + ' -i ' + FKeyFile + ' ' + FSource + ' ' + FUserName + '@' + FHostName + ':' + FDestination; end; {################################################################################################} function TSSHCommand.GetCommandParameterLine : string; begin if FPortNum = 0 then FPortNum := 22; // ssh remotehost -p 12322 -i keyfile -l user -t "command commandparameter" result := FHostName + ' -p ' + FPortNum.ToString + ' -i ' + FKeyFile + ' -l ' + FUserName + ' -t "' + FCommand + ' ' + FCommandParameter + '"'; end; {################################################################################################} function TSSHCommand.SCPFromRemote(const ASource, ADestination: string): integer; var LSCPParameterLine : string; begin if FSSHClient.IsEmpty then FSSHClient := 'scp.exe'; FSource := ASource; FDestination := ADestination; LSCPParameterLine := GetSCPFromRemoteParameterLine; result := ShellExecute( 0, 'open', PCHar( FSSHClient ), PCHar( LSCPParameterLine ), nil, SW_HIDE ); end; {################################################################################################} function TSSHCommand.SCPToRemote(const ASource, ADestination: string): integer; var LSCPParameterLine : string; begin if FSSHClient.IsEmpty then FSSHClient := 'scp.exe'; FSource := ASource; FDestination := ADestination; LSCPParameterLine := GetSCPToRemoteParameterLine; result := ShellExecute( 0, 'open', PCHar( FSSHClient ), PCHar( LSCPParameterLine ), nil, SW_HIDE ); end; {################################################################################################} function TSSHCommand.SendCommand ( const ACommand : string; const AParameter : string) : integer; var LCommandWithParameter : string; begin if FSSHClient.IsEmpty then FSSHClient := 'ssh.exe'; FCommand := ACommand; FCommandParameter := AParameter; LCommandWithParameter := GetCommandParameterLine; result := ShellExecute( 0, 'open', PCHar( FSSHClient ), PCHar( LCommandWithParameter ), nil, SW_HIDE ); end; {################################################################################################} procedure TSSHCommand.SetCommand(const Value: string); begin FCommand := Value; end; {################################################################################################} procedure TSSHCommand.SetCommandParameter(const Value: string); begin FCommandParameter := Value; end; {################################################################################################} procedure TSSHCommand.SetDestination(const Value: string); begin FDestination := Value; end; {################################################################################################} procedure TSSHCommand.SetHostName( const Value : string ); begin FHostName := Value; end; {################################################################################################} procedure TSSHCommand.SetKeyFile( const Value : string ); begin FKeyFile := Value; end; {################################################################################################} procedure TSSHCommand.SetPortNum( const Value : integer ); begin FPortNum := Value; end; {################################################################################################} procedure TSSHCommand.SetSource(const Value: string); begin FSource := Value; end; procedure TSSHCommand.SetSSHClient( const Value : string ); begin FSSHClient := Value; end; {################################################################################################} procedure TSSHCommand.SetUserName( const Value : string ); begin FUserName := Value; end; end.
{ *********************************************************************** } { } { Copyright (c) 2003 Borland Software Corporation } { } { Written by: Rick Beerendonk (rick@beerendonk.com) } { Microloon BV } { The Netherlands } { } { Thanks to Marcel van Brakel for his help with the FontSize-ComboBox } { } { ----------------------------------------------------------------------- } { THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY } { KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE } { IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A } { PARTICULAR PURPOSE. } { } { *********************************************************************** } unit Borland.Examples.Delphi.RichTextBox.Main; interface uses Borland.Examples.Delphi.RichTextBoxEx, System.Drawing, System.Collections, System.ComponentModel, System.Data, System.Drawing.Printing, System.Resources, System.Windows.Forms; type TMainForm = class(System.Windows.Forms.Form) {$REGION 'Designer Managed Code'} strict private /// <summary> /// Required designer variable. /// </summary> components: System.ComponentModel.IContainer; StatusBar: System.Windows.Forms.StatusBar; MainMenu1: System.Windows.Forms.MainMenu; FileMenu: System.Windows.Forms.MenuItem; EditMenu: System.Windows.Forms.MenuItem; HelpMenu: System.Windows.Forms.MenuItem; ToolBar: System.Windows.Forms.ToolBar; HelpInfoItem: System.Windows.Forms.MenuItem; FileNewItem: System.Windows.Forms.MenuItem; FileN1: System.Windows.Forms.MenuItem; FilePrintItem: System.Windows.Forms.MenuItem; EditUndoItem: System.Windows.Forms.MenuItem; EditN1: System.Windows.Forms.MenuItem; EditCutItem: System.Windows.Forms.MenuItem; EditCopyItem: System.Windows.Forms.MenuItem; EditPasteItem: System.Windows.Forms.MenuItem; EditN2: System.Windows.Forms.MenuItem; EditRedoItem: System.Windows.Forms.MenuItem; StatusBarPanel1: System.Windows.Forms.StatusBarPanel; StatusBarPanel2: System.Windows.Forms.StatusBarPanel; StatusBarPanel3: System.Windows.Forms.StatusBarPanel; FileSaveItem: System.Windows.Forms.MenuItem; FileOpenItem: System.Windows.Forms.MenuItem; OpenDialog: System.Windows.Forms.OpenFileDialog; EditFindItem: System.Windows.Forms.MenuItem; EditFindNextItem: System.Windows.Forms.MenuItem; SaveDialog: System.Windows.Forms.SaveFileDialog; FileSaveAsItem: System.Windows.Forms.MenuItem; FileN2: System.Windows.Forms.MenuItem; FileExitItem: System.Windows.Forms.MenuItem; NewButton: System.Windows.Forms.ToolBarButton; OpenButton: System.Windows.Forms.ToolBarButton; SaveButton: System.Windows.Forms.ToolBarButton; ToolBarImages: System.Windows.Forms.ImageList; Editor: Borland.Examples.Delphi.RichTextBoxEx.TRichTextBoxEx; Separator1: System.Windows.Forms.ToolBarButton; CutButton: System.Windows.Forms.ToolBarButton; CopyButton: System.Windows.Forms.ToolBarButton; Separator2: System.Windows.Forms.ToolBarButton; PasteButton: System.Windows.Forms.ToolBarButton; UndoButton: System.Windows.Forms.ToolBarButton; RedoButton: System.Windows.Forms.ToolBarButton; ViewMenu: System.Windows.Forms.MenuItem; ViewZoom200Item: System.Windows.Forms.MenuItem; ViewZoom100Item: System.Windows.Forms.MenuItem; ViewZoom50Item: System.Windows.Forms.MenuItem; Separator3: System.Windows.Forms.ToolBarButton; FindButton: System.Windows.Forms.ToolBarButton; FormatWordWrapItem: System.Windows.Forms.MenuItem; FormatDetectURLsItem: System.Windows.Forms.MenuItem; FontDialog: System.Windows.Forms.FontDialog; FormatMenu: System.Windows.Forms.MenuItem; FormatFontItem: System.Windows.Forms.MenuItem; FormatPanel: System.Windows.Forms.Panel; FormatToolBar: System.Windows.Forms.ToolBar; FormatPanelLeft: System.Windows.Forms.Panel; FontName: System.Windows.Forms.ComboBox; FormatToolBarDivider: System.Windows.Forms.ToolBar; BoldButton: System.Windows.Forms.ToolBarButton; ItalicButton: System.Windows.Forms.ToolBarButton; UnderlineButton: System.Windows.Forms.ToolBarButton; SeparatorFormat1: System.Windows.Forms.ToolBarButton; AlignLeftButton: System.Windows.Forms.ToolBarButton; CenterButton: System.Windows.Forms.ToolBarButton; AlignRightButton: System.Windows.Forms.ToolBarButton; SeparatorFormat2: System.Windows.Forms.ToolBarButton; BulletsButton: System.Windows.Forms.ToolBarButton; FormatAlignmentItem: System.Windows.Forms.MenuItem; FormatAlignLeftItem: System.Windows.Forms.MenuItem; FormatAlignCenterItem: System.Windows.Forms.MenuItem; FormatAlignRightItem: System.Windows.Forms.MenuItem; FormatBulletsItem: System.Windows.Forms.MenuItem; FontSize: System.Windows.Forms.ComboBox; ViewZoomItem: System.Windows.Forms.MenuItem; ViewToolbarItem: System.Windows.Forms.MenuItem; ViewFormatBarItem: System.Windows.Forms.MenuItem; ViewStatusBarItem: System.Windows.Forms.MenuItem; Separator4: System.Windows.Forms.ToolBarButton; PrintButton: System.Windows.Forms.ToolBarButton; PrintPreviewButton: System.Windows.Forms.ToolBarButton; FilePageSetupItem: System.Windows.Forms.MenuItem; FilePrintPreviewItem: System.Windows.Forms.MenuItem; PrintDocument: System.Drawing.Printing.PrintDocument; PrintDialog: System.Windows.Forms.PrintDialog; PrintPreviewDialog: System.Windows.Forms.PrintPreviewDialog; PageSetupDialog: System.Windows.Forms.PageSetupDialog; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> procedure InitializeComponent; procedure HelpInfoItem_Click(sender: System.Object; e: System.EventArgs); procedure FilePrintItem_Click(sender: System.Object; e: System.EventArgs); procedure EditUndoItem_Click(sender: System.Object; e: System.EventArgs); procedure EditCutItem_Click(sender: System.Object; e: System.EventArgs); procedure EditCopyItem_Click(sender: System.Object; e: System.EventArgs); procedure EditPasteItem_Click(sender: System.Object; e: System.EventArgs); procedure EditRedoItem_Click(sender: System.Object; e: System.EventArgs); {$ENDREGION} procedure Application_Idle(sender: System.Object; e: System.EventArgs); procedure EditFindItem_Click(sender: System.Object; e: System.EventArgs); procedure EditFindNextItem_Click(sender: System.Object; e: System.EventArgs); procedure FileExitItem_Click(sender: System.Object; e: System.EventArgs); procedure FileNewItem_Click(sender: System.Object; e: System.EventArgs); procedure FileOpenItem_Click(sender: System.Object; e: System.EventArgs); procedure FileSaveItem_Click(sender: System.Object; e: System.EventArgs); procedure FileSaveAsItem_Click(sender: System.Object; e: System.EventArgs); procedure FormatAlignLeftItem_Click(sender: System.Object; e: System.EventArgs); procedure FormatAlignCenterItem_Click(sender: System.Object; e: System.EventArgs); procedure FormatAlignRightItem_Click(sender: System.Object; e: System.EventArgs); procedure FormatBulletsItem_Click(sender: System.Object; e: System.EventArgs); procedure ViewZoom200Item_Click(sender: System.Object; e: System.EventArgs); procedure ViewZoom100Item_Click(sender: System.Object; e: System.EventArgs); procedure ViewZoom50Item_Click(sender: System.Object; e: System.EventArgs); procedure FormatDetectURLsItem_Click(sender: System.Object; e: System.EventArgs); procedure FormatWordWrapItem_Click(sender: System.Object; e: System.EventArgs); procedure FormatFontItem_Click(sender: System.Object; e: System.EventArgs); procedure FontName_SelectionChangeCommitted(sender: System.Object; e: System.EventArgs); procedure ToolBar_ButtonClick(sender: System.Object; e: System.Windows.Forms.ToolBarButtonClickEventArgs); procedure FormatToolBar_ButtonClick(sender: System.Object; e: System.Windows.Forms.ToolBarButtonClickEventArgs); procedure FontSize_SelectionChangeCommitted(sender: System.Object; e: System.EventArgs); procedure ViewToolbarItem_Click(sender: System.Object; e: System.EventArgs); procedure ViewFormatBarItem_Click(sender: System.Object; e: System.EventArgs); procedure ViewStatusBarItem_Click(sender: System.Object; e: System.EventArgs); procedure TMainForm_DragEnter(sender: System.Object; e: System.Windows.Forms.DragEventArgs); procedure TMainForm_DragDrop(sender: System.Object; e: System.Windows.Forms.DragEventArgs); procedure FilePrintPreviewItem_Click(sender: System.Object; e: System.EventArgs); procedure FilePageSetupItem_Click(sender: System.Object; e: System.EventArgs); procedure PrintDocument_BeginPrint(sender: System.Object; e: System.Drawing.Printing.PrintEventArgs); procedure PrintDocument_EndPrint(sender: System.Object; e: System.Drawing.Printing.PrintEventArgs); procedure PrintDocument_PrintPage(sender: System.Object; e: System.Drawing.Printing.PrintPageEventArgs); strict protected /// <summary> /// Clean up any resources being used. /// </summary> procedure Dispose(Disposing: Boolean); override; private FFileName: string; FFindOptions: RichTextBoxFinds; FFindPrevious: Integer; FFindText: string; FFirstCharOnPage: Integer; // Needed for printing FUpdating: Boolean; function CanCloseCurrentFile: Boolean; procedure GetFontNames; procedure PerformFileOpen(const AFileName: string); procedure SetFileName(const AFileName: string); procedure SetZoom(const AZoomFactor: Single); // UI procedure EditCut; procedure EditCopy; procedure EditPaste; procedure EditUndo; procedure EditRedo; procedure FileNew; procedure FileOpen; procedure FileSave; procedure FileSaveAs; procedure FilePrint; procedure FilePrintWithDialog; procedure FilePrintPreview; procedure FilePageSetup; procedure Find; procedure FindNext; procedure FormatAlignLeft; procedure FormatAlignRight; procedure FormatBullets; procedure FormatCenter; procedure FormatFont; procedure FormatFontBold; procedure FormatFontItalic; procedure FormatFontUnderline; public constructor Create; end; [assembly: RuntimeRequiredAttribute(TypeOf(TMainForm))] implementation uses Borland.Examples.Delphi.RichTextBox.Find, Borland.Examples.Delphi.RichTextBox.Info, System.Drawing.Text, System.Globalization, System.IO; resourcestring sUntitled = 'Untitled'; sModified = 'Modified'; sReadOnly = 'Read-only'; sConfirm = 'Confirm'; sMenuRedo = '&Redo'; sMenuUndo = '&Undo'; sBtnRedo = 'Redo'; sBtnUndo = 'Undo'; {$REGION 'Windows Form Designer generated code'} /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> procedure TMainForm.InitializeComponent; type TSystem_Windows_Forms_StatusBarPanelArray = array of System.Windows.Forms.StatusBarPanel; TSystem_Windows_Forms_MenuItemArray = array of System.Windows.Forms.MenuItem; TSystem_Windows_Forms_ToolBarButtonArray = array of System.Windows.Forms.ToolBarButton; TSystem_ObjectArray = array of System.Object; var resources: System.Resources.ResourceManager; begin Self.components := System.ComponentModel.Container.Create; resources := System.Resources.ResourceManager.Create(TypeOf(TMainForm)); Self.StatusBar := System.Windows.Forms.StatusBar.Create; Self.StatusBarPanel1 := System.Windows.Forms.StatusBarPanel.Create; Self.StatusBarPanel2 := System.Windows.Forms.StatusBarPanel.Create; Self.StatusBarPanel3 := System.Windows.Forms.StatusBarPanel.Create; Self.MainMenu1 := System.Windows.Forms.MainMenu.Create; Self.FileMenu := System.Windows.Forms.MenuItem.Create; Self.FileNewItem := System.Windows.Forms.MenuItem.Create; Self.FileOpenItem := System.Windows.Forms.MenuItem.Create; Self.FileSaveItem := System.Windows.Forms.MenuItem.Create; Self.FileSaveAsItem := System.Windows.Forms.MenuItem.Create; Self.FileN1 := System.Windows.Forms.MenuItem.Create; Self.FilePrintItem := System.Windows.Forms.MenuItem.Create; Self.FilePrintPreviewItem := System.Windows.Forms.MenuItem.Create; Self.FilePageSetupItem := System.Windows.Forms.MenuItem.Create; Self.FileN2 := System.Windows.Forms.MenuItem.Create; Self.FileExitItem := System.Windows.Forms.MenuItem.Create; Self.EditMenu := System.Windows.Forms.MenuItem.Create; Self.EditUndoItem := System.Windows.Forms.MenuItem.Create; Self.EditRedoItem := System.Windows.Forms.MenuItem.Create; Self.EditN1 := System.Windows.Forms.MenuItem.Create; Self.EditCutItem := System.Windows.Forms.MenuItem.Create; Self.EditCopyItem := System.Windows.Forms.MenuItem.Create; Self.EditPasteItem := System.Windows.Forms.MenuItem.Create; Self.EditN2 := System.Windows.Forms.MenuItem.Create; Self.EditFindItem := System.Windows.Forms.MenuItem.Create; Self.EditFindNextItem := System.Windows.Forms.MenuItem.Create; Self.ViewMenu := System.Windows.Forms.MenuItem.Create; Self.ViewZoomItem := System.Windows.Forms.MenuItem.Create; Self.ViewZoom50Item := System.Windows.Forms.MenuItem.Create; Self.ViewZoom100Item := System.Windows.Forms.MenuItem.Create; Self.ViewZoom200Item := System.Windows.Forms.MenuItem.Create; Self.ViewToolbarItem := System.Windows.Forms.MenuItem.Create; Self.ViewFormatBarItem := System.Windows.Forms.MenuItem.Create; Self.ViewStatusBarItem := System.Windows.Forms.MenuItem.Create; Self.FormatMenu := System.Windows.Forms.MenuItem.Create; Self.FormatFontItem := System.Windows.Forms.MenuItem.Create; Self.FormatAlignmentItem := System.Windows.Forms.MenuItem.Create; Self.FormatAlignLeftItem := System.Windows.Forms.MenuItem.Create; Self.FormatAlignCenterItem := System.Windows.Forms.MenuItem.Create; Self.FormatAlignRightItem := System.Windows.Forms.MenuItem.Create; Self.FormatBulletsItem := System.Windows.Forms.MenuItem.Create; Self.FormatDetectURLsItem := System.Windows.Forms.MenuItem.Create; Self.FormatWordWrapItem := System.Windows.Forms.MenuItem.Create; Self.HelpMenu := System.Windows.Forms.MenuItem.Create; Self.HelpInfoItem := System.Windows.Forms.MenuItem.Create; Self.ToolBar := System.Windows.Forms.ToolBar.Create; Self.NewButton := System.Windows.Forms.ToolBarButton.Create; Self.OpenButton := System.Windows.Forms.ToolBarButton.Create; Self.SaveButton := System.Windows.Forms.ToolBarButton.Create; Self.Separator1 := System.Windows.Forms.ToolBarButton.Create; Self.PrintButton := System.Windows.Forms.ToolBarButton.Create; Self.PrintPreviewButton := System.Windows.Forms.ToolBarButton.Create; Self.Separator2 := System.Windows.Forms.ToolBarButton.Create; Self.CutButton := System.Windows.Forms.ToolBarButton.Create; Self.CopyButton := System.Windows.Forms.ToolBarButton.Create; Self.PasteButton := System.Windows.Forms.ToolBarButton.Create; Self.Separator3 := System.Windows.Forms.ToolBarButton.Create; Self.UndoButton := System.Windows.Forms.ToolBarButton.Create; Self.RedoButton := System.Windows.Forms.ToolBarButton.Create; Self.Separator4 := System.Windows.Forms.ToolBarButton.Create; Self.FindButton := System.Windows.Forms.ToolBarButton.Create; Self.ToolBarImages := System.Windows.Forms.ImageList.Create(Self.components); Self.OpenDialog := System.Windows.Forms.OpenFileDialog.Create; Self.SaveDialog := System.Windows.Forms.SaveFileDialog.Create; Self.Editor := Borland.Examples.Delphi.RichTextBoxEx.TRichTextBoxEx.Create; Self.FontDialog := System.Windows.Forms.FontDialog.Create; Self.FormatPanel := System.Windows.Forms.Panel.Create; Self.FormatToolBar := System.Windows.Forms.ToolBar.Create; Self.BoldButton := System.Windows.Forms.ToolBarButton.Create; Self.ItalicButton := System.Windows.Forms.ToolBarButton.Create; Self.UnderlineButton := System.Windows.Forms.ToolBarButton.Create; Self.SeparatorFormat1 := System.Windows.Forms.ToolBarButton.Create; Self.AlignLeftButton := System.Windows.Forms.ToolBarButton.Create; Self.CenterButton := System.Windows.Forms.ToolBarButton.Create; Self.AlignRightButton := System.Windows.Forms.ToolBarButton.Create; Self.SeparatorFormat2 := System.Windows.Forms.ToolBarButton.Create; Self.BulletsButton := System.Windows.Forms.ToolBarButton.Create; Self.FormatPanelLeft := System.Windows.Forms.Panel.Create; Self.FontSize := System.Windows.Forms.ComboBox.Create; Self.FontName := System.Windows.Forms.ComboBox.Create; Self.FormatToolBarDivider := System.Windows.Forms.ToolBar.Create; Self.PrintDocument := System.Drawing.Printing.PrintDocument.Create; Self.PrintDialog := System.Windows.Forms.PrintDialog.Create; Self.PrintPreviewDialog := System.Windows.Forms.PrintPreviewDialog.Create; Self.PageSetupDialog := System.Windows.Forms.PageSetupDialog.Create; (System.ComponentModel.ISupportInitialize(Self.StatusBarPanel1)).BeginInit; (System.ComponentModel.ISupportInitialize(Self.StatusBarPanel2)).BeginInit; (System.ComponentModel.ISupportInitialize(Self.StatusBarPanel3)).BeginInit; Self.FormatPanel.SuspendLayout; Self.FormatPanelLeft.SuspendLayout; Self.SuspendLayout; // // StatusBar // Self.StatusBar.Location := System.Drawing.Point.Create(0, 404); Self.StatusBar.Name := 'StatusBar'; Self.StatusBar.Panels.AddRange(TSystem_Windows_Forms_StatusBarPanelArray.Create(Self.StatusBarPanel1, Self.StatusBarPanel2, Self.StatusBarPanel3)); Self.StatusBar.Size := System.Drawing.Size.Create(632, 22); Self.StatusBar.TabIndex := 3; // // StatusBarPanel1 // Self.StatusBarPanel1.Width := 120; // // StatusBarPanel2 // Self.StatusBarPanel2.Alignment := System.Windows.Forms.HorizontalAlignment.Center; Self.StatusBarPanel2.Width := 70; // // StatusBarPanel3 // Self.StatusBarPanel3.Width := 50; // // MainMenu1 // Self.MainMenu1.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.FileMenu, Self.EditMenu, Self.ViewMenu, Self.FormatMenu, Self.HelpMenu)); // // FileMenu // Self.FileMenu.Index := 0; Self.FileMenu.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.FileNewItem, Self.FileOpenItem, Self.FileSaveItem, Self.FileSaveAsItem, Self.FileN1, Self.FilePrintItem, Self.FilePrintPreviewItem, Self.FilePageSetupItem, Self.FileN2, Self.FileExitItem)); Self.FileMenu.Text := '&File'; // // FileNewItem // Self.FileNewItem.Index := 0; Self.FileNewItem.Shortcut := System.Windows.Forms.Shortcut.CtrlN; Self.FileNewItem.Text := '&New'; Include(Self.FileNewItem.Click, Self.FileNewItem_Click); // // FileOpenItem // Self.FileOpenItem.Index := 1; Self.FileOpenItem.Shortcut := System.Windows.Forms.Shortcut.CtrlO; Self.FileOpenItem.Text := '&Open...'; Include(Self.FileOpenItem.Click, Self.FileOpenItem_Click); // // FileSaveItem // Self.FileSaveItem.Index := 2; Self.FileSaveItem.Shortcut := System.Windows.Forms.Shortcut.CtrlS; Self.FileSaveItem.Text := '&Save'; Include(Self.FileSaveItem.Click, Self.FileSaveItem_Click); // // FileSaveAsItem // Self.FileSaveAsItem.Index := 3; Self.FileSaveAsItem.Text := 'Save &As...'; Include(Self.FileSaveAsItem.Click, Self.FileSaveAsItem_Click); // // FileN1 // Self.FileN1.Index := 4; Self.FileN1.Text := '-'; // // FilePrintItem // Self.FilePrintItem.Index := 5; Self.FilePrintItem.Shortcut := System.Windows.Forms.Shortcut.CtrlP; Self.FilePrintItem.Text := '&Print...'; Include(Self.FilePrintItem.Click, Self.FilePrintItem_Click); // // FilePrintPreviewItem // Self.FilePrintPreviewItem.Index := 6; Self.FilePrintPreviewItem.Text := 'Print Pre&view'; Include(Self.FilePrintPreviewItem.Click, Self.FilePrintPreviewItem_Click); // // FilePageSetupItem // Self.FilePageSetupItem.Index := 7; Self.FilePageSetupItem.Text := 'Page Set&up...'; Include(Self.FilePageSetupItem.Click, Self.FilePageSetupItem_Click); // // FileN2 // Self.FileN2.Index := 8; Self.FileN2.Text := '-'; // // FileExitItem // Self.FileExitItem.Index := 9; Self.FileExitItem.Text := '&Exit'; Include(Self.FileExitItem.Click, Self.FileExitItem_Click); // // EditMenu // Self.EditMenu.Index := 1; Self.EditMenu.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.EditUndoItem, Self.EditRedoItem, Self.EditN1, Self.EditCutItem, Self.EditCopyItem, Self.EditPasteItem, Self.EditN2, Self.EditFindItem, Self.EditFindNextItem)); Self.EditMenu.Text := '&Edit'; // // EditUndoItem // Self.EditUndoItem.Index := 0; Self.EditUndoItem.Shortcut := System.Windows.Forms.Shortcut.CtrlZ; Self.EditUndoItem.Text := '&Undo'; Include(Self.EditUndoItem.Click, Self.EditUndoItem_Click); // // EditRedoItem // Self.EditRedoItem.Index := 1; Self.EditRedoItem.Shortcut := System.Windows.Forms.Shortcut.CtrlY; Self.EditRedoItem.Text := '&Redo'; Include(Self.EditRedoItem.Click, Self.EditRedoItem_Click); // // EditN1 // Self.EditN1.Index := 2; Self.EditN1.Text := '-'; // // EditCutItem // Self.EditCutItem.Index := 3; Self.EditCutItem.Shortcut := System.Windows.Forms.Shortcut.CtrlX; Self.EditCutItem.Text := 'Cu&t'; Include(Self.EditCutItem.Click, Self.EditCutItem_Click); // // EditCopyItem // Self.EditCopyItem.Index := 4; Self.EditCopyItem.Shortcut := System.Windows.Forms.Shortcut.CtrlC; Self.EditCopyItem.Text := '&Copy'; Include(Self.EditCopyItem.Click, Self.EditCopyItem_Click); // // EditPasteItem // Self.EditPasteItem.Index := 5; Self.EditPasteItem.Shortcut := System.Windows.Forms.Shortcut.CtrlV; Self.EditPasteItem.Text := '&Paste'; Include(Self.EditPasteItem.Click, Self.EditPasteItem_Click); // // EditN2 // Self.EditN2.Index := 6; Self.EditN2.Text := '-'; // // EditFindItem // Self.EditFindItem.Index := 7; Self.EditFindItem.Shortcut := System.Windows.Forms.Shortcut.CtrlF; Self.EditFindItem.Text := '&Find...'; Include(Self.EditFindItem.Click, Self.EditFindItem_Click); // // EditFindNextItem // Self.EditFindNextItem.Index := 8; Self.EditFindNextItem.Shortcut := System.Windows.Forms.Shortcut.F3; Self.EditFindNextItem.Text := 'Find &Next'; Include(Self.EditFindNextItem.Click, Self.EditFindNextItem_Click); // // ViewMenu // Self.ViewMenu.Index := 2; Self.ViewMenu.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.ViewZoomItem, Self.ViewToolbarItem, Self.ViewFormatBarItem, Self.ViewStatusBarItem)); Self.ViewMenu.Text := '&View'; // // ViewZoomItem // Self.ViewZoomItem.Index := 0; Self.ViewZoomItem.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.ViewZoom50Item, Self.ViewZoom100Item, Self.ViewZoom200Item)); Self.ViewZoomItem.Text := '&Zoom'; // // ViewZoom50Item // Self.ViewZoom50Item.Index := 0; Self.ViewZoom50Item.RadioCheck := True; Self.ViewZoom50Item.Shortcut := System.Windows.Forms.Shortcut.CtrlShift1; Self.ViewZoom50Item.Text := '&50%'; Include(Self.ViewZoom50Item.Click, Self.ViewZoom50Item_Click); // // ViewZoom100Item // Self.ViewZoom100Item.Checked := True; Self.ViewZoom100Item.Index := 1; Self.ViewZoom100Item.RadioCheck := True; Self.ViewZoom100Item.Shortcut := System.Windows.Forms.Shortcut.CtrlShift2; Self.ViewZoom100Item.Text := '&100%'; Include(Self.ViewZoom100Item.Click, Self.ViewZoom100Item_Click); // // ViewZoom200Item // Self.ViewZoom200Item.Index := 2; Self.ViewZoom200Item.RadioCheck := True; Self.ViewZoom200Item.Shortcut := System.Windows.Forms.Shortcut.CtrlShift3; Self.ViewZoom200Item.Text := '&200%'; Include(Self.ViewZoom200Item.Click, Self.ViewZoom200Item_Click); // // ViewToolbarItem // Self.ViewToolbarItem.Index := 1; Self.ViewToolbarItem.Text := '&Toolbar'; Include(Self.ViewToolbarItem.Click, Self.ViewToolbarItem_Click); // // ViewFormatBarItem // Self.ViewFormatBarItem.Index := 2; Self.ViewFormatBarItem.Text := '&Format Bar'; Include(Self.ViewFormatBarItem.Click, Self.ViewFormatBarItem_Click); // // ViewStatusBarItem // Self.ViewStatusBarItem.Index := 3; Self.ViewStatusBarItem.Text := '&Status Bar'; Include(Self.ViewStatusBarItem.Click, Self.ViewStatusBarItem_Click); // // FormatMenu // Self.FormatMenu.Index := 3; Self.FormatMenu.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.FormatFontItem, Self.FormatAlignmentItem, Self.FormatBulletsItem, Self.FormatDetectURLsItem, Self.FormatWordWrapItem)); Self.FormatMenu.Text := 'F&ormat'; // // FormatFontItem // Self.FormatFontItem.Index := 0; Self.FormatFontItem.Text := '&Font...'; Include(Self.FormatFontItem.Click, Self.FormatFontItem_Click); // // FormatAlignmentItem // Self.FormatAlignmentItem.Index := 1; Self.FormatAlignmentItem.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.FormatAlignLeftItem, Self.FormatAlignCenterItem, Self.FormatAlignRightItem)); Self.FormatAlignmentItem.Text := '&Alignment'; // // FormatAlignLeftItem // Self.FormatAlignLeftItem.Index := 0; Self.FormatAlignLeftItem.RadioCheck := True; Self.FormatAlignLeftItem.Text := '&Left'; Include(Self.FormatAlignLeftItem.Click, Self.FormatAlignLeftItem_Click); // // FormatAlignCenterItem // Self.FormatAlignCenterItem.Index := 1; Self.FormatAlignCenterItem.RadioCheck := True; Self.FormatAlignCenterItem.Text := '&Center'; Include(Self.FormatAlignCenterItem.Click, Self.FormatAlignCenterItem_Click); // // FormatAlignRightItem // Self.FormatAlignRightItem.Index := 2; Self.FormatAlignRightItem.RadioCheck := True; Self.FormatAlignRightItem.Text := '&Right'; Include(Self.FormatAlignRightItem.Click, Self.FormatAlignRightItem_Click); // // FormatBulletsItem // Self.FormatBulletsItem.Index := 2; Self.FormatBulletsItem.Text := '&Bullet Style'; Include(Self.FormatBulletsItem.Click, Self.FormatBulletsItem_Click); // // FormatDetectURLsItem // Self.FormatDetectURLsItem.Checked := True; Self.FormatDetectURLsItem.Index := 3; Self.FormatDetectURLsItem.Text := '&Detect URL'; Include(Self.FormatDetectURLsItem.Click, Self.FormatDetectURLsItem_Click); // // FormatWordWrapItem // Self.FormatWordWrapItem.Index := 4; Self.FormatWordWrapItem.Text := '&Word wrap'; Include(Self.FormatWordWrapItem.Click, Self.FormatWordWrapItem_Click); // // HelpMenu // Self.HelpMenu.Index := 4; Self.HelpMenu.MenuItems.AddRange(TSystem_Windows_Forms_MenuItemArray.Create(Self.HelpInfoItem)); Self.HelpMenu.Text := '&Help'; // // HelpInfoItem // Self.HelpInfoItem.Index := 0; Self.HelpInfoItem.Text := '&Info'; Include(Self.HelpInfoItem.Click, Self.HelpInfoItem_Click); // // ToolBar // Self.ToolBar.Appearance := System.Windows.Forms.ToolBarAppearance.Flat; Self.ToolBar.Buttons.AddRange(TSystem_Windows_Forms_ToolBarButtonArray.Create(Self.NewButton, Self.OpenButton, Self.SaveButton, Self.Separator1, Self.PrintButton, Self.PrintPreviewButton, Self.Separator2, Self.CutButton, Self.CopyButton, Self.PasteButton, Self.Separator3, Self.UndoButton, Self.RedoButton, Self.Separator4, Self.FindButton)); Self.ToolBar.DropDownArrows := True; Self.ToolBar.ImageList := Self.ToolBarImages; Self.ToolBar.Location := System.Drawing.Point.Create(0, 0); Self.ToolBar.Name := 'ToolBar'; Self.ToolBar.ShowToolTips := True; Self.ToolBar.Size := System.Drawing.Size.Create(632, 28); Self.ToolBar.TabIndex := 1; Self.ToolBar.TextAlign := System.Windows.Forms.ToolBarTextAlign.Right; Self.ToolBar.Wrappable := False; Include(Self.ToolBar.ButtonClick, Self.ToolBar_ButtonClick); // // NewButton // Self.NewButton.ImageIndex := 0; Self.NewButton.ToolTipText := 'New'; // // OpenButton // Self.OpenButton.ImageIndex := 1; Self.OpenButton.ToolTipText := 'Open'; // // SaveButton // Self.SaveButton.ImageIndex := 2; Self.SaveButton.ToolTipText := 'Save'; // // Separator1 // Self.Separator1.Style := System.Windows.Forms.ToolBarButtonStyle.Separator; // // PrintButton // Self.PrintButton.ImageIndex := 3; Self.PrintButton.ToolTipText := 'Print'; // // PrintPreviewButton // Self.PrintPreviewButton.ImageIndex := 4; Self.PrintPreviewButton.ToolTipText := 'Print Preview'; // // Separator2 // Self.Separator2.Style := System.Windows.Forms.ToolBarButtonStyle.Separator; // // CutButton // Self.CutButton.ImageIndex := 5; Self.CutButton.ToolTipText := 'Cut'; // // CopyButton // Self.CopyButton.ImageIndex := 6; Self.CopyButton.ToolTipText := 'Copy'; // // PasteButton // Self.PasteButton.ImageIndex := 7; Self.PasteButton.ToolTipText := 'Paste'; // // Separator3 // Self.Separator3.Style := System.Windows.Forms.ToolBarButtonStyle.Separator; // // UndoButton // Self.UndoButton.ImageIndex := 8; Self.UndoButton.ToolTipText := 'Undo'; // // RedoButton // Self.RedoButton.ImageIndex := 9; Self.RedoButton.ToolTipText := 'Redo'; // // Separator4 // Self.Separator4.Style := System.Windows.Forms.ToolBarButtonStyle.Separator; // // FindButton // Self.FindButton.ImageIndex := 10; Self.FindButton.ToolTipText := 'Find'; // // ToolBarImages // Self.ToolBarImages.ImageSize := System.Drawing.Size.Create(16, 16); Self.ToolBarImages.ImageStream := (System.Windows.Forms.ImageListStreamer(resources.GetObject('ToolBarImages.ImageStream'))); Self.ToolBarImages.TransparentColor := System.Drawing.Color.Fuchsia; // // OpenDialog // Self.OpenDialog.Filter := 'Rich Text Files (*.rtf)|*.rtf|Text Files (*.txt)|*.txt'; Self.OpenDialog.ShowReadOnly := True; // // SaveDialog // Self.SaveDialog.Filter := 'Rich Text Files (*.rtf)|*.rtf|Text Files (*.txt)|*.txt'; // // Editor // Self.Editor.AllowDrop := True; Self.Editor.Dock := System.Windows.Forms.DockStyle.Fill; Self.Editor.Location := System.Drawing.Point.Create(0, 56); Self.Editor.Name := 'Editor'; Self.Editor.Size := System.Drawing.Size.Create(632, 348); Self.Editor.TabIndex := 0; Self.Editor.Text := ''; // // FontDialog // Self.FontDialog.FontMustExist := True; Self.FontDialog.ShowColor := True; // // FormatPanel // Self.FormatPanel.Controls.Add(Self.FormatToolBar); Self.FormatPanel.Controls.Add(Self.FormatPanelLeft); Self.FormatPanel.Dock := System.Windows.Forms.DockStyle.Top; Self.FormatPanel.Location := System.Drawing.Point.Create(0, 28); Self.FormatPanel.Name := 'FormatPanel'; Self.FormatPanel.Size := System.Drawing.Size.Create(632, 28); Self.FormatPanel.TabIndex := 2; // // FormatToolBar // Self.FormatToolBar.Appearance := System.Windows.Forms.ToolBarAppearance.Flat; Self.FormatToolBar.Buttons.AddRange(TSystem_Windows_Forms_ToolBarButtonArray.Create(Self.BoldButton, Self.ItalicButton, Self.UnderlineButton, Self.SeparatorFormat1, Self.AlignLeftButton, Self.CenterButton, Self.AlignRightButton, Self.SeparatorFormat2, Self.BulletsButton)); Self.FormatToolBar.DropDownArrows := True; Self.FormatToolBar.ImageList := Self.ToolBarImages; Self.FormatToolBar.Location := System.Drawing.Point.Create(232, 0); Self.FormatToolBar.Name := 'FormatToolBar'; Self.FormatToolBar.ShowToolTips := True; Self.FormatToolBar.Size := System.Drawing.Size.Create(400, 28); Self.FormatToolBar.TabIndex := 2; Include(Self.FormatToolBar.ButtonClick, Self.FormatToolBar_ButtonClick); // // BoldButton // Self.BoldButton.ImageIndex := 11; Self.BoldButton.Style := System.Windows.Forms.ToolBarButtonStyle.ToggleButton; Self.BoldButton.ToolTipText := 'Bold'; // // ItalicButton // Self.ItalicButton.ImageIndex := 12; Self.ItalicButton.Style := System.Windows.Forms.ToolBarButtonStyle.ToggleButton; Self.ItalicButton.ToolTipText := 'Italic'; // // UnderlineButton // Self.UnderlineButton.ImageIndex := 13; Self.UnderlineButton.Style := System.Windows.Forms.ToolBarButtonStyle.ToggleButton; Self.UnderlineButton.ToolTipText := 'Underline'; // // SeparatorFormat1 // Self.SeparatorFormat1.Style := System.Windows.Forms.ToolBarButtonStyle.Separator; // // AlignLeftButton // Self.AlignLeftButton.ImageIndex := 14; Self.AlignLeftButton.Style := System.Windows.Forms.ToolBarButtonStyle.ToggleButton; Self.AlignLeftButton.ToolTipText := 'Align Left'; // // CenterButton // Self.CenterButton.ImageIndex := 15; Self.CenterButton.Style := System.Windows.Forms.ToolBarButtonStyle.ToggleButton; Self.CenterButton.ToolTipText := 'Center'; // // AlignRightButton // Self.AlignRightButton.ImageIndex := 16; Self.AlignRightButton.Style := System.Windows.Forms.ToolBarButtonStyle.ToggleButton; Self.AlignRightButton.ToolTipText := 'Align Right'; // // SeparatorFormat2 // Self.SeparatorFormat2.Style := System.Windows.Forms.ToolBarButtonStyle.Separator; // // BulletsButton // Self.BulletsButton.ImageIndex := 17; Self.BulletsButton.Style := System.Windows.Forms.ToolBarButtonStyle.ToggleButton; Self.BulletsButton.ToolTipText := 'Bullets'; // // FormatPanelLeft // Self.FormatPanelLeft.Controls.Add(Self.FontSize); Self.FormatPanelLeft.Controls.Add(Self.FontName); Self.FormatPanelLeft.Controls.Add(Self.FormatToolBarDivider); Self.FormatPanelLeft.Dock := System.Windows.Forms.DockStyle.Left; Self.FormatPanelLeft.Location := System.Drawing.Point.Create(0, 0); Self.FormatPanelLeft.Name := 'FormatPanelLeft'; Self.FormatPanelLeft.Size := System.Drawing.Size.Create(232, 28); Self.FormatPanelLeft.TabIndex := 1; // // FontSize // Self.FontSize.DropDownStyle := System.Windows.Forms.ComboBoxStyle.DropDownList; // Workaround; string() is needed, otherwise we add characters: Self.FontSize.Items.AddRange(TSystem_ObjectArray.Create(string('8'), string('9'), '10', '11', '12', '14', '16', '18', '20', '22', '24', '26', '28', '36', '48', '72')); Self.FontSize.Location := System.Drawing.Point.Create(180, 4); Self.FontSize.MaxDropDownItems := 12; Self.FontSize.Name := 'FontSize'; Self.FontSize.Size := System.Drawing.Size.Create(52, 21); Self.FontSize.TabIndex := 2; Include(Self.FontSize.SelectionChangeCommitted, Self.FontSize_SelectionChangeCommitted); // // FontName // Self.FontName.DropDownStyle := System.Windows.Forms.ComboBoxStyle.DropDownList; Self.FontName.Location := System.Drawing.Point.Create(4, 4); Self.FontName.MaxDropDownItems := 12; Self.FontName.Name := 'FontName'; Self.FontName.Size := System.Drawing.Size.Create(172, 21); Self.FontName.TabIndex := 0; Include(Self.FontName.SelectionChangeCommitted, Self.FontName_SelectionChangeCommitted); // // FormatToolBarDivider // Self.FormatToolBarDivider.Dock := System.Windows.Forms.DockStyle.Fill; Self.FormatToolBarDivider.DropDownArrows := True; Self.FormatToolBarDivider.Location := System.Drawing.Point.Create(0, 0); Self.FormatToolBarDivider.Name := 'FormatToolBarDivider'; Self.FormatToolBarDivider.ShowToolTips := True; Self.FormatToolBarDivider.Size := System.Drawing.Size.Create(232, 42); Self.FormatToolBarDivider.TabIndex := 1; // // PrintDocument // Include(Self.PrintDocument.BeginPrint, Self.PrintDocument_BeginPrint); Include(Self.PrintDocument.EndPrint, Self.PrintDocument_EndPrint); Include(Self.PrintDocument.PrintPage, Self.PrintDocument_PrintPage); // // PrintDialog // Self.PrintDialog.Document := Self.PrintDocument; // // PrintPreviewDialog // Self.PrintPreviewDialog.AutoScrollMargin := System.Drawing.Size.Create(0, 0); Self.PrintPreviewDialog.AutoScrollMinSize := System.Drawing.Size.Create(0, 0); Self.PrintPreviewDialog.ClientSize := System.Drawing.Size.Create(480, 320); Self.PrintPreviewDialog.Document := Self.PrintDocument; Self.PrintPreviewDialog.Enabled := True; Self.PrintPreviewDialog.Icon := (System.Drawing.Icon(resources.GetObject('PrintPreviewDialog.Icon'))); Self.PrintPreviewDialog.Location := System.Drawing.Point.Create(307, 54); Self.PrintPreviewDialog.MinimumSize := System.Drawing.Size.Create(375, 250); Self.PrintPreviewDialog.Name := 'PrintPreviewDialog'; Self.PrintPreviewDialog.StartPosition := System.Windows.Forms.FormStartPosition.CenterParent; Self.PrintPreviewDialog.TransparencyKey := System.Drawing.Color.Empty; Self.PrintPreviewDialog.Visible := False; // // PageSetupDialog // Self.PageSetupDialog.Document := Self.PrintDocument; // // TMainForm // Self.AllowDrop := True; Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13); Self.ClientSize := System.Drawing.Size.Create(632, 426); Self.Controls.Add(Self.Editor); Self.Controls.Add(Self.FormatPanel); Self.Controls.Add(Self.ToolBar); Self.Controls.Add(Self.StatusBar); Self.Icon := (System.Drawing.Icon(resources.GetObject('$this.Icon'))); Self.Menu := Self.MainMenu1; Self.Name := 'TMainForm'; Self.StartPosition := System.Windows.Forms.FormStartPosition.CenterScreen; Self.Text := 'Rich Text Box Control Demo'; Include(Self.DragDrop, Self.TMainForm_DragDrop); Include(Self.DragEnter, Self.TMainForm_DragEnter); (System.ComponentModel.ISupportInitialize(Self.StatusBarPanel1)).EndInit; (System.ComponentModel.ISupportInitialize(Self.StatusBarPanel2)).EndInit; (System.ComponentModel.ISupportInitialize(Self.StatusBarPanel3)).EndInit; Self.FormatPanel.ResumeLayout(False); Self.FormatPanelLeft.ResumeLayout(False); Self.ResumeLayout(False); end; {$ENDREGION} procedure TMainForm.Application_Idle(sender: System.Object; e: System.EventArgs); var i: Integer; s: string; ClipboardFormats: array of string; begin // Paste ClipboardFormats := Clipboard.GetDataObject.GetFormats(True); i := 0; EditPasteItem.Enabled := False; while not EditPasteItem.Enabled and (i < Length(ClipboardFormats)) do begin EditPasteItem.Enabled := Editor.CanPaste(DataFormats.GetFormat(ClipboardFormats[i])); Inc(i); end; PasteButton.Enabled := EditPasteItem.Enabled; // Undo s := Editor.UndoActionName; if Length(s) > 0 then s := ' ' + s; EditUndoItem.Enabled := Editor.CanUndo; EditUndoItem.Text := sMenuUndo + s; UndoButton.Enabled := Editor.CanUndo; UndoButton.ToolTipText := sBtnUndo + s; // Redo s := Editor.RedoActionName; if Length(s) > 0 then s := ' ' + s; EditRedoItem.Enabled := Editor.CanRedo; EditRedoItem.Text := sMenuRedo + s; RedoButton.Enabled := Editor.CanRedo; RedoButton.ToolTipText := sBtnRedo + s; EditFindNextItem.Enabled := FFindPrevious > -1; // Format FUpdating := True; try // Menu status ViewToolbarItem.Checked := ToolBar.Visible; ViewFormatBarItem.Checked := FormatPanel.Visible; ViewStatusBarItem.Checked := StatusBar.Visible; FormatDetectURLsItem.Checked := Editor.DetectUrls; FormatWordWrapItem.Checked := Editor.WordWrap; FormatAlignLeftItem.Checked := Editor.SelectionAlignment = HorizontalAlignment.Left; FormatAlignCenterItem.Checked := Editor.SelectionAlignment = HorizontalAlignment.Center; FormatAlignRightItem.Checked := Editor.SelectionAlignment = HorizontalAlignment.Right; FormatBulletsItem.Checked := Editor.SelectionBullet; // Toolbar status (pushed / comboboxes) if not FontName.DroppedDown then if Assigned(Editor.SelectionFont) then // Not assigned if multiple fonts are in the selection! FontName.SelectedIndex := FontName.Items.IndexOf(Editor.SelectionFont.Name) else FontName.SelectedIndex := -1; // Editor.SelectionFont is not assigned if multiple fonts are in the // selection! This makes it hard to adjust size or fontstyle because you // need the fonttype to do that: if not FontSize.DroppedDown then begin FontSize.Enabled := Assigned(Editor.SelectionFont); if Assigned(Editor.SelectionFont) then FontSize.SelectedIndex := FontSize.Items.IndexOf(Editor.SelectionFont.Size.ToString) else FontSize.SelectedIndex := -1; end; BoldButton.Enabled := Assigned(Editor.SelectionFont); BoldButton.Pushed := Assigned(Editor.SelectionFont) and Editor.SelectionFont.Bold; ItalicButton.Enabled := Assigned(Editor.SelectionFont); ItalicButton.Pushed := Assigned(Editor.SelectionFont) and Editor.SelectionFont.Italic; UnderlineButton.Enabled := Assigned(Editor.SelectionFont); UnderlineButton.Pushed := Assigned(Editor.SelectionFont) and Editor.SelectionFont.Underline; AlignLeftButton.Pushed := Editor.SelectionAlignment = HorizontalAlignment.Left; CenterButton.Pushed := Editor.SelectionAlignment = HorizontalAlignment.Center; AlignRightButton.Pushed := Editor.SelectionAlignment = HorizontalAlignment.Right; BulletsButton.Pushed := Editor.SelectionBullet; finally FUpdating := False; end; // Status if Editor.Modified then s := sModified else if Editor.ReadOnly then s := sReadOnly else s := ''; if StatusBar.ShowPanels then StatusBar.Panels.Item[1].Text := s else StatusBar.Text := s; end; function TMainForm.CanCloseCurrentFile: Boolean; begin if Editor.Modified then begin case MessageBox.Show('Save changes to ' + FFileName + '?', sConfirm, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) of System.Windows.Forms.DialogResult.Yes: begin FileSave; Result := True; end; System.Windows.Forms.DialogResult.No: Result := True; else // System.Windows.Forms.DialogResult.Cancel: Result := False; end; end else Result := True; end; procedure TMainForm.Dispose(Disposing: Boolean); begin if Disposing then begin Editor.remove_DragDrop(TMainForm_DragDrop); Editor.remove_DragEnter(TMainForm_DragEnter); Application.remove_Idle(Application_Idle); if Components <> nil then Components.Dispose(); end; inherited Dispose(Disposing); end; constructor TMainForm.Create; begin inherited Create; // // Required for Windows Form Designer support // InitializeComponent; // // TODO: Add any constructor code after InitializeComponent call // FFindPrevious := -1; Application.add_Idle(Application_Idle); Editor.add_DragEnter(TMainForm_DragEnter); Editor.add_DragDrop(TMainForm_DragDrop); SetFileName(sUntitled); GetFontNames; end; procedure TMainForm.PrintDocument_PrintPage(sender: System.Object; e: System.Drawing.Printing.PrintPageEventArgs); begin // To print the boundaries of the current page margins // uncomment the next line: //e.Graphics.DrawRectangle(System.Drawing.Pens.Blue, e.MarginBounds); // Make the RichTextBoxEx calculate and render as much text as will // fit on the page and remember the last character printed for the // beginning of the next page FFirstCharOnPage := Editor.FormatRange(False, e, FFirstCharOnPage, Editor.TextLength); // Check if there are more pages to print e.HasMorePages := FFirstCharOnPage < Editor.TextLength; end; procedure TMainForm.PrintDocument_EndPrint(sender: System.Object; e: System.Drawing.Printing.PrintEventArgs); begin // Clean up cached information Editor.FormatRangeDone; end; procedure TMainForm.PrintDocument_BeginPrint(sender: System.Object; e: System.Drawing.Printing.PrintEventArgs); begin // Start at the beginning of the text FFirstCharOnPage := 0; end; procedure TMainForm.FilePageSetupItem_Click(sender: System.Object; e: System.EventArgs); begin FilePageSetup; end; procedure TMainForm.FilePrintPreviewItem_Click(sender: System.Object; e: System.EventArgs); begin FilePrintPreview; end; procedure TMainForm.TMainForm_DragDrop(sender: System.Object; e: System.Windows.Forms.DragEventArgs); type StringArray = array of string; var Files: StringArray; begin Files := StringArray(e.Data.GetData('FileDrop', False)); PerformFileOpen(Files[0]); end; procedure TMainForm.TMainForm_DragEnter(sender: System.Object; e: System.Windows.Forms.DragEventArgs); begin if e.Data.GetDataPresent(DataFormats.FileDrop) then e.Effect := DragDropEffects.All else e.Effect := DragDropEffects.None; end; procedure TMainForm.ViewStatusBarItem_Click(sender: System.Object; e: System.EventArgs); begin StatusBar.Visible := not StatusBar.Visible; end; procedure TMainForm.ViewFormatBarItem_Click(sender: System.Object; e: System.EventArgs); begin FormatPanel.Visible := not FormatPanel.Visible; end; procedure TMainForm.ViewToolbarItem_Click(sender: System.Object; e: System.EventArgs); begin ToolBar.Visible := not ToolBar.Visible; end; procedure TMainForm.FontSize_SelectionChangeCommitted(sender: System.Object; e: System.EventArgs); begin if FUpdating then Exit; if FontSize.SelectedIndex > -1 then begin Editor.Focus; Editor.SelectionFont := System.Drawing.Font.Create(Editor.SelectionFont.Name, Convert.ToSingle(FontSize.Items[FontSize.SelectedIndex]), Editor.SelectionFont.Style); end; end; procedure TMainForm.FormatAlignRightItem_Click(sender: System.Object; e: System.EventArgs); begin FormatAlignRight; end; procedure TMainForm.FormatAlignCenterItem_Click(sender: System.Object; e: System.EventArgs); begin FormatCenter; end; procedure TMainForm.FormatAlignLeftItem_Click(sender: System.Object; e: System.EventArgs); begin FormatAlignLeft; end; procedure TMainForm.FormatBulletsItem_Click(sender: System.Object; e: System.EventArgs); begin FormatBullets; end; procedure TMainForm.FontName_SelectionChangeCommitted(sender: System.Object; e: System.EventArgs); begin if FUpdating then Exit; Editor.Focus; if Assigned(Editor.SelectionFont) then Editor.SelectionFont := System.Drawing.Font.Create( string(FontName.Items[FontName.SelectedIndex]), Editor.SelectionFont.Size, Editor.SelectionFont.Style) else Editor.SelectionFont := System.Drawing.Font.Create( string(FontName.Items[FontName.SelectedIndex]), 8.25); end; procedure TMainForm.FormatToolBar_ButtonClick(sender: System.Object; e: System.Windows.Forms.ToolBarButtonClickEventArgs); begin if e.Button = BoldButton then FormatFontBold else if e.Button = ItalicButton then FormatFontItalic else if e.Button = UnderlineButton then FormatFontUnderline else if e.Button = AlignLeftButton then FormatAlignLeft else if e.Button = CenterButton then FormatCenter else if e.Button = AlignRightButton then FormatAlignRight else if e.Button = BulletsButton then FormatBullets; end; procedure TMainForm.FormatFontItem_Click(sender: System.Object; e: System.EventArgs); begin FormatFont; end; procedure TMainForm.FormatDetectURLsItem_Click(sender: System.Object; e: System.EventArgs); begin Editor.DetectUrls := not Editor.DetectUrls; end; procedure TMainForm.FormatWordWrapItem_Click(sender: System.Object; e: System.EventArgs); begin Editor.WordWrap := not Editor.WordWrap; end; procedure TMainForm.ViewZoom50Item_Click(sender: System.Object; e: System.EventArgs); begin SetZoom(0.5); end; procedure TMainForm.ViewZoom100Item_Click(sender: System.Object; e: System.EventArgs); begin SetZoom(1); end; procedure TMainForm.ViewZoom200Item_Click(sender: System.Object; e: System.EventArgs); begin SetZoom(2); end; procedure TMainForm.ToolBar_ButtonClick(sender: System.Object; e: System.Windows.Forms.ToolBarButtonClickEventArgs); begin if e.Button = NewButton then FileNew else if e.Button = OpenButton then FileOpen else if e.Button = SaveButton then FileSave else if e.Button = PrintButton then FilePrint else if e.Button = PrintPreviewButton then FilePrintPreview else if e.Button = CutButton then EditCut else if e.Button = CopyButton then EditCopy else if e.Button = PasteButton then EditPaste else if e.Button = UndoButton then EditUndo else if e.Button = RedoButton then EditRedo else if e.Button = FindButton then Find; end; procedure TMainForm.FileExitItem_Click(sender: System.Object; e: System.EventArgs); begin Close; end; procedure TMainForm.FileSaveAsItem_Click(sender: System.Object; e: System.EventArgs); begin FileSaveAs; end; procedure TMainForm.EditFindNextItem_Click(sender: System.Object; e: System.EventArgs); begin FindNext; end; procedure TMainForm.EditFindItem_Click(sender: System.Object; e: System.EventArgs); begin Find; end; procedure TMainForm.FileOpenItem_Click(sender: System.Object; e: System.EventArgs); begin FileOpen; end; procedure TMainForm.FileSaveItem_Click(sender: System.Object; e: System.EventArgs); begin FileSave; end; procedure TMainForm.EditRedoItem_Click(sender: System.Object; e: System.EventArgs); begin EditRedo; end; procedure TMainForm.EditPasteItem_Click(sender: System.Object; e: System.EventArgs); begin EditPaste; end; procedure TMainForm.EditCopyItem_Click(sender: System.Object; e: System.EventArgs); begin EditCopy; end; procedure TMainForm.EditCutItem_Click(sender: System.Object; e: System.EventArgs); begin EditCut; end; procedure TMainForm.EditUndoItem_Click(sender: System.Object; e: System.EventArgs); begin EditUndo; end; procedure TMainForm.EditCut; begin Editor.Cut; end; procedure TMainForm.EditCopy; begin Editor.Copy; end; procedure TMainForm.EditPaste; begin Editor.Paste; end; procedure TMainForm.EditUndo; begin Editor.Undo; end; procedure TMainForm.EditRedo; begin Editor.Redo; end; procedure TMainForm.FileNew; begin if CanCloseCurrentFile then begin SetFileName(sUntitled); Editor.Clear; Editor.Modified := False; end; end; procedure TMainForm.FileNewItem_Click(sender: System.Object; e: System.EventArgs); begin FileNew; end; procedure TMainForm.FileOpen; begin if CanCloseCurrentFile then begin if OpenDialog.ShowDialog = System.Windows.Forms.DialogResult.OK then begin PerformFileOpen(OpenDialog.FileName); Editor.ReadOnly := OpenDialog.ReadOnlyChecked or ((System.IO.File.GetAttributes(OpenDialog.FileName) and FileAttributes.ReadOnly) = FileAttributes.ReadOnly); end; end; end; procedure TMainForm.FilePrintItem_Click(sender: System.Object; e: System.EventArgs); begin FilePrintWithDialog; end; procedure TMainForm.FileSave; begin try if FFileName = sUntitled then FileSaveAs else begin // TODO: Save as plaintext if needed if (Path.GetExtension(FFileName) = '.RTF') or (Path.GetExtension(FFileName) = '.rtf') then Editor.SaveFile(FFileName) else Editor.SaveFile(FFileName, RichTextBoxStreamType.PlainText); Editor.Modified := False; end; except on E: Exception do MessageBox.Show(E.Message, 'Error'); end; end; procedure TMainForm.FileSaveAs; begin if SaveDialog.ShowDialog = System.Windows.Forms.DialogResult.OK then begin case SaveDialog.FilterIndex of 1: Editor.SaveFile(SaveDialog.FileName); 2: Editor.SaveFile(SaveDialog.FileName, RichTextBoxStreamType.PlainText); end; SetFileName(SaveDialog.FileName); Editor.Modified := False; Editor.ReadOnly := False; end; end; procedure TMainForm.Find; begin with TFindForm.Create do begin SearchOptions := FFindOptions; SearchText := FFindText; if ShowDialog = System.Windows.Forms.DialogResult.OK then begin FFindText := SearchText; FFindOptions := SearchOptions; FFindPrevious := Editor.Find(FFindText, FFindOptions); end; end; end; procedure TMainForm.FindNext; begin if (FFindOptions and RichTextBoxFinds.Reverse) <> RichTextBoxFinds.None then FFindPrevious := Editor.Find(FFindText, 0, FFindPrevious, FFindOptions) else FFindPrevious := Editor.Find(FFindText, FFindPrevious + 1, FFindOptions); end; procedure TMainForm.HelpInfoItem_Click(sender: System.Object; e: System.EventArgs); begin with TInfoBox.Create do ShowDialog; end; procedure TMainForm.PerformFileOpen(const AFileName: string); begin if (Path.GetExtension(AFileName) = '.RTF') or (Path.GetExtension(AFileName) = '.rtf') then Editor.LoadFile(AFileName) else Editor.LoadFile(AFileName, RichTextBoxStreamType.PlainText); SetFileName(AFileName); Editor.Focus; Editor.Modified := False; end; procedure TMainForm.SetFileName(const AFileName: string); begin FFileName := AFileName; Text := Path.GetFileName(AFileName) + ' - ' + Application.ProductName; PrintDocument.DocumentName := AFileName; end; procedure TMainForm.SetZoom(const AZoomFactor: SIngle); begin Editor.ZoomFactor := AZoomFactor; ViewZoom200Item.Checked := AZoomFactor = 2; ViewZoom100Item.Checked := AZoomFactor = 1; ViewZoom50Item.Checked := AZoomFactor = 0.5; end; procedure TMainForm.FormatFont; begin FontDialog.Color := Editor.SelectionColor; FontDialog.Font := Editor.SelectionFont; if FontDialog.ShowDialog = System.Windows.Forms.DialogResult.OK then begin Editor.SelectionFont := FontDialog.Font; Editor.SelectionColor := FontDialog.Color; end; end; procedure TMainForm.GetFontNames; var i: Integer; InstalledFonts: System.Drawing.Text.InstalledFontCollection; begin FontName.BeginUpdate; try FontName.Items.Clear; InstalledFonts := System.Drawing.Text.InstalledFontCollection.Create; for i := 0 to Length(InstalledFonts.Families) - 1 do FontName.Items.Add(InstalledFonts.Families[i].Name); finally FontName.EndUpdate; end; end; procedure TMainForm.FormatAlignLeft; begin Editor.SelectionAlignment := System.Windows.Forms.HorizontalAlignment.Left; end; procedure TMainForm.FormatAlignRight; begin Editor.SelectionAlignment := System.Windows.Forms.HorizontalAlignment.Right; end; procedure TMainForm.FormatBullets; begin Editor.SelectionBullet := not Editor.SelectionBullet; end; procedure TMainForm.FormatCenter; begin Editor.SelectionAlignment := System.Windows.Forms.HorizontalAlignment.Center; end; procedure TMainForm.FormatFontBold; var NewFontStyle: FontStyle; begin if FUpdating then Exit; Editor.Focus; if Editor.SelectionFont.Bold then NewFontStyle := Editor.SelectionFont.Style xor FontStyle.Bold else NewFontStyle := Editor.SelectionFont.Style or FontStyle.Bold; Editor.SelectionFont := System.Drawing.Font.Create(Editor.SelectionFont.Name, Editor.SelectionFont.Size, NewFontStyle); end; procedure TMainForm.FormatFontItalic; var NewFontStyle: FontStyle; begin if FUpdating then Exit; Editor.Focus; if Editor.SelectionFont.Italic then NewFontStyle := Editor.SelectionFont.Style xor FontStyle.Italic else NewFontStyle := Editor.SelectionFont.Style or FontStyle.Italic; Editor.SelectionFont := System.Drawing.Font.Create(Editor.SelectionFont.Name, Editor.SelectionFont.Size, NewFontStyle); end; procedure TMainForm.FormatFontUnderline; var NewFontStyle: FontStyle; begin if FUpdating then Exit; Editor.Focus; if Editor.SelectionFont.Underline then NewFontStyle := Editor.SelectionFont.Style xor FontStyle.Underline else NewFontStyle := Editor.SelectionFont.Style or FontStyle.Underline; Editor.SelectionFont := System.Drawing.Font.Create(Editor.SelectionFont.Name, Editor.SelectionFont.Size, NewFontStyle); end; procedure TMainForm.FilePageSetup; begin PageSetupDialog.ShowDialog; end; procedure TMainForm.FilePrint; begin PrintDocument.Print; end; procedure TMainForm.FilePrintWithDialog; begin if PrintDialog.ShowDialog = System.Windows.Forms.DialogResult.OK then FilePrint; end; procedure TMainForm.FilePrintPreview; begin PrintPreviewDialog.ShowDialog; end; end.
unit CrcUnit; interface uses Classes; type TCRCProgress = procedure(const aCurrent, aMax: Int64); const cBufferSize = $FFFF; //64 * 1024; { === CRC-32-IEEE 802.3 Polynomial (Reversed) 0xEDB88320 =================== } procedure CRC32(var aCrc32: Cardinal; BufPtr: Pointer; Len: Cardinal); Function CRC32Stream(const AStream: TStream; var aCrc32: Cardinal; const aBufferSize: Integer = cBufferSize; const aProgress: TCRCProgress = nil): Boolean; { === CRC-64-ECMA Polynomial (Normal) 0x42F0E1EBA9EA3693 ===================== } procedure crc64(var aCrc64: Int64; aData: PByte; aLen: Cardinal); Function CRC64Stream(const AStream: TStream; var aCrc64: Int64; const aBufferSize: Integer = cBufferSize; const aProgress: TCRCProgress = nil): Boolean; implementation const CRC32Table: array [Byte] of Cardinal = ($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, $04FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $048B2364B, $D80D2BDA, $AF0A1B4C, $36034AF6, $041047A60, $DF60EFC3, $A867DF55, $316E8EEF, $04669BE79, $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); crc64_table: array [Byte] of Int64 = ($0000000000000000, $42F0E1EBA9EA3693, $85E1C3D753D46D26, $C711223CFA3E5BB5, $493366450E42ECDF, $0BC387AEA7A8DA4C, $CCD2A5925D9681F9, $8E224479F47CB76A, $9266CC8A1C85D9BE, $D0962D61B56FEF2D, $17870F5D4F51B498, $5577EEB6E6BB820B, $DB55AACF12C73561, $99A54B24BB2D03F2, $5EB4691841135847, $1C4488F3E8F96ED4, $663D78FF90E185EF, $24CD9914390BB37C, $E3DCBB28C335E8C9, $A12C5AC36ADFDE5A, $2F0E1EBA9EA36930, $6DFEFF5137495FA3, $AAEFDD6DCD770416, $E81F3C86649D3285, $F45BB4758C645C51, $B6AB559E258E6AC2, $71BA77A2DFB03177, $334A9649765A07E4, $BD68D2308226B08E, $FF9833DB2BCC861D, $388911E7D1F2DDA8, $7A79F00C7818EB3B, $CC7AF1FF21C30BDE, $8E8A101488293D4D, $499B3228721766F8, $0B6BD3C3DBFD506B, $854997BA2F81E701, $C7B97651866BD192, $00A8546D7C558A27, $4258B586D5BFBCB4, $5E1C3D753D46D260, $1CECDC9E94ACE4F3, $DBFDFEA26E92BF46, $990D1F49C77889D5, $172F5B3033043EBF, $55DFBADB9AEE082C, $92CE98E760D05399, $D03E790CC93A650A, $AA478900B1228E31, $E8B768EB18C8B8A2, $2FA64AD7E2F6E317, $6D56AB3C4B1CD584, $E374EF45BF6062EE, $A1840EAE168A547D, $66952C92ECB40FC8, $2465CD79455E395B, $3821458AADA7578F, $7AD1A461044D611C, $BDC0865DFE733AA9, $FF3067B657990C3A, $711223CFA3E5BB50, $33E2C2240A0F8DC3, $F4F3E018F031D676, $B60301F359DBE0E5, $DA050215EA6C212F, $98F5E3FE438617BC, $5FE4C1C2B9B84C09, $1D14202910527A9A, $93366450E42ECDF0, $D1C685BB4DC4FB63, $16D7A787B7FAA0D6, $5427466C1E109645, $4863CE9FF6E9F891, $0A932F745F03CE02, $CD820D48A53D95B7, $8F72ECA30CD7A324, $0150A8DAF8AB144E, $43A04931514122DD, $84B16B0DAB7F7968, $C6418AE602954FFB, $BC387AEA7A8DA4C0, $FEC89B01D3679253, $39D9B93D2959C9E6, $7B2958D680B3FF75, $F50B1CAF74CF481F, $B7FBFD44DD257E8C, $70EADF78271B2539, $321A3E938EF113AA, $2E5EB66066087D7E, $6CAE578BCFE24BED, $ABBF75B735DC1058, $E94F945C9C3626CB, $676DD025684A91A1, $259D31CEC1A0A732, $E28C13F23B9EFC87, $A07CF2199274CA14, $167FF3EACBAF2AF1, $548F120162451C62, $939E303D987B47D7, $D16ED1D631917144, $5F4C95AFC5EDC62E, $1DBC74446C07F0BD, $DAAD56789639AB08, $985DB7933FD39D9B, $84193F60D72AF34F, $C6E9DE8B7EC0C5DC, $01F8FCB784FE9E69, $43081D5C2D14A8FA, $CD2A5925D9681F90, $8FDAB8CE70822903, $48CB9AF28ABC72B6, $0A3B7B1923564425, $70428B155B4EAF1E, $32B26AFEF2A4998D, $F5A348C2089AC238, $B753A929A170F4AB, $3971ED50550C43C1, $7B810CBBFCE67552, $BC902E8706D82EE7, $FE60CF6CAF321874, $E224479F47CB76A0, $A0D4A674EE214033, $67C58448141F1B86, $253565A3BDF52D15, $AB1721DA49899A7F, $E9E7C031E063ACEC, $2EF6E20D1A5DF759, $6C0603E6B3B7C1CA, $F6FAE5C07D3274CD, $B40A042BD4D8425E, $731B26172EE619EB, $31EBC7FC870C2F78, $BFC9838573709812, $FD39626EDA9AAE81, $3A28405220A4F534, $78D8A1B9894EC3A7, $649C294A61B7AD73, $266CC8A1C85D9BE0, $E17DEA9D3263C055, $A38D0B769B89F6C6, $2DAF4F0F6FF541AC, $6F5FAEE4C61F773F, $A84E8CD83C212C8A, $EABE6D3395CB1A19, $90C79D3FEDD3F122, $D2377CD44439C7B1, $15265EE8BE079C04, $57D6BF0317EDAA97, $D9F4FB7AE3911DFD, $9B041A914A7B2B6E, $5C1538ADB04570DB, $1EE5D94619AF4648, $02A151B5F156289C, $4051B05E58BC1E0F, $87409262A28245BA, $C5B073890B687329, $4B9237F0FF14C443, $0962D61B56FEF2D0, $CE73F427ACC0A965, $8C8315CC052A9FF6, $3A80143F5CF17F13, $7870F5D4F51B4980, $BF61D7E80F251235, $FD913603A6CF24A6, $73B3727A52B393CC, $31439391FB59A55F, $F652B1AD0167FEEA, $B4A25046A88DC879, $A8E6D8B54074A6AD, $EA16395EE99E903E, $2D071B6213A0CB8B, $6FF7FA89BA4AFD18, $E1D5BEF04E364A72, $A3255F1BE7DC7CE1, $64347D271DE22754, $26C49CCCB40811C7, $5CBD6CC0CC10FAFC, $1E4D8D2B65FACC6F, $D95CAF179FC497DA, $9BAC4EFC362EA149, $158E0A85C2521623, $577EEB6E6BB820B0, $906FC95291867B05, $D29F28B9386C4D96, $CEDBA04AD0952342, $8C2B41A1797F15D1, $4B3A639D83414E64, $09CA82762AAB78F7, $87E8C60FDED7CF9D, $C51827E4773DF90E, $020905D88D03A2BB, $40F9E43324E99428, $2CFFE7D5975E55E2, $6E0F063E3EB46371, $A91E2402C48A38C4, $EBEEC5E96D600E57, $65CC8190991CB93D, $273C607B30F68FAE, $E02D4247CAC8D41B, $A2DDA3AC6322E288, $BE992B5F8BDB8C5C, $FC69CAB42231BACF, $3B78E888D80FE17A, $7988096371E5D7E9, $F7AA4D1A85996083, $B55AACF12C735610, $724B8ECDD64D0DA5, $30BB6F267FA73B36, $4AC29F2A07BFD00D, $08327EC1AE55E69E, $CF235CFD546BBD2B, $8DD3BD16FD818BB8, $03F1F96F09FD3CD2, $41011884A0170A41, $86103AB85A2951F4, $C4E0DB53F3C36767, $D8A453A01B3A09B3, $9A54B24BB2D03F20, $5D45907748EE6495, $1FB5719CE1045206, $919735E51578E56C, $D367D40EBC92D3FF, $1476F63246AC884A, $568617D9EF46BED9, $E085162AB69D5E3C, $A275F7C11F7768AF, $6564D5FDE549331A, $279434164CA30589, $A9B6706FB8DFB2E3, $EB46918411358470, $2C57B3B8EB0BDFC5, $6EA7525342E1E956, $72E3DAA0AA188782, $30133B4B03F2B111, $F7021977F9CCEAA4, $B5F2F89C5026DC37, $3BD0BCE5A45A6B5D, $79205D0E0DB05DCE, $BE317F32F78E067B, $FCC19ED95E6430E8, $86B86ED5267CDBD3, $C4488F3E8F96ED40, $0359AD0275A8B6F5, $41A94CE9DC428066, $CF8B0890283E370C, $8D7BE97B81D4019F, $4A6ACB477BEA5A2A, $089A2AACD2006CB9, $14DEA25F3AF9026D, $562E43B4931334FE, $913F6188692D6F4B, $D3CF8063C0C759D8, $5DEDC41A34BBEEB2, $1F1D25F19D51D821, $D80C07CD676F8394, $9AFCE626CE85B507); { === CRC-32-IEEE 802.3 ======================================================== } procedure CRC32(var aCrc32: Cardinal; BufPtr: Pointer; Len: Cardinal); var index: Integer; i: Cardinal; begin for i := 0 to Len - 1 do begin index := (aCrc32 xor Cardinal(Pointer(BufPtr + i)^)) and $000000FF; aCrc32 := (aCrc32 shr 8) xor CRC32Table[index]; end; end; Function CRC32Stream(const AStream: TStream; var aCrc32: Cardinal; const aBufferSize: Integer; const aProgress: TCRCProgress): Boolean; procedure _Progress(const aCurrent, aMax: Int64); inline; Begin if Assigned(aProgress) then aProgress(aCurrent, aMax); end; var iCount: Integer; aBuffer: PByte; Begin aCrc32 := 0; Result := Assigned(AStream); if not Assigned(AStream) then Exit; GetMem(aBuffer, aBufferSize); aCrc32 := $FFFFFFFF; try try AStream.Position := 0; iCount := AStream.Read(aBuffer^, cBufferSize); while (iCount <> 0) do begin _Progress(AStream.Position, AStream.Size); CRC32(aCrc32, aBuffer, iCount); iCount := AStream.Read(aBuffer^, cBufferSize); end; // while aCrc32 := aCrc32 xor $FFFFFFFF; finally FreeMem(aBuffer); end; // try except Result := False; end; // try End; { === CRC-64-ECMA Polynomial (Normal) 0x42F0E1EBA9EA3693 ======================= } procedure crc64(var aCrc64: Int64; aData: PByte; aLen: Cardinal); var iData: PByte; iLen, index: Cardinal; Begin iData := aData; iLen := aLen; while (iLen > 0) do Begin index := ((aCrc64 shr 56) xor iData^) and $FF; aCrc64 := crc64_table[index] xor (aCrc64 shl 8); Inc(iData); Dec(iLen); end; // while end; Function CRC64Stream(const AStream: TStream; var aCrc64: Int64; const aBufferSize: Integer; const aProgress: TCRCProgress): Boolean; procedure _Progress(const aCurrent, aMax: Int64); inline; Begin if Assigned(aProgress) then aProgress(aCurrent, aMax); end; var iCount: Integer; aBuffer: PByte; Begin aCrc64 := 0; Result := Assigned(AStream); if not Assigned(AStream) then Exit; GetMem(aBuffer, aBufferSize); aCrc64 := $FFFFFFFFFFFFFFFF; try try AStream.Position := 0; iCount := AStream.Read(aBuffer^, cBufferSize); while (iCount <> 0) do begin _Progress(AStream.Position, AStream.Size); crc64(aCrc64, aBuffer, iCount); iCount := AStream.Read(aBuffer^, cBufferSize); end; // while aCrc64 := aCrc64 xor $FFFFFFFFFFFFFFFF; finally FreeMem(aBuffer); end; // try except Result := False; end; // try End; end.
(* AVR Basic Compiler Copyright 1997-2002 Silicon Studio Ltd. Copyright 2008 Trioflex OY http://www.trioflex.com *) unit MStrings; {$N+} interface uses {$IFDEF Win32} SysUtils {$ELSE} Objects, Strings {$ENDIF}; const HexNum: PCHAR = '0123456789ABCDEF'; const MaxChar = 512; FillChr: Char = ' '; type PCString = ^CString; CString = array[0..MaxChar] of Char; function Otsad(Txt: string): string; procedure Add(Dest: PChar; Source: Char); procedure Del(Txt: PChar; Start, Count: Integer); function Isnumeric(Txt: string): Boolean; function Isalpha(Ch: Char): Boolean; function _Replace(Txt: string; Mida, Millega: Char): string; function GetWord(var Txt: string; Erase: Boolean): string; function KillSpace(Txt: string): string; function ToLower(Txt: string): string; function ToUpper(Txt: string): string; function Mirror(Txt: string): string; function L2Oct(Nr, Len: LongInt): string; function Oct2L(Nr: LongInt): LongInt; function L2Hex(Nr, Len: CARDINAL): string; function L2Bin(bb: Byte): string; function Bin2S(Txt: string): Byte; function PasStr(S: string): PChar; function I2C(Nr: Integer; Len: Byte): PChar; function L2C(Nr: LongInt; Len: Byte): PChar; function M2C(Nr: Double; Len: Byte): PChar; function R2C(Nr: Real; Len: Byte): PChar; function I2S(Nr: Integer; Len: Byte): string; function L2S(Nr: LongInt; Len: Byte): string; function M2S(Nr: Double; Len: Byte): string; function R2S(Nr: Real; Len: Byte): string; function S2I(Txt: string): Integer; function S2M(Txt: string): real; function S2L(Txt: string): LongInt; function S2R(Txt: string): Real; function SetLen(Nr, Len: LongInt): string; function Set_koma(Nr: longint): string; function SetStr(count, ascii: Byte): string; function GetStr(mida: string; var kust: string): Byte; function Getfmask(param: string): string; function KillStr(Txt, What: string): string; function Num(Txt: string): Boolean; {Si} function Hex2W(Hex: string): Word; implementation function Otsad(Txt: string): string; begin while (Txt[1] = ' ') and (Txt <> '') do Delete(Txt, 1, 1); while (Txt[Length(Txt)] = ' ') and (Txt <> '') do Delete(Txt, Length(Txt), 1); Otsad := Txt; end; procedure Add(Dest: PChar; Source: Char); var I: Integer; begin I := StrLen(Dest); Dest[I] := Source; Dest[I + 1] := #0; end; procedure Del(Txt: PChar; Start, Count: Integer); var S: Integer; begin S := StrLen(Txt); if ((Start + Count) > S) then Exit; Move(Txt[Start + Count], Txt[Start], StrLen(Txt) - Count); Txt[S - Count] := #0; end; function Num(Txt: string): Boolean; var I: Integer; begin for I := 1 to Length(Txt) do if (IsAlpha(Txt[I])) then begin Num := False; Exit; end; Num := True; end; function KillSpace(Txt: string): string; var I: Integer; begin for I := 1 to Length(Txt) do if (Txt[I] = #32) then Delete(Txt, I, 1); KillSpace := Txt; end; function _Replace; var I: Integer; begin for I := 1 to Length(Txt) do if (Txt[I] = Mida) then Txt[I] := Millega; _Replace := Txt; end; function GetWord; var Tmp: string; I: Integer; begin Tmp := Txt; while (Tmp[1] = ' ') and (Tmp <> '') do Delete(Tmp, 1, 1); I := 1; while (Tmp[I] <> ' ') and (I <= Length(Tmp)) do Inc(I); Tmp := Copy(Tmp, 1, I); if (Erase) then begin while (Txt[1] = ' ') and (Txt <> '') do Delete(Txt, 1, 1); Delete(Txt, 1, Length(Tmp)); end; if (Tmp[Length(Tmp)] = ' ') and (Tmp <> '') then Delete(Tmp, Length(Tmp), 1); GetWord := Tmp; end; function ToLower(Txt: string): string; var I: Integer; begin for I := 1 to Length(Txt) do if (Txt[i] > chr(ord('A') - 1)) and (Txt[i] < chr(ord('Z') + 1)) then Txt[i] := chr(ord(Txt[i]) + 32); ToLower := Txt; end; function ToUpper(Txt: string): string; var I: Integer; begin for I := 1 to Length(Txt) do Txt[I] := UpCase(Txt[I]); ToUpper := Txt; end; function Mirror(Txt: string): string; var T: string; I: Integer; begin T := ''; for i := Length(Txt) downto 1 do T := T + Txt[i]; Mirror := T; end; function Oct2L(Nr: LongInt): LongInt; const Pwd: array[1..6] of Word = (0, 8, 64, 512, 4096, 32768); var Txt: string; I: Integer; J, L: LongInt; begin Txt := L2S(Nr, 0); L := 0; for I := Length(Txt) downto 2 do begin J := Byte(Txt[Length(Txt) - I + 1]); L := L + (J - 48) * Pwd[I]; end; L := L + (Byte(Txt[Length(Txt)]) - 48); Oct2L := L; end; function L2Oct; const OctNr: array[0..7] of Char = ('0', '1', '2', '3', '4', '5', '6', '7'); var I, J: Integer; S: string; begin S := ''; repeat I := Nr div 8; J := Nr mod 8; Nr := I; S := OctNr[j] + S; until Nr = 0; if (Length(s) > Len) then Delete(S, 1, Length(S) - Len) else while Length(s) < Len do S := '0' + S; L2Oct := S; end; function L2Hex; const HexNr: array[0..15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); var I, J: Integer; S: string; begin S := ''; repeat I := Nr div 16; J := Nr mod 16; Nr := I; S := HexNr[j] + S; until Nr = 0; if (Len > 0) then if (Length(s) > Len) then Delete(S, 1, Length(S) - Len) else while Length(s) < Len do S := '0' + S; L2Hex := S; end; function L2Bin(bb: Byte): string; const BinNr: array[0..7] of Byte = (1, 2, 4, 8, 16, 32, 64, 128); var I: Integer; T: string; begin T := ''; for I := 0 to 7 do if ((Bb and BinNr[i]) = BinNr[i]) then T := T + '1' else T := T + '0'; L2Bin := T; end; function Bin2S(Txt: string): Byte; const BinNr: array[1..8] of Byte = (1, 2, 4, 8, 16, 32, 64, 128); var Pp, I: Integer; begin pp := 0; while Length(Txt) < 8 do Txt := '0' + Txt; for i := 1 to Length(Txt) do if Txt[i] = '1' then inc(pp, binNr[9 - i]); bin2s := pp; end; function SetLen; var Txt: string; begin str(Nr, Txt); if (Len < Length(Txt)) then Delete(Txt, 1, Length(Txt) - Len) else while Length(Txt) < Len do Txt := '0' + Txt; SetLen := Txt; end; function I2S(Nr: Integer; Len: Byte): string; var S: string; begin Str(Nr, S); if Len > 0 then while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); I2S := S; end; function M2S(Nr: Double; Len: Byte): string; var S: string; begin Str(Nr: 0: 2, S); if Len > 0 then while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); M2S := S; end; function L2S(Nr: LongInt; Len: Byte): string; var S: string; begin Str(Nr, S); if Len > 0 then while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); L2S := S; end; function R2S(Nr: Real; Len: Byte): string; var S: string; begin Str(Nr: 0: 2, S); while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); R2S := S; end; {- pchar tüüpi funktsioonid -} function PasStr(S: string): PChar; var Txt: Cstring; begin Move(S[1], Txt, Length(S)); Txt[Length(S)] := #0; PasStr := Txt; end; function I2C(Nr: Integer; Len: Byte): PChar; var S: string; I: Byte; begin Str(Nr, S); if Len > 0 then while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); I2C := PasStr(S); end; function M2C(Nr: Double; Len: Byte): PChar; var S: string; begin Str(Nr: 0: 2, S); if Len > 0 then while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); M2C := PasStr(S); end; function L2C(Nr: LongInt; Len: Byte): PChar; var S: string; begin Str(Nr: Len, S); if Len > 0 then while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); L2C := PasStr(S); end; function R2C(Nr: Real; Len: Byte): PChar; var S: string; begin Str(Nr: 0: 2, S); if Len > 0 then while (Length(S) < Len) do if (S[1] <> '-') and (S[1] <> '+') then S := FillChr + S else Insert(FillChr, S, 2); R2C := PasStr(S); end; function S2I(Txt: string): Integer; var i, c: Integer; begin Val(Txt, i, c); s2i := i; end; function S2M(Txt: string): real; var i: Real; c: Integer; begin Val(Txt, i, c); s2m := i; end; function S2L(Txt: string): Longint; var i: LongInt; c: Integer; begin Val(Txt, i, c); s2l := i; end; function S2R(Txt: string): Real; var C: Integer; I: Real; begin Val(Txt, I, C); S2R := I; end; function set_koma(Nr: longint): string; var Txt: string; i, j: Integer; begin str(Nr, Txt); i := 1; j := Length(Txt); while (i < j) do begin if i mod 3 = 0 then insert(',', Txt, j - i + 1); inc(i) end; set_koma := Txt; end; function setstr(count, ascii: Byte): string; var Txt: string; i: Byte; begin Txt := ''; for i := 1 to count do Txt := Txt + chr(ascii); setstr := Txt; end; function getstr(mida: string; var kust: string): Byte; begin getstr := 0; while True do begin if pos(mida, kust) = 0 then exit; getstr := pos(mida, kust); delete(kust, pos(mida, kust), Length(mida)); end; end; function getfmask(param: string): string; var j: Byte; begin j := pos('*', param); if j = 0 then j := pos('?', param); if j = 0 then begin j := pos('.', param); if j = 0 then param := param + '*.*' else begin if j = Length(param) then param := param + '*'; if j = 1 then param := '*' + param; end; end; for j := 1 to Length(param) do if param[j] = #$20 then delete(param, j, 1); getfmask := param; end; function IsAlpha(Ch: Char): Boolean; begin if (Ch in ['A'..'Z']) or (Ch in ['a'..'z']) then IsAlpha := True else IsAlpha := False; end; function isnumeric(Txt: string): Boolean; var Nr, c: Integer; begin Val(Txt, Nr, c); if c = 0 then IsNumeric := True else IsNumeric := False; end; function KillStr(Txt, What: string): string; var I: Byte; begin I := 1; while (Length(Txt) > 0) and (I > 0) do begin I := Pos(What, Txt); if I > 0 then Delete(Txt, I, Length(What)); end; KillStr := Txt; end; procedure HexStr(S: PCHAR; N: Longint; pos: Integer); var i, slen: Integer; begin slen := StrLen(S); if (pos > 0) and (pos < 9) then begin for i := pos - 1 downto 0 do begin S[slen + i] := HexNum[N and 15]; N := N shr 4; end; S[slen + pos] := #0; end; end; function Hex2W; var i, W: Word; C: Char; begin W := 0; for i := 1 to 4 do begin C := Hex[i]; W := W shl 4; case C of '0'..'9': W := W or (ord(C) - $30); 'a'..'f': W := W or (ord(C) - ord('a') + 10); 'A'..'F': W := W or (ord(C) - ord('A') + 10); end; Hex2W := W; end; end; end.
unit caMemMapImage; {$INCLUDE ca.inc} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, caControls; type TcaBMPFilename = type string; //---------------------------------------------------------------------------- // TcaMemMapImage   //---------------------------------------------------------------------------- TcaMemMapImage = class(TcaGraphicControl) private FPalette: HPalette; FData: Pointer; FBitmapWidth: Integer; FBitmapHeight: Integer; FColours: Integer; FFileHeader: PBitmapFileHeader; FInfoHeader: PBitmapInfoHeader; FInfo: PBitmapInfo; FPixelStart: Pointer; // Property fields FActive: Boolean; FAutoSize: Boolean; FFileName: TcaBMPFilename; FOffsetX: Integer; FOffsetY: Integer; FStretch: Boolean; FCentre: Boolean; // Property methods procedure SetActive(Value: Boolean); procedure SetFilename(const Value: TcaBMPFilename); procedure SetOffsetX(const Value: Integer); procedure SetOffsetY(const Value: Integer); procedure SetStretch(Value: Boolean); procedure SetCentre(Value: Boolean); protected // Protected property methods procedure SetAutoSize(Value: Boolean); override; // Protected methods procedure Changed; virtual; procedure CloseViewer; virtual; procedure GetBitmapPalette; procedure OpenViewer; virtual; procedure BufferedPaint(C: TCanvas; R: TRect); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // Public methods procedure Close; procedure Open; // Public properties property BitmapFileHeader: PBitmapFileHeader read FFileHeader; property BitmapInfoHeader: PBitmapInfoHeader read FInfoHeader; property BitmapInfo: PBitmapInfo read FInfo; property PixelStart: Pointer read FPixelStart; property Palette: HPalette read FPalette; published // Published properties property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property Centre: Boolean read FCentre write SetCentre default False; property Filename: TcaBMPFilename read FFilename write SetFilename; property OffsetX: Integer read FOffsetX write SetOffsetX; property OffsetY: Integer read FOffsetY write SetOffsetY; property Stretch: Boolean read FStretch write SetStretch default False; // Read-only properties property Colours: Integer read FColours; property BitmapHeight: Integer read FBitmapHeight; property BitmapWidth: Integer read FBitmapWidth; // Promoted properties property Align; property DragCursor; property DragMode; property Enabled; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; // This must be streamed last property Active: Boolean read FActive write SetActive default False; end; implementation const BitmapSignature = $4D42; procedure InvalidBitmap; begin raise Exception.Create('Bitmap image is not valid') end; procedure NotWhenActive; begin raise Exception.Create('Not on an active big bitmap viewer') end; constructor TcaMemMapImage.Create(AOwner: TComponent); begin inherited; Width := 150; Height := 150; end; destructor TcaMemMapImage.Destroy; begin CloseViewer; inherited; end; // Public methods procedure TcaMemMapImage.Close; begin Active := False; end; procedure TcaMemMapImage.Open; begin Active := True; end; // Protected methods procedure TcaMemMapImage.Changed; begin if (BitmapWidth >= Width) and (BitmapHeight >= Height) then ControlStyle := ControlStyle + [csOpaque] else ControlStyle := ControlStyle - [csOpaque]; if AutoSize and (BitmapWidth > 0) and (BitmapHeight > 0) then SetBounds(Left, Top, BitmapWidth, BitmapHeight) else Invalidate; end; procedure TcaMemMapImage.CloseViewer; begin if FActive then begin FActive := False; if FData <> nil then begin UnmapViewOfFile(FData); FData := nil end; if FPalette <> 0 then DeleteObject(FPalette); end; end; procedure TcaMemMapImage.GetBitmapPalette; var SysPalSize: Integer; Index: Integer; LogSize: Integer; LogPalette: PLogPalette; DC: HDC; Focus: HWND; begin if FColours > 2 then begin LogSize := SizeOf(TLogPalette) + pred(FColours) * SizeOf(TPaletteEntry); LogPalette := AllocMem(LogSize); try LogPalette^.palNumEntries := FColours; LogPalette^.palVersion := $0300; {$IFOPT R+} {$DEFINE R_PLUS} {$R-} {$ENDIF} Focus := GetFocus; DC := GetDC(Focus); try SysPalSize := GetDeviceCaps(DC, SIZEPALETTE); if (FColours = 16) and (SysPalSize >= 16) then begin GetSystemPaletteEntries(DC, 0, 8, LogPalette^.palPalEntry); Index := 8; GetSystemPaletteEntries(DC, SysPalSize - Index, Index, LogPalette^.palPalEntry[Index]) end else begin for Index := 0 to pred(FColours) do begin LogPalette^.palPalEntry[Index].peRed := FInfo^.bmiColors[Index].rgbRed; LogPalette^.palPalEntry[Index].peGreen := FInfo^.bmiColors[Index].rgbGreen; LogPalette^.palPalEntry[Index].peBlue := FInfo^.bmiColors[Index].rgbBlue end end; finally ReleaseDC(Focus, DC) end; {$IFDEF R_PLUS} {$R+} {$UNDEF R_PLUS} {$ENDIF} FPalette := CreatePalette(LogPalette^) finally FreeMem(LogPalette, LogSize) end end end; procedure TcaMemMapImage.OpenViewer; var FileHandle: THandle; MapHandle: THandle; begin if FActive then exit; // Open file FileHandle := FileOpen(FFileName, fmOpenRead + fmShareDenyNone); if FileHandle = INVALID_HANDLE_VALUE then raise Exception.Create('Failed to open ' + FFilename); // Create file map try MapHandle := CreateFileMapping(FileHandle, nil, PAGE_READONLY, 0, 0, nil); if MapHandle = 0 then raise Exception.Create('Failed to map file') finally CloseHandle(FileHandle) end; // View file map try FData := MapViewOfFile(MapHandle, FILE_MAP_READ, 0, 0, 0); if FData = nil then raise Exception.Create('Failed to view map file') finally CloseHandle(MapHandle) end; // Set Pointers into file view FFileHeader := FData; // Test for valid bitmap file: if FFileHeader^.bfType <> BitmapSignature then begin UnmapViewOfFile(FData); FData := nil; InvalidBitmap end; // Set up other Pointers FInfoHeader := Pointer(integer(FData) + sizeof(TBitmapFileHeader)); FInfo := Pointer(FInfoHeader); FPixelStart := Pointer(LongWord(FData) + FFileHeader^.bfOffBits); // Get number of colours if FInfoHeader^.biClrUsed <> 0 then FColours := FInfoHeader^.biClrUsed else begin case FInfoHeader^.biBitCount of 1, 4, 8 : FColours := 1 shl FInfoHeader^.biBitCount else FColours := 0 end; end; // Get bitmap size into easy to access variables FBitmapHeight := FInfoHeader^.biHeight; FBitmapWidth := FInfoHeader^.biWidth; // Fetch the palette GetBitmapPalette; // Trigger the changes FActive := True; Changed; end; procedure TcaMemMapImage.BufferedPaint(C: TCanvas; R: TRect); var OldPalette: HPalette; Dest: TRect; begin if (csDesigning in ComponentState) and not FActive then begin C.Pen.Style := psDash; C.Brush.Style := bsClear; C.Rectangle(0, 0, Width, Height) end else begin if FPalette <> 0 then OldPalette := SelectPalette(C.Handle, FPalette, False) else OldPalette := 0; try RealizePalette(C.Handle); if FStretch then Dest := ClientRect else begin if Centre then Dest := Rect((Width - FBitmapWidth) div 2, (Height - FBitmapHeight) div 2, FBitmapWidth, FBitmapHeight) else Dest := Rect(0, 0, FBitmapWidth, FBitmapHeight); end; // OffsetRect(Dest, FOffsetX, FOffsetY); Dest.Left := Dest.Left + FOffsetX; Dest.Right := Dest.Right + FOffsetX; Dest.Top := Dest.Top + FOffsetY; Dest.Bottom := Dest.Bottom + FOffsetY; StretchDIBits(C.Handle, Dest.Left, Dest.Top, Dest.Right, Dest.Bottom, 0, 0, FBitmapWidth, FBitmapHeight, FPixelStart, FInfo^, DIB_RGB_COLORS, SRCCOPY) finally if OldPalette <> 0 then SelectPalette(C.Handle, OldPalette, False) end; end; end; // Property methods procedure TcaMemMapImage.SetActive(Value : boolean); begin if Value <> FActive then if Value then OpenViewer else CloseViewer end; procedure TcaMemMapImage.SetAutoSize(Value : boolean); begin if Value <> FAutoSize then begin FAutoSize := Value; Changed end end; procedure TcaMemMapImage.SetStretch(Value : boolean); begin if Value <> FStretch then begin FStretch := Value; Changed end end; procedure TcaMemMapImage.SetCentre(Value : boolean); begin if Value <> FCentre then begin FCentre := Value; Changed end end; procedure TcaMemMapImage.SetFilename(const Value : TcaBMPFilename); begin if Value <> FFilename then begin if FActive then NotWhenActive; FFilename := Value end end; procedure TcaMemMapImage.SetOffsetX(const Value: Integer); begin if Value <> FOffsetX then begin FOffsetX := Value; Invalidate; end; end; procedure TcaMemMapImage.SetOffsetY(const Value: Integer); begin if Value <> FOffsetY then begin FOffsetY := Value; Invalidate; end; end; end.
unit FrmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Toolsapi, Menus; type TForm2 = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; Label1: TLabel; Label2: TLabel; ListBox1: TListBox; ListBox2: TListBox; CheckBox1: TCheckBox; procedure ListBox1Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation uses WizMain; {$R *.dfm} procedure TForm2.ListBox1Click(Sender: TObject); var i: Integer; TS: TStringList; function GetPackageIndex(Name: string): Integer; var j: Integer; begin Result := 0; for j := 0 to TS.Count-1 do if TS.Strings[j] = Name then begin Result := j; Break; end; end; begin TS := TStringList.Create; try for i := 0 to PackageTest.PackageCount-1 do TS.Add(PackageTest.PackageNames[i]); Listbox2.Clear; if PackageTest.GetComponentCount(GetPackageIndex(Listbox1.Items.Strings[Listbox1.ItemIndex])) > 0 then begin for i := 0 to PackageTest.GetComponentCount(GetPackageIndex(Listbox1.Items.Strings[Listbox1.ItemIndex])) do Listbox2.Items.Add(PackageTest.GetComponentName(GetPackageIndex(Listbox1.Items.Strings[Listbox1.ItemIndex]), i)); end else ListBox2.Items.Add('<No components>'); finally TS.Free; end; end; procedure TForm2.CheckBox1Click(Sender: TObject); var i: Integer; begin Listbox1.Items.Clear; if CheckBox1.Checked then begin for i := 0 to PackageTest.PackageCount-1 do if PackageTest.ComponentCount[i] > 0 then Listbox1.Items.Add(PackageTest.PackageNames[i]); end else for i := 0 to PackageTest.PackageCount-1 do Listbox1.Items.Add(PackageTest.PackageNames[i]); end; end.
unit MasterMind.View.Mock; {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} interface uses MasterMind.API; type TPreviousGuessesProc = procedure(const PreviousGuesses: TPreviousGuesses) of object; IGameViewMock = interface ['{E6FBEA3B-01F7-41AA-8BA4-A374323C39A5}'] procedure SetOnStartRequestGuess(const Value: TPreviousGuessesProc); procedure SetOnShowGuesses(const Value: TPreviousGuessesProc); procedure SetOnShowPlayerWins(const Value: TPreviousGuessesProc); procedure SetOnShowPlayerLoses(const Value: TPreviousGuessesProc); property OnStartRequestGuess: TPreviousGuessesProc write SetOnStartRequestGuess; property OnShowGuesses: TPreviousGuessesProc write SetOnShowGuesses; property OnShowPlayerWins: TPreviousGuessesProc write SetOnShowPlayerWins; property OnShowPlayerLoses: TPreviousGuessesProc write SetOnShowPlayerLoses; end; TMasterMindViewMock = class(TInterfacedObject, IGameView, IGameViewMock) private FOnStartRequestGuess: TPreviousGuessesProc; FOnShowGuesses: TPreviousGuessesProc; FOnShowPlayerWinsMessage: TPreviousGuessesProc; FOnShowPlayerLoses: TPreviousGuessesProc; public procedure StartRequestGuess(const PreviousGuesses: TPreviousGuesses); procedure ShowGuesses(const PreviousGuesses: TPreviousGuesses); procedure SetOnStartRequestGuess(const Value: TPreviousGuessesProc); procedure SetOnShowGuesses(const Value: TPreviousGuessesProc); procedure ShowPlayerWinsMessage(const PreviousGuesses: TPreviousGuesses); procedure SetOnShowPlayerWins(const Value: TPreviousGuessesProc); procedure ShowPlayerLosesMessage(const PreviousGuesses: TPreviousGuesses); procedure SetOnShowPlayerLoses(const Value: TPreviousGuessesProc); procedure Start; end; implementation procedure TMasterMindViewMock.StartRequestGuess(const PreviousGuesses: TPreviousGuesses); begin FOnStartRequestGuess(PreviousGuesses); end; procedure TMasterMindViewMock.ShowGuesses(const PreviousGuesses: TPreviousGuesses); begin FOnShowGuesses(PreviousGuesses); end; procedure TMasterMindViewMock.SetOnStartRequestGuess(const Value: TPreviousGuessesProc); begin FOnStartRequestGuess := Value; end; procedure TMasterMindViewMock.SetOnShowGuesses(const Value: TPreviousGuessesProc); begin FOnShowGuesses := Value; end; procedure TMasterMindViewMock.ShowPlayerWinsMessage(const PreviousGuesses: TPreviousGuesses); begin FOnShowPlayerWinsMessage(PreviousGuesses); end; procedure TMasterMindViewMock.SetOnShowPlayerWins(const Value: TPreviousGuessesProc); begin FOnShowPlayerWinsMessage := Value; end; procedure TMasterMindViewMock.ShowPlayerLosesMessage(const PreviousGuesses: TPreviousGuesses); begin FOnShowPlayerLoses(PreviousGuesses); end; procedure TMasterMindViewMock.SetOnShowPlayerLoses(const Value: TPreviousGuessesProc); begin FOnShowPlayerLoses := Value; end; procedure TMasterMindViewMock.Start; begin end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2016-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Win.HighDpi; interface function IsDpiAware: Boolean; function SetHighDpiAware: Boolean; implementation uses Winapi.Windows, Winapi.ShellScaling, System.SysUtils; function SetHighDpiAware: Boolean; begin if CheckWin32Version(6,3) then Result := SetProcessDpiAwareness(TProcessDpiAwareness.PROCESS_PER_MONITOR_DPI_AWARE) = S_OK else Result := SetProcessDpiAware; end; function IsDpiAware: Boolean; var LLevel: TProcessDpiAwareness; begin if CheckWin32Version(6,3) then begin GetProcessDpiAwareness(GetCurrentProcess, LLevel); Result := LLevel = TProcessDpiAwareness.PROCESS_PER_MONITOR_DPI_AWARE; end else {$WARN SYMBOL_DEPRECATED OFF} Result := IsProcessDPIAware; {$WARN SYMBOL_DEPRECATED DEFAULT} end; {$IFDEF MSWINDOWS} initialization SetHighDpiAware; {$ENDIF} end.
unit EditAddDelSQL; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.ImageList, System.Rtti, System.Bindings.Outputs, System.Actions, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ActnList, Vcl.WinXPanels, Vcl.Imaging.pngimage, Vcl.CategoryButtons, Vcl.ImgList, Vcl.BaseImageCollection, Vcl.ImageCollection, Vcl.WinXCtrls, Vcl.Mask, Vcl.DBCtrls, Vcl.Bind.DBEngExt, Vcl.Buttons, RzEdit, RzDBEdit, Data.Db, PngSpeedButton, JvComponentBase, JvFormPlacement, JvExControls, JvLabel, JvDBControls; type TEditAddDelSQLBtns = class(TForm) crdpnl1: TCardPanel; spltvw: TSplitView; ilIcons: TImageList; ctgrybtns1: TCategoryButtons; pnlToolbar: TPanel; imgMenu: TImage; lblTitle: TLabel; actlst1: TActionList; crd_Edit: TCard; crd_Add: TCard; crd_Delete: TCard; act_Edit: TAction; act_Add: TAction; act_Delete: TAction; dbedtCaption: TDBEdit; rg_ColsMoveBtnTo: TRadioGroup; rzdbnmrcdtLocationCode: TRzDBNumericEdit; rzdbnmrcdtBtnOrder: TRzDBNumericEdit; rzdbnmrcdtLocationCode1: TRzDBNumericEdit; dbedtCaption1: TDBEdit; dbedtExtraText: TDBEdit; lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; lbl5: TLabel; dbchkSpaceAfterCursor: TDBCheckBox; dbchkUseExtenedSQL: TDBCheckBox; dbmmoSQLCode: TDBMemo; lbl6: TLabel; btn_CutSQLCodeCloseOpenSV: TPngSpeedButton; act_CloseOpenSV: TAction; ctgrypnlgrp1: TCategoryPanelGroup; ctgrypnl1: TCategoryPanel; tglswtchChangeIcons: TToggleSwitch; tglswtchChangeSVCloseStyle: TToggleSwitch; jvfrmstrg_SQLBtns1: TJvFormStorage; act_ChangeIcons: TAction; act_ChangeSVCloseStyle: TAction; act_Exit: TAction; jvdbstslbl1: TJvDBStatusLabel; procedure act_EditExecute(Sender: TObject); procedure act_AddExecute(Sender: TObject); procedure act_DeleteExecute(Sender: TObject); procedure rzdbnmrcdtLocationCodeChange(Sender: TObject); procedure rg_ColsMoveBtnToClick(Sender: TObject); procedure crdpnl1CardChange(Sender: TObject; PrevCard, NextCard: TCard); procedure act_CloseOpenSVExecute(Sender: TObject); procedure ctgrypnlgrp1Click(Sender: TObject); procedure act_ChangeIconsExecute(Sender: TObject); procedure act_ChangeSVCloseStyleExecute(Sender: TObject); procedure act_ExitExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } public { Public declarations } function Execute: Boolean; end; var EditAddDelSQLBtns: TEditAddDelSQLBtns; implementation uses DataMod, NxToolsMain; {$R *.dfm} { TForm1 } // ====================================== // Actions // ====================================== procedure TEditAddDelSQLBtns.act_AddExecute(Sender: TObject); begin if dm_DataMod.NxSqlButtonsDbT.State in[dsEdit] then dm_DataMod.NxSqlButtonsDbT.Post; crdpnl1.ActiveCard := crd_Add; dm_DataMod.NxSqlButtonsDbT.Insert; end; procedure TEditAddDelSQLBtns.act_DeleteExecute(Sender: TObject); begin if dm_DataMod.NxSqlButtonsDbT.State in[dsEdit, dsInsert] then dm_DataMod.NxSqlButtonsDbT.Post; crdpnl1.ActiveCard := crd_Delete; end; procedure TEditAddDelSQLBtns.act_EditExecute(Sender: TObject); begin crdpnl1.ActiveCard := crd_Edit; end; procedure TEditAddDelSQLBtns.act_ExitExecute(Sender: TObject); begin Close; end; procedure TEditAddDelSQLBtns.crdpnl1CardChange(Sender: TObject; PrevCard, NextCard: TCard); begin lblTitle.Caption := crdpnl1.ActiveCard.Caption; end; procedure TEditAddDelSQLBtns.ctgrypnlgrp1Click(Sender: TObject); begin spltvw.open; end; procedure TEditAddDelSQLBtns.act_ChangeIconsExecute(Sender: TObject); begin if tglswtchChangeIcons.State = tssON then begin act_Edit.ImageIndex := 8; act_Add.ImageIndex := 9; act_Delete.ImageIndex := 10; act_Exit.ImageIndex := 12; end else begin act_Edit.ImageIndex := 5; act_Add.ImageIndex := 6; act_Delete.ImageIndex := 7; act_Exit.ImageIndex := 11; end; end; procedure TEditAddDelSQLBtns.act_ChangeSVCloseStyleExecute(Sender: TObject); begin if tglswtchChangeSVCloseStyle.state = tssOff then spltvw.CloseStyle := svcCompact else spltvw.CloseStyle := svcCollapse; end; procedure TEditAddDelSQLBtns.act_CloseOpenSVExecute(Sender: TObject); begin if spltvw.Opened then spltvw.Close else spltvw.Open; end; procedure TEditAddDelSQLBtns.rg_ColsMoveBtnToClick(Sender: TObject); begin dm_DataMod.NxSqlButtonsDbT.Edit; // dm_DataMod.NxSqlButtonsDbTLocationCode.AsInteger := rg_ColsMoveBtnTo.ItemIndex; dm_DataMod.NxSqlButtonsDbT.Post; end; procedure TEditAddDelSQLBtns.rzdbnmrcdtLocationCodeChange(Sender: TObject); begin // if dm_DataMod.NxSqlButtonsDbT.active then // rg_ColsMoveBtnTo.ItemIndex := dm_DataMod.fdqry_BtnTableLocationCode.AsInteger - 1; end; function TEditAddDelSQLBtns.Execute: Boolean; begin Result := (ShowModal = mrOK); end; procedure TEditAddDelSQLBtns.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin // TDataSetState = [dsInactive, dsBrowse, dsEdit, dsInsert, dsSetKey, // dsCalcFields, dsFilter, dsNewValue, dsOldValue, dsCurValue, dsBlockRead, // dsInternalCalc, dsOpening]; // if dm_DataMod.NxSqlButtonsDbT.State in [dsEdit, dsInsert] then dm_DataMod.NxSqlButtonsDbT.Post; CanClose := True; end; procedure TEditAddDelSQLBtns.FormShow(Sender: TObject); begin dm_DataMod.NxSqlButtonsDbT.Edit; end; end.
unit rhlMurmur2_64; interface uses rhlCore; type { TrhlMurmur2_64 } TrhlMurmur2_64 = class(TrhlHashWithKey) private const CKEY: DWord = $C58F1A7B; M: QWord = $C6A4A7935BD1E995; R: Integer = 47; var m_key, m_working_key: DWord; m_h: QWord; protected procedure UpdateBytes(const ABuffer; ASize: LongWord); override; function GetKey: TBytes; override; procedure SetKey(AValue: TBytes); override; public constructor Create; override; procedure Init; override; procedure Final(var ADigest); override; end; implementation { TrhlMurmur2_64 } procedure TrhlMurmur2_64.UpdateBytes(const ABuffer; ASize: LongWord); var a_data: array[0..0] of Byte absolute ABuffer; ci: Integer; k: QWord; begin if (ASize = 0) then Exit; m_h := m_working_key xor ASize; ci := 0; while (ASize >= 8) do begin k := (QWord(a_data[ci+0])) or (QWord(a_data[ci+1]) shl 8) or (QWord(a_data[ci+2]) shl 16) or (QWord(a_data[ci+3]) shl 24) or (QWord(a_data[ci+4]) shl 32) or (QWord(a_data[ci+5]) shl 40) or (QWord(a_data[ci+6]) shl 48) or (QWord(a_data[ci+7]) shl 56); k := k * M; k := k xor (k shr R); k := k * M; m_h := m_h xor k; m_h := m_h * M; Inc(ci, 8); Dec(ASize, 8); end; case ASize of 7: m_h := m_h xor ((QWord(a_data[ci+0]) shl 48) or (QWord(a_data[ci+1]) shl 40) or (QWord(a_data[ci+2]) shl 32) or (QWord(a_data[ci+3]) shl 24) or (QWord(a_data[ci+4]) shl 16) or (QWord(a_data[ci+5]) shl 8) or QWord(a_data[ci+6])); 6: m_h := m_h xor ((QWord(a_data[ci+0]) shl 40) or (QWord(a_data[ci+1]) shl 32) or (QWord(a_data[ci+2]) shl 24) or (QWord(a_data[ci+3]) shl 16) or (QWord(a_data[ci+4]) shl 8) or QWord(a_data[ci+5])); 5: m_h := m_h xor ((QWord(a_data[ci+0]) shl 32) or (QWord(a_data[ci+1]) shl 24) or (QWord(a_data[ci+2]) shl 16) or (QWord(a_data[ci+3]) shl 8) or QWord(a_data[ci+4])); 4: m_h := m_h xor ((QWord(a_data[ci+0]) shl 24) or (QWord(a_data[ci+1]) shl 16) or (QWord(a_data[ci+2]) shl 8) or QWord(a_data[ci+3])); 3: m_h := m_h xor ((QWord(a_data[ci+0]) shl 16) or (QWord(a_data[ci+1]) shl 8) or QWord(a_data[ci+2])); 2: m_h := m_h xor ((QWord(a_data[ci+0]) shl 8) or QWord(a_data[ci+1])); 1: m_h := m_h xor (QWord(a_data[ci+0])); end; if ASize >= 1 then m_h := m_h * M; m_h := m_h xor (m_h shr R); m_h := m_h * M; m_h := m_h xor (m_h shr R); end; function TrhlMurmur2_64.GetKey: TBytes; begin SetLength(Result, SizeOf(DWord)); Move(m_key, Result[0], SizeOf(DWord)); end; procedure TrhlMurmur2_64.SetKey(AValue: TBytes); begin if Length(AValue) = SizeOf(m_key) then Move(AValue[0], m_key, SizeOf(m_key)); end; constructor TrhlMurmur2_64.Create; begin HashSize := 8; BlockSize := 8; m_key := CKEY; end; procedure TrhlMurmur2_64.Init; begin inherited Init; m_working_key := m_key; end; procedure TrhlMurmur2_64.Final(var ADigest); begin Move(m_h, ADigest, SizeOf(m_h)); end; end.
unit TestDeref; interface implementation uses Classes; type TAmoeba = class; PTAmoeba = ^TAmoeba; TAmoeba = class(TObject) private fsName: string; function GetName: string; procedure SetName(const Value: string); function GetStuff(const psIndex: string): TAmoeba; procedure GetValueList(List: TStrings); public function GetBar(const piIndex: integer): TAmoeba; function MyFudgeFactor: TAmoeba; function Pointer: PTAmoeba; function MyIndex: integer; property Name: string read GetName write SetName; property Stuff[const psIndex: string]: TAmoeba read GetStuff; end; procedure TestHatExpr(var Foo: TAmoeba); begin { modeled on an expression in Delphi source } if ((Foo.Stuff['x'].Pointer)^.MyIndex = 0) then Foo := nil; end; procedure DoTestDeref(var Foo: TAmoeba); var ls: string; begin // the goal of this unit is to get the following silly line to compile foo.GetBar(1).Stuff['fish'].MyFudgeFactor.GetBar(2).Name := 'Jiim'; // let's try this one ls := foo.Stuff['fish'].GetBar(1).MyFudgeFactor.GetBar(2).Name; end; { TAmoeba } function TAmoeba.getBar(const piIndex: integer): TAmoeba; begin Result := self; end; function TAmoeba.GetName: string; begin result := fsName; end; function TAmoeba.GetStuff(const psIndex: string): TAmoeba; begin Result := self; end; function TAmoeba.MyFudgeFactor: TAmoeba; begin Result := self; end; procedure TAmoeba.SetName(const Value: string); begin fsName := Value; end; { this line echoes the structure code in BDReg.pas that failed } procedure TAmoeba.GetValueList(List: TStrings); begin (GetStuff('0') as TAmoeba).MyFudgeFactor.GetValueList(List); end; function TAmoeba.Pointer: PTAmoeba; begin Result := @self; end; function TAmoeba.MyIndex: integer; begin Result := 1; end; end.
{ Version 12 Copyright (c) 2011-2012 by Bernd Gabriel 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. Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS are covered by separate copyright notices located in those modules. } {$I htmlcons.inc} unit StyleParser; interface uses Windows, Graphics, Classes, SysUtils, Variants, // Parser, HtmlBuffer, HtmlGlobals, HtmlSymbols, HtmlStyles, StyleTypes; type EParseError = class(Exception); // about parsing CSS 2.1 style sheets: // http://www.w3.org/TR/2010/WD-CSS2-20101207/syndata.html // http://www.w3.org/TR/2010/WD-CSS2-20101207/grammar.html THtmlStyleParser = class(TCustomParser) private FOrigin: TPropertyOrigin; FSupportedMediaTypes: TMediaTypes; // LCh: ThtChar; FCanCharset, FCanImport: Boolean; FMediaTypes: TMediaTypes; // debug stuff LIdentPos, LMediaPos, LWhiteSpacePos, LSelectorPos: Integer; procedure checkPosition(var Pos: Integer); // The result is enclose in 'url(' and ')'. function AddUrlPath(const S: ThtString): ThtString; {$ifdef UseInline} inline; {$endif} // basic parser methods function IsWhiteSpace: Boolean; {$ifdef UseInline} inline; {$endif} procedure GetCh; procedure GetChSkipWhiteSpace; {$ifdef UseInline} inline; {$endif} procedure SkipComment; procedure SkipWhiteSpace; // token retrieving methods. They do not skip trailing white spaces. function GetIdentifier(out Identifier: ThtString): Boolean; function GetString(out Str: ThtString): Boolean; function GetUrl(out Url: ThtString): Boolean; // syntax parsing methods. They skip trailing white spaces. function ParseDeclaration(out Name: ThtString; out Terms: ThtStringArray; out Important: Boolean): Boolean; function ParseExpression(out Terms: ThtStringArray): Boolean; function ParseProperties(var Properties: TStylePropertyList): Boolean; function ParseRuleset(out Ruleset: TRuleset): Boolean; function ParseSelectors(var Selectors: TStyleSelectorList): Boolean; procedure ParseAtRule(Rulesets: TRulesetList); procedure ParseSheet(Rulesets: TRulesetList); procedure setMediaTypes(const Value: TMediaTypes); procedure setSupportedMediaTypes(const Value: TMediaTypes); public class procedure ParseCssDefaults(Rulesets: TRulesetList); overload; constructor Create(Origin: TPropertyOrigin; Doc: TBuffer; const LinkPath: ThtString = ''); // ParseProperties() parses any tag's style attribute. If starts with quote, then must end with same quote. function ParseStyleProperties(var LCh: ThtChar; out Properties: TStylePropertyList): Boolean; // ParseStyleSheet() parses an entire style sheet document: procedure ParseStyleSheet(Rulesets: TRulesetList); // ParseStyleTag() parses a style tag of an html document: procedure ParseStyleTag(var LCh: ThtChar; Rulesets: TRulesetList); property SupportedMediaTypes: TMediaTypes read FSupportedMediaTypes write setSupportedMediaTypes; property MediaTypes: TMediaTypes read FMediaTypes write setMediaTypes; // used to retrieve imported style sheets. If OnGetDocument not given tries to load file from local file system. property LinkPath; property OnGetBuffer; end; implementation //-- BG ---------------------------------------------------------- 20.03.2011 -- function GetCssDefaults: TBuffer; overload; var Stream: TStream; begin Stream := HtmlStyles.GetCssDefaults; try Result := TBuffer.Create(Stream, 'css-defaults'); finally Stream.Free; end; end; //-- BG ---------------------------------------------------------- 20.03.2011 -- function THtmlStyleParser.AddUrlPath(const S: ThtString): ThtString; {for <link> styles, the path is relative to that of the stylesheet directory and must be added now} begin Result := 'url(' + AddPath(ReadUrl(S)) + ')'; end; //-- BG ---------------------------------------------------------- 19.03.2011 -- procedure THtmlStyleParser.checkPosition(var Pos: Integer); procedure stopHere(); begin end; begin if Pos = Doc.Position then stopHere(); Pos := Doc.Position; end; //-- BG ---------------------------------------------------------- 14.03.2011 -- constructor THtmlStyleParser.Create(Origin: TPropertyOrigin; Doc: TBuffer; const LinkPath: ThtString); begin inherited Create(Doc, LinkPath); FOrigin := Origin; SupportedMediaTypes := AllMediaTypes; end; //-- BG ---------------------------------------------------------- 14.03.2011 -- procedure THtmlStyleParser.GetCh; begin LCh := Doc.NextChar; case LCh of #13, #12: LCh := LfChar; #9: LCh := SpcChar; '/': if Doc.PeekChar = '*' then begin SkipComment; LCh := SpcChar; end; end; end; //-- BG ---------------------------------------------------------- 20.03.2011 -- procedure THtmlStyleParser.GetChSkipWhiteSpace; begin LCh := Doc.NextChar; SkipWhiteSpace; end; //-- BG ---------------------------------------------------------- 13.03.2011 -- function THtmlStyleParser.GetIdentifier(out Identifier: ThtString): Boolean; begin // can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, // plus the hyphen (-) and the underscore (_); // Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code // (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F". Result := True; SetLength(Identifier, 0); // they cannot start with a digit, two hyphens, or a hyphen followed by a digit. case LCh of '0'..'9': Result := False; '-': begin case Doc.PeekChar of '0'..'9', '-': Result := False; else SetLength(Identifier, Length(Identifier) + 1); Identifier[Length(Identifier)] := LCh; GetCh; end; end; end; // loop through all allowed characters: while Result do begin case LCh of 'A'..'Z', 'a'..'z', '0'..'9', '-', '_': ; else if LCh < #$A0 then break; end; SetLength(Identifier, Length(Identifier) + 1); Identifier[Length(Identifier)] := LCh; GetCh; end; if Result then Result := Length(Identifier) > 0 else checkPosition(LIdentPos); end; //-- BG ---------------------------------------------------------- 13.03.2011 -- function THtmlStyleParser.GetString(out Str: ThtString): Boolean; // Must start and end with single or double quote. // Returns string incl. quotes and with the original escape sequences. var Esc: Boolean; Term: ThtChar; begin Term := #0; // valium for the compiler SetLength(Str, 0); case LCh of '''', '"': begin SetLength(Str, Length(Str) + 1); Str[Length(Str)] := LCh; Term := LCh; Result := True; end; else Result := False; end; Esc := False; while Result do begin GetCh; case LCh of '\': begin SetLength(Str, Length(Str) + 1); Str[Length(Str)] := LCh; Esc := True; end; LfChar: begin Result := False; break; end; else SetLength(Str, Length(Str) + 1); Str[Length(Str)] := LCh; if (LCh = Term) and not Esc then begin GetCh; break; end; Esc := False; end; end; end; //-- BG ---------------------------------------------------------- 20.03.2011 -- function THtmlStyleParser.GetUrl(out Url: ThtString): Boolean; procedure GetUrlRest; begin repeat case LCh of SpcChar: begin SkipWhiteSpace; Result := LCh = ')'; if Result then GetCh; break; end; ')': begin Result := True; GetCh; break; end; EofChar: break; end; SetLength(Url, Length(Url) + 1); Url[Length(Url)] := LCh; GetCh; until False; end; begin Result := False; case LCh of '"': Result := GetString(URL); 'u': begin if GetIdentifier(URL) then if LowerCase(URL) = 'url' then if LCh = '(' then begin GetChSkipWhiteSpace; if GetString(URL) then begin SkipWhiteSpace; Result := LCh = ')'; if Result then GetCh; end else GetUrlRest; end; end; else SetLength(Url, 0); GetUrlRest; end; end; //-- BG ---------------------------------------------------------- 19.03.2011 -- function THtmlStyleParser.IsWhiteSpace: Boolean; begin case LCh of SpcChar, LfChar, CrChar, FfChar, TabChar: Result := True; else Result := False; end; end; //-- BG ---------------------------------------------------------- 17.03.2011 -- procedure THtmlStyleParser.ParseAtRule(Rulesets: TRulesetList); function GetMediaTypes: TMediaTypes; var Identifier: ThtString; MediaType: TMediaType; begin Result := []; if not GetIdentifier(Identifier) then exit; repeat checkPosition(LMediaPos); if TryStrToMediaType(htLowerCase(Identifier), MediaType) then Include(Result, MediaType); SkipWhiteSpace; if LCh <> ',' then break; GetChSkipWhiteSpace; if not GetIdentifier(Identifier) then break; until False; end; procedure DoMedia; var Media: TMediaTypes; Ruleset: TRuleset; begin Media := TranslateMediaTypes(GetMediaTypes); case LCh of '{': begin GetChSkipWhiteSpace; MediaTypes := Media * SupportedMediaTypes; try repeat case LCh of '}': begin GetChSkipWhiteSpace; break; end; EofChar, '<': break; else if ParseRuleset(Ruleset) then Rulesets.Add(Ruleset); end; until False; finally MediaTypes := SupportedMediaTypes; end; end; end; end; procedure DoImport; var Result: Boolean; URL: ThtString; LinkUrl: ThtString; Media: TMediaTypes; Inclusion: TBuffer; Parser: THtmlStyleParser; begin Result := GetUrl(URL); if Result then if FCanImport then begin SkipWhiteSpace; if Length(Url) > 2 then case Url[1] of '"', '''': Url := Copy(Url, 2, Length(Url) - 2); end; Media := GetMediaTypes; if Media = [] then Media := AllMediaTypes; Media := Media * SupportedMediaTypes; if Media <> [] then begin LinkUrl := AddPath(Url); Inclusion := GetBuffer(LinkUrl); if Inclusion <> nil then try Parser := THtmlStyleParser.Create(FOrigin, Inclusion, LinkPath); Parser.SupportedMediaTypes := Media; try Parser.ParseStyleSheet(Rulesets); finally Parser.Free; end; finally Inclusion.Free; end; end; end; repeat case LCh of ';': begin GetChSkipWhiteSpace; break; end; '@', EofChar, '<': break; end; GetChSkipWhiteSpace; until False; end; procedure DoCharset; var Charset: ThtString; Info: TBuffCharSetCodePageInfo; begin if GetString(Charset) then if FCanCharset then begin Info := GetCharSetCodePageInfo(Charset); if Info <> nil then begin Doc.CharSet := Info.CharSet; Doc.CodePage := Info.CodePage; end; SkipWhiteSpace; end; repeat case LCh of ';': begin GetChSkipWhiteSpace; break; end; '@', EofChar, '<': break; end; GetChSkipWhiteSpace; until False; end; var AtRule: ThtString; begin GetCh; // skip the '@'; if GetIdentifier(AtRule) then begin SkipWhiteSpace; AtRule := LowerCase(AtRule); if AtRule = 'media' then DoMedia else if AtRule = 'import' then DoImport else if AtRule = 'charset' then DoCharset else if LCh = '{' then repeat GetChSkipWhiteSpace; case LCh of '}': begin GetChSkipWhiteSpace; break; end; EofChar: break; end; until False; end; end; //-- BG ---------------------------------------------------------- 20.03.2011 -- class procedure THtmlStyleParser.ParseCssDefaults(Rulesets: TRulesetList); var CssDefaults: TBuffer; begin CssDefaults := GetCssDefaults; try with THtmlStyleParser.Create(poDefault, CssDefaults) do try ParseStyleSheet(Rulesets); finally Free; end; finally CssDefaults.Free; end; end; //-- BG ---------------------------------------------------------- 15.03.2011 -- function THtmlStyleParser.ParseDeclaration(out Name: ThtString; out Terms: ThtStringArray; out Important: Boolean): Boolean; function GetImportant(out Important: Boolean): Boolean; var Id: ThtString; begin Important := False; Result := LCh <> '!'; // '!important' is optional, thus it's OK, not to find '!' if not Result then begin GetChSkipWhiteSpace; if GetIdentifier(Id) then begin SkipWhiteSpace; Important := LowerCase(Id) = 'important'; Result := True; end; end; end; begin Result := GetIdentifier(Name); if Result then begin SkipWhiteSpace; Result := (LCh = ':') or (LCh = '='); if Result then begin GetChSkipWhiteSpace; Result := ParseExpression(Terms); if Result then Result := GetImportant(Important); end; end; // correct end of declaration or error recovery: find end of declaration repeat case LCh of ';': begin GetChSkipWhiteSpace; break; end; '}', EofChar: break; else GetChSkipWhiteSpace; end; until false; end; //-- BG ---------------------------------------------------------- 14.03.2011 -- function THtmlStyleParser.ParseExpression(out Terms: ThtStringArray): Boolean; function GetTerm(out Term: ThtString): Boolean; function GetTilEnd(): Boolean; begin repeat SetLength(Term, Length(Term) + 1); Term[Length(Term)] := LCh; GetCh; case LCh of SpcChar, TabChar, LfChar, CrChar, FfChar: begin SkipWhiteSpace; break; end; ';', '}', '!', ',', EofChar: break; end; until False; Result := Length(Term) > 0; end; function GetParams(): Boolean; var Level: Integer; Str: ThtString; begin Level := 1; repeat case LCh of ';', '}', '!', ',', EofChar: break; '"', '''': begin Result := GetString(Str); if not Result then exit; Term := Term + Str; continue; end; ')': begin Dec(Level); if Level = 0 then begin SetLength(Term, Length(Term) + 1); Term[Length(Term)] := LCh; GetCh; break; end; end; '(': Inc(Level); end; SetLength(Term, Length(Term) + 1); Term[Length(Term)] := LCh; GetCh; until False; Result := Length(Term) > 0; end; var Str: ThtString; begin SetLength(Term, 0); repeat case LCh of '+', '-': case Doc.PeekChar of '0'..'9': Result := GetTilEnd; else Result := False; break; end; '0'..'9', '#': Result := GetTilEnd; '"', '''': begin Result := GetString(Str); if Result then if Length(Term) > 0 then Term := Term + ' ' + Str else Term := Str; end; else Result := GetIdentifier(Str); if Result then begin if Length(Term) > 0 then Term := Term + ' ' + Str else Term := Str; case LCh of '(': begin SetLength(Term, Length(Term) + 1); Term[Length(Term)] := LCh; GetChSkipWhiteSpace; Result := GetParams; end; end; end; end; SkipWhiteSpace; if LCh <> ',' then break; SetLength(Term, Length(Term) + 1); Term[Length(Term)] := LCh; GetChSkipWhiteSpace; until False; end; var Term: ThtString; begin SetLength(Terms, 0); repeat if not GetTerm(Term) then break; SetLength(Terms, Length(Terms) + 1); Terms[High(Terms)] := Term; case LCh of ';', '!': break; end; until False; Result := Length(Terms) > 0; end; //-- BG ---------------------------------------------------------- 15.03.2011 -- function THtmlStyleParser.ParseProperties(var Properties: TStylePropertyList): Boolean; function GetPrecedence(Important: Boolean; Origin: TPropertyOrigin): TPropertyPrecedence; {$ifdef UseInline} inline; {$endif} begin Result := CPropertyPrecedenceOfOrigin[Important, Origin]; end; var Precedence: TPropertyPrecedence; procedure ProcessProperty(Prop: TStylePropertySymbol; const Value: Variant); begin if FMediaTypes * FSupportedMediaTypes <> [] then if VarIsStr(Value) and (Value = 'inherit') then Properties.Add(TStyleProperty.Create(Prop, Precedence, Inherit)) else Properties.Add(TStyleProperty.Create(Prop, Precedence, Value)); end; var Values: ThtStringArray; procedure DoBackground; { do the Background shorthand property specifier } var S: array [0..1] of ThtString; I, N: Integer; Color: TColor; begin N := 0; for I := 0 to Length(Values) - 1 do // image if (Pos('url(', Values[I]) > 0) then begin if LinkPath <> '' then {path added now only for <link...>} Values[I] := AddUrlPath(Values[I]); ProcessProperty(BackgroundImage, Values[I]); end else if Values[I] = 'none' then begin ProcessProperty(BackgroundImage, Values[I]); ProcessProperty(BackgroundColor, 'transparent'); {9.41} end // color else if Values[I] = 'transparent' then ProcessProperty(BackgroundColor, Values[I]) else if TryStrToColor(Values[I], True, Color) then ProcessProperty(BackgroundColor, Color) // repeat else if Pos('repeat', Values[I]) > 0 then ProcessProperty(BackgroundRepeat, Values[I]) // attachment else if (Values[I] = 'fixed') or (Values[I] = 'scroll') then ProcessProperty(BackgroundAttachment, Values[I]) // position (2 values: horz and vert). else if N < 2 then begin S[N] := Values[I]; Inc(N); end else begin // only process last 2 values of malformed background property S[0] := S[1]; S[1] := Values[I]; end; case N of 1: ProcessProperty(BackgroundPosition, S[0]); 2: ProcessProperty(BackgroundPosition, S[0] + ' ' + S[1]); end; end; procedure DoBorder(WidthProp, StyleProp, ColorProp: TStylePropertySymbol); { do the Border, Border-Top/Right/Bottom/Left shorthand properties.} var I: Integer; Color: TColor; Style: TBorderStyle; begin for I := 0 to Length(Values) - 1 do begin if TryStrToColor(Values[I], True, Color) then ProcessProperty(ColorProp, Color) else if TryStrToBorderStyle(Values[I], Style) then ProcessProperty(StyleProp, Style) else ProcessProperty(WidthProp, Values[I]); end; end; procedure DoFont; { do the Font shorthand property specifier } type FontEnum = (italic, oblique, normal, bolder, lighter, bold, smallcaps, larger, smaller, xxsmall, xsmall, small, medium, large, xlarge, xxlarge); function FindWord(const S: ThtString; var Index: FontEnum): boolean; const FontWords: array[FontEnum] of ThtString = ( // style 'italic', 'oblique', // weight 'normal', 'bolder', 'lighter', 'bold', // variant 'small-caps', // size 'larger', 'smaller', 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large' ); var I: FontEnum; begin Result := False; for I := Low(FontEnum) to High(FontEnum) do if FontWords[I] = S then begin Result := True; Index := I; Exit; end; end; var I: integer; Index: FontEnum; begin for I := 0 to Length(Values) - 1 do begin if Values[I, 1] = '/' then ProcessProperty(LineHeight, Copy(Values[I], 2, Length(Values[I]) - 1)) else if FindWord(Values[I], Index) then begin case Index of italic..oblique: ProcessProperty(FontStyle, Values[I]); normal..bold: ProcessProperty(FontWeight, Values[I]); smallcaps: ProcessProperty(FontVariant, Values[I]); else {larger..xxlarge:} ProcessProperty(FontSize, Values[I]); end; end else case Values[I, 1] of '0'..'9': {the following will pass 100pt, 100px, but not 100 or larger} if StrToIntDef(Values[I], -1) < 100 then ProcessProperty(FontSize, Values[I]); else ProcessProperty(FontFamily, Values[I]); end; end; end; procedure DoListStyle; { do the List-Style shorthand property specifier } var I: integer; begin for I := 0 to Length(Values) - 1 do begin if Pos('url(', Values[I]) > 0 then begin if LinkPath <> '' then {path added now only for <link...>} Values[I] := AddPath(Values[I]); ProcessProperty(ListStyleImage, Values[I]); end else ProcessProperty(ListStyleType, Values[I]); {TODO: should also do List-Style-Position } end; end; procedure DoMarginItems(Prop: TStylePropertySymbol); { Do the Margin, Border, Padding shorthand property specifiers} const Index: array[1..4,0..3] of Integer = ( (0, 0, 0, 0), (0, 1, 0, 1), (0, 1, 2, 1), (0, 1, 2, 3) ); var I, N: integer; begin N := Length(Values); if (N > 0) and (N <= 4) then for I := 0 to 3 do ProcessProperty(TStylePropertySymbol(Ord(Prop) + I), Values[Index[N, I]]); end; var Term: ThtChar; Name: ThtString; Index: TPropertySymbol; Important: Boolean; begin case LCh of '{': begin Term := '}'; GetChSkipWhiteSpace; end; '''', '"': begin Term := LCh; GetChSkipWhiteSpace; end; else Term := EofChar; end; repeat if LCh = Term then begin GetChSkipWhiteSpace; Result := True; exit; end; if ParseDeclaration(Name, Values, Important) then if TryStrToPropertySymbol(Name, Index) then begin Precedence := GetPrecedence(Important, FOrigin); case Index of MarginX: DoMarginItems(MarginTop); PaddingX: DoMarginItems(PaddingTop); BorderWidthX: DoMarginItems(BorderTopWidth); BorderColorX: DoMarginItems(BorderTopColor); BorderStyleX: DoMarginItems(BorderTopStyle); FontX: DoFont; BorderX: begin DoBorder(BorderTopWidth, BorderTopStyle, BorderTopColor); DoBorder(BorderRightWidth, BorderRightStyle, BorderRightColor); DoBorder(BorderBottomWidth, BorderBottomStyle, BorderBottomColor); DoBorder(BorderLeftWidth, BorderLeftStyle, BorderLeftColor); end; BorderTX: DoBorder(BorderTopWidth, BorderTopStyle, BorderTopColor); BorderRX: DoBorder(BorderRightWidth, BorderRightStyle, BorderRightColor); BorderBX: DoBorder(BorderBottomWidth, BorderBottomStyle, BorderBottomColor); BorderLX: DoBorder(BorderLeftWidth, BorderLeftStyle, BorderLeftColor); BackgroundX: DoBackground; ListStyleX: DoListStyle; else if Length(Values) > 0 then ProcessProperty(Index, Values[0]); end; end; until LCh = EofChar; Result := False; end; //-- BG ---------------------------------------------------------- 15.03.2011 -- function THtmlStyleParser.ParseRuleset(out Ruleset: TRuleset): Boolean; begin Ruleset := TRuleset.Create(MediaTypes); Result := ParseSelectors(Ruleset.Selectors); if Result then Result := ParseProperties(Ruleset.Properties); if Ruleset.Selectors.IsEmpty or Ruleset.Properties.IsEmpty then begin Result := False; FreeAndNil(Ruleset); end; end; //-- BG ---------------------------------------------------------- 15.03.2011 -- function THtmlStyleParser.ParseSelectors(var Selectors: TStyleSelectorList): Boolean; function GetSelector(out Selector: TStyleSelector): Boolean; function GetSimpleSelector(Selector: TStyleSelector): Boolean; function GetElementName(out Name: ThtString): Boolean; begin case LCh of '*': begin Result := True; Name := LCh; GetCh; end; else Result := GetIdentifier(Name); end; end; function GetAttributeMatch(out Match: TAttributeMatch): Boolean; function GetMatchOperator(out Oper: TAttributeMatchOperator): Boolean; var Str: ThtString; begin SetLength(Str, 0); repeat case LCh of ']': begin Result := Length(Str) = 0; if Result then Oper := amoSet; exit; end; '=': begin SetLength(Str, Length(Str) + 1); Str[Length(Str)] := LCh; GetChSkipWhiteSpace; Result := TryStrToAttributeMatchOperator(Str, Oper); exit; end; EofChar, '{': begin Result := False; exit; end; end; SetLength(Str, Length(Str) + 1); Str[Length(Str)] := LCh; GetCh; until False; end; var Str: ThtString; Attr: THtmlAttributeSymbol; Oper: TAttributeMatchOperator; begin Result := GetIdentifier(Str) and TryStrToAttributeSymbol(htUpperCase(Str), Attr); if Result then begin SkipWhiteSpace; Result := GetMatchOperator(Oper); if Result then begin if Oper <> amoSet then begin SkipWhiteSpace; Result := GetIdentifier(Str) or GetString(Str); SkipWhiteSpace; end; if Result then begin Result := LCh = ']'; if Result then begin Match := TAttributeMatch.Create(Attr, Oper, Str); GetChSkipWhiteSpace; end; end; end; end; end; var Name: ThtString; Pseudo: TPseudo; Match: TAttributeMatch; begin Result := GetElementName(Name); if Result then Selector.AddTag(htUpperCase(Name)); repeat case LCh of '#': begin GetCh; Result := GetIdentifier(Name); if Result then Selector.AddId(Name) else exit; end; ':': begin GetCh; Result := GetIdentifier(Name) and TryStrToPseudo(Name, Pseudo); if Result then Selector.AddPseudo(Pseudo) else exit; end; '.': begin GetCh; Result := GetIdentifier(Name); if Result then Selector.AddClass(Name) else exit; end; '[': begin GetChSkipWhiteSpace; Result := GetAttributeMatch(Match); if Result then Selector.AddAttributeMatch(Match) else exit; end; else break; end; until False; end; var Combinator: TStyleCombinator; begin Selector := TStyleSelector.Create; repeat checkPosition(LSelectorPos); Result := GetSimpleSelector(Selector); if not Result then break; if IsWhiteSpace then Combinator := scDescendant else Combinator := scNone; SkipWhiteSpace; case LCh of '>': begin Combinator := scChild; GetChSkipWhiteSpace; end; '+': begin Combinator := scFollower; GetChSkipWhiteSpace; end; '{': break; end; if Combinator = scNone then break; Selector := TCombinedSelector.Create(Selector, Combinator); until False; if not Result then FreeAndNil(Selector); end; var Selector: TStyleSelector; begin repeat if GetSelector(Selector) then Selectors.Add(Selector); // correct end of selector or error recovery: find end of selector repeat case LCh of ',': begin GetChSkipWhiteSpace; break; end; '{': begin Result := True; exit; end; '}', EofChar: begin GetChSkipWhiteSpace; Result := False; exit; end; end; GetCh; until False; until False; end; //-- BG ---------------------------------------------------------- 17.03.2011 -- procedure THtmlStyleParser.ParseSheet(Rulesets: TRulesetList); var Ruleset: TRuleset; begin repeat case LCh of '@': ParseAtRule(Rulesets); '<', EofChar: break; else FCanImport := False; if ParseRuleset(Ruleset) then Rulesets.Add(Ruleset); end; FCanCharset := False; until False; end; //-- BG ---------------------------------------------------------- 17.03.2011 -- function THtmlStyleParser.ParseStyleProperties(var LCh: ThtChar; out Properties: TStylePropertyList): Boolean; begin Properties.Init; FCanCharset := False; FCanImport := False; Self.LCh := LCh; SkipWhiteSpace; Result := ParseProperties(Properties); LCh := Self.LCh; end; //-- BG ---------------------------------------------------------- 17.03.2011 -- procedure THtmlStyleParser.ParseStyleSheet(Rulesets: TRulesetList); begin FCanCharset := True; FCanImport := True; GetChSkipWhiteSpace; ParseSheet(Rulesets); end; //-- BG ---------------------------------------------------------- 17.03.2011 -- procedure THtmlStyleParser.ParseStyleTag(var LCh: ThtChar; Rulesets: TRulesetList); begin Self.LCh := LCh; FCanCharset := False; FCanImport := False; SkipWhiteSpace; ParseSheet(Rulesets); LCh := Self.LCh; end; //-- BG ---------------------------------------------------------- 20.03.2011 -- procedure THtmlStyleParser.setMediaTypes(const Value: TMediaTypes); begin FMediaTypes := TranslateMediaTypes(Value); end; //-- BG ---------------------------------------------------------- 20.03.2011 -- procedure THtmlStyleParser.setSupportedMediaTypes(const Value: TMediaTypes); begin FSupportedMediaTypes := TranslateMediaTypes(Value); FMediaTypes := FSupportedMediaTypes; end; //-- BG ---------------------------------------------------------- 20.03.2011 -- procedure THtmlStyleParser.SkipComment; var LastCh: ThtChar; begin LCh := Doc.NextChar; // skip '/' LCh := Doc.NextChar; // skip '*' repeat LastCh := LCh; LCh := Doc.NextChar; if LCh = EofChar then raise EParseError.Create('Unterminated comment in style file: ' + Doc.Name); until (LCh = '/') and (LastCh = '*'); end; //-- BG ---------------------------------------------------------- 14.03.2011 -- procedure THtmlStyleParser.SkipWhiteSpace; begin repeat checkPosition(LWhiteSpacePos); case LCh of SpcChar, TabChar, LfChar, FfChar, CrChar: ; '/': if Doc.PeekChar = '*' then SkipComment else break; else break; end; LCh := Doc.NextChar; until False; end; end.
{ $Id: SQLite3Utils.pas 10 2010-02-13 05:37:54Z yury@plashenkov.com $ Complete SQLite3 API translation and simple wrapper for Delphi and FreePascal Copyright © 2010 IndaSoftware Inc. and contributors. All rights reserved. http://www.indasoftware.com/fordev/sqlite3/ SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The source code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private. SQLite is the most widely deployed SQL database engine in the world. This package contains complete SQLite3 API translation for Delphi and FreePascal, as well as a simple Unicode-enabled object wrapper to simplify the use of this database engine. The contents of this file are used with permission, subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. } { Miscellaneous utility functions } unit SQLite3Utils; {$WARN SYMBOL_DEPRECATED OFF} interface function StrToUTF8(const S: WideString): AnsiString; function UTF8ToStr(const S: PAnsiChar; const Len: Integer = -1): WideString; function QuotedStr(const S: WideString): WideString; function FloatToSQLStr(Value: Extended): WideString; implementation uses SysUtils; function StrToUTF8(const S: WideString): AnsiString; begin Result := UTF8Encode(S); end; function UTF8ToStr(const S: PAnsiChar; const Len: Integer): WideString; var UTF8Str: AnsiString; begin if Len < 0 then begin Result := UTF8Decode(S); end else if Len > 0 then begin SetLength(UTF8Str, Len); Move(S^, UTF8Str[1], Len); Result := UTF8Decode(UTF8Str); end else Result := ''; end; function QuotedStr(const S: WideString): WideString; const Quote = #39; var I: Integer; begin Result := S; for I := Length(Result) downto 1 do if Result[I] = Quote then Insert(Quote, Result, I); Result := Quote + Result + Quote; end; function FloatToSQLStr(Value: Extended): WideString; var SaveSeparator: Char; begin SaveSeparator := DecimalSeparator; DecimalSeparator := '.'; try Result := FloatToStr(Value); finally DecimalSeparator := SaveSeparator; end; end; end.
{*******************************************************} { } { Delphi Runtime Library } { Interface Invoker Support } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Soap.Rio; { RIO is currently implemented with WININET } (*$HPPEMIT '#if defined(__WIN32__)' *) (*$HPPEMIT '#pragma link "wininet.lib"' *) (*$HPPEMIT '#endif' *) {$DEFINE ATTACHMENT_SUPPORT} interface uses System.Classes, System.Rtti, Soap.IntfInfo, Soap.OPConvert, Soap.InvokeRegistry, Soap.WebNode, Soap.SOAPAttachIntf, Soap.WSDLIntf; type TRIO = class; { This interface provides access back to the RIO from an interface that the RIO implements NOTE: It is *NOT* implemented at the RIO level; therefore it cannot control the lifetime of the RIO; therefore you should not hang on to this interface as its underlying RIO could go away! Use the interface for quick RIO configuration when you still have the interface implemented by the RIO; then quickly "Let It Go!" } IRIOAccess = interface ['{FEF7C9CC-A477-40B7-ACBE-487EDA3E5DFE}'] function GetRIO: TRIO; property RIO: TRIO read GetRIO; end; TBeforeExecuteEvent = procedure(const MethodName: string; SOAPRequest: TStream) of object; TAfterExecuteEvent = procedure(const MethodName: string; SOAPResponse: TStream) of object; TRIO = class(TComponent, IInterface, IRIOAccess) private type TRioVirtualInterface = class(TVirtualInterface) private FRio: TRio; protected function _AddRef: Integer; override; stdcall; function _Release: Integer; override; stdcall; public constructor Create(ARio: TRio; AInterface: Pointer); function QueryInterface(const IID: TGUID; out Obj): HRESULT; override; stdcall; end; private FInterface: IInterface; FRefCount: Integer; { Headers } FSOAPHeaders: TSOAPHeaders; FHeadersOutBound: THeaderList; FHeadersInbound: THeaderList; FOnAfterExecute: TAfterExecuteEvent; FOnBeforeExecute: TBeforeExecuteEvent; FOnSendAttachment: TOnSendAttachmentEvent; FOnGetAttachment: TOnGetAttachmentEvent; procedure Generic(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue); function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { IRIOAccess } function GetRIO: TRIO; protected FIID: TGUID; IntfMD: TIntfMetaData; FConverter: IOPConvert; FWebNode: IWebNode; procedure DoDispatch(const Context: TInvContext; MethNum: Integer; const MethMD: TIntfMethEntry); function InternalQI(const IID: TGUID; out Obj): HResult; stdcall; { Routines that derived RIOs may override } procedure DoAfterExecute(const MethodName: string; Response: TStream); virtual; procedure DoBeforeExecute(const MethodName: string; Request: TStream); virtual; function GetResponseStream(BindingType: TWebServiceBindingType): TStream; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall; { Behave like a TInterfacedObject, (only when Owner = nil) } procedure AfterConstruction; override; procedure BeforeDestruction; override; class function NewInstance: TObject; override; property RefCount: Integer read FRefCount; property Converter: IOPConvert read FConverter write FConverter; property WebNode: IWebNode read FWebNode write FWebNode; property SOAPHeaders: TSOAPHeaders read FSOAPHeaders; published property OnAfterExecute: TAfterExecuteEvent read FOnAfterExecute write FOnAfterExecute; property OnBeforeExecute: TBeforeExecuteEvent read FOnBeforeExecute write FOnBeforeExecute; property OnSendAttachment: TOnSendAttachmentEvent read FOnSendAttachment write FOnSendAttachment; property OnGetAttachment: TOnGetAttachmentEvent read FOnGetAttachment write FOnGetAttachment; end; implementation uses {$IFDEF MSWINDOWS}Winapi.Windows,{$ENDIF} {$IFDEF POSIX}Posix.Unistd,{$ENDIF} System.TypInfo, Soap.WebServExp, System.SysUtils, System.SyncObjs, Xml.XMLDoc, Soap.SOAPConst, Xml.XMLIntf, Soap.SOAPAttach, Soap.OpConvertOptions; type TTempFileStream = class(THandleStream) private FTempFile: string; public constructor Create; reintroduce; destructor Destroy; override; end; { TTempFileStream } constructor TTempFileStream.Create; begin FTempFile := GetTempDir + 'EmbarcaderoSoapMimeCache'; inherited Create(GetTempHandle(FTempFile)); end; destructor TTempFileStream.Destroy; var Handle: Integer; begin Handle := Self.Handle; inherited; FileClose(Handle); if FileExists(FTempFile) then DeleteFile(FTempFile); end; { TRIO } constructor TRIO.Create(AOwner: TComponent); begin inherited Create(AOwner); { Headers } FSOAPHeaders := TSOAPHeaders.Create(Self); FHeadersInbound := THeaderList.Create; FHeadersOutBound:= THeaderList.Create; { We don't own sent objects - just like we don't own TRemotable parameters sent to a Service - We will take ownership of headers received (returned by Service) unless Client removes them } FHeadersOutbound.OwnsObjects := False; (FSOAPHeaders as IHeadersSetter).SetHeadersInOut(FHeadersInbound, FHeadersOutBound); end; destructor TRIO.Destroy; begin TRIOVirtualInterface(Pointer(FInterface)).Free; Pointer(FInterface) := nil; FSOAPHeaders.Free; FHeadersInbound.Free; FHeadersOutBound.Free; inherited; end; procedure TRIO.AfterConstruction; begin TInterlocked.Decrement(FRefCount); // Release the constructor's implicit refcount end; procedure TRIO.BeforeDestruction; begin inherited; if FRefCount <> 0 then raise Exception.Create(SInvalidPointer); end; class function TRIO.NewInstance: TObject; begin // Set an implicit refcount so that refcounting // during construction won't destroy the object. Result := inherited NewInstance; TRIO(Result).FRefCount := 1; end; function TRIO.GetRIO: TRIO; begin Result := Self; end; function TRIO.GetResponseStream(BindingType: TWebServiceBindingType): TStream; begin if (BindingType in [btMime, btDime]) and (soCacheMimeResponse in FConverter.Options) then Result := TTempFileStream.Create else Result := TMemoryStream.Create; end; procedure TRIO.DoBeforeExecute(const MethodName: string; Request: TStream); begin if Assigned(FOnBeforeExecute) then begin FOnBeforeExecute(MethodName, Request); Request.Position := 0; end; end; procedure TRIO.DoAfterExecute(const MethodName: string; Response: TStream); begin if Assigned(FOnAfterExecute) then begin FOnAfterExecute(MethodName, Response); Response.Position := 0; end; end; procedure TRio.DoDispatch(const Context: TInvContext; MethNum: Integer; const MethMD: TIntfMethEntry); var Req, Resp, RespXML: TStream; XMLStream: TMemoryStream; AttachHandler: IMimeAttachmentHandler; BindingType, RespBindingType: TWebServiceBindingType; AttachHeader: String; begin { Convert parameter to XML packet } Req := FConverter.InvContextToMsg(IntfMD, MethNum, Context, FHeadersOutBound); try {$IFDEF ATTACHMENT_SUPPORT} { Get the Binding Type NOTE: We're interested in the input/call } BindingType := GetBindingType(MethMD, True); { NOTE: Creation of AttachHandler could be delayed - doesn't seem to matter much though } AttachHandler := GetMimeAttachmentHandler(BindingType); AttachHandler.OnGetAttachment := OnGetAttachment; AttachHandler.OnSendAttachment := OnSendAttachment; {$ELSE} BindingType := btSOAP; {$ENDIF} try {$IFDEF ATTACHMENT_SUPPORT} { Create MIME stream if we're MIME bound } if (BindingType = btMIME) then begin { Create a MIME stream from the request and attachments } AttachHandler.CreateMimeStream(Req, FConverter.Attachments); { Set the MIME Boundary Investigate: Since one of the weaknesses of MIME is the boundary, it seems that we should be going the other way. IOW, since the programmer can configure IWebNode's MIMEBoundary, we should be using that to initialize the AttachHandler's MIME Boundary. IOW, allow the programmer to customize the boundary... instead of ignoring whatever value the programmer may have put there at design time and hardcoding the MIMEBoundary. Or maybe that property should not be exposed at the Designer Level ???? } FWebNode.MimeBoundary := AttachHandler.MIMEBoundary; { Allow for transport-specific initialization that needs to take place prior to execution - NOTE: It's important to call this routine before calling FinalizeStream - this allows the attachment's stream to be modified/configured } { NOTE: Skip 3 for AddRef,Release & QI } { NOTE: Hardcoding '3' makes an assumption: that the interface derived directly from IInvokable (i.e. IUnknown). Under that condition 3 represent the three standard methods of IUknown. However, someone could ask the RIO for an interface that derives from something else that derives from IUnknown. In that case, the '3' here would be wrong. The importer always generates interfaces derived from IInvokable - so we're *relatively* safe. } FWebNode.BeforeExecute(IntfMD, MethMD, MethNum-3, AttachHandler); { This is a hack - but for now, LinkedRIO requires that FinalizeStream be called from here - doing so, breaks HTTPRIO - so we resort to a hack. Ideally, I'm thinking of exposing a thin AttachHeader interface that the transport can use to set SOAP headers - allowing each transport to perform any packet customization } if AttachHeader <> '' then AttachHandler.AddSoapHeader(AttachHeader); AttachHandler.FinalizeStream; end else {$ENDIF} { NOTE: Skip 3 for AddRef,Release & QI - See comment above about '3' } FWebNode.BeforeExecute(IntfMD, MethMD, MethNum-3, nil); { Allow event to see packet we're sending } { This allows the handler to see the whole packet - i.e. attachments too } {$IFDEF ATTACHMENT_SUPPORT} if BindingType = btMIME then DoBeforeExecute(MethMD.Name, AttachHandler.GetMIMEStream) else {$ENDIF} DoBeforeExecute(MethMD.Name, Req); {$IFDEF ATTACHMENT_SUPPORT} RespBindingType := GetBindingType(MethMD, False); {$ELSE} RespBindingType := btSOAP; {$ENDIF} Resp := GetResponseStream(RespBindingType); try {$IFDEF ATTACHMENT_SUPPORT} if (BindingType = btMIME) then begin try FWebNode.Execute(AttachHandler.GetMIMEStream, Resp) finally FConverter.Attachments.Clear; FHeadersOutBound.Clear; end; end else {$ENDIF} try FWebNode.Execute(Req, Resp); finally { Clear Outbound headers } FHeadersOutBound.Clear; end; { Assume the response is the SOAP Envelope in XML format. NOTE: In case of attachments, this could actually be a Multipart/Related response } RespXML := Resp; XMLStream := TMemoryStream.Create; try { This allows the handler to see the whole packet - i.e. attachments too } DoAfterExecute(MethMD.Name, Resp); {$IFDEF ATTACHMENT_SUPPORT} { If we're expecting MIME parts, process 'em } if FWebNode.MimeBoundary <> '' then begin AttachHandler.ProcessMultiPartForm(Resp, XMLStream, FWebNode.MimeBoundary, nil, FConverter.Attachments, FConverter.TempDir); { Now point RespXML to Envelope } RespXML := XMLStream; end; {$ENDIF} FConverter.ProcessResponse(RespXML, IntfMD, MethMD, Context, FHeadersInbound); finally XMLStream.Free; end; finally Resp.Free; end; finally FConverter.Attachments.Clear; end; finally Req.Free; end; end; function TRIO._AddRef: Integer; begin Result := TInterlocked.Increment(FRefCount); end; function TRIO._Release: Integer; begin Result := TInterlocked.Decrement(FRefCount); if (Result = 0) and not (Owner is TComponent) then Destroy; end; function TRIO.InternalQI(const IID: TGUID; out Obj): HResult; begin Result := E_NOINTERFACE; { ISoap Headers } if IID = ISoapHeaders then if FSOAPHeaders.GetInterface(IID, Obj) then Result := 0; { IInterface, IRIOAccess } if (IID = IInterface) or (IID = IRIOAccess) then if GetInterface(IID, Obj) then Result := 0; { NOTE: Are there other interfaces that we would want to QI the RIOVirtualInterface for? } if (Result <> 0) and (FInterface <> nil) and (IID = FIID) then Result := TRIOVirtualInterface(Pointer(FInterface)).QueryInterface(IID, Obj); end; function TRIO.QueryInterface(const IID: TGUID; out Obj): HResult; var InvokeOptions: TIntfInvokeOptions; PInfo: Pointer; begin if FInterface = nil then begin PInfo := InvRegistry.GetInterfaceTypeInfo(IID); if PInfo <> nil then try Pointer(FInterface) := TRioVirtualInterface.Create(Self, PInfo); TRIOVirtualInterface(Pointer(FInterface)).OnInvoke := Generic; GetIntfMetaData(PInfo, IntfMD, True); FIID := IID; except TRIOVirtualInterface(Pointer(FInterface)).Free; Pointer(FInterface) := nil; end; end; Result := InternalQI(IID, Obj); { Here we override the Converter Options based on Invoke Options registered for this particular interface } if (Result = 0) and (FConverter <> nil) then begin InvokeOptions := InvRegistry.GetIntfInvokeOptions(IID); { Encode or passing document-style? } if ioDocument in InvokeOptions then FConverter.Options := FConverter.Options + [soDocument] else FConverter.Options := FConverter.Options - [soDocument]; { And did we unwind or do we have literal parameters? } if ioLiteral in InvokeOptions then FConverter.Options := FConverter.Options + [soLiteralParams] else FConverter.Options := FConverter.Options - [soLiteralParams]; { Are we to use v1.2 of SOAP } if ioSOAP12 in InvokeOptions then begin FConverter.Options := FConverter.Options + [soSOAP12]; FWebNode.Options := FWebNode.Options + [wnoSOAP12]; end else begin FConverter.Options := FConverter.Options - [soSOAP12]; FWebNode.Options := FWebNode.Options - [wnoSOAP12]; end; end; end; { TRIO.TRioVirtualInterface } constructor TRIO.TRioVirtualInterface.Create(ARio: TRio; AInterface: Pointer); begin FRio := ARio; inherited Create(AInterface); end; function TRIO.TRioVirtualInterface.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin Result := inherited; if Result <> 0 then Result := FRio.InternalQI(IID, Obj); end; function TRIO.TRioVirtualInterface._AddRef: Integer; begin Result := FRio._AddRef; end; function TRIO.TRioVirtualInterface._Release: Integer; begin Result := FRio._Release; end; procedure TRio.Generic(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue); var MethMD: TIntfMethEntry; I: Integer; MethNum: Integer; Context: TInvContext; begin if not Assigned(FConverter) then raise Exception.Create(SNoMessageConverter); if not Assigned(FWebNode) then raise Exception.Create(SNoMsgProcessingNode); Context := TInvContext.Create; try MethNum := 0; for I := 0 to Length(Intfmd.MDA) do if intfMD.MDA[I].Pos = method.VirtualIndex then begin MethNum := I; MethMD := IntfMD.MDA[I]; Context.SetMethodInfo(MethMD); break; end; for I := 1 to methmd.ParamCount do Context.SetParamPointer(I-1, Args[I].GetReferenceToRawData); if Assigned(MethMd.ResultInfo) then begin TValue.Make(nil, MethMD.ResultInfo, Result); Context.SetResultPointer(Result.GetReferenceToRawData); end else Context.SetResultPointer(nil); DoDispatch(Context, MethNum, MethMD); finally Context.Free; end; end; end.
unit SimpleInterface; interface uses System.Classes, System.Generics.Collections, Data.DB, System.TypInfo, {$IFNDEF CONSOLE} {$IFDEF FMX} FMX.Forms, {$ELSE} Vcl.Forms, {$ENDIF} {$ENDIF} System.SysUtils; type iSimpleDAOSQLAttribute<T : class> = interface; iSimpleDAO<T : class> = interface ['{19261B52-6122-4C41-9DDE-D3A1247CC461}'] {$IFNDEF CONSOLE} function Insert: iSimpleDAO<T>; overload; function Update : iSimpleDAO<T>; overload; function Delete : iSimpleDAO<T>; overload; {$ENDIF} function Insert(aValue : T) : iSimpleDAO<T>; overload; function Update(aValue : T) : iSimpleDAO<T>; overload; function Delete(aValue : T) : iSimpleDAO<T>; overload; function LastID : iSimpleDAO<T>; function LastRecord : iSimpleDAO<T>; function Delete(aField : String; aValue : String) : iSimpleDAO<T>; overload; function DataSource( aDataSource : TDataSource) : iSimpleDAO<T>; function Find(aBindList : Boolean = True) : iSimpleDAO<T>; overload; function Find(var aList : TObjectList<T>) : iSimpleDAO<T> ; overload; function Find(aId : Integer) : T; overload; function Find(aKey : String; aValue : Variant) : iSimpleDAO<T>; overload; function SQL : iSimpleDAOSQLAttribute<T>; {$IFNDEF CONSOLE} function BindForm(aForm : TForm) : iSimpleDAO<T>; {$ENDIF} end; iSimpleDAOSQLAttribute<T : class> = interface ['{5DE6F977-336B-4142-ABD1-EB0173FFF71F}'] function Fields (aSQL : String) : iSimpleDAOSQLAttribute<T>; overload; function Where (aSQL : String) : iSimpleDAOSQLAttribute<T>; overload; function OrderBy (aSQL : String) : iSimpleDAOSQLAttribute<T>; overload; function GroupBy (aSQL : String) : iSimpleDAOSQLAttribute<T>; overload; function Join (aSQL : String) : iSimpleDAOSQLAttribute<T>; overload; function Join : String; overload; function Fields : String; overload; function Where : String; overload; function OrderBy : String; overload; function GroupBy : String; overload; function Clear : iSimpleDAOSQLAttribute<T>; function &End : iSimpleDAO<T>; end; iSimpleRTTI<T : class> = interface ['{EEC49F47-24AC-4D82-9BEE-C259330A8993}'] function TableName(var aTableName: String): ISimpleRTTI<T>; function ClassName (var aClassName : String) : iSimpleRTTI<T>; function DictionaryFields(var aDictionary : TDictionary<string, variant>) : iSimpleRTTI<T>; function ListFields (var List : TList<String>) : iSimpleRTTI<T>; function Update (var aUpdate : String) : iSimpleRTTI<T>; function Where (var aWhere : String) : iSimpleRTTI<T>; function Fields (var aFields : String) : iSimpleRTTI<T>; function FieldsInsert (var aFields : String) : iSimpleRTTI<T>; function Param (var aParam : String) : iSimpleRTTI<T>; function DataSetToEntityList (aDataSet : TDataSet; var aList : TObjectList<T>) : iSimpleRTTI<T>; function DataSetToEntity (aDataSet : TDataSet; var aEntity : T) : iSimpleRTTI<T>; function PrimaryKey(var aPK : String) : iSimpleRTTI<T>; {$IFNDEF CONSOLE} function BindClassToForm (aForm : TForm; const aEntity : T) : iSimpleRTTI<T>; function BindFormToClass (aForm : TForm; var aEntity : T) : iSimpleRTTI<T>; {$ENDIF} end; iSimpleSQL<T> = interface ['{1590A7C6-6E32-4579-9E60-38C966C1EB49}'] function Insert (var aSQL : String) : iSimpleSQL<T>; function Update (var aSQL : String) : iSimpleSQL<T>; function Delete (var aSQL : String) : iSimpleSQL<T>; function Select (var aSQL : String) : iSimpleSQL<T>; function SelectId(var aSQL: String): iSimpleSQL<T>; function Fields (aSQL : String) : iSimpleSQL<T>; function Where (aSQL : String) : iSimpleSQL<T>; function OrderBy (aSQL : String) : iSimpleSQL<T>; function GroupBy (aSQL : String) : iSimpleSQL<T>; function Join (aSQL : String) : iSimpleSQL<T>; function LastID (var aSQL : String) : iSimpleSQL<T>; function LastRecord (var aSQL : String) : iSimpleSQL<T>; end; iSimpleQuery = interface ['{6DCCA942-736D-4C66-AC9B-94151F14853A}'] function SQL : TStrings; function Params : TParams; function ExecSQL : iSimpleQuery; function DataSet : TDataSet; function Open(aSQL : String) : iSimpleQuery; overload; function Open : iSimpleQuery; overload; end; implementation end.
{ Main configuration form implemetation. See Simulator.dpr comments to uderstand how to interact with it. LICENSE: Copyright 2015-2021 Michal Petrilak, Jan Horacek 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 fConfig; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, IniFiles, Menus, StdCtrls, Spin; const _DEFAULT_CFG_FILE = 'rcs/simcfg.ini'; // Config file. Change MTB ranges to make form more synoptic. _MAX_MTB = 255; _PINS = 16; type TMyEvent = function(Sender: TObject): Integer of object; stdcall; TMyErrorEvent = function(Sender: TObject; errValue: word; errAddr: Cardinal; errStr: string) : Integer of object; stdcall; // Simulation status: TSimulatorStatus = (closed = 0, opening = 1, closing = 2, stopped = 3, starting = 4, running = 5, stopping = 6); TRCSIPortType = (iptPlain = 0, iptIR = 1); TRCSOPortType = (optPlain = 0, optSCom = 1); TModule = record name: string; typ: string; fw: string; exists: boolean; failure: boolean; irs: Cardinal; scoms: Cardinal; warning: boolean; error: boolean; end; TFormConfig = class(TForm) T_flick: TTimer; procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure T_flickTimer(Sender: TObject); private present: array [0 .. _MAX_MTB] of boolean; Cfgbtn: array [0 .. _MAX_MTB] of TButton; // configuration buttons pin: Array [0 .. _MAX_MTB, 0 .. _PINS - 1] of TShape; // pins (= ports) fstatus: TSimulatorStatus; // simulation status procedure ChangeInput(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ShowAddress(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure CfgBtnOnClick(Sender: TObject); procedure CfgBtnOnMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SetStatus(new: TSimulatorStatus); public config_fn: string; flick: Boolean; procedure RePaintPins(); procedure RePaintPin(module, port: Cardinal); procedure LoadData(filename: string); procedure SaveData(filename: string); procedure CreatePins(); procedure FreePins(); procedure OnOpen(Sender: TObject); procedure OnClose(Sender: TObject); procedure OnStart(Sender: TObject); procedure OnStop(Sender: TObject); procedure OnScanned(Sender: TObject); property Status: TSimulatorStatus read fstatus write SetStatus; end; var FormConfig: TFormConfig; var inputs: Array [0 .. _MAX_MTB, 0 .. _PINS - 1] of Integer; // input states outputs: Array [0 .. _MAX_MTB, 0 .. _PINS - 1] of Integer; // output states modules: array [0 .. _MAX_MTB] of TModule; // modules config api_version: Cardinal; implementation uses Board, LibraryEvents, version; {$R *.dfm} procedure TFormConfig.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin CanClose := false; Self.Hide(); end; procedure TFormConfig.FormCreate(Sender: TObject); begin for var i := 0 to _MAX_MTB do Self.present[i] := false; Self.config_fn := _DEFAULT_CFG_FILE; try Self.LoadData(Self.config_fn); except end; Self.CreatePins(); Self.Status := TSimulatorStatus.closed; Self.Caption := 'RCS Simulator v' + VersionStr(GetModuleName(HInstance)); end; procedure TFormConfig.FormDestroy(Sender: TObject); begin try Self.SaveData(Self.config_fn); Self.FreePins(); except end; end; procedure TFormConfig.CreatePins(); var i, port: Cardinal; begin i := 0; for var module := 0 to _MAX_MTB do begin if (not present[module]) then begin Cfgbtn[module] := nil; for port := 0 to _PINS - 1 do pin[module, port] := nil; continue; end; Cfgbtn[module] := TButton.Create(FormConfig); with (Cfgbtn[module]) do begin Parent := FormConfig; Top := 5; Left := i * 15 + 5; Caption := '?'; Height := 25; Width := 13; Tag := module; OnClick := Self.CfgBtnOnClick; OnMouseMove := Self.CfgBtnOnMove; end; for port := 0 to _PINS - 1 do begin pin[module, port] := TShape.Create(FormConfig); with pin[module, port] do begin Parent := FormConfig; Left := i * 15 + 5; Top := port * 15 + 35; Width := 13; Height := 13; Pen.Width := 2; Tag := _PINS * module + port; ShowHint := true; Hint := IntToStr(module) + ':' + IntToStr(port) + ' : 0'; OnMouseUp := ChangeInput; OnMouseMove := ShowAddress; end; end; Inc(i); end; Self.RePaintPins(); Self.ClientWidth := (i * 15) + 8; Self.ClientHeight := (_PINS * 15) + 40; end; procedure TFormConfig.FreePins(); begin for var i := 0 to _MAX_MTB do begin present[i] := false; if (Assigned(Self.Cfgbtn[i])) then FreeAndNil(Self.Cfgbtn[i]); for var j := 0 to _PINS - 1 do if (Assigned(Self.pin[i, j])) then FreeAndNil(Self.pin[i, j]); end; end; procedure TFormConfig.ChangeInput(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var module, port: Integer; begin module := (Sender as TShape).Tag div _PINS; port := (Sender as TShape).Tag mod _PINS; inputs[module, port] := inputs[module, port] XOR 1; RePaintPin(module, port); if (Assigned(LibEvents.OnInputChanged.event)) then LibEvents.OnInputChanged.event(Self, LibEvents.OnInputChanged.data, module); end; procedure TFormConfig.RePaintPins(); begin for var module := 0 to _MAX_MTB do begin if (not present[module]) then continue; for var port := 0 to _PINS - 1 do Self.RePaintPin(module, port); end; end; procedure TFormConfig.RePaintPin(module, port: Cardinal); begin if (not present[module]) then Exit(); var sh := pin[module, port]; if ((modules[module].irs shr port) and $1 > 0) then sh.Pen.Color := clFuchsia * inputs[module, port] else sh.Pen.Color := clRed * inputs[module, port]; if ((modules[module].scoms shr port) and $1 > 0) then begin sh.Brush.Color := clAqua * Integer(outputs[module, port] > 0); end else begin sh.Brush.Color := clLime * Integer((outputs[module, port] > 0) and ((outputs[module, port] <= 1) or (flick))); end; sh.Hint := IntToStr(module) + ':' + IntToStr(port) + ' : ' + IntToStr(outputs[module, port]); end; procedure TFormConfig.ShowAddress(Sender: TObject; Shift: TShiftState; X, Y: Integer); var module, port: Integer; begin module := (Sender as TShape).Tag div _PINS; port := (Sender as TShape).Tag mod _PINS; Caption := Format('%.3d / %.3d', [module, port]) end; procedure TFormConfig.T_flickTimer(Sender: TObject); begin Self.flick := not Self.flick; Self.RePaintPins(); end; procedure TFormConfig.LoadData(filename: string); var Ini: TMemIniFile; ranges_str, range_str: string; ranges, range: TStrings; begin Ini := TMemIniFile.Create(filename, TEncoding.UTF8); ranges := TStringList.Create(); range := TStringList.Create(); try ranges_str := Ini.ReadString('MTB', 'ranges', ''); if (ranges_str = '') then begin // backward compatibility ranges_str := Ini.ReadString('MTB', 'start', '0') + '-' + Ini.ReadString('MTB', 'end', '0'); if (ranges_str = '0-0') then ranges_str := '0-31'; end; ExtractStrings([','], [], PChar(ranges_str), ranges); for range_str in ranges do begin range.Clear(); ExtractStrings(['-'], [], PChar(range_str), range); if (range.Count = 1) then present[StrToInt(range[0])] := true else if (range.Count = 2) then begin var start := StrToInt(range[0]); if (start < 0) then start := 0; if (start > _MAX_MTB) then start := _MAX_MTB; var finish := StrToInt(range[1]); if (finish < 0) then finish := 0; if (finish > _MAX_MTB) then finish := _MAX_MTB; for var i := start to finish do present[i] := true; end; end; for var i := 0 to _MAX_MTB do begin modules[i].name := Ini.ReadString('MTB' + IntToStr(i), 'name', 'Simulator' + IntToStr(i)); modules[i].typ := Ini.ReadString('MTB' + IntToStr(i), 'typ', 'MTB-UNI'); modules[i].fw := Ini.ReadString('MTB' + IntToStr(i), 'fw', 'VIRTUAL'); modules[i].exists := Ini.ReadBool('MTB' + IntToStr(i), 'is', present[i]); modules[i].irs := Ini.ReadInteger('MTB' + IntToStr(i), 'irs', 0); modules[i].scoms := Ini.ReadInteger('MTB' + IntToStr(i), 'scoms', 0); end; finally Ini.Free(); ranges.Free(); range.Free(); end; end; // function procedure TFormConfig.SaveData(filename: string); begin var Ini := TMemIniFile.Create(filename, TEncoding.UTF8); try for var i := 0 to _MAX_MTB do begin ini.EraseSection('MTB' + IntToStr(i)); if (modules[i].name <> '') and (modules[i].name <> 'Simulator' + IntToStr(i)) then Ini.WriteString('MTB' + IntToStr(i), 'name', modules[i].name); if ((modules[i].typ <> 'MTB-UNI') or (modules[i].exists)) then Ini.WriteString('MTB' + IntToStr(i), 'typ', modules[i].typ); if (modules[i].fw <> 'VIRTUAL') then Ini.WriteString('MTB' + IntToStr(i), 'fw', modules[i].fw); if (modules[i].exists) then Ini.WriteBool('MTB' + IntToStr(i), 'is', modules[i].exists); if (modules[i].irs > 0) then Ini.WriteInteger('MTB' + IntToStr(i), 'irs', modules[i].irs); if (modules[i].scoms > 0) then Ini.WriteInteger('MTB' + IntToStr(i), 'scoms', modules[i].scoms); end; finally Ini.UpdateFile(); Ini.Free(); end; end; procedure TFormConfig.CfgBtnOnClick(Sender: TObject); begin F_Board.OpenForm((Sender as TButton).Tag); end; procedure TFormConfig.CfgBtnOnMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Caption := Format('%.3d', [(Sender as TButton).Tag]); end; procedure TFormConfig.SetStatus(new: TSimulatorStatus); begin case (new) of TSimulatorStatus.closed: Self.Caption := 'Closed'; TSimulatorStatus.opening: Self.Caption := 'Opening...'; TSimulatorStatus.stopped: Self.Caption := 'Openned, stopped'; TSimulatorStatus.starting: Self.Caption := 'Starting...'; TSimulatorStatus.running: Self.Caption := 'Running'; TSimulatorStatus.stopping: Self.Caption := 'Stopping...'; TSimulatorStatus.closing: Self.Caption := 'Closing...'; end; // case Self.fstatus := new; end; /// ///////////////////////////////////////////////////////////////////////////// // events from simulator timer: procedure TFormConfig.OnOpen(Sender: TObject); begin (Sender as TTimer).Enabled := false; Status := TSimulatorStatus.stopped; if (Assigned(LibEvents.AfterOpen.event)) then LibEvents.AfterOpen.event(FormConfig, LibEvents.AfterOpen.data); end; procedure TFormConfig.OnClose(Sender: TObject); begin (Sender as TTimer).Enabled := false; Status := TSimulatorStatus.closed; if (Assigned(LibEvents.AfterClose.event)) then LibEvents.AfterClose.event(FormConfig, LibEvents.AfterClose.data); end; procedure TFormConfig.OnStart(Sender: TObject); begin Status := TSimulatorStatus.running; if (Assigned(LibEvents.AfterStart.event)) then LibEvents.AfterStart.event(FormConfig, LibEvents.AfterStart.data); (Sender as TTimer).Interval := 500; (Sender as TTimer).OnTimer := Self.OnScanned; end; procedure TFormConfig.OnStop(Sender: TObject); begin (Sender as TTimer).Enabled := false; Status := TSimulatorStatus.stopped; if (Assigned(LibEvents.AfterStop.event)) then LibEvents.AfterStop.event(FormConfig, LibEvents.AfterStop.data); end; procedure TFormConfig.OnScanned(Sender: TObject); begin (Sender as TTimer).Enabled := false; if (Assigned(LibEvents.OnScanned.event)) then LibEvents.OnScanned.event(FormConfig, LibEvents.OnScanned.data); end; /// ///////////////////////////////////////////////////////////////////////////// initialization finalization FreeAndNil(FormConfig); end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus, Grids; type { TForm1 } TForm1 = class(TForm) MainMenu1: TMainMenu; MenuItem1: TMenuItem; MenuItem10: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; StringGrid1: TStringGrid; procedure FormCreate(Sender: TObject); procedure MenuItem10Click(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuItem3Click(Sender: TObject); procedure MenuItem4Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure MenuItem6Click(Sender: TObject); procedure MenuItem7Click(Sender: TObject); procedure MenuItem9Click(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} // Наши собственные типы данных, используемые в приложении Type // тип для отдельно взятого студена Stud = Record No : integer; // Номер (его ID) Name : string[12]; // Имя Gr : string[8]; // Группа o1,o2,o3 : integer; // Оценки end; // Глобальные переменные var sf: string; // Спецификация файла - его полное имя //Собственные процедуры и функции {Параметры таблицы по умолчанию} procedure TabForFile; var i: integer; begin // Используем менеджер контекста для сокращения, // чтобы слишком часто не писать длинную строчку для доступа к атрибуту // По типу Form1.Stringgrid1.attr, как бы считаем что мы внутри StringGrid1 // И Можем не указывать полное имя, чтобы поменять что-то внутри with Form1.StringGrid1 do begin ColCount := 6; // Число столбцов для (1)номера, (2)имени, (3)групы и (4-6)оценок одного студента RowCount := 50; // Количество строк // Устанавливаем ширину отдельных ячеек, т.к. для, например, имени и оценки нужно разное число полей // Столбцы (как почти и всё) нумеруются с нуля!!! ColWidths[0] := 20; // на Номер студента 20 пикселей ColWidths[1] := 120; // на Фамилию - 120 ColWidths[2] := 80; // Группа ColWidths[3] := 40; // Маленкое поле для Оценки 1 ColWidths[4] := 40; // Оц 2 ColWidths[5] := 40; // Оц 3 // Заполняем заголовок нашей таблицы Cells[0,0] := '№'; Cells[1,0] := 'Фамилия'; Cells[2,0] := 'Группа'; Cells[3,0] := 'Оц 1'; Cells[4,0] := 'Оц 2'; Cells[5,0] := 'Оц 3'; // Теперь устанавливаем ширину всей таблицы width := 25; // дополнительные 25 пикселей на полосу прокрути и прочее for i:=0 to ColCount-1 do width:= width + ColWidths[i]; // Прибавляем ширину i-го столбца к общей ширине таблицы end; end; {Процедура очищения таблицы (без заголовка)} // StringGrid1.Clean - очищает всю таблицу // Процедура НЕОБЯЗАТЕЛЬНАЯ, можно спокойно писать каждый раз TabForFile - // Устанавливать параметры таблицы по умолчанию Procedure ClearTab; var i, j: integer; begin with Form1.StringGrid1 do // Перебираем все строки кроме заголока(i=0) for i:= 1 to RowCount -1 do // Не имеет смысла очищать строку если она пустая if (CellS[0,i] <>'') then // Перебираем все столбцы for j:=0 to ColCount-1 do Cells[j,i] :=''; // 'обнуляем'нужные ячейки end; {Сохранить данные о студентах в файл} procedure SaveToFileOfStud; var f: file of stud; s: stud; // Переменная для СЧИТЫВАНИЯ ИЗ StringGrid1 одного студента и записи его в файл i: integer; begin // Здесь считаем что sf - не пустая строка, то есть имя файла уже задано // Стандартные действия по подготовке к ЗАПИСИ в файл AssignFile(f, sf); Rewrite(f); with Form1.StringGrid1 do // Перебираем строки // Причом начинаем с 1, тк на 0 месте строка ЗАГОЛОВКА for i:=1 to RowCount -1 do // Перебираем НЕ ПУСТЫЕ строки if CellS[0,i] <>'' then begin // Записываем в s нужные поля, кто он, где учится, как учится и тп s.No := StrToInt(Cells[0,i]); // Заполняем Номер студента s.Name := Cells[1,i]; // Получаем Фамилию студента s.Gr := Cells[2,i]; // Группа студента // Оценки s.o1 := StrToInt(Cells[3,i]); s.o2 := StrToInt(Cells[4,i]); s.o3 := StrToInt(Cells[5,i]); // Полученного студента записываем в файл write(f,s); end; // в самом конце закрываем файл CloseFile(f); end; {Загрузить данные о студентах в таблицу из файла} procedure LoadFromFileOfStud; var f: file of Stud; s: stud; // Переменная для ЗАПИСИ В StringGrid1 одного студента и считывания его из файла i: integer; begin // Сначала нужно очистить таблицу от предыдущих записей ClearTab; // Например если мы загрузим НОВЫЙ файл, число записей в котором МЕНЬШЕ // чем в ПРЕДЫДУЩИМ, то снизу останутся строки старого файла // А если мы ВПЕРВЫЕ открываем файл в табличном редакторе, то // функция ClearTab просто ничего не будет делать // Подготавливаем файл к ЧТЕНИЮ AssignFile(f, sf); Reset(f); with Form1.StringGrid1 do // Опять же начинаем с еденицы, чтобы не задеть заголовок for i:=1 to filesize(f) do begin // Считываем одного студента read(f,s); // И записываем данные о нём в таблицу Cells[0,i]:= IntToStr(s.No); // Его Номер Cells[1,i]:= s.Name; // Фамилия Cells[2,i]:= s.Gr; // Группа Cells[3,i]:= IntToStr(s.o1); Cells[4,i]:= IntToStr(s.o2); {И оценки} Cells[5,i]:= IntToStr(s.o3); end; // и в самом конце закрываем файл closefile(f); end; // Процедуры-Обработчики на форме { TForm1 } {Особые действия при открытии программы} procedure TForm1.FormCreate(Sender: TObject); begin TabForFile; // Устанавливаем параметры таблицы по умолчанию // Добавляем оциию редактирования содержимого таблицы StringGrid1.Options:=StringGrid1.Options + [goEditing]; StringGrid1.FixedCols:=0; //Чтобы можно было редактировать номера StringGrid1.Modified := False; sf := ''; // Никакого файла мы ещё не открывали // Каталоги для сохраненияи открытия по умочанию (Папка проекта) OpenDialog1.InitialDir:=''; SaveDialog1.InitialDir:=''; end; {Создать} procedure TForm1.MenuItem2Click(Sender: TObject); begin ClearTab; // Очищаем таблицу своей процедурой, что равносильно изменению Таблицы StringGrid1.Modified:= False; // Таблица не была изменена sf:=''; // А у файла нет ещё имени Form1.Caption:= 'Form1'; end; {Открыть} procedure TForm1.MenuItem3Click(Sender: TObject); begin // диалог сохранинея файла if StringGrid1.Modified then case MessageDlg('Текст был изменён' + #13 + 'Сохранить его?', mtConfirmation,[mbYes, mbNo, mbCancel],0) of mrYes : MenuItem5Click(self); // Сохраняем файл mrNo : ; // Ничего не делаем mrCancel: Exit; // выходим из процедуры {Открыть} end; // Если дилог открытия файла завершился нормально, // То есть его не закрыли и не нажали cancel // То есть юзер выбрал нужный ему файл и нажал ОК if openDialog1.Execute then begin sf:=OpenDialog1.FileName; // Извлекаем имя файла из этого диалога LoadFromFileOfStud; // Выводим его в StringGrid1 StringGrid1.Modified:=False; // Что равносильно его изменению, но мы же не изменяли файл Form1.Caption:='Form1 ' + sf; // В заголовок окна выводим имя файла end; end; {Закрыть} procedure TForm1.MenuItem4Click(Sender: TObject); begin // Стандартных диалог сохранения файла // Если таблица была изменена if StringGrid1.Modified then // Стандартное окно Сообщения case MessageDlg('Данные о студентах были изменены' + #13 + 'Сохранить их?', mtConfirmation,[mbYes, mbNo, mbCancel],0) of mrYes: MenuItem5Click(self); // Сохраняем файл mrNo:; // Ничего не делаем mrCancel: Exit; // Выходим из окна сообщения, и возвращаемся к редактированию таблицы(действия ниже выполняться не будут) end; // Если мы НЕ вишли через 'Cancel', то совершаем стандартные действия ClearTab; // Очищаем таблицу процедурой собственного производства и тд StringGrid1.Modified:= False; sf:=''; Form1.Caption:= 'Form1'; end; {Сохранить} procedure TForm1.MenuItem5Click(Sender: TObject); begin // Исли имя файла не задано то вызываем Окно {сохранить как} if sf = '' then MenuItem6Click(self) else // Иначе, то есть имя файла уже установлено begin SaveToFileOfStud; // Сразу сохраняем его на диск StringGrid1.Modified:= False; // Содержание устанавливаем не изменённым, тк сохранили всё на диск end; end; {Сохранить как} procedure TForm1.MenuItem6Click(Sender: TObject); begin // Если диалог сохранения прошёл хорошо if SaveDialog1.Execute then begin sf:= SaveDialog1.FileName; // Извлекаем имя файла SaveToFileOfStud; // Используя нашу процедуру, сохраняем содержимое таблицы в файл StringGrid1.Modified := False; // Содержимое в таблице соответсвует файлу на диске Form1.Caption:= 'Form1 ' + sf; // Устанавливаем заголовок приложения с именем файла end; end; {Выход} procedure TForm1.MenuItem7Click(Sender: TObject); begin // Сообщение: Сохранить ли именённый файл if StringGrid1.Modified then case MessageDlg('Таблица была изменена' + #13 + 'Сохранить её?', mtConfirmation,[mbYes, mbNo, mbCancel],0) of mrYes : MenuItem5Click(self); // Сохраняем изменения в файл mrNo : ; // Ничего не делаем mrCancel: Exit; // Возвращаемся к редактирования таблицы end; // Закрываем приложение Close; end; // Обработка {Обработка 1} procedure TForm1.MenuItem9Click(Sender: TObject); begin end; {Обработка 2} procedure TForm1.MenuItem10Click(Sender: TObject); begin end; end.
unit JSONUtils; interface uses System.JSON, Winapi.Windows; type IJSONUtils = interface ['{13E2E283-DC11-4B27-A936-51D72C20875E}'] procedure SetJSONProperty(const Value: TJSONPair); function getProperty(const AProperty, AJSON: string): IJSONUtils; function getChildProperty(const AParent, AProperty, AJSON: string): IJSONUtils; function getValue(): string; function getPair(): string; function formatJSON(const AJSON: string): IJSONUtils; function validateJSON(const AJSON: string): Boolean; procedure show(AHandle: HWND); property JSONProperty: TJSONPair write SetJSONProperty; end; TJSONUtils = class(TInterfacedObject, IJSONUtils) private FJSONProperty: TJSONPair; FJSON, FJSONPair: TJSONObject; FJSONArray: TJSONArray; FHTML: string; procedure SetJSONProperty(const Value: TJSONPair); public function getProperty(const AProperty, AJSON: string): IJSONUtils; function getChildProperty(const AParent, AProperty, AJSON: string): IJSONUtils; function getValue(): string; function getPair(): string; function formatJSON(const AJSON: string): IJSONUtils; procedure show(AHandle: HWND); class function new(): IJSONUtils; constructor Create; destructor Destroy(); override; function validateJSON(const AJSON: string): Boolean; property JSONProperty: TJSONPair write SetJSONProperty; end; implementation uses System.SysUtils, System.Classes, Vcl.Forms, Winapi.ShellAPI; { TJSONUtils } constructor TJSONUtils.Create; begin FJSON := TJSONObject.Create; FJSONPair := TJSONObject.Create; end; destructor TJSONUtils.Destroy; begin FreeAndNil(FJSON); FreeAndNil(FJSONPair); inherited; end; function TJSONUtils.formatJSON(const AJSON: string): IJSONUtils; var html: TStringBuilder; begin html := TStringBuilder.Create; try FHTML := html.append('<html>') .appendLine() .append('') .appendLine() .append('<head>') .appendLine() .Append('<title>JSON</title>') .appendLine() .append(' <script>') .appendLine() .append('') .appendLine() .append('') .appendLine() .append(' var module, window, define, renderjson = (function () {') .appendLine() .append(' var themetext = function (/* [class, text]+ */) {') .appendLine() .append(' var spans = [];') .appendLine() .append(' while (arguments.length)') .appendLine() .append(' spans.push(append(span(Array.prototype.shift.call(arguments)),') .appendLine() .append(' text(Array.prototype.shift.call(arguments))));') .appendLine() .append(' return spans;') .appendLine() .append(' };') .appendLine() .append(' var append = function (/* el, ... */) {') .appendLine() .append(' var el = Array.prototype.shift.call(arguments);') .appendLine() .append(' for (var a = 0; a < arguments.length; a++)') .appendLine() .append(' if (arguments[a].constructor == Array)') .appendLine() .append(' append.apply(this, [el].concat(arguments[a]));') .appendLine() .append(' else') .appendLine() .append(' el.appendChild(arguments[a]);') .appendLine() .append(' return el;') .appendLine() .append(' };') .appendLine() .append(' var prepend = function (el, child) {') .appendLine() .append(' el.insertBefore(child, el.firstChild);') .appendLine() .append(' return el;') .appendLine() .append(' }') .appendLine() .append(' var isempty = function (obj, pl) {') .appendLine() .append(' var keys = pl || Object.keys(obj);') .appendLine() .append(' for (var i in keys) if (Object.hasOwnProperty.call(obj, keys[i])) return false;') .appendLine() .append(' return true;') .appendLine() .append(' }') .appendLine() .append(' var text = function (txt) { return document.createTextNode(txt) };') .appendLine() .append(' var div = function () { return document.createElement("div") };') .appendLine() .append(' var span = function (classname) {') .appendLine() .append(' var s = document.createElement("span");') .appendLine() .append(' if (classname) s.className = classname;') .appendLine() .append(' return s;') .appendLine() .append(' };') .appendLine() .append(' var A = function A(txt, classname, callback) {') .appendLine() .append(' var a = document.createElement("a");') .appendLine() .append(' if (classname) a.className = classname;') .appendLine() .append(' a.appendChild(text(txt));') .appendLine() .append(' a.href = ''#'';') .appendLine() .append(' a.onclick = function (e) { callback(); if (e) e.stopPropagation(); return false; };') .appendLine() .append(' return a;') .appendLine() .append(' };') .appendLine() .append('') .appendLine() .append(' function _renderjson(json, indent, dont_indent, show_level, options) {') .appendLine() .append(' var my_indent = dont_indent ? "" : indent;') .appendLine() .append('') .appendLine() .append(' var disclosure = function (open, placeholder, close, type, builder) {') .appendLine() .append(' var content;') .appendLine() .append(' var empty = span(type);') .appendLine() .append(' var show = function () {') .appendLine() .append(' if (!content) append(empty.parentNode,') .appendLine() .append(' content = prepend(builder(),') .appendLine() .append(' A(options.hide, "disclosure",') .appendLine() .append(' function () {') .appendLine() .append(' content.style.display = "none";') .appendLine() .append(' empty.style.display = "inline";') .appendLine() .append(' })));') .appendLine() .append(' content.style.display = "inline";') .appendLine() .append(' empty.style.display = "none";') .appendLine() .append(' };') .appendLine() .append(' append(empty,') .appendLine() .append(' A(options.show, "disclosure", show),') .appendLine() .append(' themetext(type + " syntax", open),') .appendLine() .append(' A(placeholder, null, show),') .appendLine() .append(' themetext(type + " syntax", close));') .appendLine() .append('') .appendLine() .append(' var el = append(span(), text(my_indent.slice(0, -1)), empty);') .appendLine() .append(' if (show_level > 0 && type != "string")') .appendLine() .append(' show();') .appendLine() .append(' return el;') .appendLine() .append(' };') .appendLine() .append('') .appendLine() .append(' if (json === null) return themetext(null, my_indent, "keyword", "null");') .appendLine() .append(' if (json === void 0) return themetext(null, my_indent, "keyword", "undefined");') .appendLine() .append('') .appendLine() .append(' if (typeof (json) == "string" && json.length > options.max_string_length)') .appendLine() .append(' return disclosure(''"'', json.substr(0, options.max_string_length) + " ...", ''"'', "string", function () {') .appendLine() .append(' return append(span("string"), themetext(null, my_indent, "string", JSON.stringify(json)));') .appendLine() .append(' });') .appendLine() .append('') .appendLine() .append(' if (typeof (json) != "object" || [Number, String, Boolean, Date].indexOf(json.constructor) >= 0) // Strings, numbers and bools') .appendLine() .append(' return themetext(null, my_indent, typeof (json), JSON.stringify(json));') .appendLine() .append('') .appendLine() .append(' if (json.constructor == Array) {') .appendLine() .append(' if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]");') .appendLine() .append('') .appendLine() .append(' return disclosure("[", options.collapse_msg(json.length), "]", "array", function () {') .appendLine() .append(' var as = append(span("array"), themetext("array syntax", "[", null, "\n"));') .appendLine() .append(' for (var i = 0; i < json.length; i++)') .appendLine() .append(' append(as,') .appendLine() .append(' _renderjson(options.replacer.call(json, i, json[i]), indent + " ", false, show_level - 1, options),') .appendLine() .append(' i != json.length - 1 ? themetext("syntax", ",") : [],') .appendLine() .append(' text("\n"));') .appendLine() .append(' append(as, themetext(null, indent, "array syntax", "]"));') .appendLine() .append(' return as;') .appendLine() .append(' });') .appendLine() .append(' }') .appendLine() .append('') .appendLine() .append(' // object') .appendLine() .append(' if (isempty(json, options.property_list))') .appendLine() .append(' return themetext(null, my_indent, "object syntax", "{}");') .appendLine() .append('') .appendLine() .append(' return disclosure("{", options.collapse_msg(Object.keys(json).length), "}", "object", function () {') .appendLine() .append(' var os = append(span("object"), themetext("object syntax", "{", null, "\n"));') .appendLine() .append(' for (var k in json) var last = k;') .appendLine() .append(' var keys = options.property_list || Object.keys(json);') .appendLine() .append(' if (options.sort_objects)') .appendLine() .append(' keys = keys.sort();') .appendLine() .append(' for (var i in keys) {') .appendLine() .append(' var k = keys[i];') .appendLine() .append(' if (!(k in json)) continue;') .appendLine() .append(' append(os, themetext(null, indent + " ", "key", ''"'' + k + ''"'', "object syntax", '': ''),') .appendLine() .append(' _renderjson(options.replacer.call(json, k, json[k]), indent + " ", true, show_level - 1, options),') .appendLine() .append(' k != last ? themetext("syntax", ",") : [],') .appendLine() .append(' text("\n"));') .appendLine() .append(' }') .appendLine() .append(' append(os, themetext(null, indent, "object syntax", "}"));') .appendLine() .append(' return os;') .appendLine() .append(' });') .appendLine() .append(' }') .appendLine() .append('') .appendLine() .append(' var renderjson = function renderjson(json) {') .appendLine() .append(' var options = new Object(renderjson.options);') .appendLine() .append(' options.replacer = typeof (options.replacer) == "function" ? options.replacer : function (k, v) { return v; };') .appendLine() .append(' var pre = append(document.createElement("pre"), _renderjson(json, "", false, options.show_to_level, options));') .appendLine() .append(' pre.className = "renderjson";') .appendLine() .append(' return pre;') .appendLine() .append(' }') .appendLine() .append(' renderjson.set_icons = function (show, hide) {') .appendLine() .append(' renderjson.options.show = show;') .appendLine() .append(' renderjson.options.hide = hide;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' renderjson.set_show_to_level = function (level) {') .appendLine() .append(' renderjson.options.show_to_level = typeof level == "string" &&') .appendLine() .append(' level.toLowerCase() === "all" ? Number.MAX_VALUE') .appendLine() .append(' : level;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' renderjson.set_max_string_length = function (length) {') .appendLine() .append(' renderjson.options.max_string_length = typeof length == "string" &&') .appendLine() .append(' length.toLowerCase() === "none" ? Number.MAX_VALUE') .appendLine() .append(' : length;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' renderjson.set_sort_objects = function (sort_bool) {') .appendLine() .append(' renderjson.options.sort_objects = sort_bool;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' renderjson.set_replacer = function (replacer) {') .appendLine() .append(' renderjson.options.replacer = replacer;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' renderjson.set_collapse_msg = function (collapse_msg) {') .appendLine() .append(' renderjson.options.collapse_msg = collapse_msg;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' renderjson.set_property_list = function (prop_list) {') .appendLine() .append(' renderjson.options.property_list = prop_list;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' // Backwards compatiblity. Use set_show_to_level() for new code.') .appendLine() .append(' renderjson.set_show_by_default = function (show) {') .appendLine() .append(' renderjson.options.show_to_level = show ? Number.MAX_VALUE : 0;') .appendLine() .append(' return renderjson;') .appendLine() .append(' };') .appendLine() .append(' renderjson.options = {};') .appendLine() .append(' renderjson.set_icons(''+'', ''-'');') .appendLine() .append(' renderjson.set_show_by_default(false);') .appendLine() .append(' renderjson.set_sort_objects(false);') .appendLine() .append(' renderjson.set_max_string_length("none");') .appendLine() .append(' renderjson.set_replacer(void 0);') .appendLine() .append(' renderjson.set_property_list(void 0);') .appendLine() .append(' renderjson.set_collapse_msg(function (len) { return len + " item" + (len == 1 ? "" : "s") })') .appendLine() .append(' return renderjson;') .appendLine() .append(' })();') .appendLine() .append('') .appendLine() .append(' if (define) define({ renderjson: renderjson })') .appendLine() .append(' else (module || {}).exports = (window || {}).renderjson = renderjson; ') .appendLine() .append(' </script>') .appendLine() .append('') .appendLine() .append(' <style>') .appendLine() .append(' body {') .appendLine() .append(' background-color: #303030; ') .appendLine() .append(' }') .appendLine() .append(' .renderjson a { text-decoration: none; color: pink}') .appendLine() .append(' .renderjson .disclosure { color: crimson;') .appendLine() .append(' font-size: 15px; }') .appendLine() .append(' .renderjson .syntax { color: grey; }') .appendLine() .append(' .renderjson .string { color: red; }') .appendLine() .append(' .renderjson .number { color: cyan; }') .appendLine() .append(' .renderjson .boolean { color: plum; }') .appendLine() .append(' .renderjson .key { color: lightblue; }') .appendLine() .append(' .renderjson .keyword { color: lightgoldenrodyellow; }') .appendLine() .append(' .renderjson .object.syntax { color: lightseagreen; }') .appendLine() .append(' .renderjson .array.syntax { color: lightsalmon; }') .appendLine() .append(' </style>') .appendLine() .append('</head>') .appendLine() .append('') .appendLine() .append('<body>') .appendLine() .append(' <div id="json"></div>') .appendLine() .append(' <script>') .appendLine() .append(' renderjson.set_show_to_level(4);') .appendLine() .append(' renderjson.set_icons(''+'', ''-'');') .appendLine() .append(' document.getElementById("json")') .appendLine() .append(' .appendChild(') .appendLine() .append(' renderjson(') .appendLine() .append(' %s') .appendLine() .append(' )') .appendLine() .append(' );') .appendLine() .append(' </script>') .appendLine() .append('</body>') .appendLine() .append('') .appendLine() .append('</html>') .Replace('%s', AJSON).ToString; Result := Self; finally FreeAndNil(html); end; end; function TJSONUtils.getChildProperty(const AParent, AProperty, AJSON: string): IJSONUtils; begin FJSON.Parse(BytesOf(AJSON), 0); FJSONArray := (FJSON.Get(AParent).JsonValue as TJSONArray); FJSONPair.Parse(BytesOf(FJSONArray.Items[0].ToJSON), 0); Result := getProperty(AProperty, FJSONPair.ToString); end; function TJSONUtils.getProperty(const AProperty, AJSON: string): IJSONUtils; begin FJSON.Parse(BytesOf(UTF8Encode(AJSON)), 0); if Assigned(FJSON.Get(AProperty)) then FJSONProperty := FJSON.get(AProperty); Result := Self; end; class function TJSONUtils.new: IJSONUtils; begin Result := Self.Create; end; procedure TJSONUtils.SetJSONProperty(const Value: TJSONPair); begin FJSONProperty := Value; end; procedure TJSONUtils.show(AHandle: HWND); var json: TStringList; path, fileHTML: string; begin json := TStringList.Create; try path := ExtractFilePath(Application.ExeName); fileHTML := path + 'json.html'; json.Text := FHTML; json.SaveToFile(fileHTML); ShellExecute(AHandle, 'open', PChar(fileHTML), nil, nil, SW_SHOW); Sleep(10000); DeleteFile(fileHTML); finally FreeAndNil(json); end; end; function TJSONUtils.getValue(): string; begin if Assigned(FJSONProperty) then Result := FJSONProperty.JsonValue.ToString; end; function TJSONUtils.validateJSON(const AJSON: string): Boolean; begin try Result := FJSON.Parse(BytesOf(AJSON), 0) >= 0; except on E: EJSONException do raise Exception.Create(E.Message); end; end; function TJSONUtils.getPair(): string; begin if Assigned(FJSONProperty) then Result := FJSONProperty.ToJSON; end; end.
unit TDevRopcks.Util.Background; interface uses FMX.Objects, FMX.Types, System.UITypes, System.Classes; type TBackground = class private class var FBackground : TRectangle; FActionPosHide : TNotifyEvent; class procedure Click(Sender: TObject); public class procedure Show(AParent: TFMXObject; const AActionPosHide: TNotifyEvent = nil); class procedure Hide; end; implementation { TBackuground } class procedure TBackground.Click(Sender: TObject); begin if Assigned(FActionPosHide) then FActionPosHide(Sender); Hide; end; class procedure TBackground.Hide; begin if Assigned(FBackground) then begin FBackground.AnimateFloat('OPACITY', 0); FBackground.Visible := False; FBackground.DisposeOf; FBackground := nil; end; end; class procedure TBackground.Show(AParent: TFMXObject; const AActionPosHide: TNotifyEvent); begin FBackground := TRectangle.Create(nil); FBackground.Parent := AParent; //Application.MainForm; FBackground.Fill.Color := TAlphaColorRec.Black; FBackground.Opacity := 0.0; FBackground.Visible := True; FBackground.Align := TAlignLayout.Contents; if Assigned(AActionPosHide) then FActionPosHide := AActionPosHide; FBackground.OnClick := Click; FBackground.BringToFront; FBackground.AnimateFloat('OPACITY', 0.4); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileZLIB<p> <b>History : </b><font size=-1><ul> <li>04/02/15 - PW - Changed using GLSZLibEx to System.ZLib <li>22/08/10 - DaStr - Removed warnings, converted comments from Unicode to ASCII <li>04/06/10 - Yar - Added to GLScene (Created by Rustam Asmandiarov aka Predator) </ul><p> } unit GLFileZLIB; {$I GLScene.inc} interface uses System.Classes, System.SysUtils, System.ZLib, GLSArchiveManager; const SIGN = 'ZLIB'; //Signature for compressed zlib. Type TZLibHeader = record Signature: array[0..3] of AnsiChar; DirOffset: integer; DirLength: integer; end; TFileSection = record FileName: array[0..119] of AnsiChar; FilePos: integer; FileLength: integer; CbrMode: TCompressionLevel; end; { TZLibArchive } TZLibArchive=class(TBaseArchive) private FHeader: TZLibHeader; FStream: TFileStream; function GetContentCount: integer; procedure MakeContentList; public property ContentCount: integer Read GetContentCount; destructor Destroy; override; procedure LoadFromFile(const FileName: string); override; procedure Clear; override; function ContentExists(ContentName: string): boolean;override; function GetContent(aStream: TStream; index: integer): TStream; override; function GetContent(index: integer): TStream; override; function GetContent(ContentName: string): TStream; override; function GetContentSize(index: integer): integer; override; function GetContentSize(ContentName: string): integer; override; procedure AddFromStream(ContentName, Path: string; FS: TStream);override; procedure AddFromFile(FileName, Path: string); override; procedure RemoveContent(index: integer); overload; override; procedure RemoveContent(ContentName: string); overload;override; procedure Extract(index: integer; NewName: string); override; procedure Extract(ContentName, NewName: string); override; end; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- implementation //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- var Dir: TFileSection; { TZLibArchive } function TZLibArchive.GetContentCount: integer; begin Result := FHeader.DirLength div SizeOf(TFileSection); end; procedure TZLibArchive.MakeContentList; var I: integer; begin FStream.Seek(FHeader.DirOffset, soFromBeginning); FContentList.Clear; for i := 0 to ContentCount - 1 do begin FStream.ReadBuffer(Dir, SizeOf(TFileSection)); FContentList.Add(string(Dir.FileName)); end; end; destructor TZLibArchive.Destroy; begin inherited Destroy; end; procedure TZLibArchive.LoadFromFile(const FileName: string); begin FFileName := FileName; FStream := TFileStream.Create(FileName, fmOpenReadWrite or fmShareDenyWrite); if FStream.Size = 0 then begin FHeader.Signature := SIGN; FHeader.DirOffset := SizeOf(TZLibHeader); FHeader.DirLength := 0; FStream.WriteBuffer(FHeader, SizeOf(TZlibHeader)); FStream.Position := 0; end; FStream.ReadBuffer(FHeader, SizeOf(TZlibHeader)); if FHeader.Signature <> SIGN then begin FreeAndNil(FStream); // nil it too to avoid own Clear() giving AV raise Exception.Create(FileName+' - This is not ZLIB file'); Exit; end; if ContentCount <> 0 then MakeContentList; end; procedure TZLibArchive.Clear; begin FContentList.Clear; If FStream <> nil then FStream.Free; end; function TZLibArchive.ContentExists(ContentName: string): boolean; begin Result := (FContentList.IndexOf(ContentName) > -1); end; function TZLibArchive.GetContent(aStream: TStream; index: integer): TStream; var tempStream: TMemoryStream; decompr : TZDecompressionStream; begin Result := nil; If FStream = nil then exit; Result := aStream; //Find file FStream.Seek(FHeader.DirOffset + SizeOf(TFileSection) * index, soFromBeginning); FStream.Read(Dir, SizeOf(TFileSection)); FStream.Seek(Dir.FilePos, soFromBeginning); //Copy file to temp stream tempStream := TMemoryStream.Create; tempStream.CopyFrom(FStream, Dir.FileLength); tempStream.Position := 0; //decompress decompr := TZDecompressionStream.Create(tempStream); try Result.CopyFrom(decompr, 0); finally decompr.Free; tempStream.Free; end; Result.Position := 0; end; function TZLibArchive.GetContent(index: integer): TStream; begin Result:=GetContent(TMemoryStream.Create,index); end; function TZLibArchive.GetContent(ContentName: string): TStream; begin Result := nil; if ContentExists(ContentName) then Result := GetContent(FContentList.IndexOf(ContentName)); end; function TZLibArchive.GetContentSize(index: integer): integer; begin Result := -1; If FStream = nil then exit; FStream.Seek(FHeader.DirOffset + SizeOf(TFileSection) * index, soFromBeginning); FStream.Read(Dir, SizeOf(Dir)); Result := Dir.FileLength; end; function TZLibArchive.GetContentSize(ContentName: string): integer; begin Result := -1; if ContentExists(ContentName) then Result := GetContentSize(FContentList.IndexOf(ContentName)); end; procedure TZLibArchive.AddFromStream(ContentName, Path: string; FS: TStream); var Temp, compressed: TMemoryStream; FCompressor: TZCompressionStream; LCompLevel : TZCompressionLevel; begin if (FStream = nil) or ContentExists(ContentName) then exit; FStream.Position := FHeader.DirOffset; //??? if FHeader.DirLength > 0 then begin Temp := TMemoryStream.Create; Temp.CopyFrom(FStream, FHeader.DirLength); Temp.Position := 0; FStream.Position := FHeader.DirOffset; end else Temp := nil; Dir.FilePos := FHeader.DirOffset; Dir.CbrMode := compressionLevel; compressed := TMemoryStream.Create; // Archive data to stream case CompressionLevel of clNone : LCompLevel := zcNone; clFastest : LCompLevel := zcFastest; clMax : LCompLevel := zcMax; else LCompLevel := zcDefault; end; FCompressor := TZCompressionStream.Create(compressed, LCompLevel, 15); FCompressor.CopyFrom(FS, FS.Size); FCompressor.Free; // Copy results FStream.CopyFrom(compressed, 0); Dir.FileLength := compressed.Size; Compressed .Free; // ??? FHeader.DirOffset := FStream.Position; if FHeader.DirLength > 0 then begin FStream.CopyFrom(Temp, 0); Temp.Free; end; StrPCopy(Dir.FileName, AnsiString(Path + ExtractFileName(ContentName))); FStream.WriteBuffer(Dir, SizeOf(TFileSection)); FHeader.DirLength := FHeader.DirLength + SizeOf(TFileSection); FStream.Position := 0; FStream.WriteBuffer(FHeader, SizeOf(TZLibHeader)); FContentList.Add(string(Dir.FileName)); end; procedure TZLibArchive.AddFromFile(FileName, Path: string); var FS: TFileStream; begin if not FileExists(FileName) then exit; FS := TFileStream.Create(FileName, fmOpenRead); try AddFromStream(FileName, Path, FS); finally FS.Free; end; end; procedure TZLibArchive.RemoveContent(index: integer); var Temp: TMemoryStream; i: integer; f: TFileSection; begin Temp := TMemoryStream.Create; FStream.Seek(FHeader.DirOffset + SizeOf(TFileSection) * index, soFromBeginning); FStream.ReadBuffer(Dir, SizeOf(TFileSection)); FStream.Seek(Dir.FilePos + Dir.FileLength, soFromBeginning); Temp.CopyFrom(FStream, FStream.Size - FStream.Position); FStream.Position := Dir.FilePos; FStream.CopyFrom(Temp, 0); FHeader.DirOffset := FHeader.DirOffset - dir.FileLength; Temp.Clear; for i := 0 to ContentCount - 1 do if i > index then begin FStream.Seek(FHeader.DirOffset + SizeOf(TFileSection) * i, soFromBeginning); FStream.ReadBuffer(f, SizeOf(TFileSection)); FStream.Position := FStream.Position - SizeOf(TFileSection); f.FilePos := f.FilePos - dir.FileLength; FStream.WriteBuffer(f, SizeOf(TFileSection)); end; i := FHeader.DirOffset + SizeOf(TFileSection) * index; FStream.Position := Cardinal(i + SizeOf(TFileSection)); if FStream.Position < FStream.Size then begin Temp.CopyFrom(FStream, FStream.Size - FStream.Position); FStream.Position := i; FStream.CopyFrom(Temp, 0); end; Temp.Free; FHeader.DirLength := FHeader.DirLength - SizeOf(TFileSection); FStream.Position := 0; FStream.WriteBuffer(FHeader, SizeOf(TZLibHeader)); FStream.Size := FStream.Size - dir.FileLength - SizeOf(TFileSection); MakeContentList; end; procedure TZLibArchive.RemoveContent(ContentName: string); begin if ContentExists(ContentName) then RemoveContent(FContentList.IndexOf(ContentName)); end; procedure TZLibArchive.Extract(index: integer; NewName: string); var vExtractFileStream: TFileStream; vTmpStream: Tstream; begin if NewName = '' then Exit; if (index < 0) or (index >= ContentCount) then exit; vExtractFileStream := TFileStream.Create(NewName, fmCreate); vTmpStream := GetContent(index); vExtractFileStream.CopyFrom(vTmpStream, 0); vTmpStream.Free; vExtractFileStream.Free; end; procedure TZLibArchive.Extract(ContentName, NewName: string); begin if ContentExists(ContentName) then Extract(FContentList.IndexOf(ContentName), NewName); end; initialization RegisterArchiveFormat('zlib', 'GLScene file uses the zlib compression algorithm', TZLibArchive); end.
unit Ths.Erp.Database.Table.PersonelDilBilgisi; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table, Ths.Erp.Database.Table.AyarPrsYabanciDil, Ths.Erp.Database.Table.AyarPrsYabanciDilSeviyesi, Ths.Erp.Database.Table.PersonelKarti; type TPersonelDilBilgisi = class(TTable) private FDilID: TFieldDB; FDil: TFieldDB; FOkumaSeviyesiID: TFieldDB; FOkumaSeviyesi: TFieldDB; FYazmaSeviyesiID: TFieldDB; FYazmaSeviyesi: TFieldDB; FKonusmaSeviyesiID: TFieldDB; FKonusmaSeviyesi: TFieldDB; FPersonelID: TFieldDB; FPersonelAd: TFieldDB; FPersonelSoyad: TFieldDB; protected vPersonelDil: TAyarPrsYabanciDil; vPersonelDilSeviyesi: TAyarPrsYabanciDilSeviyesi; vPersonel: TPersonelKarti; published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property DilID: TFieldDB read FDilID write FDilID; Property Dil: TFieldDB read FDil write FDil; Property OkumaSeviyesiID: TFieldDB read FOkumaSeviyesiID write FOkumaSeviyesiID; Property OkumaSeviyesi: TFieldDB read FOkumaSeviyesi write FOkumaSeviyesi; Property YazmaSeviyesiID: TFieldDB read FYazmaSeviyesiID write FYazmaSeviyesiID; Property YazmaSeviyesi: TFieldDB read FYazmaSeviyesi write FYazmaSeviyesi; Property KonusmaSeviyesiID: TFieldDB read FKonusmaSeviyesiID write FKonusmaSeviyesiID; Property KonusmaSeviyesi: TFieldDB read FKonusmaSeviyesi write FKonusmaSeviyesi; Property PersonelID: TFieldDB read FPersonelID write FPersonelID; Property PersonelAd: TFieldDB read FPersonelAd write FPersonelAd; Property PersonelSoyad: TFieldDB read FPersonelSoyad write FPersonelSoyad; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TPersonelDilBilgisi.Create(OwnerDatabase:TDatabase); begin TableName := 'personel_dil_bilgisi'; SourceCode := '1000'; inherited Create(OwnerDatabase); FDilID := TFieldDB.Create('dil_id', ftInteger, 0); FDil := TFieldDB.Create('dil', ftString, ''); FOkumaSeviyesiID := TFieldDB.Create('okuma_seviyesi_id', ftInteger, 0); FOkumaSeviyesi := TFieldDB.Create('okuma_seviyesi', ftString, ''); FYazmaSeviyesiID := TFieldDB.Create('yazma_seviyesi_id', ftInteger, 0); FYazmaSeviyesi := TFieldDB.Create('yazma_seviyesi', ftString, ''); FKonusmaSeviyesiID := TFieldDB.Create('konusma_seviyesi_id', ftInteger, 0); FKonusmaSeviyesi := TFieldDB.Create('konusma_seviyesi', ftString, ''); FPersonelID := TFieldDB.Create('personel_id', ftInteger, 0); FPersonelAd := TFieldDB.Create('personel_ad', ftString, ''); FPersonelSoyad := TFieldDB.Create('personel_soyad', ftString, ''); end; procedure TPersonelDilBilgisi.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin vPersonelDil := TAyarPrsYabanciDil.Create(Database); vPersonelDilSeviyesi := TAyarPrsYabanciDilSeviyesi.Create(Database); vPersonel := TPersonelKarti.Create(Database); try Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FDilID.FieldName, ColumnFromIDCol(vPersonelDil.YabanciDil.FieldName, vPersonelDil.TableName, FDilID.FieldName, FDil.FieldName, TableName), TableName + '.' + FOkumaSeviyesiID.FieldName, ColumnFromIDCol(vPersonelDilSeviyesi.YabanciDilSeviyesi.FieldName, vPersonelDilSeviyesi.TableName, FOkumaSeviyesiID.FieldName, FOkumaSeviyesi.FieldName, TableName), TableName + '.' + FYazmaSeviyesiID.FieldName, ColumnFromIDCol(vPersonelDilSeviyesi.YabanciDilSeviyesi.FieldName, vPersonelDilSeviyesi.TableName, FYazmaSeviyesiID.FieldName, FYazmaSeviyesi.FieldName, TableName), TableName + '.' + FKonusmaSeviyesiID.FieldName, ColumnFromIDCol(vPersonelDilSeviyesi.YabanciDilSeviyesi.FieldName, vPersonelDilSeviyesi.TableName, FKonusmaSeviyesiID.FieldName, FKonusmaSeviyesi.FieldName, TableName), TableName + '.' + FPersonelID.FieldName, ColumnFromIDCol(vPersonel.PersonelAd.FieldName, vPersonel.TableName, FPersonelID.FieldName, FPersonelAd.FieldName, TableName), ColumnFromIDCol(vPersonel.PersonelAd.FieldName, vPersonel.TableName, FPersonelID.FieldName, FPersonelSoyad.FieldName, TableName) ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FDilID.FieldName).DisplayLabel := 'Dil ID'; Self.DataSource.DataSet.FindField(FDil.FieldName).DisplayLabel := 'Dil'; Self.DataSource.DataSet.FindField(FOkumaSeviyesiID.FieldName).DisplayLabel := 'Okuma Seviyesi ID'; Self.DataSource.DataSet.FindField(FOkumaSeviyesi.FieldName).DisplayLabel := 'Okuma Seviyesi'; Self.DataSource.DataSet.FindField(FYazmaSeviyesiID.FieldName).DisplayLabel := 'Yazma Seviyesi ID'; Self.DataSource.DataSet.FindField(FYazmaSeviyesi.FieldName).DisplayLabel := 'Yazma Seviyesi'; Self.DataSource.DataSet.FindField(FKonusmaSeviyesiID.FieldName).DisplayLabel := 'Konuşma Seviyesi ID'; Self.DataSource.DataSet.FindField(FKonusmaSeviyesi.FieldName).DisplayLabel := 'Konuşma Seviyesi'; Self.DataSource.DataSet.FindField(FPersonelID.FieldName).DisplayLabel := 'Personel ID'; Self.DataSource.DataSet.FindField(FPersonelAd.FieldName).DisplayLabel := 'Personel Ad'; Self.DataSource.DataSet.FindField(FPersonelSoyad.FieldName).DisplayLabel := 'Personel Soyad'; finally vPersonelDil.Free; vPersonelDilSeviyesi.Free; vPersonel.Free; end; end; end; end; procedure TPersonelDilBilgisi.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FDilID.FieldName, ColumnFromIDCol(vPersonelDil.YabanciDil.FieldName, vPersonelDil.TableName, FDilID.FieldName, FDil.FieldName, TableName), TableName + '.' + FOkumaSeviyesiID.FieldName, ColumnFromIDCol(vPersonelDilSeviyesi.YabanciDilSeviyesi.FieldName, vPersonelDilSeviyesi.TableName, FOkumaSeviyesiID.FieldName, FOkumaSeviyesi.FieldName, TableName), TableName + '.' + FYazmaSeviyesiID.FieldName, ColumnFromIDCol(vPersonelDilSeviyesi.YabanciDilSeviyesi.FieldName, vPersonelDilSeviyesi.TableName, FYazmaSeviyesiID.FieldName, FYazmaSeviyesi.FieldName, TableName), TableName + '.' + FKonusmaSeviyesiID.FieldName, ColumnFromIDCol(vPersonelDilSeviyesi.YabanciDilSeviyesi.FieldName, vPersonelDilSeviyesi.TableName, FKonusmaSeviyesiID.FieldName, FKonusmaSeviyesi.FieldName, TableName), TableName + '.' + FPersonelID.FieldName, ColumnFromIDCol(vPersonel.PersonelAd.FieldName, vPersonel.TableName, FPersonelID.FieldName, FPersonelAd.FieldName, TableName), ColumnFromIDCol(vPersonel.PersonelAd.FieldName, vPersonel.TableName, FPersonelID.FieldName, FPersonelSoyad.FieldName, TableName) ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FDilID.Value := FormatedVariantVal(FieldByName(FDilID.FieldName).DataType, FieldByName(FDilID.FieldName).Value); FDil.Value := FormatedVariantVal(FieldByName(FDil.FieldName).DataType, FieldByName(FDil.FieldName).Value); FOkumaSeviyesiID.Value := FormatedVariantVal(FieldByName(FOkumaSeviyesiID.FieldName).DataType, FieldByName(FOkumaSeviyesiID.FieldName).Value); FOkumaSeviyesi.Value := FormatedVariantVal(FieldByName(FOkumaSeviyesi.FieldName).DataType, FieldByName(FOkumaSeviyesi.FieldName).Value); FYazmaSeviyesiID.Value := FormatedVariantVal(FieldByName(FYazmaSeviyesiID.FieldName).DataType, FieldByName(FYazmaSeviyesiID.FieldName).Value); FYazmaSeviyesi.Value := FormatedVariantVal(FieldByName(FYazmaSeviyesi.FieldName).DataType, FieldByName(FYazmaSeviyesi.FieldName).Value); FKonusmaSeviyesiID.Value := FormatedVariantVal(FieldByName(FKonusmaSeviyesiID.FieldName).DataType, FieldByName(FKonusmaSeviyesiID.FieldName).Value); FKonusmaSeviyesi.Value := FormatedVariantVal(FieldByName(FKonusmaSeviyesi.FieldName).DataType, FieldByName(FKonusmaSeviyesi.FieldName).Value); FPersonelID.Value := FormatedVariantVal(FieldByName(FPersonelID.FieldName).DataType, FieldByName(FPersonelID.FieldName).Value); FPersonelAd.Value := FormatedVariantVal(FieldByName(FPersonelAd.FieldName).DataType, FieldByName(FPersonelAd.FieldName).Value); FPersonelSoyad.Value := FormatedVariantVal(FieldByName(FPersonelSoyad.FieldName).DataType, FieldByName(FPersonelSoyad.FieldName).Value); List.Add(Self.Clone()); Next; end; Close; end; end; end; procedure TPersonelDilBilgisi.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FDilID.FieldName, FOkumaSeviyesiID.FieldName, FYazmaSeviyesiID.FieldName, FKonusmaSeviyesiID.FieldName, FPersonelID.FieldName ]); NewParamForQuery(QueryOfInsert, FDilID); NewParamForQuery(QueryOfInsert, FOkumaSeviyesiID); NewParamForQuery(QueryOfInsert, FYazmaSeviyesiID); NewParamForQuery(QueryOfInsert, FKonusmaSeviyesiID); NewParamForQuery(QueryOfInsert, FPersonelID); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TPersonelDilBilgisi.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FDilID.FieldName, FOkumaSeviyesiID.FieldName, FYazmaSeviyesiID.FieldName, FKonusmaSeviyesiID.FieldName, FPersonelID.FieldName ]); NewParamForQuery(QueryOfUpdate, FDilID); NewParamForQuery(QueryOfUpdate, FOkumaSeviyesiID); NewParamForQuery(QueryOfUpdate, FYazmaSeviyesiID); NewParamForQuery(QueryOfUpdate, FKonusmaSeviyesiID); NewParamForQuery(QueryOfUpdate, FPersonelID); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; function TPersonelDilBilgisi.Clone():TTable; begin Result := TPersonelDilBilgisi.Create(Database); Self.Id.Clone(TPersonelDilBilgisi(Result).Id); FDilID.Clone(TPersonelDilBilgisi(Result).FDilID); FDil.Clone(TPersonelDilBilgisi(Result).FDil); FOkumaSeviyesiID.Clone(TPersonelDilBilgisi(Result).FOkumaSeviyesiID); FOkumaSeviyesi.Clone(TPersonelDilBilgisi(Result).FOkumaSeviyesi); FYazmaSeviyesiID.Clone(TPersonelDilBilgisi(Result).FYazmaSeviyesiID); FYazmaSeviyesi.Clone(TPersonelDilBilgisi(Result).FYazmaSeviyesi); FKonusmaSeviyesiID.Clone(TPersonelDilBilgisi(Result).FKonusmaSeviyesiID); FKonusmaSeviyesi.Clone(TPersonelDilBilgisi(Result).FKonusmaSeviyesi); FPersonelID.Clone(TPersonelDilBilgisi(Result).FPersonelID); FPersonelAd.Clone(TPersonelDilBilgisi(Result).FPersonelAd); FPersonelSoyad.Clone(TPersonelDilBilgisi(Result).FPersonelSoyad); end; end.
unit ArrayNodeReader; interface uses BaseNodeReader, GMGlobals, SysUtils; type TArrayNodeReader = class(TBaseNodeReader) public procedure ReadChildren(ID_Node: int); override; procedure AddNew(ID_Parent: int; p: PVTNodeData); override; procedure NewCaption(p: PVTNodeData); override; procedure Delete(p: PVTNodeData); override; end; implementation { TArrayNodeReader } uses GMDBClasses; procedure TArrayNodeReader.AddNew(ID_Parent: int; p: PVTNodeData); begin raise Exception.Create('Edit not allowed!'); end; procedure TArrayNodeReader.Delete(p: PVTNodeData); begin raise Exception.Create('Edit not allowed!'); end; procedure TArrayNodeReader.NewCaption(p: PVTNodeData); begin raise Exception.Create('Edit not allowed!'); end; procedure TArrayNodeReader.ReadChildren(ID_Node: int); var nd: TGMNode; chn: TGMNodeChannel; rec: TVTNodeData; begin ReadResult.Clear(); for nd in GMNodes do begin if nd.ID_Parent <> ID_Node then continue; InitVND(@rec); rec.sTxt := nd.Name; rec.ID_Obj := nd.ID_Node; rec.ObjType := nd.NodeType; rec.Obj := nd; ReadResult.Add(rec); end; for chn in GMNodeChannels do begin if (chn.Node = nil) or (chn.Node.ID_Node <> ID_Node) then continue; InitVND(@rec); rec.ID_Prm := chn.ID_Prm; rec.sTxt := chn.Caption; rec.Obj := chn; ReadResult.Add(rec); end; end; end.
unit Getter.DriveList.Removable; interface uses Windows, Getter.DriveList; type TRemovableDriveListGetter = class sealed(TDriveListGetter) protected function GetDriveTypeToGet: TDriveSet; override; end; implementation function TRemovableDriveListGetter.GetDriveTypeToGet: TDriveSet; begin result := [DRIVE_REMOVABLE]; end; end.
unit ServerMethodsUnit1; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth; type {$METHODINFO ON} TServerMethods1 = class(TComponent) private { Private declarations } public { Public declarations } { function EchoString(Value: string): string; function ReverseString(Value: string): string; } function Usuario(Value: String): String; function acceptUsuario(Value: String): String; function cancelUsuario(Value: String): String; function updateUsuario(Value: String): String; end; {$METHODINFO OFF} implementation uses System.StrUtils, clsTUsuario, libEnumTypes; function TServerMethods1.updateUsuario(Value: String): String; var usu: TUsuario; begin usu := TUsuario.Create(Value); //usu.FromJSON(Value); usu.Persiste(todUpdate); Result := usu.ToJSON; FreeAndNil(usu); end; function TServerMethods1.Usuario(Value: String): String; var usu: TUsuario; begin usu := TUsuario.Create; usu.DTO.Email := Value; usu.Persiste(todSelect); Result := usu.ToJSON; FreeAndNil(usu); end; { function TServerMethods1.EchoString(Value: string): string; begin Result := Value; end; } function TServerMethods1.acceptUsuario(Value: String): String; var usu: TUsuario; begin usu := TUsuario.Create(Value); //usu.FromJSON(Value); usu.Persiste(todInsert); Result := usu.ToJSON; FreeAndNil(usu); end; function TServerMethods1.cancelUsuario(Value: String): String; var usu: TUsuario; begin usu := TUsuario.Create(Value); //usu.FromJSON(Value); usu.Persiste(todDelete); Result := 'Usuario "'+usu.DTO.Nome+'" excluído'; FreeAndNil(usu); end; { function TServerMethods1.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; } end.
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, frxClass, Vcl.Menus, System.Actions, Vcl.ActnList, frxExportPDF, frxDBSet; type TfPrincipal = class(TForm) Button1: TButton; OpenDialog: TOpenDialog; btnSalvarPDF: TButton; frxSAT: TfrxReport; procedure Button1Click(Sender: TObject); procedure btnSalvarPDFClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FStream: TMemoryStream; FSistema: string; function CarregarXML: ansistring; function GerarImpressao(const Report: TfrxReport): Boolean; function ConverterFastReportParaString(Relatorio: TfrxReport): string; end; var fPrincipal: TfPrincipal; implementation uses ACBrSAT, Xml.XMLDoc, Xml.XMLIntf, ACBrSATExtratoFR; {$R *.dfm} function TfPrincipal.CarregarXML: ansistring; var XMLDocument: IXMLDocument; ArquivoXML: TStringList; i: Integer; begin OpenDialog.Options := [ofAllowMultiSelect]; if OpenDialog.Execute then begin for i := 0 to OpenDialog.Files.Count -1 do begin ArquivoXML := TStringList.Create; ArquivoXML.LoadFromFile(OpenDialog.FileName, TEncoding.UTF8); Result := ArquivoXML.Text // XMLDocument := TXMLDocument.Create(nil); // XMLDocument.LoadFromFile(OpenDialog.Files[i], TEncoding.UTF8TEncoding.UTF8); // // Result := XMLDocument.XML.Text; end; end; end; procedure TfPrincipal.FormCreate(Sender: TObject); begin FStream := TMemoryStream.Create; FSistema := 'https://www.iaush.com.br'; end; procedure TfPrincipal.FormDestroy(Sender: TObject); begin FStream.Free; inherited; end; procedure TfPrincipal.btnSalvarPDFClick(Sender: TObject); begin FStream.SaveToFile('SAT.pdf'); end; function TfPrincipal.ConverterFastReportParaString(Relatorio: TfrxReport): string; var StringStream: TStringStream; begin StringStream := TStringStream.Create(''); Relatorio.SaveToStream(StringStream); Result := StringStream.DataString; StringStream.Free; end; procedure TfPrincipal.Button1Click(Sender: TObject); var ACBrDFe: TACBrSAT; begin ACBrDFe := TACBrSAT.Create(Self); ACBrDFe.CFe.SetXMLString(AnsiString(CarregarXML)); ACBrDFe.Extrato := TACBrSATExtratoFast.Create(ACBrDFe); with ACBrDFe.Extrato as TACBrSATExtratoFast do try // Logo := FLogotipo; FastFile := ConverterFastReportParaString(frxSAT); Sistema := FSistema; // MargemEsquerda := 0.1; // MargemSuperior := 1.5; // MargemDireita := 0.1; // MargemInferior := 1.0; // ImprimirExtrato GerarImpressao(PreparedReport); MostraPreview := True; // ImprimirDAMDFe(MDFe); // FStream.SaveToFile('SAT.pdf'); finally FreeAndNil(ACBrDFe); end; end; function TfPrincipal.GerarImpressao(const Report: TfrxReport): Boolean; var PDFExport: TfrxPDFExport; i :integer; s: string; begin FStream.Clear; PDFExport := TfrxPDFExport.Create(Self); with PDFExport do begin ShowDialog := False; ShowProgress := False; Stream := FStream; FileName := 'Sat.PDF'; EmbeddedFonts := True; Title := 'SAT Extrato FR'; end; Result := Report.Export(PDFExport); Report.ShowReport; // Report.SaveToFile('Sat.PDF'); end; end.
unit FC.Trade.Trader.PipsRSI; {$I Compiler.inc} interface uses Classes, Math,Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage, StockChart.Definitions.Drawing,Graphics; type IStockTraderPipsRSI = interface ['{5C4D7EFC-ECFF-48DB-933A-34E64810BAD4}'] end; TStockTraderPipsRSI = class (TStockTraderBase,IStockTraderPipsRSI) private FRSI_M1: ISCIndicatorTRSIMA; FRSI_M5: ISCIndicatorTRSIMA; FRSI_M15: ISCIndicatorTRSIMA; FMA84_M1 : ISCIndicatorMA; protected function Spread: TSCRealNumber; function ToPrice(aPoints: integer): TSCRealNumber; procedure AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); procedure SetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses Variants,DateUtils, SystemService, Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; { TStockTraderPipsRSI } constructor TStockTraderPipsRSI.Create; begin inherited Create; // UnRegisterProperties([PropTrailingStop,PropTrailingStopDescend,PropMinimizationRiskType]); end; destructor TStockTraderPipsRSI.Destroy; begin inherited; end; procedure TStockTraderPipsRSI.Dispose; begin inherited; end; procedure TStockTraderPipsRSI.OnBeginWorkSession; begin inherited; end; procedure TStockTraderPipsRSI.SetMark(const aOrder: IStockOrder;const aMarkType: TSCChartMarkKind; const aMessage: string); begin AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; procedure TStockTraderPipsRSI.SetProject(const aValue: IStockProject); var aCreated: boolean; begin if GetProject=aValue then exit; inherited; if aValue <> nil then begin FRSI_M1:=CreateOrFindIndicator(aValue.GetStockChart(sti1),ISCIndicatorTRSIMA,'RSI'+'_'+StockTimeIntervalNames[sti1],true, aCreated) as ISCIndicatorTRSIMA; FRSI_M5:=CreateOrFindIndicator(aValue.GetStockChart(sti5),ISCIndicatorTRSIMA,'RSI'+'_'+StockTimeIntervalNames[sti5],true, aCreated) as ISCIndicatorTRSIMA; FRSI_M15:=CreateOrFindIndicator(aValue.GetStockChart(sti15),ISCIndicatorTRSIMA,'RSI'+'_'+StockTimeIntervalNames[sti15],true, aCreated) as ISCIndicatorTRSIMA; FMA84_M1:=CreateOrFindIndicator(aValue.GetStockChart(sti1),ISCIndicatorMA,'MA84'+'_'+StockTimeIntervalNames[sti1],true, aCreated) as ISCIndicatorMA; //Ничего не нашли, создадим нового эксперта if aCreated then begin FMA84_M1.SetPeriod(84); end; end; end; function TStockTraderPipsRSI.ToPrice(aPoints: integer): TSCRealNumber; begin result:=GetBroker.PointToPrice(GetSymbol,1); end; function TStockTraderPipsRSI.Spread: TSCRealNumber; begin result:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread); end; procedure TStockTraderPipsRSI.UpdateStep2(const aTime: TDateTime); var aIdxM1: integer; aIdxM5: integer; aIdxM15: integer; aOpen,aClose : integer; //aRSIValueM1_1,aRSIValueM1_0, aRSIValueM5_1,aRSIValueM5_0 : TSCRealNumber; aMAValue,aRSIValue: TSCRealNumber; x: integer; begin RemoveClosedOrders; //aInputData:=aChart.GetInputData; aIdxM1:=TStockDataUtils.FindBar(FRSI_M1.GetInputData,aTime,sti1); aIdxM5:=TStockDataUtils.FindBar(FRSI_M5.GetInputData,aTime,sti5); aIdxM15:=TStockDataUtils.FindBar(FRSI_M15.GetInputData,aTime,sti15); if (aIdxM1<>-1) and (aIdxM1>=FRSI_M1.GetPeriod) and (aIdxM5<>-1) and (aIdxM5>=FRSI_M5.GetPeriod) and (aIdxM15<>-1) and (aIdxM15>=FRSI_M15.GetPeriod) then begin aOpen:=0; aClose:=0; (*aRSIValueM1_1:=FRSI_M1.GetValue(aIdxM1-2); aRSIValueM1_0:=FRSI_M1.GetValue(aIdxM1-1); aRSIValueM5_1:=FRSI_M5.GetValue(aIdxM5-2); aRSIValueM5_0:=FRSI_M5.GetValue(aIdxM5-1); //Открываем ордер if //(aRSIValueM1_1<30) and (aRSIValueM1_0>aRSIValueM1_1) and (aRSIValueM5_1<30) and (aRSIValueM5_0>aRSIValueM5_1) then aOpen:=1 else if //(aRSIValueM1_1>70) and (aRSIValueM1_0<aRSIValueM1_1) and (aRSIValueM5_1>70) and (aRSIValueM5_0<aRSIValueM5_1) then aOpen:=-1; *) aRSIValue:=FRSI_M1.GetValue(aIdxM1); aMAValue:=FMA84_M1.GetValue(aIdxM1); x:=Sign(FMA84_M1.GetInputData.Items[aIdxM1].DataClose-aMAValue); if x<>Sign(FMA84_M1.GetInputData.Items[aIdxM1-1].DataClose-aMAValue) then begin if (x>0) and (aRSIValue>50) then begin aOpen:=1; aClose:=-1; end else if (x<0) and (aRSIValue<50) then begin aOpen:=-1; aClose:=1; end; end; (* if (FRSI_M1.GetValue(aIdxM1-1)<50) and (FRSI_M1.GetValue(aIdxM1)>=50) then begin aOpen:=1; aClose:=-1; end else if (FRSI_M1.GetValue(aIdxM1-1)>50) and (FRSI_M1.GetValue(aIdxM1)<=50) then begin aOpen:=-1; aClose:=1; end;*) if aClose=-1 then CloseAllSellOrders('') else if aClose=1 then CloseAllBuyOrders(''); if aOpen<>0 then begin //BUY if (aOpen=1) and (LastOrderType<>lotBuy) then begin OpenOrder(okBuy); end //SELL else if (aOpen=-1) and (LastOrderType<>lotSell) then begin OpenOrder(okSell); end; end; end; end; procedure TStockTraderPipsRSI.AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); begin GetBroker.AddMessage(aOrder,aMessage); AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','PipsRSI',TStockTraderPipsRSI,IStockTraderPipsRSI); end.
unit AddEditLanLeituraHidrometro; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AddEditPadrao2, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, FMTBcd, DB, DBClient, Provider, SqlExpr, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit, Buttons, cxTextEdit, cxDBEdit, cxCheckBox, cxCalc, cxLabel, dxSkinsCore, dxSkinsDefaultPainters, cxCalendar, cxCurrencyEdit; type TfrmAddEditLanLeituraHidrom = class(TfrmAddEditPadrao2) edLeituraAnterior: TcxDBTextEdit; edObservacao: TcxDBTextEdit; edNomePessoa: TcxDBTextEdit; sbUnidConsum: TSpeedButton; qryLeituraAnter: TSQLQuery; qryUnidComsumidora: TSQLQuery; cxLabel3: TcxLabel; cxLabel1: TcxLabel; cxLabel2: TcxLabel; cxLabel4: TcxLabel; edConsumo_m3: TcxDBTextEdit; cxLabel5: TcxLabel; edDtLeitura: TcxDateEdit; cxLabel6: TcxLabel; cxLabel7: TcxLabel; edNumHidrometro: TcxDBTextEdit; cxLabel8: TcxLabel; edEndereco: TcxTextEdit; edBairroDistrito: TcxTextEdit; qryUnidComsumidoraNOME_PESSOA: TStringField; qryUnidComsumidoraENDER_DESCR_LOGRAD: TStringField; qryUnidComsumidoraENDER_DESCR_BAIRRO: TStringField; qryUnidComsumidoraENDER_DESCR_DISTRITO: TStringField; qryUnidComsumidoraNUM_HIDROMETRO: TStringField; qryUnidComsumidoraENDER_COMPLEMENTO: TStringField; qryUnidComsumidoraENDER_ID_LOGRAD: TIntegerField; edLeituraAtual: TcxDBCurrencyEdit; edIdUnidConsum: TcxMaskEdit; qryUnidComsumidoraENDER_UC_NUM_LETRA: TStringField; qry1ANO_MES: TStringField; qry1ID_UNID_CONSUM: TIntegerField; qry1DT_LEITURA: TDateField; qry1LEITURA_ANTERIOR: TIntegerField; qry1LEITURA_ATUAL: TIntegerField; qry1CONSUMO_M3: TLargeintField; qry1OBSERVACAO: TStringField; qry1ID_SERVID_LEITURA: TIntegerField; qry1NOME_PESSOA: TStringField; qry1NUM_HIDROMETRO: TStringField; qry1ENDER_DESCR_LOGRAD: TStringField; qry1ENDER_NUM_LETRA: TStringField; qry1ENDER_COMPLEMENTO: TStringField; qry1ENDER_DESCR_BAIRRO: TStringField; qry1ENDER_DESCR_DISTRITO: TStringField; cds1ANO_MES: TStringField; cds1ID_UNID_CONSUM: TIntegerField; cds1DT_LEITURA: TDateField; cds1LEITURA_ANTERIOR: TIntegerField; cds1LEITURA_ATUAL: TIntegerField; cds1CONSUMO_M3: TLargeintField; cds1OBSERVACAO: TStringField; cds1ID_SERVID_LEITURA: TIntegerField; cds1NOME_PESSOA: TStringField; cds1NUM_HIDROMETRO: TStringField; cds1ENDER_DESCR_LOGRAD: TStringField; cds1ENDER_NUM_LETRA: TStringField; cds1ENDER_COMPLEMENTO: TStringField; cds1ENDER_DESCR_BAIRRO: TStringField; cds1ENDER_DESCR_DISTRITO: TStringField; provLeituraAnter: TDataSetProvider; cdsLeituraAnter: TClientDataSet; cdsLeituraAnterANO_MES: TStringField; cdsLeituraAnterLEITURA_ATUAL: TIntegerField; cdsLeituraAnterCONSUMO_M3: TLargeintField; qryLeituraLancada: TSQLQuery; qryLeituraLancadaLEITURA_ATUAL: TIntegerField; qryLeituraLancadaCONSUMO_M3: TLargeintField; procedure FormCreate(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cds1AfterInsert(DataSet: TDataSet); procedure sbUnidConsumClick(Sender: TObject); procedure edIDServidorPropertiesChange(Sender: TObject); procedure edIdUnidConsumExit(Sender: TObject); procedure edIdUnidConsumKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cds1AfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); procedure edLeituraAtualExit(Sender: TObject); procedure cds1BeforePost(DataSet: TDataSet); private { Private declarations } Procedure MostraEvento; Function LeituraJaLancada: Boolean; public { Public declarations } end; var frmAddEditLanLeituraHidrom: TfrmAddEditLanLeituraHidrom; implementation uses udmPrincipal, VarGlobais, gsLib, UtilsDb, FindUnidConsumidora; {$R *.dfm} procedure TfrmAddEditLanLeituraHidrom.btnGravarClick(Sender: TObject); begin if cds1.State = dsInsert then begin if LeituraJaLancada then exit; // Verica se o evento já está lançado pro Servidor no mês/ano .. cds1ID_UNID_CONSUM.AsString := ExtraiPonto(Trim(edIdUnidConsum.Text)); cds1ANO_MES.Value := glb_sAnoMesTrab; end; cds1DT_LEITURA.Value := StrToDate(edDtLeitura.Text); inherited; pb_iIdAddEdit := cds1ID_UNID_CONSUM.Value end; procedure TfrmAddEditLanLeituraHidrom.cds1AfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); begin dmPrincipal.GeraLog(cds1,iIf(pb_lAdd,'1','2'),'LEITURA_HIDROMETRO', pb_sFormCall,Self.Name); end; procedure TfrmAddEditLanLeituraHidrom.cds1AfterInsert(DataSet: TDataSet); begin inherited; cds1LEITURA_ATUAL.AsCurrency := 0; cds1CONSUMO_M3.AsCurrency := 0; end; procedure TfrmAddEditLanLeituraHidrom.cds1BeforePost(DataSet: TDataSet); begin inherited; cds1DT_LEITURA.AsString := ValData(edDtLeitura.Text); end; procedure TfrmAddEditLanLeituraHidrom.edIdUnidConsumExit(Sender: TObject); begin if Trim(ExtraiPonto(edIdUnidConsum.Text)) = '' then exit; edIdUnidConsum.Text := LeftSpace(Trim(edIdUnidConsum.Text),8); qryUnidComsumidora.Close; qryUnidComsumidora.Params[0].AsString := Trim(ExtraiPonto(edIdUnidConsum.Text)); qryUnidComsumidora.Open; if qryUnidComsumidoraNOME_PESSOA.IsNull then begin Mensagem('Identificador de Unid. Consumidora, inválido ...', 'E r r o !!!',MB_ICONERROR+MB_OK); edIdUnidConsum.SetFocus; exit; end; cds1NOME_PESSOA.Value := qryUnidComsumidoraNOME_PESSOA.Value; cds1NUM_HIDROMETRO.Value := qryUnidComsumidoraNUM_HIDROMETRO.Value; edEndereco.Text := qryUnidComsumidoraENDER_DESCR_LOGRAD.Value+', '+ Trim(qryUnidComsumidoraENDER_UC_NUM_LETRA.Value)+' - '+ qryUnidComsumidoraENDER_COMPLEMENTO.Value; edBairroDistrito.Text := qryUnidComsumidoraENDER_DESCR_BAIRRO.Value+' - '+ qryUnidComsumidoraENDER_DESCR_DISTRITO.Value; if qryUnidComsumidoraENDER_ID_LOGRAD.Value <> pb_iId2 then begin Mensagem('Essa Unid. Consumidora é de outro Logradouro ...', 'E r r o !!!',MB_ICONERROR+MB_OK); edIdUnidConsum.SetFocus; exit; end; if LeituraJaLancada then begin edIdUnidConsum.SetFocus; exit; end; if pb_lAdd then begin cdsLeituraAnter.Close; qryLeituraAnter.ParamByName('pAnoMes').Value := glb_sAnoMesTrab; qryLeituraAnter.ParamByName('pUnidConsum').AsString:= Trim(ExtraiPonto(edIdUnidConsum.Text)); cdsLeituraAnter.Open; cdsLeituraAnter.Last; try try cds1LEITURA_ANTERIOR.Value := cdsLeituraAnterLEITURA_ATUAL.Value; if cds1LEITURA_ANTERIOR.IsNull then cds1LEITURA_ANTERIOR.Value := 0; except cds1LEITURA_ANTERIOR.Value := 0; end; finally cdsLeituraAnter.Close; end; end; end; procedure TfrmAddEditLanLeituraHidrom.edIdUnidConsumKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if ((Shift = [ssCtrl]) and (Key = VK_RETURN)) or ((Shift = []) and (Key = VK_F3)) then sbUnidConsum.Click end; procedure TfrmAddEditLanLeituraHidrom.edLeituraAtualExit(Sender: TObject); begin if cds1LEITURA_ATUAL.Value >= cds1LEITURA_ANTERIOR.Value then cds1CONSUMO_M3.Value := cds1LEITURA_ATUAL.Value - cds1LEITURA_ANTERIOR.Value else begin Mensagem('A Leitura Atual NÃO pode ser Menor que a Anterior ...', 'E r r o !!!',MB_OK+MB_ICONEXCLAMATION); edLeituraAtual.SetFocus; end; end; procedure TfrmAddEditLanLeituraHidrom.edIDServidorPropertiesChange( Sender: TObject); begin if (not cds1.Active) or (cds1.State = dsBrowse) or (Trim(edIdUnidConsum.Text) <> '') then exit; cds1NOME_PESSOA.Value := ''; cds1NUM_HIDROMETRO.Value := ''; edEndereco.Text := ''; edBairroDistrito.Text := ''; end; procedure TfrmAddEditLanLeituraHidrom.FormClose(Sender: TObject; var Action: TCloseAction); begin qryUnidComsumidora.Close; qryLeituraLancada.Close; cdsLeituraAnter.Close; if (cds1.State in [dsInsert, dsEdit]) then begin cds1.Cancel; cds1.CancelUpdates; end; inherited; end; procedure TfrmAddEditLanLeituraHidrom.FormCreate(Sender: TObject); begin inherited; pb_sNomeTab := 'LEITURA_HIDROMETRO'; //pb_sNomeCampoPK := 'ID_EVENTO'; pb_sNovoNova := 'NOVO'; pb_sTitJanela := 'LANÇAMENTO DE LEITURA DE HIDRÔMETRO'; end; procedure TfrmAddEditLanLeituraHidrom.FormShow(Sender: TObject); begin inherited; Caption := iIf(pb_lAdd,'INCLUINDO NOVA LEITURA ...', 'ALTERANDO LANÇAMENTO DE LEITURA ...'); cds1.Close; qry1.ParamByName('pAnoMes').Value := glb_sAnoMesTrab; qry1.ParamByName('pUnidConsum').Value:= pb_iId1; cds1.Open; if pb_lAdd then cds1.Insert else begin cds1.Edit; edDtLeitura.Text := cds1DT_LEITURA.AsString; end; if pb_iId1 > 0 then // pb_iId1 = Id_Servidor begin edIdUnidConsum.Style.StyleController:= dmPrincipal.cxEditStyleReadyOnly; edIdUnidConsum.Text := LeftSpace(IntToStr(pb_iId1),8); edEndereco.Text := Trim(cds1ENDER_DESCR_LOGRAD.Value)+', '+Trim(cds1ENDER_NUM_LETRA.Value)+' - '+ cds1ENDER_COMPLEMENTO.Value; edBairroDistrito.Text := cds1ENDER_DESCR_BAIRRO.Value+' - '+cds1ENDER_DESCR_DISTRITO.Value; cds1ID_UNID_CONSUM.Value := pb_iId1; edIdUnidConsumExit(edIdUnidConsum); end else begin edIdUnidConsum.Style.StyleController:= dmPrincipal.cxEditStyleNormal; end; edIdUnidConsum.Properties.ReadOnly:= not (pb_iId1=0); edIdUnidConsum.TabStop := (pb_iId1=0); sbUnidConsum.Enabled := (pb_iId1=0); if pb_iId1 = 0 then edIdUnidConsum.SetFocus else edDtLeitura.SetFocus; end; procedure TfrmAddEditLanLeituraHidrom.sbUnidConsumClick(Sender: TObject); begin //frmFindUnidConsumidora := TfrmFindUnidConsumidora.Create(Self); frmFindUnidConsum.ShowModal; if glb_sCodigo <> '' then cds1ID_UNID_CONSUM.AsString := glb_sCodigo; edIdUnidConsum.SetFocus; //FreeAndNil(frmFindUnidConsumidora); end; Function TfrmAddEditLanLeituraHidrom.LeituraJaLancada: Boolean; Var iQtdM3: integer; begin Result := False; if (pb_lAdd = False) or (Trim(ExtraiPonto(edIdUnidConsum.Text))='') then exit; qryLeituraLancada.Close; qryLeituraLancada.ParamByName('pAnoMes').Value := glb_sAnoMesTrab; qryLeituraLancada.ParamByName('pUnidConsum').AsString:= Trim(ExtraiPonto(edIdUnidConsum.Text)); qryLeituraLancada.Open; try Result := (not qryLeituraLancadaCONSUMO_M3.IsNull); if Result = True then iQtdM3 := qryLeituraLancadaCONSUMO_M3.Value; finally qryLeituraLancada.Close; end; if Result = True then Mensagem('Já está lançada a Leitura pra essa'+#13+ 'Unidade Consumdora nesse Mês/ano.'+#13+ IntToStr(iQtdM3)+' m³', 'Aviso !!!',MB_ICONEXCLAMATION+MB_OK); end; Procedure TfrmAddEditLanLeituraHidrom.MostraEvento; begin end; end.
{ @html(<b>) Trashcah @html(</b>) - Copyright (c) Danijel Tkalcec @html(<br><br>) Garbage collection used by the RTC SDK to avoid destroying objects which need to remain in memory until all other things have been destroyed. @exclude } unit rtcTrashcan; {$INCLUDE rtcDefs.inc} interface uses SysUtils, rtcSyncObjs; // Add pointer "p" to garbage collector. procedure Garbage(p:pointer); overload; // Add object "o" to garbage collector. procedure Garbage(o:TObject); overload; implementation var CS:TRtcCritSec; p_can:array of pointer; o_can:array of TObject; pcan_cnt:integer=0; ocan_cnt:integer=0; // Add pointer "p" to garbage collector. procedure Garbage(p:pointer); overload; begin if p=nil then Exit; CS.Enter; try Inc(pcan_cnt); if length(p_can)<pcan_cnt then SetLength(p_can, length(p_can)+32); p_can[pcan_cnt-1]:=p; finally CS.Leave; end; end; // Add object "o" to garbage collector. procedure Garbage(o:TObject); overload; var a:integer; begin if o=nil then Exit; CS.Enter; try for a:=0 to ocan_cnt-1 do if o_can[a]=o then raise Exception.Create('Object already added!'); Inc(ocan_cnt); if length(o_can)<ocan_cnt then SetLength(o_can, length(o_can)+32); o_can[ocan_cnt-1]:=o; finally CS.Leave; end; end; procedure CleanGarbage; var a:integer; begin CS.Enter; try for a:=0 to pcan_cnt-1 do FreeMem(p_can[a]); pcan_cnt:=0; for a:=0 to ocan_cnt-1 do o_can[a].Free; ocan_cnt:=0; finally CS.Leave; end; SetLength(p_can,0); SetLength(o_can,0); CS.Free; end; initialization CS:=TRtcCritSec.Create; SetLength(p_can,0); SetLength(o_can,0); finalization CleanGarbage; end.
(* * Copyright(c) 2019 Embarcadero Technologies, Inc. * * This code was generated by the TaskGen tool from file * "ILINK32Task.xml" * Version: 26.0.0.0 * Runtime Version: v4.0.30319 * Changes to this file may cause incorrect behavior and will be * overwritten when the code is regenerated. *) unit ILinkStrs; interface const sTaskName = 'ilink32'; sLibraryPath = 'ILINK_LibraryPath'; sSysLibraryPath = 'ILINK_SysLibraryPath'; sSysRoot = 'ILINK_SysRoot'; sFrameworks = 'ILINK_Frameworks'; // ILINKOutputParameters sOutputFileName = 'ILINK_OutputFileName'; sMapFileName = 'ILINK_MapFileName'; // ILINKPaths sObjectSearchPath = 'ILINK_ObjectSearchPath'; sIntermediateOutputPath = 'ILINK_IntermediateOutputPath'; sBpiLibOutputDir = 'ILINK_BpiLibOutputDir'; // ILINKLinking sImageChecksum = 'ILINK_ImageChecksum'; sAdditionalOptions = 'ILINK_AdditionalOptions'; sFastTLS = 'ILINK_FastTLS'; sReplaceResources = 'ILINK_ReplaceResources'; sClearState = 'ILINK_ClearState'; sCaseSensitive = 'ILINK_CaseSensitive'; sVerbose = 'ILINK_Verbose'; sDelayLoadDll = 'ILINK_DelayLoadDll'; sSymbolsToExport = 'ILINK_SymbolsToExport'; siOSMinimumVersion = 'ILINK_iOSMinimumVersion'; smacOSMinimumVersion = 'ILINK_macOSMinimumVersion'; sLinkwithSQL = 'ILINK_LinkwithSQL'; sLinkwithIntebaseTogo = 'ILINK_LinkwithIntebaseTogo'; sLinkwithMidas = 'ILINK_LinkwithMidas'; sLinkwithSSLandCrypto = 'ILINK_LinkwithSSLandCrypto'; sLinkwithZLib = 'ILINK_LinkwithZLib'; sLinkwithSQLite = 'ILINK_LinkwithSQLite'; sLinkwithIndy = 'ILINK_LinkwithIndy'; sLinkwithRegEx = 'ILINK_LinkwithRegEx'; sLinkwithDUnitXRuntime = 'ILINK_LinkwithDUnitXRuntime'; sLinkwithPThread = 'ILINK_LinkwithPThread'; sAdditionalLinkerFiles = 'ILINK_AdditionalLinkerFiles'; sFileAlignment = 'ILINK_FileAlignment'; sObjectAlignment = 'ILINK_ObjectAlignment'; sHeapInfo = 'ILINK_HeapInfo'; sHeapCode = 'ILINK_HeapCode'; sHeapROData = 'ILINK_HeapROData'; sHeapData = 'ILINK_HeapData'; sHeapTDS = 'ILINK_HeapTDS'; sHeapDwarf_aranges = 'ILINK_HeapDwarf_aranges'; sHeapDwarf_macinfo = 'ILINK_HeapDwarf_macinfo'; sHeapDwarf_pubtypes = 'ILINK_HeapDwarf_pubtypes'; sHeapDwarf_info = 'ILINK_HeapDwarf_info'; sHeapDwarf_abbrev = 'ILINK_HeapDwarf_abbrev'; sHeapDwarf_line = 'ILINK_HeapDwarf_line'; sHeapDwarf_str = 'ILINK_HeapDwarf_str'; sHeapDwarf_loc = 'ILINK_HeapDwarf_loc'; sHeapDwarf_ranges = 'ILINK_HeapDwarf_ranges'; sFullDebugInfo = 'ILINK_FullDebugInfo'; sRemoveTmpLnkFile = 'ILINK_RemoveTmpLnkFile'; sGenerateImportLibrary = 'ILINK_GenerateImportLibrary'; sGenerateLibFile = 'ILINK_GenerateLibFile'; sGenerateDRC = 'ILINK_GenerateDRC'; sDisableIncrementalLinking = 'ILINK_DisableIncrementalLinking'; sMaxErrors = 'ILINK_MaxErrors'; sSuppressBanner = 'ILINK_SuppressBanner'; sKeepOutputFiles = 'ILINK_KeepOutputFiles'; sDisplayTime = 'ILINK_DisplayTime'; // ILINKInternalOptions sFilenameAlias = 'ILINK_FilenameAlias'; // ILINKTargetOptions sAppType = 'ILINK_AppType'; sAppType_Console = 'Console'; sAppType_Windows = 'Windows'; sAppType_DeviceDriver = 'DeviceDriver'; sWinAppType = 'ILINK_WinAppType'; sWinAppType_Executable = 'Executable'; sWinAppType_DLL = 'DLL'; sWinAppType_Package = 'Package'; // ILINKOutput sGenerateMapFile = 'ILINK_GenerateMapFile'; sMapWithMangledNames = 'ILINK_MapWithMangledNames'; sMapFileType = 'ILINK_MapFileType'; sMapFileType_Segments = 'Segments'; sMapFileType_Publics = 'Publics'; sMapFileType_DetailedSegments = 'DetailedSegments'; sMapFileType_None = 'None'; sBaseAddress = 'ILINK_BaseAddress'; sHeapReserveSize = 'ILINK_HeapReserveSize'; sHeapCommitSize = 'ILINK_HeapCommitSize'; sStackReserveSize = 'ILINK_StackReserveSize'; sStackCommitSize = 'ILINK_StackCommitSize'; sDescription = 'ILINK_Description'; sImageComment = 'ILINK_ImageComment'; sSectionFlags = 'ILINK_SectionFlags'; sImageFlags = 'ILINK_ImageFlags'; sOSVersion = 'ILINK_OSVersion'; sUserVersion = 'ILINK_UserVersion'; // ILINKPackageOptions sPackageType = 'ILINK_PackageType'; sPackageType_Runtime = 'Runtime'; sPackageType_Designtime = 'Designtime'; sPackageType_Both = 'Both'; sPackageBaseName = 'ILINK_PackageBaseName'; // ILINKWarnings sAllWarnings = 'ILINK_AllWarnings'; sDisableWarnings = 'ILINK_DisableWarnings'; sSelectedWarnings = 'ILINK_SelectedWarnings'; swexp = 'ILINK_wexp'; swrty = 'ILINK_wrty'; swdup = 'ILINK_wdup'; swdpl = 'ILINK_wdpl'; swnou = 'ILINK_wnou'; swuld = 'ILINK_wuld'; swsrd = 'ILINK_wsrd'; swdee = 'ILINK_wdee'; swsnf = 'ILINK_wsnf'; // Outputs sOutput_OutputFile = 'OutputFile'; sOutput_StateFiles = 'StateFiles'; sOutput_MapFile = 'MapFile'; sOutput_SymbolFile = 'SymbolFile'; sOutput_ImportLibrary = 'ImportLibrary'; sOutput_PackageStaticLibrary = 'PackageStaticLibrary'; implementation end.
unit NetDEVSDK; interface uses System.Classes, System.SysUtils, Winapi.Windows, System.IOUtils; const NETDEVSDK_DLL = 'NetDEVSDK.DLL'; DEFAULT_CHANNEL = 1; NETDEV_LEN_64 = 63; ERROR_CODE: array [0 .. 157, 0 .. 1] of string = // (('0', 'Succeeded'), // ('-1', 'Failed'), // ('1', 'Common error'), // ('2', 'Common error returned by device'), // ('3', 'Failed to call system function. See errno'), // ('4', 'Null pointer'), // ('5', 'Invalid parameter'), // ('6', 'Invalid module ID'), // ('7', 'Failed to allocate memory'), // ('8', 'Not supported by device'), // ('9', 'listen Failed to create socketlisten'), // ('10', 'Failed to initialize lock'), // ('11', 'Failed to initialize semaphore'), // ('12', 'Error occurred during SDK resource allocation'), // ('13', 'SDK not initialized'), // ('14', 'SDK already initialized'), // ('15', 'Data not all sent'), // ('16', 'More data required'), // ('17', 'Failed to create connection'), // ('18', 'Failed to send request message'), // ('19', 'Message timeout'), // ('20', 'Failed to decode response message'), // ('21', 'Socket failed to receive message'), // ('22', 'Maximum number reached. The assigned numbers of registration connections and preview connections reached the maximum supported by SDK'), ('24', 'Failed to obtain local port number'), // ('25', 'Failed to create thread'), // ('26', 'Buffer is too small for receiving device data'), // ('27', 'Failed to obtain the IP or MACaddress of the local PC'), // ('28', 'Resource code not exist'), // ('31', 'Incorrect message content'), // ('32', 'Failed to obtain capabilities'), // ('33', 'User not subscribed to alarms'), // ('34', 'User authentication failed'), // ('35', 'Failed to bind alarms'), // ('36', 'Not enough permission. In Windows, it is normally because the operator is not an administrator.'), ('37', 'Manufacturers that are not supported'), // ('38', 'Function not supported'), // ('39', 'File transmission failed'), // ('40', 'Json common error'), // ('41', 'No result'), // ('42', 'Device type that are not supported'), // ('101', 'Incorrect password'), // ('102', 'Number of login users reachedthe upper limit'), // ('103', 'User not online'), // ('104', 'User not online'), // ('105', 'User has no rights'), // ('106', 'Reached the upper limitno moreusers can be added'), // ('107', 'User already exists'), // ('108', 'Password changed'), // ('109', 'Remote user with weak password'), // ('250', 'Playback ended'), // ('251', 'Playback controlling module not exist'), // ('252', 'Beyond playback capability'), // ('253', 'Recording file controlling module not exist'), // ('254', 'No recording'), // ('255', 'Cannot get the URL for playback'), // ('300', 'Failed to set preset'), // ('301', 'Failed to query preset'), // ('302', 'Failed to query route'), // ('303', 'Failed to start route recording'), // ('304', 'Failed to end route recording'), // ('305', 'Failed to query patrol route'), // ('306', 'Failed to set patrol route'), // ('307', 'PTZ operation failed'), // ('308', 'Preset is being used in patrol route and cannot be deleted'), // ('309', 'Discontinuous presets'), // ('310', 'Route is in use and cannotbe deleted'), // ('311', 'Serial modes do not match'), // ('312', 'Route does not exist'), // ('313', 'Route points are full'), // ('500', 'Device stream full'), // ('501', 'Device stream closed'), // ('502', 'Device stream does not exist'), // ('503', 'Failed to read file (directory) status'), // ('504', 'File does not exist'), // ('505', 'Failed to create directory'), // ('506', 'Subscription is full for current user'), // ('507', 'Only admin can upgrade'), // ('508', 'Upgrade not started'), // ('509', 'Upgrade in process'), // ('510', 'Insufficient memory for upgrade'), // ('511', 'Error occurred while opening the mirror file during upgrade'), // ('512', 'Error occurred while upgrading FLASH'), // ('513', 'Cannot load multiple upgrade processes at the same time'), // ('514', 'Upgrade timeout'), // ('515', 'Invalid configuration file'), // ('516', 'Storage resource not allocated'), // ('1000', 'Basic decoding error code'), // ('1001', 'Basic decoding error code'), // ('1002', 'Invalid input parameter'), // ('1003', 'Not enough system memory'), // ('1004', 'Failed to create SOCKET'), // ('1005', 'Failed to receive'), // ('1006', 'None received'), // ('1007', 'Currently not supported'), // ('1008', 'Failed to create the thread'), // ('1009', 'Failed to load the dynamiclibrary'), // ('1010', 'Failed to get the dynamiclibrary'), // ('1011', 'Failed to send'), // ('1012', 'No permission to create the file'), // ('1013', 'Failed to find the file toread'), // ('1014', 'Close log'), // ('1257', 'Failed to initialize the player'), // ('1258', 'Failed to allocate playingchannel resources'), // ('1259', 'Failed to get playing channel resources'), // ('1260', 'Cache queue full'), // ('1261', 'Cache queue empty'), // ('1262', 'Failed to open the file'), // ('1263', 'The file is read'), // ('1264', 'Disk space full'), // ('1265', 'Failed to read'), // ('1266', 'The microphone does not exist'), // ('1267', 'TS packing not finished'), // ('1268', 'Recording saved'), // ('1269', 'Resolution changed'), // ('1270', 'Video Record'), // ('1513', 'Failed to start media streaming'), // ('1514', 'Failed to close media streaming'), // ('1515', 'Failed to receive data dueto network error'), // ('1516', 'Failed to handle media data'), // ('1517', 'Playing not started in playing channel'), // ('1518', 'Failed to enter media stream data'), // ('1519', 'Input data cache full'), // ('1520', 'Failed to set media streamdata callback function'), // ('1521', 'Error occurred when running voice service'), // ('1522', 'Failed to start voice service'), // ('1523', 'Failed to close voice service'), // ('1524', 'Unknown media stream'), // ('1525', 'Packet loss'), // ('1526', 'More packets are needed for the packing'), // ('1527', 'Failed to create the decoder'), // ('1528', 'Failed to decode'), // ('1529', 'Not enough data received'), // ('1530', 'Display resources full'), // ('1531', 'Display resources do not exist'), // ('1532', 'Failed to create the resources'), // ('1533', 'Audio resources do not exist'), // ('1534', 'Decoder requires more data'), // ('1535', 'Failed to create encoder'), // ('1536', 'Capture resources do not exist'), // ('1537', 'Recording already opened'), // ('1538', 'Decoding in progress, please wait'), // ('1539', 'Too much data, still needpacking'), // ('2000', 'Live video service alreadyestablished'), // ('2001', 'Media stream not ready'), // ('2002', 'Display resource is busy for live video service'), // ('2003', 'Control module for live video not exist'), // ('2004', 'Live stream resource full'), // ('2100', 'Format of captured image not supported'), // ('2101', 'Insufficient disk space'), // ('2102', 'No decoded image for capture'), // ('2103', 'Single capture failed'), // ('2200', 'Two-way audio already exists'), // ('2201', 'Two-way audio service doesnot exist'), // ('2202', 'Invalid two-way audio resource code'), // ('2203', 'Audio resource is being used by two-way audio'), // ('2204', 'Two-way audio failed'), // ('2205', 'No more audio service allowed')); type TNETDEVAlarmInfo = record tAlarmTime: Int64; dwChannelID: Int32; wIndex: UINT16; pszName: PAnsiChar; dwTotalBandWidth: Int32; dwUnusedBandwidth: Int32; dwTotalStreamNum: Int32; dwFreeStreamNum: Int32; byRes: Array [0 .. 10 - 1] of BYTE; end; TNETDEV_ExceptionCallBack_PF = procedure(plUserID: IntPtr; dwType: Int32; plExpHandle: IntPtr; plUserData: IntPtr)stdcall; TNetDEVLiveStreamIndex = (NETDEV_LIVE_STREAM_INDEX_MAIN, NETDEV_LIVE_STREAM_INDEX_AUX, NETDEV_LIVE_STREAM_INDEX_THIRD, NETDEV_LIVE_STREAM_INDEX_INVALID); TNetDEVProtocol = (NETDEV_TRANSPROTOCOL_RTPUDP, NETDEV_TRANSPROTOCOL_RTPTCP); TNetDEVPictureFluency = (NETDEV_PICTURE_REAL, NETDEV_PICTURE_FLUENCY); TNetDEVPictureFormat = (NETDEV_PICTURE_BMP, NETDEV_PICTURE_JPG, NETDEV_PICTURE_INVALID); TNETDEVException = (NETDEV_EXCEPTION_REPORT_VOD_END = 300, NETDEV_EXCEPTION_REPORT_VOD_ABEND = 301, NETDEV_EXCEPTION_REPORT_BACKUP_END = 302, NETDEV_EXCEPTION_REPORT_BACKUP_DISC_OUT = 303, NETDEV_EXCEPTION_REPORT_BACKUP_DISC_FULL = 304, NETDEV_EXCEPTION_REPORT_BACKUP_ABEND = 305, NETDEV_EXCEPTION_EXCHANGE = $8000, NETDEV_EXCEPTION_REPORT_INVALID = $FFFF); TOnException = procedure(AType: TNETDEVException) of object; TNetDEVDeviceInfo = record dwDevType: Int32; wAlarmInPortNum: Int16; wAlarmOutPortNum: Int16; dwChannelNum: Int32; byRes: array [0 .. 47] of BYTE; end; TPreviewInfo = record dwChannelID: Int32; dwStreamType: Int32; dwLinkMode: Int32; hPlayWnd: IntPtr; dwFluency: Int32; byRes: array [0 .. 259] of BYTE; constructor Create(AHandle: HWND; AType: TNetDEVLiveStreamIndex = NETDEV_LIVE_STREAM_INDEX_MAIN; AChannel: Int32 = DEFAULT_CHANNEL; AMode: TNetDEVProtocol = NETDEV_TRANSPROTOCOL_RTPTCP; AFluncy: TNetDEVPictureFluency = NETDEV_PICTURE_REAL); end; TNETDEVVideoStreamInfo = record enStreamType: Int32; bEnableFlag: Int32; dwHeight: Int32; dwWidth: Int32; dwFrameRate: Int32; dwBitRate: Int32; enCodeType: Int32; enQuality: Int32; dwGop: Int32; byRes: Array [0 .. 31] of BYTE; end; TNETDEVDeviceBasicInfo = record szDevModel: Array [0 .. NETDEV_LEN_64] of AnsiChar; szSerialNum: Array [0 .. NETDEV_LEN_64] of AnsiChar; szFirmwareVersion: Array [0 .. NETDEV_LEN_64] of AnsiChar; szMacAddress: Array [0 .. NETDEV_LEN_64] of AnsiChar; szDeviceName: Array [0 .. NETDEV_LEN_64] of AnsiChar; byRes: Array [0 .. 447] of BYTE; end; TSourceDataCallBack = procedure(lpRealHandle: IntPtr; var pucBuffer: BYTE; dwBufSize: Int32; dwMediaDataType: Int32; lpUserParam: IntPtr)stdcall; TExceptionCallBack = procedure(plUserID: IntPtr; dwType: Int32; var stAlarmInfo: TNETDEVAlarmInfo; plExpHandle, plUserData: IntPtr)stdcall; TNETDEV_Init = function: Boolean stdcall; TNETDEV_Login = function(pszDevIP: PAnsiChar; wDevPort: Int16; pszUserName: PAnsiChar; pszPassword: PAnsiChar; var pstDevInfo: TNetDEVDeviceInfo): IntPtr stdcall; TNETDEV_Logout = function(lpUserID: IntPtr): Boolean stdcall; TNETDEV_GetDevConfig = function(lpUserID: IntPtr; dwChannelID: Int32; dwCommand: Int32; var lpOutBuffer: TNETDEVVideoStreamInfo; dwOutBufferSize: Int32; var pdwBytesReturned: Int32): Boolean stdcall; TNETDEV_RealPlay = function(lpUserID: IntPtr; var pstPreviewInfo: TPreviewInfo; cbDataCallBack: TSourceDataCallBack; lpUserData: IntPtr): IntPtr stdcall; TNETDEV_StopRealPlay = function(lpRealHandle: IntPtr): Boolean stdcall; TNETDEV_CapturePicture = function(lpRealHandle: IntPtr; szFileName: PAnsiChar; dwCaptureMode: Int32): Boolean stdcall; TNETDEV_GetLastError = function(): Int32 stdcall; TNETDEV_SetExceptionCallBack = function(cbExceptionCallBack: TNETDEV_ExceptionCallBack_PF; lpUserData: IntPtr): Boolean stdcall; TNETDEV_Cleanup = function(): Boolean stdcall; NETDEV_SetLogPath = function(pszLogPath: PAnsiChar): Boolean stdcall; TNETDEV_SetPlayDataCallBack = function(lpRealHandle: IntPtr; cbPlayDataCallBack: IntPtr; bContinue: Int32; lpUserData: IntPtr): Boolean stdcall; TCCTVInfo = record Enable: Boolean; IP: String; Port: Integer; ID: String; Password: String; function Equals(AInfo: TCCTVInfo): Boolean; end; TNetDEV = class private FDLLHandle: THandle; FInited: Boolean; FUserID: IntPtr; FRealHandle: IntPtr; FNETDEV_StopRealPlay: TNETDEV_StopRealPlay; FNETDEV_Init: TNETDEV_Init; FNETDEV_SetExceptionCallBack: TNETDEV_SetExceptionCallBack; FNETDEV_CapturePicture: TNETDEV_CapturePicture; FNETDEV_RealPlay: TNETDEV_RealPlay; FNETDEV_SetPlayDataCallBack: TNETDEV_SetPlayDataCallBack; FNETDEV_Logout: TNETDEV_Logout; FNETDEV_GetDevConfig: TNETDEV_GetDevConfig; FNETDEV_Login: TNETDEV_Login; FNETDEV_Cleanup: TNETDEV_Cleanup; FNETDEV_SetLogPath: NETDEV_SetLogPath; FNETDEV_GetLastError: TNETDEV_GetLastError; FCCTVInfo: TCCTVInfo; FTag: Cardinal; procedure FreeDLL; procedure LoadDLL(APath: string); procedure SetOnException(const Value: TOnException); public constructor Create(const ALibPath: string; const ALogPath: string); destructor Destroy; override; function GetLastError: string; function Played: Boolean; function Init: Boolean; function Cleanup: Boolean; function Login: Boolean; overload; function Login(const pszDevIP: String; const wDevPort: Int16; const pszUserName: String; const pszPassword: String): Boolean; overload; function Logout: Boolean; function GetStreamInfo(const dwChannelID: Int32; var lpOutBuffer: TNETDEVVideoStreamInfo; const dwOutBufferSize: Int32; var pdwBytesReturned: Int32): Boolean; function RealPlay(APreviewInfo: TPreviewInfo): Boolean; function StopRealPlay: Boolean; function CapturePicture(const szFileName: String; const dwCaptureMode: TNetDEVPictureFormat = NETDEV_PICTURE_JPG): Boolean; function SetLogPath(const szPath: string): Boolean; property OnException: TOnException write SetOnException; property CCTVInfo: TCCTVInfo read FCCTVInfo write FCCTVInfo; property Tag: Cardinal read FTag write FTag; end; implementation var MyOnException: TOnException; procedure ExceptionCallBack(plUserID: IntPtr; dwType: Int32; plExpHandle, plUserData: IntPtr)stdcall; begin if Assigned(MyOnException) then MyOnException(TNETDEVException(dwType)); end; { TNetDEV } function TNetDEV.CapturePicture(const szFileName: String; const dwCaptureMode: TNetDEVPictureFormat): Boolean; var Name: AnsiString; begin if FRealHandle = 0 then raise Exception.Create('StopRealPlay'); Name := AnsiString(szFileName); result := FNETDEV_CapturePicture(FRealHandle, PAnsiChar(Name), Int32(dwCaptureMode)); end; function TNetDEV.Cleanup: Boolean; begin if not FInited then Exit(False); result := FNETDEV_Cleanup; FInited := not result; end; constructor TNetDEV.Create(const ALibPath: string; const ALogPath: string); begin if not TDirectory.Exists(ALibPath) then raise Exception.Create('path not exist. [' + ALibPath + ']'); MyOnException := nil; FInited := False; FDLLHandle := 0; FUserID := 0; FRealHandle := 0; FTag := 0; LoadDLL(ALibPath); SetLogPath(ALogPath); Init; end; destructor TNetDEV.Destroy; begin try StopRealPlay; Logout; Cleanup; except on E: Exception do end; FreeDLL; inherited; end; procedure TNetDEV.FreeDLL; begin if FDLLHandle <> 0 then begin try FDLLHandle := 0; except on E: Exception do end; end; end; function TNetDEV.GetStreamInfo(const dwChannelID: Int32; var lpOutBuffer: TNETDEVVideoStreamInfo; const dwOutBufferSize: Int32; var pdwBytesReturned: Int32): Boolean; const NETDEV_GET_STREAMCFG = 120; begin if FUserID = 0 then Exit(False); result := FNETDEV_GetDevConfig(FUserID, dwChannelID, NETDEV_GET_STREAMCFG, lpOutBuffer, dwOutBufferSize, pdwBytesReturned); end; function TNetDEV.Init: Boolean; begin result := FNETDEV_Init; FInited := result; end; function TNetDEV.GetLastError: String; var I: Integer; Code: Integer; begin if FDLLHandle = 0 then Exit('Unload DLL'); Code := FNETDEV_GetLastError; for I := Low(ERROR_CODE) to High(ERROR_CODE) do begin if ERROR_CODE[I, 0].ToInteger = Code then Exit(ERROR_CODE[I, 1]); end; result := 'Unknown Error'; end; procedure TNetDEV.LoadDLL(APath: string); begin SetCurrentDir(APath); FDLLHandle := LoadLibrary(NETDEVSDK_DLL); if FDLLHandle < 32 then raise Exception.Create('Load DLL Exception'); @FNETDEV_Init := GetProcAddress(FDLLHandle, 'NETDEV_Init'); @FNETDEV_Login := GetProcAddress(FDLLHandle, 'NETDEV_Login'); @FNETDEV_Logout := GetProcAddress(FDLLHandle, 'NETDEV_Logout'); @FNETDEV_RealPlay := GetProcAddress(FDLLHandle, 'NETDEV_RealPlay'); @FNETDEV_GetDevConfig := GetProcAddress(FDLLHandle, 'NETDEV_GetDevConfig'); @FNETDEV_StopRealPlay := GetProcAddress(FDLLHandle, 'NETDEV_StopRealPlay'); @FNETDEV_CapturePicture := GetProcAddress(FDLLHandle, 'NETDEV_CapturePicture'); @FNETDEV_GetLastError := GetProcAddress(FDLLHandle, 'NETDEV_GetLastError'); @FNETDEV_SetExceptionCallBack := GetProcAddress(FDLLHandle, 'NETDEV_SetExceptionCallBack'); @FNETDEV_SetPlayDataCallBack := GetProcAddress(FDLLHandle, 'NETDEV_SetPlayDataCallBack'); @FNETDEV_Cleanup := GetProcAddress(FDLLHandle, 'NETDEV_Cleanup'); @FNETDEV_SetLogPath := GetProcAddress(FDLLHandle, 'NETDEV_SetLogPath'); SetCurrentDir(TPath.GetDocumentsPath); end; function TNetDEV.Login(const pszDevIP: String; const wDevPort: Int16; const pszUserName, pszPassword: String): Boolean; var pstDevInfo: TNetDEVDeviceInfo; IP, ID, Pwd: AnsiString; begin if FUserID > 0 then Exit(True); IP := AnsiString(pszDevIP); ID := AnsiString(pszUserName); Pwd := AnsiString(pszPassword); FUserID := FNETDEV_Login(PAnsiChar(IP), wDevPort, PAnsiChar(ID), PAnsiChar(Pwd), pstDevInfo); result := FUserID > 0; end; function TNetDEV.Login: Boolean; begin result := Login(FCCTVInfo.IP, FCCTVInfo.Port, FCCTVInfo.ID, FCCTVInfo.Password); end; function TNetDEV.Logout: Boolean; begin if FUserID = 0 then Exit(False); result := FNETDEV_Logout(FUserID); if result then FUserID := 0; end; function TNetDEV.Played: Boolean; begin result := FRealHandle > 0; end; function TNetDEV.RealPlay(APreviewInfo: TPreviewInfo): Boolean; begin if FUserID = 0 then raise Exception.Create('Logout'); if FRealHandle > 0 then StopRealPlay; FRealHandle := FNETDEV_RealPlay(FUserID, APreviewInfo, nil, 0); result := FRealHandle > 0; if result then FNETDEV_SetExceptionCallBack(ExceptionCallBack, 0); end; function TNetDEV.SetLogPath(const szPath: string): Boolean; var Path: AnsiString; begin Path := AnsiString(szPath); result := FNETDEV_SetLogPath(PAnsiChar(Path)); end; procedure TNetDEV.SetOnException(const Value: TOnException); begin MyOnException := Value; end; function TNetDEV.StopRealPlay: Boolean; begin if FRealHandle = 0 then Exit(False); result := FNETDEV_StopRealPlay(FRealHandle); if result then begin FRealHandle := 0; FNETDEV_SetExceptionCallBack(nil, 0) end; end; { TPreviewInfo } constructor TPreviewInfo.Create(AHandle: HWND; AType: TNetDEVLiveStreamIndex; AChannel: Int32; AMode: TNetDEVProtocol; AFluncy: TNetDEVPictureFluency); begin Self.dwChannelID := AChannel; Self.dwStreamType := Int32(AType); Self.dwLinkMode := Int32(AMode); Self.hPlayWnd := AHandle; Self.dwFluency := Int32(AFluncy); end; { TCCTVInfo } function TCCTVInfo.Equals(AInfo: TCCTVInfo): Boolean; begin result := (Self.IP = AInfo.IP) and (Self.Port = AInfo.Port) and (Self.ID = AInfo.ID) and (Self.Password = AInfo.Password) end; end.
{Ejercicio 10 Realice las funciones de una calculadora simple. Los datos de entrada serán una secuencia de dígitos decimales y los operadores +, *, / y -, seguida de un signo =. Los operadores se aplican en el orden en que aparecen en los datos de entrada, y producen resultados enteros, o sea, si bien se ingresa el operador de la división con el símbolo /, el comportamiento es el de DIV. Asuma que se ingresa al menos un número. Ej. de entrada: 4 + 3 / 2 * 8 - 4 = Ej. de salida: 20 a) Escriba un programa en PASCAL que resuelva el problema, suponiendo que hay exactamente un espacio en blanco de separación entre cada dígito decimal y operador (o símbolo de =). b) Escriba otro programa en PASCAL que resuelva nuevamente el problema, suponiendo ahora que no hay ningún espacio en blanco de separación entre cada dígito decimal y operador (o símbolo de =). Es decir, que cada díigito está inmediatamente seguido por un operador (o símbolo de =). c) ¿Qué cambios sería necesario realizar a los programas de las partes anteriores si en vez de dígitos (de una cifra) se ingresan enteros cualesquiera (de una o más cifras)?} program ejercicio10; var entrada : char; aux, resultado, auxsuma, auxresta, auxprod, auxdiv : integer; begin writeln('Ingrese los datos a evaluar:'); read(entrada); //resultado := ord(entrada)-48; while (entrada <> '=') do begin aux := ord(entrada); //writeln(entrada,'<--->',aux); //writeln; if (aux >= 48) and (aux <= 57) then begin resultado := aux - 48; //writeln('resultado1-->',resultado); end; if (aux = 43) then begin read(entrada); read(entrada); auxsuma := ord(entrada) - 48; //writeln('auxsuma--->',auxsuma); resultado := resultado + auxsuma; //writeln('Resultado suma--->',resultado) end; if (aux = 45) then begin read(entrada); read(entrada); auxresta := ord(entrada) - 48; //writeln('auxresta--->',auxresta); resultado := resultado - auxresta; //writeln('Resultado resta--->',resultado) end; if (aux = 42) then begin read(entrada); read(entrada); auxprod := ord(entrada) - 48; //writeln('auxprod--->',auxprod); resultado := resultado * auxprod; //writeln('Resultado producto--->',resultado) end; if (aux = 47) then begin read(entrada); read(entrada); auxdiv := ord(entrada) - 48; //writeln('auxdiv--->',auxdiv); resultado := resultado div auxdiv; //writeln('Resultado division entera--->',resultado) end; read(entrada) end; writeln('Resultado final--->',resultado); end.
unit Dialogs4D.Modal.Confirm; interface uses Dialogs4D.Modal.Intf; type TDialogModalConfirm = class(TInterfacedObject, IDialogModalConfirm) private /// <summary> /// Displays a dialog box for the user with a question. /// </summary> /// <param name="Content"> /// Question to be displayed to the user. /// </param> /// <returns> /// Returns true if the user has confirmed the question. /// </returns> function Show(const Content: string): Boolean; end; implementation uses {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} UniGuiDialogs, UniGuiTypes, {$ELSEIF DEFINED(MSWINDOWS)} Vcl.Forms, Winapi.Windows, Vcl.BlockUI.Intf, Vcl.BlockUI, {$ENDIF} Vcl.Controls, System.SysUtils, Dialogs4D.Constants; {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} function TDialogModalConfirm.Show(const Content: string): Boolean; begin Result := MessageDlg(Content, mtConfirmation, [mbYes, mbNo]) = mrYes; end; {$ELSEIF DEFINED(MSWINDOWS)} function TDialogModalConfirm.Show(const Content: string): Boolean; var BlockUI: IBlockUI; begin BlockUI := TBlockUI.Create(); Result := Application.MessageBox(PWideChar(Content), PWideChar(Application.Title), MB_ICONQUESTION + MB_YESNO) = mrYes; end; {$ELSE} function TDialogModalConfirm.Show(const Content: string): Boolean; begin raise Exception.Create(DIRECTIVE_NOT_DEFINED); end; {$ENDIF} end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC SAP SQL Anywhere metadata } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.ASAMeta; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator, FireDAC.Phys; type TFDPhysASAMetadata = class (TFDPhysConnectionMetadata) protected function GetKind: TFDRDBMSKind; override; function GetTxSavepoints: Boolean; override; function GetEventKinds: String; override; function GetEventSupported: Boolean; override; function GetParamNameMaxLength: Integer; override; function GetNameParts: TFDPhysNameParts; override; function GetNameQuotedCaseSensParts: TFDPhysNameParts; override; function GetNameCaseSensParts: TFDPhysNameParts; override; function GetNameDefLowCaseParts: TFDPhysNameParts; override; function GetIdentityInsertSupported: Boolean; override; function GetDefValuesSupported: TFDPhysDefaultValues; override; function GetAsyncAbortSupported: Boolean; override; function GetLimitOptions: TFDPhysLimitOptions; override; function GetSelectOptions: TFDPhysSelectOptions; override; function GetBackslashEscSupported: Boolean; override; function InternalEscapeBoolean(const AStr: String): String; override; function InternalEscapeDate(const AStr: String): String; override; function InternalEscapeDateTime(const AStr: String): String; override; function InternalEscapeFloat(const AStr: String): String; override; function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override; function InternalEscapeTime(const AStr: String): String; override; function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override; public constructor Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVerison: TFDVersion; const ACSVKeywords: String); end; TFDPhysASACommandGenerator = class(TFDPhysCommandGenerator) protected function GetIdentity(ASessionScope: Boolean): String; override; function GetPessimisticLock: String; override; function GetSavepoint(const AName: String): String; override; function GetRollbackToSavepoint(const AName: String): String; override; function GetCall(const AName: String): String; override; function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; override; function GetColumnType(AColumn: TFDDatSColumn): String; override; function GetMerge(AAction: TFDPhysMergeAction): String; override; end; implementation uses System.SysUtils, FireDAC.Stan.Consts, FireDAC.Stan.Util; {-------------------------------------------------------------------------------} { TFDPhysOraMetadata } {-------------------------------------------------------------------------------} constructor TFDPhysASAMetadata.Create(const AConnectionObj: TFDPhysConnection; AServerVersion, AClientVerison: TFDVersion; const ACSVKeywords: String); var i: Integer; begin inherited Create(AConnectionObj, AServerVersion, AClientVerison, False); if ACSVKeywords <> '' then begin FKeywords.CommaText := ACSVKeywords; // Early ASA ODBC drivers erroneously return 'DBA' as a keyword. // But really it is not a keyword and may be used as identifier. i := FKeywords.IndexOf('dba'); if i >= 0 then FKeywords.Delete(i); end; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.SQLAnywhere; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetNameCaseSensParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetNameDefLowCaseParts: TFDPhysNameParts; begin Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetParamNameMaxLength: Integer; begin Result := 128; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetNameParts: TFDPhysNameParts; begin Result := [npSchema, npBaseObject, npObject]; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetTxSavepoints: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetEventSupported: Boolean; begin {$IFDEF MSWINDOWS} Result := True; {$ELSE} Result := False; {$ENDIF} end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetEventKinds: String; begin {$IFDEF MSWINDOWS} Result := S_FD_EventKind_ASA_Events; {$ELSE} Result := ''; {$ENDIF} end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetIdentityInsertSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetDefValuesSupported: TFDPhysDefaultValues; begin Result := dvDef; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetAsyncAbortSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetLimitOptions: TFDPhysLimitOptions; begin if GetServerVersion >= cvSybaseASA9 then Result := [loSkip, loRows] else Result := [loRows]; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetSelectOptions: TFDPhysSelectOptions; begin Result := [soWithoutFrom, soInlineView]; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.GetBackslashEscSupported: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.InternalEscapeBoolean(const AStr: String): String; begin if CompareText(AStr, S_FD_True) = 0 then Result := '1' else Result := '0'; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.InternalEscapeDate(const AStr: String): String; begin Result := 'CONVERT(DATETIME, ' + AnsiQuotedStr(AStr, '''') + ', 20)'; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.InternalEscapeDateTime(const AStr: String): String; begin Result := 'CONVERT(DATETIME, ' + AnsiQuotedStr(AStr, '''') + ', 20)'; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.InternalEscapeTime(const AStr: String): String; begin Result := 'CONVERT(DATETIME, ' + AnsiQuotedStr(AStr, '''') + ', 114)'; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.InternalEscapeFloat(const AStr: String): String; begin Result := AStr; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; var sName: String; A1, A2, A3: String; rSeq: TFDPhysEscapeData; i: Integer; function AddArgs: string; begin Result := '(' + AddEscapeSequenceArgs(ASeq) + ')'; end; begin sName := ASeq.FName; if Length(ASeq.FArgs) >= 1 then begin A1 := ASeq.FArgs[0]; if Length(ASeq.FArgs) >= 2 then begin A2 := ASeq.FArgs[1]; if Length(ASeq.FArgs) >= 3 then A3 := ASeq.FArgs[2]; end; end; case ASeq.FFunc of // the same // char efASCII, efCHAR, efLEFT, efLTRIM, efREPLACE, efRIGHT, efRTRIM, efSPACE, efSUBSTRING, // numeric efACOS, efASIN, efATAN, efABS, efCEILING, efCOS, efCOT, efDEGREES, efEXP, efFLOOR, efLOG, efLOG10, efPOWER, efPI, efSIGN, efSIN, efSQRT, efTAN: Result := sName + AddArgs; // character efBIT_LENGTH: Result := '(LENGTH(' + A1 + ') * 8)'; efCHAR_LENGTH: Result := 'LENGTH' + AddArgs; efCONCAT: Result := '(' + A1 + ' + ' + A2 + ')'; efINSERT: Result := 'STUFF' + AddArgs; efLCASE: Result := 'LOWER' + AddArgs; efLENGTH: Result := 'LENGTH(RTRIM(' + A1 + '))'; efLOCATE: begin Result := 'LOCATE(' + A2 + ', ' + A1; if A3 <> '' then Result := Result + ', ' + A3; Result := Result + ')'; end; efOCTET_LENGTH:Result := 'LENGTH' + AddArgs; efPOSITION: Result := 'CHARINDEX' + AddArgs; efREPEAT: Result := 'REPLICATE' + AddArgs; efUCASE: Result := 'UPPER' + AddArgs; // numeric efRANDOM: Result := 'RAND' + AddArgs; efTRUNCATE: Result := 'CAST(' + A1 + ' AS BIGINT)'; efATAN2: Result := 'ATN2' + AddArgs; efMOD: Result := 'MOD' + AddArgs; efROUND: if A2 = '' then Result := sName + '(' + A1 + ', 0)' else Result := sName + AddArgs; efRADIANS: Result := sName + '(' + A1 + ' + 0.0)'; // date and time efCURDATE, efCURTIME, efNOW: Result := 'GETDATE()'; efDAYNAME: Result := 'DATENAME(WEEKDAY, ' + A1 + ')'; efDAYOFMONTH: Result := 'DATEPART(DAY, ' + A1 + ')'; efDAYOFWEEK: Result := 'DATEPART(WEEKDAY, ' + A1 + ')'; efDAYOFYEAR: Result := 'DATEPART(DAYOFYEAR, ' + A1 + ')'; efEXTRACT: begin rSeq.FKind := eskFunction; A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'DAY' then A1 := 'DAYOFMONTH'; rSeq.FName := A1; SetLength(rSeq.FArgs, 1); rSeq.FArgs[0] := ASeq.FArgs[1]; EscapeFuncToID(rSeq); Result := InternalEscapeFunction(rSeq); end; efHOUR: Result := 'DATEPART(HOUR, ' + A1 + ')'; efMINUTE: Result := 'DATEPART(MINUTE, ' + A1 + ')'; efMONTH: Result := 'DATEPART(MONTH, ' + A1 + ')'; efMONTHNAME: Result := 'DATENAME(MONTH, ' + A1 + ')'; efQUARTER: Result := 'DATEPART(QUARTER, ' + A1 + ')'; efSECOND: Result := 'DATEPART(SECOND, ' + A1 + ')'; efTIMESTAMPADD: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'FRAC_SECOND' then begin A1 := 'MILLISECOND'; A2 := '(' + A2 + ' / 1000)'; end; ASeq.FArgs[0] := A1; ASeq.FArgs[1] := A2; Result := 'DATEADD' + AddArgs; end; efTIMESTAMPDIFF: begin A1 := UpperCase(FDUnquote(Trim(A1), '''')); if A1 = 'FRAC_SECOND' then A1 := 'MILLISECOND'; ASeq.FArgs[0] := A1; Result := 'DATEDIFF' + AddArgs; if A1 = 'MILLISECOND' then Result := '(' + Result + ' * 1000.0)'; end; efWEEK: Result := 'DATEPART(WEEK, ' + A1 + ')'; efYEAR: Result := 'DATEPART(YEAR, ' + A1 + ')'; // system efCATALOG: Result := 'DB_NAME()'; efSCHEMA: Result := 'CURRENT_USER()'; efIFNULL: Result := 'CASE WHEN ' + A1 + ' IS NULL THEN ' + A2 + ' ELSE ' + A1 + ' END'; efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END'; efDECODE: begin Result := 'CASE ' + ASeq.FArgs[0]; i := 1; while i < Length(ASeq.FArgs) - 1 do begin Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1]; Inc(i, 2); end; if i = Length(ASeq.FArgs) - 1 then Result := Result + ' ELSE ' + ASeq.FArgs[i]; Result := Result + ' END'; end; // convert efCONVERT: Result := 'CONVERT(' + A2 + ', ' + A1 + ')'; else UnsupportedEscape(ASeq); end; end; {-------------------------------------------------------------------------------} function TFDPhysASAMetadata.InternalGetSQLCommandKind( const ATokens: TStrings): TFDPhysCommandKind; var sToken: String; begin sToken := ATokens[0]; if sToken = 'CALL' then Result := skExecute else if sToken = 'BEGIN' then if ATokens.Count = 1 then Result := skNotResolved else if ATokens[1] = 'TRANSACTION' then Result := skStartTransaction else Result := inherited InternalGetSQLCommandKind(ATokens) else Result := inherited InternalGetSQLCommandKind(ATokens); end; {-------------------------------------------------------------------------------} { TFDPhysASACommandGenerator } {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetIdentity(ASessionScope: Boolean): String; begin Result := '@@IDENTITY'; end; {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetPessimisticLock: String; var lNeedFrom: Boolean; begin Result := 'BEGIN '; if FOptions.UpdateOptions.LockWait then Result := Result + 'SET TEMPORARY OPTION BLOCKING_TIMEOUT = 0; ' else Result := Result + 'SET TEMPORARY OPTION BLOCKING_TIMEOUT = 1000; '; Result := Result + 'SELECT ' + GetSelectList(True, False, lNeedFrom) + ' FROM ' + GetFrom + ' WHERE ' + GetWhere(False, True, False) + ' FOR UPDATE BY LOCK; '; Result := Result + 'SET TEMPORARY OPTION BLOCKING_TIMEOUT =; ' + 'EXCEPTION WHEN OTHERS THEN SET TEMPORARY OPTION BLOCKING_TIMEOUT =; RESIGNAL; END'; FCommandKind := skSelectForLock; ASSERT(lNeedFrom); end; {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetSavepoint(const AName: String): String; begin Result := 'SAVEPOINT ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetRollbackToSavepoint(const AName: String): String; begin Result := 'ROLLBACK TO SAVEPOINT ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetCall(const AName: String): String; begin Result := 'CALL ' + AName; end; {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetLimitSelect(const ASQL: String; ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String; var s: String; iAfter: Integer; begin if (FConnMeta.ServerVersion >= cvSybaseASA9) and (ASkip > 0) and (ARows <> 0) and FDStartsWithKW(ASQL, 'SELECT', iAfter) and not FDStartsWithKW(ASQL, 'SELECT TOP', iAfter) then begin Result := 'SELECT TOP '; s := UpperCase(ASQL); if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or FDHasKW(s, 'EXCEPT') then Result := Result + IntToStr(ARows) + ' START AT ' + IntToStr(ASkip + 1) + ' * FROM (' + BRK + ASQL + BRK + ') A' else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then Result := 'SELECT DISTINCT TOP ' + IntToStr(ARows) + ' START AT ' + IntToStr(ASkip + 1) + Copy(ASQL, iAfter, MAXINT) else Result := Result + IntToStr(ARows) + ' START AT ' + IntToStr(ASkip + 1) + Copy(ASQL, iAfter, MAXINT); end else Result := inherited GetLimitSelect(ASQL, ASkip, ARows, AOptions); end; {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String; begin case AColumn.DataType of dtBoolean: Result := 'BIT'; dtSByte: Result := 'TINYINT'; dtInt16: Result := 'SMALLINT'; dtInt32: Result := 'INTEGER'; dtInt64: Result := 'BIGINT'; dtByte: Result := 'UNSIGNED TINYINT'; dtUInt16: Result := 'UNSIGNED SMALLINT'; dtUInt32: Result := 'UNSIGNED INTEGER'; dtUInt64: Result := 'UNSIGNED BIGINT'; dtSingle: Result := 'REAL'; dtDouble, dtExtended: Result := 'DOUBLE'; dtCurrency: Result := 'MONEY'; dtBCD, dtFmtBCD: Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, FOptions.FormatOptions.MaxBcdPrecision, 0); dtDateTime: Result := 'DATETIME'; dtTime: Result := 'TIME'; dtDate: Result := 'DATE'; dtDateTimeStamp: Result := 'TIMESTAMP'; dtAnsiString: begin if caFixedLen in AColumn.ActualAttributes then Result := 'CHAR' else Result := 'VARCHAR'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtWideString: begin if caFixedLen in AColumn.ActualAttributes then Result := 'NCHAR' else Result := 'NVARCHAR'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtByteString: begin if caFixedLen in AColumn.ActualAttributes then Result := 'BINARY' else Result := 'VARBINARY'; Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1); end; dtBlob, dtHBlob, dtHBFile: Result := 'LONG BINARY'; dtMemo, dtHMemo: Result := 'LONG VARCHAR'; dtWideMemo, dtWideHMemo: Result := 'LONG NVARCHAR'; dtXML: Result := 'XML'; dtGUID: Result := 'UNIQUEIDENTIFIER'; dtUnknown, dtTimeIntervalFull, dtTimeIntervalYM, dtTimeIntervalDS, dtRowSetRef, dtCursorRef, dtRowRef, dtArrayRef, dtParentRowRef, dtObject: Result := ''; end; if Result <> '' then if caAutoInc in AColumn.ActualAttributes then Result := Result + ' IDENTITY' else if caExpr in AColumn.ActualAttributes then Result := Result + ' COMPUTE(' + AColumn.Expression + ')'; end; {-------------------------------------------------------------------------------} function TFDPhysASACommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String; begin Result := ''; case AAction of maInsertUpdate: Result := 'INSERT INTO ' + GetFrom + BRK + GetInsert('ON EXISTING UPDATE'); maInsertIgnore: Result := 'INSERT INTO ' + GetFrom + BRK + GetInsert('ON EXISTING SKIP'); end; end; {-------------------------------------------------------------------------------} initialization FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.SQLAnywhere, S_FD_ASA_RDBMS); end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit DSAzDlgCopyBlob; interface uses Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, System.Generics.Collections, Vcl.Graphics, Vcl.Grids, Vcl.StdCtrls, Vcl.ValEdit; type TAzCopyBlob = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; gbDestination: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; edtModifiedSince: TEdit; edtUnmodified: TEdit; edtNoneMatch: TEdit; edtMatch: TEdit; vleMeta: TValueListEditor; btnAddMetadata: TButton; btnDelMetadata: TButton; lbeDestContainer: TLabeledEdit; lbeDestBlob: TLabeledEdit; gbSource: TGroupBox; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; edtSrcMod: TEdit; edtSrcUnmod: TEdit; edtSrcNoneMatch: TEdit; edtSrcMatch: TEdit; procedure btnAddMetadataClick(Sender: TObject); procedure btnDelMetadataClick(Sender: TObject); procedure lbeDestContainerChange(Sender: TObject); private { Private declarations } procedure ValidateCopy; public { Public declarations } function GetSrcModifiedSince: String; function GetSrcUnmodifiedSince: String; function GetSrcMatch: String; function GetSrcNoneMatch: String; function GetDestContainer: String; procedure SetDestContainer(const Name: String); function GetDestBlob: String; function GetDestModifiedSince: String; function GetDestUnmodifiedSince: String; function GetDestMatch: String; function GetDestNoneMatch: String; procedure AssignMetadata(const meta: TDictionary<String, String>); procedure PopulateWithMetadata(const meta: TDictionary<String, String>); function RawMetadata: TStrings; property DestContainer: string read GetDestContainer write SetDestContainer; end; implementation uses Vcl.Dialogs; {$R *.dfm} procedure TAzCopyBlob.AssignMetadata( const meta: TDictionary<String, String>); var I, Count: Integer; key, value: String; begin meta.Clear; Count := vleMeta.Strings.Count; for I := 0 to Count - 1 do begin key := vleMeta.Strings.Names[I]; value := vleMeta.Strings.ValueFromIndex[I]; if (Length(key) > 0) and (Length(value) > 0) then meta.Add(key, value); end; end; procedure TAzCopyBlob.btnAddMetadataClick(Sender: TObject); begin vleMeta.InsertRow('', '', true); vleMeta.SetFocus; end; procedure TAzCopyBlob.btnDelMetadataClick(Sender: TObject); var row: Integer; begin row := vleMeta.Row; if (row > 0) and (row < vleMeta.RowCount) then vleMeta.DeleteRow(row); end; function TAzCopyBlob.GetDestModifiedSince: String; begin Result := edtModifiedSince.Text; end; function TAzCopyBlob.GetDestUnmodifiedSince: String; begin Result := edtUnmodified.Text; end; function TAzCopyBlob.GetSrcMatch: String; begin Result := edtSrcMatch.Text; end; function TAzCopyBlob.GetSrcModifiedSince: String; begin Result := edtSrcMod.Text; end; function TAzCopyBlob.GetSrcNoneMatch: String; begin Result := edtSrcNoneMatch.Text end; function TAzCopyBlob.GetSrcUnmodifiedSince: String; begin Result := edtSrcUnmod.Text; end; procedure TAzCopyBlob.lbeDestContainerChange(Sender: TObject); begin ValidateCopy; end; function TAzCopyBlob.GetDestBlob: String; begin Result := lbeDestBlob.Text; end; function TAzCopyBlob.GetDestContainer: String; begin Result := lbeDestContainer.Text; end; function TAzCopyBlob.GetDestMatch: String; begin Result := edtMatch.Text; end; function TAzCopyBlob.GetDestNoneMatch: String; begin Result := edtNoneMatch.Text; end; procedure TAzCopyBlob.PopulateWithMetadata( const meta: TDictionary<String, String>); var keys: TArray<String>; I, Count: Integer; begin vleMeta.Strings.Clear; keys := meta.Keys.ToArray; Count := meta.Keys.Count; for I := 0 to Count - 1 do vleMeta.Values[keys[I]] := meta.Items[keys[I]]; end; function TAzCopyBlob.RawMetadata: TStrings; begin Result := vleMeta.Strings end; procedure TAzCopyBlob.SetDestContainer(const Name: String); begin lbeDestContainer.Text := Name end; procedure TAzCopyBlob.ValidateCopy; begin OKBtn.Enabled := (Length(lbeDestContainer.Text) > 0) and (Length(lbeDestBlob.Text) > 0); end; end.
unit uAtividadesCRUD; interface uses Windows, SysUtils, Classes, Controls, Forms, ComCtrls, uDAO,FireDAC.Comp.Client,uControle; type TAtividadesCRUD = class private FCodigo: String; FNome: String; // Classe de Persistencia ... Fcontrole: TControle; public constructor Create(pConexaoControle: TControle); destructor Destroy; override; // function InsereAtividade: Boolean; function AlteraAtividade: Boolean; function ExcluirAtividade: Boolean; function PesquisaAtividade(pCodigo: string): TAtividadesCRUD; // property Codigo: String read FCodigo write FCodigo; property Nome: String read FNome write FNome; end; implementation { TAtividadesCRUD } function TAtividadesCRUD.AlteraAtividade: Boolean; begin Fcontrole.SqqGeral.SQL.Clear; Fcontrole.SqqGeral.SQL.Add(' UPDATE ATIVIDADES '); Fcontrole.SqqGeral.SQL.Add(' SET NOME = :NOME '); Fcontrole.SqqGeral.ParamByName('NOME').AsString := Self.Nome; try Fcontrole.SqqGeral.ExecSQL; Result := True; except Result := False; end; end; constructor TAtividadesCRUD.Create(pConexaoControle: TControle); begin Fcontrole := pConexaoControle; end; destructor TAtividadesCRUD.Destroy; begin inherited; end; function TAtividadesCRUD.ExcluirAtividade: Boolean; begin Fcontrole.SqqGeral.Close; Fcontrole.SqqGeral.SQL.Clear; Fcontrole.SqqGeral.SQL.Add(' DELETE FROM ATIVIDADES C '); Fcontrole.SqqGeral.SQL.Add(' WHERE C.CODIGO = :CODIGO '); Fcontrole.SqqGeral.ParamByName('CODIGO').AsString := Self.Codigo; try Fcontrole.SqqGeral.ExecSQL; Result := True; except Result := False; end end; function TAtividadesCRUD.InsereAtividade: Boolean; begin Fcontrole.SqqGeral.SQL.Clear; Fcontrole.SqqGeral.SQL.Add(' INSERT INTO ATIVIDADES '); Fcontrole.SqqGeral.SQL.Add(' (CODIGO, '); Fcontrole.SqqGeral.SQL.Add(' NOME) '); Fcontrole.SqqGeral.SQL.Add(' VALUES (:CODIGO, '); Fcontrole.SqqGeral.SQL.Add(' :NOME) '); Fcontrole.SqqGeral.ParamByName('CODIGO').AsString := Self.Codigo; Fcontrole.SqqGeral.ParamByName('NOME').AsString := Self.Nome; try Fcontrole.SqqGeral.ExecSQL; Result := True; except Result := False; end; end; function TAtividadesCRUD.PesquisaAtividade(pCodigo: string): TAtividadesCRUD; begin Fcontrole.SqqGeral.Close; Fcontrole.SqqGeral.SQL.Clear; Fcontrole.SqqGeral.SQL.Add(' SELECT CODIGO, '); Fcontrole.SqqGeral.SQL.Add(' NOME '); Fcontrole.SqqGeral.SQL.Add(' FROM ATIVIDADES '); Fcontrole.SqqGeral.SQL.Add(' WHERE CODIGO = ' + pCodigo); Fcontrole.SqqGeral.Open; if Fcontrole.SqqGeral.IsEmpty then begin Self.Codigo := ''; end else begin Self.Codigo := Fcontrole.SqqGeral.ParamByName('CODIGO').AsString; Self.Nome := Fcontrole.SqqGeral.ParamByName('NOME').AsString; end; end; end.
unit Parameter; interface uses SysUtils, OS.ServiceController, IdentifyDiagnosis, SemiAutoTrimmer; type TParameter = class private ServiceController: TServiceController; procedure DeleteNaraeonSSDToolsServices; procedure OpenStopDeleteService(const ServiceName: String); procedure DiagnoseAndSetClipboardResult; procedure SemiAutoTrim(const Model, Serial: String); public function ProcessParameterAndIfNormalReturnTrue( const ParameterString: String): Boolean; end; implementation { TParameter } procedure TParameter.OpenStopDeleteService(const ServiceName: String); begin ServiceController.OpenService(ServiceName); ServiceController.StopService; ServiceController.DeleteAndCloseService; end; procedure TParameter.DeleteNaraeonSSDToolsServices; begin ServiceController := TServiceController.Create; OpenStopDeleteService('NareonSSDToolsDiag'); OpenStopDeleteService('NaraeonSSDToolsDiag'); FreeAndNil(ServiceController); end; procedure TParameter.DiagnoseAndSetClipboardResult; var IdentifyDiagnosis: TIdentifyDiagnosis; begin IdentifyDiagnosis := TIdentifyDiagnosis.Create; IdentifyDiagnosis.DiagnoseAndSetClipboardResult; FreeAndNil(IdentifyDiagnosis); end; procedure TParameter.SemiAutoTrim(const Model, Serial: String); var SemiAutoTrimmer: TSemiAutoTrimmer; begin SemiAutoTrimmer := TSemiAutoTrimmer.Create; SemiAutoTrimmer.SemiAutoTrim(Model, Serial); FreeAndNil(SemiAutoTrimmer); end; function TParameter.ProcessParameterAndIfNormalReturnTrue( const ParameterString: String): Boolean; const PointsErrFilePath = ':\'; var UpperParameterString: String; begin result := ParameterString = ''; if result then exit; UpperParameterString := UpperCase(ParameterString); if UpperParameterString = '/DIAG' then DiagnoseAndSetClipboardResult else if UpperParameterString = '/UNINSTALL' then DeleteNaraeonSSDToolsServices else if Pos(PointsErrFilePath, UpperParameterString) = 0 then SemiAutoTrim(ParamStr(1), ParamStr(2)); end; end.
unit Tests.TCommandAction; interface uses DUnitX.TestFramework, System.Classes, System.SysUtils, Pattern.Command, Pattern.CommandAction, Vcl.StdCtrls, Vcl.Forms; {$M+} type [TestFixture] TestCommandAction = class(TObject) private fOwnerComponent: TComponent; fStringList: TStringList; fAction: TCommandAction; public [Setup] procedure Setup; [TearDown] procedure TearDown; published procedure ActionWithCaption; procedure ActionWithCommand; procedure ActionWithShotcut; procedure ActionWitnEventOnUpdate; procedure ActionWitEventAfterExecution; procedure ActionWithInjections; procedure ActionCaption_WillChangeButtonCaption; end; implementation uses Vcl.Menus; type TTestCommand = class(TCommand) const DefaultRange = 10; private FRandomNumbers: TStringList; FRange: integer; protected procedure DoGuard; override; procedure DoExecute; override; public constructor Create(AOwner: TComponent); override; published property Range: integer read FRange write FRange; property RandomNumbers: TStringList read FRandomNumbers write FRandomNumbers; end; {$REGION 'implementation TTestCommand -----------------'} constructor TTestCommand.Create(AOwner: TComponent); begin inherited; Randomize; Range := DefaultRange; end; procedure TTestCommand.DoGuard; begin System.Assert(RandomNumbers <> nil); end; procedure TTestCommand.DoExecute; begin RandomNumbers.Add((1 + Random(Range)).ToString); end; {$ENDREGION --------------------------------------------} procedure TestCommandAction.Setup; begin fOwnerComponent := TComponent.Create(nil); fAction := TCommandAction.Create(fOwnerComponent); fStringList := TStringList.Create; end; procedure TestCommandAction.TearDown; begin fOwnerComponent.Free; fStringList.Free; end; procedure TestCommandAction.ActionWithCaption; begin // Arrage & Act: fAction.WithCaption('Execute test command'); // Assert Assert.AreEqual('Execute test command', fAction.Caption); end; procedure TestCommandAction.ActionWithCommand; var cmd: TTestCommand; begin // Arrage: cmd := TTestCommand.Create(fOwnerComponent); cmd.WithInjections([fStringList]); // Act: fAction.WithCommand(cmd); fAction.Execute; fAction.Execute; // Assert Assert.AreEqual(2, cmd.RandomNumbers.Count); end; procedure TestCommandAction.ActionWithShotcut; var aShortCut: TShortCut; begin aShortCut := TextToShortCut('CTRL+K'); fAction.WithShortCut(aShortCut); Assert.AreEqual(ShortCutToText(aShortCut), ShortCutToText(fAction.ShortCut)); end; procedure TestCommandAction.ActionWitnEventOnUpdate; begin fAction.WithEventOnUpdate( procedure(act: TCommandAction) begin act.Tag := act.Tag + 1; end); fAction.Update; Assert.AreEqual(1, fAction.Tag); end; procedure TestCommandAction.ActionWitEventAfterExecution; begin fAction.Tag := -1; fAction.Command := TTestCommand.Create(fOwnerComponent); fAction.Command.WithInjections([fStringList]); fAction.WitEventAfterExecution( procedure(act: TCommandAction) begin act.Tag := 99; end); fAction.Execute; Assert.AreEqual(99, fAction.Tag); end; procedure TestCommandAction.ActionWithInjections; var actualNumbers: integer; begin fAction // --+ .WithCommand(TTestCommand.Create(fOwnerComponent)) //--+ .WithInjections([fStringList]); fAction.Execute; fAction.Execute; fAction.Execute; actualNumbers := (fAction.Command as TTestCommand).RandomNumbers.Count; Assert.AreEqual(3, actualNumbers); end; procedure TestCommandAction.ActionCaption_WillChangeButtonCaption; var aButton: TButton; begin aButton := TButton.Create(fOwnerComponent); fAction.WithCaption('Sample caption'); aButton.Action := fAction; Assert.AreEqual('Sample caption', aButton.Caption); end; end.
unit ncaFrmTipoNF; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, cxControls, cxContainer, cxEdit, Vcl.StdCtrls, cxRadioGroup, cxLabel, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel; type TFrmTipoNF = class(TForm) LMDSimplePanel5: TLMDSimplePanel; btnSalvar: TcxButton; btnCancelar: TcxButton; LMDSimplePanel4: TLMDSimplePanel; lbTit: TcxLabel; cbCupom: TcxRadioButton; cbNFe: TcxRadioButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSalvarClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public function ObtemTipoNF(var aTipo: Byte): Boolean; { Public declarations } end; var FrmTipoNF: TFrmTipoNF; implementation {$R *.dfm} uses ncClassesBase, ncaDM; procedure TFrmTipoNF.btnSalvarClick(Sender: TObject); begin if (not cbCupom.Checked) and (not cbNFe.Checked) then raise Exception.Create('É necessário escolher uma das opções'); ModalResult := mrOk; end; procedure TFrmTipoNF.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmTipoNF.FormCreate(Sender: TObject); begin cbCupom.Caption := Dados.tNFConfigNFStr.Value; end; function TFrmTipoNF.ObtemTipoNF(var aTipo: Byte): Boolean; begin ShowModal; if ModalResult=mrOk then begin Result := True; if cbNFe.Checked then aTipo := tiponfe_nfe else if Dados.tNFConfigESAT.Value then aTipo := tiponfe_sat else aTipo := tiponfe_nfce; end else Result := False; end; end.
unit Threads.ObjectOnline; interface uses Windows, sysUtils, GMConst, GMGlobals, GMGenerics, Threads.Base, GMSqlQuery; type TObjectOnlineState = class ID_Obj, ObjType, N_Car: int; utOnline, utLastSaved: DWORD; function UpdateQuery(): string; end; TObjectOnlineThread = class(TGMThread) private lock: TMultiReadExclusiveWriteSynchronizer; lstObjects: TGMCollection<TObjectOnlineState>; protected procedure SafeExecute; override; function OnlineTime: LongWord; virtual; procedure ProcessObjects; function UpdateQuery(): string; public constructor Create(); destructor Destroy; override; procedure ObjectOnline(ID_Obj: int; ObjType: int = -1; N_Car: int = 0); end; implementation { TObjectOnlineThread } uses ProgramLogFile; constructor TObjectOnlineThread.Create; begin inherited Create(false); lstObjects := TGMCollection<TObjectOnlineState>.Create(); lock := TMultiReadExclusiveWriteSynchronizer.Create(); end; destructor TObjectOnlineThread.Destroy; begin lstObjects.Free(); lock.Free(); inherited; end; function TObjectOnlineThread.OnlineTime(): LongWord; begin Result := NowGM(); end; procedure TObjectOnlineThread.ObjectOnline(ID_Obj, ObjType, N_Car: int); var i: int; obj: TObjectOnlineState; begin obj := nil; lock.BeginWrite(); try for i := 0 to lstObjects.Count - 1 do begin if ( (ID_Obj > 0) and (lstObjects[i].ID_Obj = ID_Obj) ) or ( (ID_Obj <= 0) and (lstObjects[i].ObjType = ObjType) and (lstObjects[i].N_Car = N_Car) ) then begin obj := lstObjects[i]; end; end; if obj = nil then begin obj := lstObjects.Add(); obj.ID_Obj := 0; obj.ObjType := ObjType; obj.N_Car := N_Car; obj.utLastSaved := 0; end; if ID_Obj > 0 then obj.ID_Obj := ID_Obj; obj.utOnline := OnlineTime(); finally lock.EndWrite(); end; end; function TObjectOnlineThread.UpdateQuery(): string; var i: int; begin lock.BeginRead(); try Result := ''; for i := 0 to lstObjects.Count - 1 do Result := Result + lstObjects[i].UpdateQuery(); finally lock.EndRead(); end; end; procedure TObjectOnlineThread.ProcessObjects(); var sql: string; begin try sql := UpdateQuery(); ExecPLSQL(sql); except on e: Exception do ProgramLog.AddException('TObjectOnlineThread - ' + e.Message); end; end; procedure TObjectOnlineThread.SafeExecute; begin while not Terminated do begin ProcessObjects(); SleepThread(2000); end; end; { TObjectOnlineState } function TObjectOnlineState.UpdateQuery: string; var s: string; begin if utLastSaved = utOnline then Exit; if ID_Obj > 0 then s := IntToStr(ID_Obj) else s := Format('(select ID_Obj from Objects where coalesce(ObjType, 0) = %d and N_Car = %d)', [ID_Obj, N_Car]); Result := 'perform ObjectOnline(' + s + ', ' + IntToStr(utOnline) + ');'#13#10; utLastSaved := utOnline; end; end.
{**********************************************} { TDBChart for QuickReport } { Copyright (c) 1996-2004 by David Berneda } { All Rights Reserved } {**********************************************} unit QrTee; {$I TeeDefs.inc} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TeeProcs, TeEngine, Chart, QuickRpt, TeCanvas, {$IFNDEF NOUSE_BDE} DBChart, {$ENDIF} StdCtrls, Menus, ExtCtrls; type TTeeQuickMethod=(qtmBitmap, qtmMetafile); TQRChart=class; TQRDBChart=class({$IFNDEF NOUSE_BDE}TCustomDBChart{$ELSE}TCustomChart{$ENDIF}) protected public Constructor Create(AOwner : TComponent); override; Function GetRectangle:TRect; override; procedure Invalidate; override; procedure Paint; override; published {$IFNDEF NOUSE_BDE} { TCustomDBChart properties } property ShowGlassCursor; { TCustomDBChart events } property OnProcessRecord; {$ENDIF} { TCustomChart Properties } property BackImage; property BackImageInside; property BackImageMode; property BackImageTransp; property BackWall; property Border; property BorderRound; property BottomWall; property Foot; property Gradient; property LeftWall; property MarginBottom; property MarginLeft; property MarginRight; property MarginTop; property MarginUnits; property RightWall; property SubFoot; property SubTitle; property Title; { TCustomChart Events } property OnGetLegendPos; property OnGetLegendRect; { TCustomAxisPanel properties } property AxisBehind; property AxisVisible; property BottomAxis; property Chart3DPercent; property ClipPoints; property CustomAxes; property DepthAxis; property DepthTopAxis; property Frame; property LeftAxis; property Legend; property MaxPointsPerPage; property Page; property RightAxis; property ScaleLastPage; property SeriesList; property Shadow; property TopAxis; property View3D; property View3DOptions; property View3DWalls; { TCustomAxisPanel events } property OnAfterDraw; property OnBeforeDrawAxes; property OnBeforeDrawChart; property OnBeforeDrawSeries; property OnGetAxisLabel; property OnGetLegendText; property OnGetNextAxisLabel; property OnPageChange; { TPanel properties } property BevelInner; property BevelWidth; property BevelOuter default bvNone; property BorderWidth; property Color default clWhite; property ParentColor; property ParentShowHint; property PopupMenu; property ShowHint; { TPanel events } property OnEnter; property OnExit; property OnResize; end; TPrintChartEvent = procedure( Sender: TQRChart; Var PaperRect,ChartRect:TRect ) of object; TQRChart = class(TQRPrintable) private { Private declarations } FOnPrint : TPrintChartEvent; FTeePrintMethod : TTeeQuickMethod; Function GetChart:TQRDBChart; Procedure SetPrintMethod(Value:TTeeQuickMethod); protected { Protected declarations } procedure ReadState(Reader: TReader); override; public { Public declarations } Constructor Create(AOwner : TComponent); override; procedure Print(OfsX, OfsY : integer); override; procedure Paint; override; procedure SetChart(AChart:TCustomChart); published { Published declarations } property Chart:TQRDBChart read GetChart; property TeePrintMethod:TTeeQuickMethod read FTeePrintMethod write SetPrintMethod default qtmMetafile; { Published QR events } property OnPrint:TPrintChartEvent read FOnPrint write FOnPrint; end; implementation Uses {$IFNDEF D5}DsgnIntf,{$ENDIF} TeeConst; Const TeeMsg_DefaultQRChart='QRDBChart'; { <-- dont translate } { TQRDBChart } Constructor TQRDBChart.Create(AOwner : TComponent); begin inherited; Color:=clWhite; BevelOuter:=bvNone; BufferedDisplay:=False; SetBounds(-1,-1,1,1); Hide; end; Function TQRDBChart.GetRectangle:TRect; Var tmpZoomFactor : Double; begin if Assigned(Parent) then With TQRChart(Parent) do begin if Assigned(ParentReport) then tmpZoomFactor:=100.0/ParentReport.Zoom else tmpZoomFactor:=1; {$IFDEF D6} try {$ENDIF} result:=Rect(0,0, Round(ClientWidth*tmpZoomFactor), Round(ClientHeight*tmpZoomFactor) ); {$IFDEF D6} except on EOSError do begin result:=Rect(0,0, Round(Width*tmpZoomFactor), Round(Height*tmpZoomFactor) ); end; end; {$ENDIF} end else result:=GetClientRect; end; procedure TQRDBChart.Paint; Procedure DrawGraphic(AGraphic:TGraphic); var r : TRect; begin With TQRChart(Parent) do begin R:=GetClientRect; Inc(R.Right,2); // 7.0 Inc(R.Bottom,2); Canvas.StretchDraw(R,AGraphic); end; AGraphic.Free; end; begin if Assigned(Parent) then With TQRChart(Parent) do Case FTeePrintMethod of qtmMetafile: DrawGraphic(TeeCreateMetafile(True,GetRectangle)); qtmBitmap: DrawGraphic(TeeCreateBitmap(clWhite,GetRectangle)); end; end; procedure TQRDBChart.Invalidate; begin if Assigned(Parent) then Parent.Invalidate; end; { TQRChart } Constructor TQRChart.Create(AOwner : TComponent); begin inherited; FTeePrintMethod:=qtmMetafile; Width :=350; Height:=200; if (csDesigning in ComponentState) and (not (csLoading in Owner.ComponentState)) then With TQRDBChart.Create(AOwner) do begin Parent:=TWinControl(Self); Name:=TeeGetUniqueName(AOwner,TeeMsg_DefaultQRChart); With Title.Text do begin Clear; Add(Self.ClassName); end; end; end; procedure TQRChart.ReadState(Reader: TReader); Var tmpChart : TQRDBChart; begin tmpChart:=Chart; if Assigned(tmpChart) and (not (csLoading in tmpChart.ComponentState)) and (not (csAncestor in tmpChart.ComponentState)) then tmpChart.Free; inherited; end; Procedure TQRChart.SetPrintMethod(Value:TTeeQuickMethod); begin if Value<>FTeePrintMethod then begin FTeePrintMethod:=Value; Repaint; end; end; procedure TQRChart.Print(OfsX, OfsY : Integer); Var QuickRect : TRect; Procedure PrintGraphic(AGraphic:TGraphic); begin QRPrinter.Canvas.StretchDraw(QuickRect,AGraphic); AGraphic.Free; end; Var tmpRect : TRect; tmpChart : TQRDBChart; begin tmpChart:=Chart; if Assigned(tmpChart) then begin {$IFNDEF NOUSE_BDE} tmpChart.RefreshData; {$ENDIF} With ParentReport.QRPrinter do begin QuickRect:=Rect( Xpos(OfsX+Size.Left), Ypos(OfsY+Size.Top), Xpos(OfsX+Size.Left+Size.Width), Ypos(OfsY+Size.Top+Size.Height)); tmpRect:=tmpChart.GetRectangle; if Assigned(FOnPrint) then FOnPrint(Self,QuickRect,tmpRect); Case FTeePrintMethod of qtmMetafile: PrintGraphic(tmpChart.TeeCreateMetafile(True,tmpRect)); qtmBitmap: PrintGraphic(tmpChart.TeeCreateBitmap(clWhite,tmpRect)); end; end; end; inherited; end; procedure TQRChart.SetChart(AChart:TCustomChart); // 7.0 Function CloneChartTool(ATool:TTeeCustomTool):TTeeCustomTool; begin result:=TTeeCustomToolClass(ATool.ClassType).Create(Owner); result.Assign(ATool); end; var t : Integer; begin Chart.FreeAllSeries; Chart.Assign(AChart); for t:=0 to AChart.SeriesCount-1 do CloneChartSeries(AChart[t]).ParentChart:=Chart; for t:=0 to AChart.Tools.Count-1 do CloneChartTool(AChart.Tools[t]).ParentChart:=Chart; end; procedure TQRChart.Paint; begin if Assigned(Chart) then Chart.Paint; inherited; end; Function TQRChart.GetChart:TQRDBChart; begin if ControlCount>0 then result:=TQRDBChart(Controls[0]) else result:=nil; end; initialization RegisterClass(TQRDBChart); end.
unit uTestText; interface uses DUnitX.TestFramework, uText, uTestUtils; type [TestFixture] TTextTest = class(TObject) public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure TestCreate; [Test] procedure TestCopy; [Test] procedure TestLen; [Test] procedure TestEof; [Test] procedure TestText; [Test] procedure TestCh; [Test] procedure TestPos1; [Test] procedure TestPos2; [Test] procedure TestNextIf; [Test] procedure TestNextIf2; [Test] procedure TestNextWhile; [Test] procedure TestNextWhile2; end; implementation procedure TTextTest.Setup; begin end; procedure TTextTest.TearDown; begin end; procedure TTextTest.TestCh; var Text: IText; begin Text := TText.Create(''); Assert.AreEqual(chEofChar, Text.Ch); Text := TText.Create('a'); Assert.AreEqual('a', Text.Ch); Text := TText.Create('123'); Assert.AreEqual('1', Text.Ch); Text := TText.Create('123'); Text.Next; Assert.AreEqual('2', Text.Ch); Text.Next; Assert.AreEqual('3', Text.Ch); Text.Next; Assert.AreEqual(chEofChar , Text.Ch); Text.First; Assert.AreEqual('1', Text.Ch); end; procedure TTextTest.TestCopy; var Text: IText; begin Text := TText.Create(''); Assert.AreEqual('', Text.Copy(1, 0)); Assert.AreEqual('', Text.Copy(1, 1)); Text := TText.Create('asa123'); Assert.AreEqual('asa', Text.Copy(1, 3)); Assert.AreEqual('123', Text.Copy(4, 3)); Assert.AreEqual('a', Text.Copy(1, 1)); Assert.AreEqual('', Text.Copy(1, 0)); end; procedure TTextTest.TestCreate; var Text: IText; begin Text := TText.Create(''); Text := TText.Create('asaas'); Text := TText.Create(' '); end; procedure TTextTest.TestEof; var Text: IText; begin Text := TText.Create(''); Assert.IsTrue(Text.Eof); Text := TText.Create('121'); Assert.IsFalse(Text.Eof); Text := TText.Create('a'); Assert.IsFalse(Text.Eof); Text := TText.Create('a'); Text.Next; Assert.IsTrue(Text.Eof); Text := TText.Create('abc'); Text.Next; Text.Next; Assert.IsFalse(Text.Eof); Text := TText.Create('abc'); Text.Next; Text.Next; Text.Next; Assert.IsTrue(Text.Eof); Text := TText.Create('a'); Text.Next; Text.First; Assert.IsFalse(Text.Eof); Text := TText.Create('abc'); Text.Next; Text.Next; Text.First; Assert.IsFalse(Text.Eof); Text := TText.Create(''); Text.First; Assert.IsTrue(Text.Eof); end; procedure TTextTest.TestLen; var Text: IText; begin Text := TText.Create(''); Assert.AreEqual(0, Text.Len); Text := TText.Create('abc1'); Assert.AreEqual(4, Text.Len); end; procedure TTextTest.TestNextIf; var Text: IText; begin Text := TText.Create(''); Assert.IsFalse(Text.NextIf('a')); Assert.AreEqual(chEofChar, Text.Ch); Text := TText.Create('abs'); Assert.IsTrue(Text.NextIf('a')); Assert.AreEqual(2, Text.Pos.Pos); Assert.IsFalse(Text.NextIf('a')); Assert.AreEqual(2, Text.Pos.Pos); Assert.IsTrue(Text.NextIf('b')); Assert.AreEqual(3, Text.Pos.Pos); Assert.IsTrue(Text.NextIf('s')); Assert.AreEqual(chEofChar, Text.Ch); end; procedure TTextTest.TestNextIf2; var Text: IText; begin Text := TText.Create(''); Assert.IsFalse(Text.NextIf(['é'])); Assert.AreEqual(chEofChar, Text.Ch); Text := TText.Create('éöó'); Assert.IsTrue(Text.NextIf(['é', 's'])); Assert.AreEqual(2, Text.Pos.Pos); Assert.IsFalse(Text.NextIf(['é', 'f'])); Assert.AreEqual(2, Text.Pos.Pos); Assert.IsTrue(Text.NextIf(['ÿ', 'ö'])); Assert.AreEqual(3, Text.Pos.Pos); Assert.IsTrue(Text.NextIf(['ó'])); Assert.AreEqual(chEofChar, Text.Ch); end; procedure TTextTest.TestNextWhile; var Text: IText; begin Text := TText.Create(''); Text.NextWhile('a'); Assert.AreEqual(chEofChar, Text.Ch); Text := TText.Create('aabs'); Text.NextWhile('a'); Assert.AreEqual(3, Text.Pos.Pos); Text.NextWhile('a'); Assert.AreEqual(3, Text.Pos.Pos); Text.NextWhile('b'); Assert.AreEqual(4, Text.Pos.Pos); Text.NextWhile('s'); Assert.AreEqual(chEofChar, Text.Ch); end; procedure TTextTest.TestNextWhile2; var Text: IText; begin Text := TText.Create(''); Text.NextWhile(['é']); Assert.AreEqual(chEofChar, Text.Ch); Text := TText.Create('ééöó'); Text.NextWhile(['é', 's']); Assert.AreEqual(3, Text.Pos.Pos); Text.NextWhile(['é', 'f']); Assert.AreEqual(3, Text.Pos.Pos); Text.NextWhile(['ÿ', 'ö']); Assert.AreEqual(4, Text.Pos.Pos); Text.NextWhile(['ó']); Assert.AreEqual(chEofChar, Text.Ch); end; procedure TTextTest.TestPos1; var Text: IText; begin Text := TText.Create(''); Assert.AreEqual(1, Text.Pos.Line); Assert.AreEqual(1, Text.Pos.LinePos); Assert.AreEqual(1, Text.Pos.Pos); end; procedure TTextTest.TestPos2; var Text: IText; begin Text := TText.Create('ad'#13#10'f'); Assert.AreEqual(1, Text.Pos.Line); Assert.AreEqual(1, Text.Pos.LinePos); Assert.AreEqual(1, Text.Pos.Pos); Text.Next; Assert.AreEqual(1, Text.Pos.Line); Assert.AreEqual(2, Text.Pos.LinePos); Assert.AreEqual(2, Text.Pos.Pos); Text.Next; Assert.AreEqual(1, Text.Pos.Line); Assert.AreEqual(3, Text.Pos.LinePos); Assert.AreEqual(3, Text.Pos.Pos); Text.Next; Assert.AreEqual(1, Text.Pos.Line); Assert.AreEqual(4, Text.Pos.LinePos); Assert.AreEqual(4, Text.Pos.Pos); Text.Next; Assert.AreEqual(2, Text.Pos.Line); Assert.AreEqual(1, Text.Pos.LinePos); Assert.AreEqual(5, Text.Pos.Pos); end; procedure TTextTest.TestText; var Text: IText; begin Text := TText.Create(''); Assert.AreEqual('', Text.Text); Text := TText.Create('abc1'); Assert.AreEqual('abc1', Text.Text); end; initialization TDUnitX.RegisterTestFixture(TTextTest); end.
{diamond.pas} program diamond; var n, k, h, i: integer; begin {enter number in valid format} repeat writeln('Enter the diamond''s height (positive odd): '); readln(h) until (h > 0) and (h mod 2 = 1); n := h div 2; {print top part} for k := 1 to n + 1 do begin for i := 1 to n + 1 - k do write(' '); write('*'); if k > 1 then begin for i := 1 to 2*k - 3 do write(' '); write('*') end; writeln end; {print bottom part} for k := n downto 1 do begin for i := 1 to n + 1 - k do write(' '); write('*'); if k > 1 then begin for i := 1 to 2*k - 3 do write(' '); write('*'); end; writeln end end.
unit xExamControl; interface uses xClientInfo, System.SysUtils, System.Classes, xFunction, System.IniFiles, xTCPServer, xStudentInfo, xConsts, xClientType, xStudentControl, Vcl.Dialogs, Vcl.Forms, Windows; type /// <summary> /// 控制类 /// </summary> TExamControl = class private FClientList: TStringList; FColCount: Integer; FOnClinetChanged: TNotifyEvent; // FTCPServer : TTCPServer; FExamStuList: TStringList; FOnTCPLog: TGetStrProc; FExamStartTime: TDateTime; FIsExamStart: Boolean; function GetClientInfo(nIndex: Integer): TClientInfo; procedure SetClinetCount(const Value: Integer); function GetClinetCount: Integer; procedure ReadINI; procedure WriteINI; procedure ClinetChanged(Sender: TObject); procedure LoginEvent(Sender: TObject; nStuID : Integer); procedure ExamReady(Sender: TObject); procedure RevPacksData(sIP: string; nPort :Integer;aPacks: TArray<Byte>); procedure ClientChange( AIP: string; nPort: Integer; AConnected: Boolean ); function GetTrainClientCount: Integer; // procedure TCPPacksLog( sIP : string; nPort: Integer; aPacks: TArray<Byte>; bSend : Boolean); // procedure TCPLog(const S: string); public constructor Create; destructor Destroy; override; // /// <summary> // /// TCP通讯对象 // /// </summary> // property TCPServer : TTCPServer read FTCPServer write FTCPServer; /// <summary> /// 客户端数量 /// </summary> property ClinetCount : Integer read GetClinetCount write SetClinetCount; /// <summary> /// 培训状态的客户端列表 /// </summary> property TrainClientCount : Integer read GetTrainClientCount; /// <summary> /// 列表 /// </summary> property ClientList : TStringList read FClientList write FClientList; property ClientInfo[nIndex:Integer] : TClientInfo read GetClientInfo; /// <summary> /// 获取客户端 /// </summary> function GetClient(sIP : string; nPort : Integer) : TClientInfo; /// <summary> /// 显示的列数 /// </summary> property ColCount : Integer read FColCount write FColCount; /// <summary> /// 参加考试的考生列表 /// </summary> property ExamStuList : TStringList read FExamStuList write FExamStuList; /// <summary> /// 添加考生 /// </summary> procedure AddStu(AStu : TStudentInfo); /// <summary> /// 考试开始时间 /// </summary> property ExamStartTime : TDateTime read FExamStartTime write FExamStartTime; /// <summary> /// 考试是否开始 /// </summary> property IsExamStart : Boolean read FIsExamStart write FIsExamStart; /// <summary> /// 考试开始 /// </summary> procedure ExamStart; /// <summary> /// 考试停止 /// </summary> procedure ExamStop; public /// <summary> /// 改变事件 /// </summary> property OnClinetChanged : TNotifyEvent read FOnClinetChanged write FOnClinetChanged; /// <summary> /// TCP通讯数据记录 /// </summary> property OnTCPLog : TGetStrProc read FOnTCPLog write FOnTCPLog; end; var ExamControl : TExamControl; implementation { TExamControl } procedure TExamControl.AddStu(AStu: TStudentInfo); begin if Assigned(AStu) then begin FExamStuList.AddObject(IntToStr(AStu.stuNumber), AStu); end; end; procedure TExamControl.ClientChange(AIP: string; nPort: Integer; AConnected: Boolean); var AClientInfo : TClientInfo; begin AClientInfo := GetClient(AIP, nPort); if Assigned(AClientInfo) then begin if AConnected then AClientInfo.ClientState := esConned else AClientInfo.ClientState := esDisconn end else begin if AConnected then begin Application.MessageBox(PWideChar(AIP + '连接服务器,在客户机列表中没有找到对应记录!'), '提示', MB_OK + MB_ICONINFORMATION); end; end; end; procedure TExamControl.ClinetChanged(Sender: TObject); begin if Assigned(FOnClinetChanged) then begin FOnClinetChanged(Sender); end; end; constructor TExamControl.Create; begin FClientList := TStringList.Create; FExamStuList:= TStringList.Create; TCPServer.OnRevStuData := RevPacksData; TCPServer.OnClientChange := ClientChange; // FTCPServer := TTCPServer.Create; // FTCPServer.OnIPSendRev := TCPPacksLog; // FTCPServer.OnLog := TCPLog; // FTCPServer.Connect; FIsExamStart := False; ReadINI; end; destructor TExamControl.Destroy; begin WriteINI; // FTCPServer.Free; ClearStringList(FClientList); FClientList.Free; FExamStuList.Free; inherited; end; procedure TExamControl.ExamReady(Sender: TObject); var i : Integer; nTotal, nReadyCount : Integer; AInfo : TClientInfo; begin with TClientInfo(Sender) do begin ClientState := esWorkReady; end; nTotal := 0; nReadyCount := 0; for i := 0 to FClientList.Count - 1 do begin AInfo := ClientInfo[i]; if AInfo.ClientState in [esLogin, esWorkReady] then Inc(nTotal); if AInfo.ClientState = esWorkReady then begin Inc(nReadyCount); end; end; TCPServer.SendProgress(nReadyCount, nTotal); end; procedure TExamControl.ExamStart; begin FIsExamStart := True; FExamStartTime := Now; end; procedure TExamControl.ExamStop; begin FIsExamStart := False end; function TExamControl.GetClient(sIP: string; nPort: Integer): TClientInfo; var i : Integer; begin Result := nil; for i := 0 to FClientList.Count - 1 do begin with TClientInfo(FClientList.Objects[i]) do begin if (ClientIP = sIP) then begin Result := TClientInfo(FClientList.Objects[i]); Break; end; end; end; end; function TExamControl.GetClientInfo(nIndex: Integer): TClientInfo; begin if (nIndex >= 0) and (nIndex < FClientList.Count) then begin Result := TClientInfo(FClientList.Objects[nIndex]); end else begin Result := nil; end; end; function TExamControl.GetClinetCount: Integer; begin Result := FClientList.Count; end; function TExamControl.GetTrainClientCount: Integer; var i : Integer; begin Result := 0; for i := 0 to FClientList.Count - 1 do begin if TClientInfo(FClientList.Objects[i]).ClientState = esTrain then begin Inc(Result); end; end; end; procedure TExamControl.LoginEvent(Sender: TObject; nStuID: Integer); //var // nIndex : Integer; begin with TClientInfo(Sender) do begin // nIndex := FExamStuList.IndexOf(IntToStr(nStuID)); // TCPServer.LoginResult(ClientIP, ClientPort, nIndex <> -1); // // if nIndex <> -1 then // begin // StudentInfo.Assign(TStudentInfo(FExamStuList.Objects[nIndex])); // end; TCPServer.LoginResult(ClientIP, ClientPort, True); StudentInfo.Assign(StudentControl.SearchStu(nStuID)); ClientState := esLogin; end; end; procedure TExamControl.ReadINI; var s : string; i : Integer; AStuInfo : TStudentInfo; nSN : Integer; begin with TIniFile.Create( spubFilePath + 'OptionClient.ini') do begin FColCount := ReadInteger('Option', 'ClientColCount', 6); ClinetCount := ReadInteger('Option', 'ClientCount', 30); s := ReadString('Exam', 'ExamStuList', ''); GetPartValue(FExamStuList,s, ','); for i := FExamStuList.Count - 1 downto 0 do begin TryStrToInt(FExamStuList[i], nSN); AStuInfo := StudentControl.SearchStu(nSN); if Assigned(AStuInfo) then begin FExamStuList.Objects[i] := AStuInfo; end else begin FExamStuList.Delete(i); end; end; Free; end; end; procedure TExamControl.RevPacksData(sIP: string; nPort: Integer; aPacks: TArray<Byte>); var AClientInfo : TClientInfo; begin AClientInfo := GetClient(sIP, nPort); if Assigned(AClientInfo) then begin AClientInfo.RevPacksData(sIP, nPort, aPacks); end; end; procedure TExamControl.SetClinetCount(const Value: Integer); var i: Integer; AClientInfo : TClientInfo; begin if Value > FClientList.Count then begin // 添加 for i := FClientList.Count to Value - 1 do begin AClientInfo := TClientInfo.Create; AClientInfo.ClientSN := i+1; AClientInfo.OnChanged := ClinetChanged; AClientInfo.OnStuLogin := LoginEvent; AClientInfo.OnStuReady := ExamReady; FClientList.AddObject('', AClientInfo); end; end else if Value < FClientList.Count then begin for i := FClientList.Count - 1 downto Value do begin FClientList.Objects[i].Free; FClientList.Delete(i); end; end; end; //procedure TExamControl.TCPLog(const S: string); //begin // if Assigned(FOnTCPLog) then // FOnTCPLog(s); //end; // //procedure TExamControl.TCPPacksLog(sIP: string; nPort: Integer; aPacks: TArray<Byte>; // bSend: Boolean); //var // s : string; //begin // if bsend then // s := '发送' // else // s := '接收'; // // if Assigned(FOnTCPLog) then // FOnTCPLog(FormatDateTime('hh:mm:ss:zzz', Now) + s + sIP +':' + IntToStr(nPort) + ' ' + BCDPacksToStr(aPacks) ); //end; procedure TExamControl.WriteINI; var s : string; i : Integer; begin with TIniFile.Create(spubFilePath + 'OptionClient.ini') do begin WriteInteger('Option', 'ClientColCount', FColCount); WriteInteger('Option', 'ClientCount', ClinetCount); s := ''; for i := 0 to FExamStuList.Count - 1 do s := s + FExamStuList[i] + ','; WriteString('Exam', 'ExamStuList', s); Free; end; end; end.
unit CrossBoardPrint; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, Math; type TCrossBoardPrintForm = class(TForm) lblDrl_no: TLabel; btn_Print: TBitBtn; btn_cancel: TBitBtn; cboDrl_no: TComboBox; procedure FormCreate(Sender: TObject); procedure btn_PrintClick(Sender: TObject); procedure btn_cancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } //取得重塑土Cu'的最大值,参数strCuAll是保存在数据库中的Cu字段内容 function getMaxCu2(const strCuAll: string) : string; //取得原状土Cu的最大值,参数strCuAll是保存在数据库中的Cu字段内容 function getMaxCu(const strCuAll: string) : string; procedure GetDrillsNo; public { Public declarations } end; var CrossBoardPrintForm: TCrossBoardPrintForm; implementation uses MainDM, public_unit; {$R *.dfm} { TCrossBoardPrintForm } procedure TCrossBoardPrintForm.GetDrillsNo; begin cboDrl_no.Clear; with MainDataModule.qryDrills do begin close; sql.Clear; sql.Add('SELECT prj_no,drl_no '); sql.Add(' FROM drills '); sql.Add(' WHERE prj_no='+''''+g_ProjectInfo.prj_no_ForSQL+''''); open; while not Eof do begin cboDrl_no.Items.Add(FieldByName('drl_no').AsString); Next; end; close; end; SetCBWidth(cboDrl_no); end; procedure TCrossBoardPrintForm.FormCreate(Sender: TObject); begin self.Left := trunc((screen.Width -self.Width)/2); self.Top := trunc((Screen.Height - self.Height)/2); GetDrillsNo; end; procedure TCrossBoardPrintForm.btn_PrintClick(Sender: TObject); //yys edit 2010, 工勘院的CAD部门从其他部门得到的原始数据发生变化,数据不再除10,所以这里也不再*10 //const DiZengJiaoDu=10; const DiZengJiaoDu=1; var strFileName,strCuAll,strCuAll1,strMaxCu,strMaxCu2,strJiaoDuAll1,strCuAll2,strJiaoDuAll2: string; strExecute,strStratum,strSQL: string; FileList, tmpList,CuList: TStringList; i, j,intCount1,intCount2: integer; begin if g_ProjectInfo.prj_no ='' then exit; if cboDrl_no.Text ='' then exit; FileList := TStringList.Create; tmpList := TStringList.Create; CuList := TStringList.Create; strFileName:= g_AppInfo.PathOfChartFile + 'crossboard.ini'; try FileList.Add('[图纸信息]'); FileList.Add('保存用文件名=十字板剪切试验曲线图' + trim(cboDrl_no.Text)); if g_ProjectInfo.prj_ReportLanguage= trChineseReport then FileList.Add('图纸名称=十字板剪切试验曲线图') else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then FileList.Add('图纸名称=Vane shear test graph'); FileList.Add('工程编号='+g_ProjectInfo.prj_no); if g_ProjectInfo.prj_ReportLanguage= trChineseReport then FileList.Add('工程名称='+g_ProjectInfo.prj_name) else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then FileList.Add('工程名称='+g_ProjectInfo.prj_name_en) ; with MainDataModule.qryCrossBoard do begin close; sql.Clear; sql.Add('SELECT prj_no,drl_no,cb_depth,Cu,Cu_max FROM CrossBoard'); sql.Add(' WHERE prj_no=' +''''+ g_ProjectInfo.prj_no_ForSQL+ '''' + ' AND drl_no = '+''''+cboDrl_no.Text +''''); open; i:= 0; while not eof do begin Inc(i); tmpList.Add('[钻孔'+ inttostr(i)+']'); tmpList.Add('编号='+FieldByName('drl_no').AsString); tmpList.Add('测试深度=' +FormatFloat('0.00',FieldByName('cb_depth').AsFloat)+'(m)'); strSQL:='SELECT st.*,ISNULL(ea.ea_name_en,'''''''') as ea_name_en ' +'FROM stratum st,earthtype ea' +' WHERE st.prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +'''' +' AND st.drl_no=' +''''+stringReplace(cboDrl_no.Text,'''','''''',[rfReplaceAll])+'''' +' AND st.stra_depth>= ' + FieldByName('cb_depth').AsString +' AND st.ea_name = ea.ea_name ' +' ORDER BY st.stra_depth '; with MainDataModule.qryStratum do begin close; sql.Clear; sql.Add(strSQL); open; if not Eof then begin if FieldByName('sub_no').AsString='0' then strStratum := FieldByName('stra_no').AsString else strStratum := FieldByName('stra_no').AsString+'---'+FieldByName('sub_no').AsString; if g_ProjectInfo.prj_ReportLanguage= trChineseReport then strStratum := strStratum + FieldByName('ea_name').AsString else strStratum := strStratum + FieldByName('ea_name_en').AsString; tmpList.Add('土层编号及名称='+strStratum); end; close; end; //yys 2006/08/29 修改 //tmpList.Add('Cu='+FormatFloat('0.0',FieldByName('cu_max').AsFloat)); //tmpList.Add('Cu='+FormatFloat('0.00',FieldByName('cu_max').AsFloat * 10)+'(kPa)'); //end 结束修改 tmpList.Add('LineCount=2'); strCuAll := FieldByName('cu').AsString; strMaxCu := getMaxCu(strCuAll); //yys 2008/10/20 修改 原因:工勘院数据已经做过预处理,CU和CU'程序里不用再*10 //tmpList.Add('Cu='+FormatFloat('0.00',strToFloat(strMaxCu) * 10)+'(kPa)'); tmpList.Add('Cu='+FormatFloat('0.00',strToFloat(strMaxCu))+'(kPa)'); strMaxCu2 := getMaxCu2(strCuAll); if strMaxCu2='' then tmpList.Add('Cu''=') else begin //tmpList.Add('Cu''='+FormatFloat('0.00', strToFloat(strMaxCu2)* 10)+'(kPa)'); tmpList.Add('Cu''='+FormatFloat('0.00', strToFloat(strMaxCu2))+'(kPa)'); //end 结束修改 tmpList.Add('st='+FormatFloat('0.00', strToFloat(strMaxCu)/strToFloat(strMaxCu2))); end; DivideString(strCuAll,',',CuList); strJiaoDuAll1:= ''; strJiaoDuAll2:= ''; strCuAll1:=''; strCuAll2:=''; intCount1:=0; intCount2:=0; for j:=1 to CuList.Count do if (j mod 2)=1 then begin if trim(CuList.Strings[j-1])<>'' then begin intCount1:=intCount1+1; strJiaoDuAll1:= strJiaoDuAll1 + inttostr(intCount1)+','; strCuAll1:=strCuAll1+FloattoStr(StrtoFloat(CuList.Strings[j-1])*DiZengJiaoDu)+',' end end else begin if trim(CuList.Strings[j-1])<>'' then begin intCount2:=intCount2+1; strJiaoDuAll2:= strJiaoDuAll2 + inttostr(intCount2)+','; strCuAll2:=strCuAll2+FloattoStr(StrtoFloat(CuList.Strings[j-1])*DiZengJiaoDu)+','; end; end; if copy(strJiaoDuAll1,length(strJiaoDuAll1),1)=',' then strJiaoDuAll1:= copy(strJiaoDuAll1,1,length(strJiaoDuAll1)-1); if copy(strJiaoDuAll2,length(strJiaoDuAll2),1)=',' then strJiaoDuAll2:= copy(strJiaoDuAll2,1,length(strJiaoDuAll2)-1); if copy(strCuAll1,length(strCuAll1),1)=',' then strCuAll1:= copy(strCuAll1,1,length(strCuAll1)-1); if copy(strCuAll2,length(strCuAll2),1)=',' then strCuAll2:= copy(strCuAll2,1,length(strCuAll2)-1); tmpList.Add('所有角度1='+strJiaoDuAll1); tmpList.Add('所有强度1='+strCuAll1); tmpList.Add('所有角度2='+strJiaoDuAll2); tmpList.Add('所有强度2='+strCuAll2); next; end; close; end; FileList.Add('[钻孔]'); FileList.Add('个数='+ inttostr(i)); if i>0 then for i:=0 to tmpList.Count-1 do FileList.Add(tmpList.Strings[i]); FileList.SaveToFile(strFileName); finally FileList.Free; tmpList.Free; end; winexec(pAnsichar(getCadExcuteName+' '+PrintChart_CrossBoard+','+strFileName ),sw_normal); end; procedure TCrossBoardPrintForm.btn_cancelClick(Sender: TObject); begin close; end; procedure TCrossBoardPrintForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; function TCrossBoardPrintForm.getMaxCu2(const strCuAll: string): string; var i,j, iCount: integer; CuList: TStringList; dMaxCu2: Double; begin if trim(strCuAll)='' then begin result:=''; exit; end; CuList := TStringList.Create; DivideString(strCuAll,',',CuList); if CuList.Count>0 then begin for i:= 0 to CuList.Count -1 do begin if i=1 then begin if CuList.Strings[i]='' then begin result := ''; cuList.Free; exit; end; dMaxCu2:= Strtofloat(CuList.Strings[i]); continue; end; if (i mod 2)=1 then begin if CuList.Strings[i]='' then begin result := Floattostr(dMaxCu2); cuList.Free; exit; end; dMaxCu2:= max(Strtofloat(CuList.Strings[i]),dMaxCu2); end; end; result := Floattostr(dMaxCu2); end; cuList.Free; end; function TCrossBoardPrintForm.getMaxCu(const strCuAll: string): string; var i,j, iCount: integer; CuList: TStringList; dMaxCu: Double; begin if trim(strCuAll)='' then begin result:=''; exit; end; CuList := TStringList.Create; DivideString(strCuAll,',',CuList); if CuList.Count>0 then begin for i:= 0 to CuList.Count -1 do begin if i=0 then begin if CuList.Strings[i]='' then begin result := ''; cuList.Free; exit; end; dMaxCu:= Strtofloat(CuList.Strings[i]); continue; end; if (i mod 2)=0 then begin if CuList.Strings[i]='' then begin result := Floattostr(dMaxCu); cuList.Free; exit; end; dMaxCu:= max(Strtofloat(CuList.Strings[i]),dMaxCu); end; end; result := Floattostr(dMaxCu); end; cuList.Free; end; end.
PROGRAM TestWindows; (* A demo program for the WINDOWS unit *) USES Crt, Windows; CONST NewLine : string[2] = ^M^J; Esc : char = ^[; VAR Str: array[1..3] of string[50]; NumWindows : byte; Key : char; Error : boolean; begin Str[1] := ' This is the first window opened...'; Str[2] := ' This is the second window opened...'; Str[3] := ' And this is the third.'; NumWindows := 0; TextMode(CO80); ClrScr; OpenWindow(1,23,79,25,Blue,Lightgray,Error); if not(Error) then begin Write(' Type an alphanumeric Key, or press <Esc> to'); Write(' close a window.'); end; OpenWindow(30,10,70,15,Yellow,Green,Error); if not(Error) then begin Write(NewLine,NewLine,Str[1]); NumWindows := NumWindows + 1 end; OpenWindow(5,2,50,8,LightRed,Black,Error); if not(Error) then begin Write(Str[2]); NumWindows := NumWindows + 1 end; OpenWindow(20,12,55,16,White,Magenta,Error); if not(Error) then begin WriteLn(Str[3]); NumWindows := NumWindows + 1 end; while NumWindows>0 do begin Key := ReadKey; if Key = #0 then Key := ReadKey (* discard function & cursor keys *) else if Key = ^M then Writeln else if Key = Esc then begin NumWindows := NumWindows -1; CloseWindow end else Write(Key) end (* while NumWindows > 0 *); CloseWindow (* close the help window *) end. 
{********************************************************************** GnouMeter is a meter which can display an integer or a float value (Single). Just like a progress bar or a gauge, all you have do do is to define the Minimum and maximum values as well as the actual value. Above the meter, one can display the name of the data being measured (optional) and its actual value with its corresponding unit. The minimum and maximum values are respectively shown at the bottom and the top of the meter with their corresponding units. The meter is filled with the color ColorFore and its background color is defined by the ColorBack Property. THIS COMPONENT IS ENTIRELY FREEWARE Author: Jérôme Hersant jhersant@post4.tele.dk ***********************************************************************} unit indGnouMeter; {$mode objfpc}{$H+} interface uses Classes, Controls, Graphics, SysUtils, LMessages, Types, LCLType, LCLIntf; const DEFAULT_BAR_THICKNESS = 5; DEFAULT_GAP_TOP = 20; DEFAULT_GAP_BOTTOM = 10; DEFAULT_MARKER_DIST = 4; DEFAULT_MARKER_SIZE = 6; type TindGnouMeter = class(TGraphicControl) private fValue: Double; fColorFore: TColor; fColorBack: TColor; fSignalUnit: ShortString; fValueMax: Double; fValueMin: Double; fDigits: Byte; fIncrement: Double; fShowIncrements: Boolean; fGapTop: Word; fGapBottom: Word; fBarThickness: Word; fMarkerColor: TColor; fMarkerDist: Integer; fMarkerSize: Integer; fShowMarker: Boolean; //Variables used internally TopTextHeight: Word; LeftMeter: Integer; DisplayValue: String; DrawStyle: integer; TheRect: TRect; //End of variables used internally function IsBarThicknessStored: Boolean; function IsGapBottomStored: Boolean; function IsGapTopStored: Boolean; function IsMarkerDistStored: Boolean; function IsMarkerSizeStored: Boolean; procedure SetValue(val: Double); procedure SetColorBack(val: TColor); procedure SetColorFore(val: TColor); procedure SetSignalUnit(val: ShortString); procedure SetValueMin(val: Double); procedure SetValueMax(val: Double); procedure SetDigits(val: Byte); procedure SetTransparent(val: Boolean); function GetTransparent: Boolean; procedure SetIncrement(val: Double); procedure SetShowIncrements(val: Boolean); procedure SetGapTop(val: Word); procedure SetGapBottom(val: Word); procedure SetBarThickness(val: Word); procedure SetMarkerColor(val: TColor); procedure SetMarkerDist(val: Integer); procedure SetMarkerSize(val: Integer); procedure SetShowMarker(val: Boolean); procedure DrawTopText; procedure DrawMeterBar; procedure DrawIncrements; function ValueToPixels(val: Double): integer; procedure DrawValueMax; procedure DrawValueMin; procedure DrawMarker; protected procedure CMTextChanged(var {%H-}Message: TLMessage); message CM_TEXTCHANGED; procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Align; property Caption; property Visible; property ShowHint; property Value: Double read fValue write SetValue; property Color; property Font; property ParentColor; property ColorFore: Tcolor read fColorFore write SetColorFore default clRed; property ColorBack: Tcolor read fColorBack write SetColorBack default clBtnFace; property SignalUnit: ShortString read fSignalUnit write SetSignalUnit; property ValueMin: Double read fValueMin write SetValueMin; property ValueMax: Double read fValueMax write SetValueMax; property Digits: Byte read fDigits write SetDigits; property Increment: Double read fIncrement write SetIncrement; property ShowIncrements: Boolean read fShowIncrements write SetShowIncrements default true; property Transparent: Boolean read GetTransparent write SetTransparent default true; property GapTop: Word read fGapTop write SetGapTop stored IsGapTopStored; property GapBottom: Word read fGapBottom write SetGapBottom stored IsGapBottomStored; property BarThickness: Word read fBarThickness write SetBarThickness stored IsBarThicknessStored; property MarkerColor: TColor read fMarkerColor write SetMarkerColor; property MarkerDist: Integer read fMarkerDist write SetMarkerDist stored IsMarkerDistStored; property MarkerSize: Integer read fMarkerSize write SetMarkerSize stored IsMarkerSizeStored; property ShowMarker: Boolean read fShowMarker write SetShowMarker default true; end; implementation constructor TindGnouMeter.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable, csSetCaption]; Width := 100; Height := 200; fColorFore := clRed; fColorBack := clBtnFace; fMarkerColor := clBlue; fValueMin := 0; fValueMax := 100; fIncrement := 10; fShowIncrements := True; fShowMarker := True; fValue := 0; fGapTop := Scale96ToFont(DEFAULT_GAP_TOP); fGapBottom := Scale96ToFont(DEFAULT_GAP_BOTTOM); fBarThickness := Scale96ToFont(DEFAULT_BAR_THICKNESS); fMarkerDist := Scale96ToFont(DEFAULT_MARKER_DIST); fMarkerSize := Scale96ToFont(DEFAULT_MARKER_SIZE); fSignalUnit := 'Units'; end; destructor TindGnouMeter.Destroy; begin inherited Destroy; end; procedure TindGnouMeter.CMTextChanged(var Message: TLMessage); begin Invalidate; end; procedure TindGnouMeter.DoAutoAdjustLayout( const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double); begin inherited DoAutoAdjustLayout(AMode, AXProportion, AYProportion); if AMode in [lapAutoAdjustWithoutHorizontalScrolling, lapAutoAdjustForDPI] then begin DisableAutosizing; try if IsBarThicknessStored then FBarThickness := Round(FBarThickness * AXProportion); if IsGapBottomStored then FGapBottom := Round(FGapBottom * AYProportion); if IsGapTopStored then FGapTop := Round(FGapTop * AYProportion); if IsMarkerDistStored then FMarkerDist := Round(FMarkerDist * AXProportion); if IsMarkerSizeStored then FMarkerSize := Round(FMarkerSize * AXProportion); finally EnableAutoSizing; end; end; end; function TindGnouMeter.IsBarThicknessStored: Boolean; begin Result := FBarThickness <> Scale96ToFont(DEFAULT_BAR_THICKNESS); end; function TindGnouMeter.IsGapBottomStored: Boolean; begin Result := FGapBottom <> Scale96ToFont(DEFAULT_GAP_BOTTOM); end; function TindGnouMeter.IsGapTopStored: Boolean; begin Result := FGapTop <> Scale96ToFont(DEFAULT_GAP_TOP); end; function TindGnouMeter.IsMarkerDistStored: Boolean; begin Result := FMarkerDist <> Scale96ToFont(DEFAULT_MARKER_DIST); end; function TindGnouMeter.IsMarkerSizeStored: Boolean; begin Result := FMarkerSize <> Scale96ToFont(DEFAULT_MARKER_SIZE); end; procedure TindGnouMeter.SetValue(val: Double); begin if (val <> fValue) and (val >= fValueMin) and (val <= fValueMax) then begin fValue := val; Invalidate; end; end; procedure TindGnouMeter.SetColorFore(val: TColor); begin if val <> fColorFore then begin fColorFore := val; Invalidate; end; end; procedure TindGnouMeter.SetColorBack(val: TColor); begin if val <> fColorBack then begin fColorBack := val; Invalidate; end; end; procedure TindGnouMeter.SetSignalUnit(val: ShortString); begin if val <> fSignalUnit then begin fSignalUnit := val; Invalidate; end; end; procedure TindGnouMeter.SetValueMin(val: Double); begin if (val <> fValueMin) and (val <= fValue) then begin fValueMin := val; Invalidate; end; end; procedure TindGnouMeter.SetValueMax(val: Double); begin if (val <> fValueMax) and (val >= fValue) then begin fValueMax := val; Invalidate; end; end; procedure TindGnouMeter.SetDigits(val: Byte); begin if (val <> fDigits) then begin fDigits := val; Invalidate; end; end; procedure TindGnouMeter.SetIncrement(val: Double); begin if (val <> fIncrement) and (val > 0) then begin fIncrement := val; Invalidate; end; end; procedure TindGnouMeter.SetShowIncrements(val: Boolean); begin if (val <> fShowIncrements) then begin fShowIncrements := val; Invalidate; end; end; function TindGnouMeter.GetTransparent: Boolean; begin Result := not (csOpaque in ControlStyle); end; procedure TindGnouMeter.SetTransparent(Val: Boolean); begin if Val <> Transparent then begin if Val then ControlStyle := ControlStyle - [csOpaque] else ControlStyle := ControlStyle + [csOpaque]; Invalidate; end; end; procedure TindGnouMeter.SetGapTop(val: Word); begin if (val <> fGapTop) then begin fGapTop := val; Invalidate; end; end; procedure TindGnouMeter.SetGapBottom(val: Word); begin if (val <> fGapBottom) then begin fGapBottom := val; Invalidate; end; end; procedure TindGnouMeter.SetBarThickness(val: Word); begin if (val <> fBarThickness) and (val > 0) then begin fBarThickness := val; Invalidate; end; end; procedure TindGnouMeter.SetMarkerColor(val: TColor); begin if (val <> fMarkerColor) then begin fMarkerColor := val; Invalidate; end; end; procedure TindGnouMeter.SetMarkerDist(val: Integer); begin if (val <> fMarkerDist) then begin fMarkerDist := val; Invalidate; end; end; procedure TindGnouMeter.SetMarkerSize(val: Integer); begin if (val <> fMarkerSize) then begin fMarkerSize := val; Invalidate; end; end; procedure TindGnouMeter.SetShowMarker(val: Boolean); begin if (val <> fShowMarker) then begin fShowMarker := val; Invalidate; end; end; procedure TindGnouMeter.DrawIncrements; var i: Double; PosPixels: Word; begin if fShowIncrements then begin with Canvas do begin i := fValueMin; while i <= fValueMax do begin PosPixels := ValueToPixels(i); pen.color := clGray; MoveTo(LeftMeter + BarThickness + 3, PosPixels - 1); LineTo(LeftMeter + BarThickness + 7, PosPixels - 1); pen.color := clWhite; MoveTo(LeftMeter + BarThickness + 3, PosPixels); LineTo(LeftMeter + BarThickness + 7, PosPixels); i := i + fIncrement; end; end; end; end; procedure TindGnouMeter.DrawMarker; var v: Integer; dx, dy: Integer; begin if fShowMarker then begin v := ValueToPixels(fValue); with Canvas do begin dx := FMarkerSize; dy := round(FMarkerSize * sin(pi/6)); // 3D edges Pen.Color := clWhite; Brush.Style := bsClear; MoveTo(LeftMeter - FMarkerDist + 1, v); LineTo(LeftMeter - FMarkerDist - dx - 1, v - dy - 1); LineTo(LeftMeter - FMarkerDist - dx - 1, v + dy + 1); Pen.Color := clGray; LineTo(LeftMeter - FMarkerDist + 1, v); // Triangle Pen.Color := fMarkerColor; Brush.Color := fMarkerColor; Brush.Style := bsSolid; Polygon([ Point(LeftMeter - FMarkerDist, v), Point(LeftMeter - FMarkerDist - dx, v - dy), Point(LeftMeter - FMarkerDist - dx, v + dy) ]); end; end; end; procedure TindGnouMeter.DrawTopText; begin with Canvas do begin DisplayValue := Caption; Brush.Style := bsClear; TheRect := ClientRect; DrawStyle := DT_SINGLELINE + DT_NOPREFIX + DT_CENTER + DT_TOP; Font.Style := [fsBold]; TopTextHeight := DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); Font.Style := []; TheRect.Top := TopTextHeight; DisplayValue := FloatToStrF(Value, ffFixed, 8, fDigits) + ' ' + fSignalUnit; TopTextHeight := TopTextHeight + DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); TopTextHeight := TopTextHeight + fGapTop; end; end; procedure TindGnouMeter.DrawValueMin; begin with Canvas do begin TheRect := ClientRect; TheRect.Left := LeftMeter + BarThickness + Scale96ToFont(10); TheRect.Top := TopTextHeight; TheRect.Bottom := Height - fGapBottom + Scale96ToFont(6); Brush.Style := bsClear; DrawStyle := DT_SINGLELINE + DT_NOPREFIX + DT_LEFT + DT_BOTTOM; DisplayValue := FloatToStrF(ValueMin, ffFixed, 8, fDigits) + ' ' + fSignalUnit; DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); end; end; procedure TindGnouMeter.DrawValueMax; begin with Canvas do begin TheRect := ClientRect; TheRect.Left := LeftMeter + BarThickness + Scale96ToFont(10); TheRect.Top := TopTextHeight - Scale96ToFont(6); Brush.Style := bsClear; DrawStyle := DT_SINGLELINE + DT_NOPREFIX + DT_LEFT + DT_TOP; DisplayValue := FloatToStrF(ValueMax, ffFixed, 8, fDigits) + ' ' + fSignalUnit; DrawText(Handle, PChar(DisplayValue), Length(DisplayValue), TheRect, DrawStyle); end; end; procedure TindGnouMeter.DrawMeterBar; begin with Canvas do begin Pen.Color := fColorBack; Brush.Color := fColorBack; Brush.Style := bsSolid; Rectangle(LeftMeter, ValueToPixels(fValueMax), LeftMeter + fBarThickness, ValueToPixels(fValueMin)); Pen.Color := fColorFore; Brush.Color := fColorFore; Brush.Style := bsSolid; Rectangle(LeftMeter + 1, ValueToPixels(fValue), LeftMeter + fBarThickness, ValueToPixels(fValueMin)); Pen.color := clWhite; Brush.Style := bsClear; MoveTo(LeftMeter + fBarThickness - 1, ValueToPixels(fValueMax)); LineTo(LeftMeter, ValueToPixels(fValueMax)); LineTo(LeftMeter, ValueToPixels(fValueMin) - 1); Pen.color := clGray; LineTo(LeftMeter + fBarThickness, ValueToPixels(fValueMin) - 1); LineTo(LeftMeter + fBarThickness, ValueToPixels(fValueMax)); if (fValue > fValueMin) and (fValue < fValueMax) then begin Pen.color := clWhite; MoveTo(LeftMeter + 1, ValueToPixels(fValue)); LineTo(LeftMeter + fBarThickness, ValueToPixels(fValue)); Pen.color := clGray; MoveTo(LeftMeter + 1, ValueToPixels(fValue) - 1); LineTo(LeftMeter + fBarThickness, ValueToPixels(fValue) - 1); end; end; end; function TindGnouMeter.ValueToPixels(val: Double): integer; var factor: Double; begin Result := 0; if fValueMax > fValueMin then begin Factor := (Height - fGapBottom - TopTextHeight) / (fValueMin - fValueMax); Result := Round(Factor * val - Factor * fValueMax + TopTextHeight); end; end; procedure TindGnouMeter.Paint; begin LeftMeter := (Width div 2) - Scale96ToFont(10) - fBarThickness; with Canvas do begin if not Transparent then begin Brush.Color := Self.Color; Brush.Style := bsSolid; FillRect(ClientRect); end; Brush.Style := bsClear; DrawTopText; DrawValueMin; DrawValueMax; DrawMeterBar; DrawMarker; DrawIncrements; end; end; end.
unit blake2b; {Blake2B - max 512 bit hash/MAC function} interface (************************************************************************* DESCRIPTION : Blake2B - max 512 bit hash/MAC function REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : - Saarinen et al: The BLAKE2 Cryptographic Hash and Message Authentication Code (MAC); https://tools.ietf.org/html/rfc7693 - Aumasson et al: BLAKE2: simpler, smaller, fast as MD5; https://blake2.net/blake2.pdf - Official reference code: https://github.com/BLAKE2/BLAKE2 Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 06.10.17 W.Ehrhardt Initial D6 implementation (from Blake2s / RFC code) 0.11 06.10.17 we removed updatelen, max input < 2^64 0.12 06.10.17 we FPC fix 0.13 06.10.17 we blake2b_selftest 0.14 06.10.17 we used int64 instead of u64 0.15 07.10.17 we unroll compress loop for Delphi 0.16 07.10.17 we adjust/assert context size 0.17 03.11.17 we Use THashContext and internal blake2b_ctx 0.18 04.11.17 we Dummy functions for TP5-7, D1-D3, IV with longints 0.19 05.11.17 we Some commpn code for 64 and 16/32 bit 0.20 05.11.17 we 32-Bit BASM 0.21 05.11.17 we 16-Bit BASM 0.22 21.11.14 eh Faster blake2b_compress routines from EddyHawk 0.23 23.11.14 we Replace RotR(,16) with word moves for non-int64 0.24 24.11.14 we RotR63 with BASM 0.25 24.11.14 we RotR24 with byte move 0.26 24.11.14 we RotR63, Add64 for VER5X **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2017 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} uses BTypes, Hash; const BLAKE2B_BlockLen = 128; BLAKE2B_MaxDigLen = 64; BLAKE2B_MaxKeyLen = 64; type TBlake2BDigest = packed array[0..BLAKE2B_MaxDigLen-1] of byte; {max. blake2b digest} TBlake2BBlock = packed array[0..BLAKE2B_BlockLen-1] of byte; function blake2b_Init(var ctx: THashContext; key: pointer; keylen, diglen: word): integer; {-Initialize context for a digest of diglen bytes; keylen=0: no key} procedure blake2b_update(var ctx: THashContext; msg: pointer; mlen: longint); {-Add "mlen" bytes from "msg" into the hash} procedure blake2b_Final(var ctx: THashContext; var Digest: TBlake2BDigest); {-Finalize calculation, generate message digest, clear context} function blake2b_full(var dig: TBlake2BDigest; diglen: word; key: pointer; keylen: word; msg: pointer; mlen: longint): integer; {-Calculate hash digest of Msg with init/update/final} function blake2b_selftest: boolean; {-Return true, if self test is OK} implementation {The next comment is copy from blake2b-ref.c} (* BLAKE2 reference source code package - reference C implementations Copyright 2012, Samuel Neves <sneves@dei.uc.pt>. You may use this under the terms of the CC0, the OpenSSL Licence, or the Apache Public License 2.0, at your option. The terms of these licenses can be found at: - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0 - OpenSSL license : https://www.openssl.org/source/license.html - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0 More information about the BLAKE2 hash function can be found at https://blake2.net. *) {Initialization Vector, longints for compatibility} const blake2b_ivl: array[0..15] of longint = ( longint($F3BCC908), longint($6A09E667), longint($84CAA73B), longint($BB67AE85), longint($FE94F82B), longint($3C6EF372), longint($5F1D36F1), longint($A54FF53A), longint($ADE682D1), longint($510E527F), longint($2B3E6C1F), longint($9B05688C), longint($FB41BD6B), longint($1F83D9AB), longint($137E2179), longint($5BE0CD19)); const sigma: array[0..11,0..15] of byte = ( ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ), ( 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 ), ( 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 ), ( 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 ), ( 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 ), ( 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 ), ( 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 ), ( 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 ), ( 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 ), ( 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 ), ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ), ( 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 ) ); {$ifdef HAS_INT64} type blake2b_ctx = packed record h: packed array[0..7] of int64; t: packed array[0..1] of int64; b: TBlake2BBlock; c: longint; outlen: longint; fill4: packed array[217..HASHCTXSIZE] of byte; end; {---------------------------------------------------------------------------} procedure blake2b_compress(var ctx: blake2b_ctx; last: boolean); {- Compression function, "last" indicates last block} var v,m: array[0..15] of int64; tem: int64; round,k: integer; begin with ctx do begin {init work variables} move(h, v, sizeof(h)); move(blake2b_ivl, v[8], sizeof(h)); v[12] := v[12] xor t[0]; {low 64 bits of offset} v[13] := v[13] xor t[1]; {high 64 bits} if last then v[14] := not v[14]; {last block flag set} {get little-endian words} move(b, m, sizeof(m)); {do 12 rounds} for round:=0 to 11 do begin {** EddyHawk speed-ups **} {use same rearrangements as blake2s' 32/64 bit code} v[ 0] := (v[ 0] + v[ 4]) + m[sigma[round][ 0]]; v[ 1] := (v[ 1] + v[ 5]) + m[sigma[round][ 2]]; v[ 2] := (v[ 2] + v[ 6]) + m[sigma[round][ 4]]; v[ 3] := (v[ 3] + v[ 7]) + m[sigma[round][ 6]]; tem := v[12] xor v[ 0]; v[12] := (tem shr 32) or (tem shl (64-32)); tem := v[13] xor v[ 1]; v[13] := (tem shr 32) or (tem shl (64-32)); tem := v[14] xor v[ 2]; v[14] := (tem shr 32) or (tem shl (64-32)); tem := v[15] xor v[ 3]; v[15] := (tem shr 32) or (tem shl (64-32)); v[ 8] := v[ 8] + v[12]; v[ 9] := v[ 9] + v[13]; v[10] := v[10] + v[14]; v[11] := v[11] + v[15]; tem := v[ 4] xor v[ 8]; v[ 4] := (tem shr 24) or (tem shl (64-24)); tem := v[ 5] xor v[ 9]; v[ 5] := (tem shr 24) or (tem shl (64-24)); tem := v[ 6] xor v[10]; v[ 6] := (tem shr 24) or (tem shl (64-24)); tem := v[ 7] xor v[11]; v[ 7] := (tem shr 24) or (tem shl (64-24)); {---} v[ 0] := (v[ 0] + v[ 4]) + m[sigma[round][ 1]]; v[ 1] := (v[ 1] + v[ 5]) + m[sigma[round][ 3]]; v[ 2] := (v[ 2] + v[ 6]) + m[sigma[round][ 5]]; v[ 3] := (v[ 3] + v[ 7]) + m[sigma[round][ 7]]; tem := v[12] xor v[ 0]; v[12] := (tem shr 16) or (tem shl (64-16)); tem := v[13] xor v[ 1]; v[13] := (tem shr 16) or (tem shl (64-16)); tem := v[14] xor v[ 2]; v[14] := (tem shr 16) or (tem shl (64-16)); tem := v[15] xor v[ 3]; v[15] := (tem shr 16) or (tem shl (64-16)); v[ 8] := v[ 8] + v[12]; v[ 9] := v[ 9] + v[13]; v[10] := v[10] + v[14]; v[11] := v[11] + v[15]; tem := v[ 4] xor v[ 8]; v[ 4] := (tem shr 63) or (tem shl (64-63)); tem := v[ 5] xor v[ 9]; v[ 5] := (tem shr 63) or (tem shl (64-63)); tem := v[ 6] xor v[10]; v[ 6] := (tem shr 63) or (tem shl (64-63)); tem := v[ 7] xor v[11]; v[ 7] := (tem shr 63) or (tem shl (64-63)); {---} v[ 0] := (v[ 0] + v[ 5]) + m[sigma[round][ 8]]; v[ 1] := (v[ 1] + v[ 6]) + m[sigma[round][10]]; v[ 2] := (v[ 2] + v[ 7]) + m[sigma[round][12]]; v[ 3] := (v[ 3] + v[ 4]) + m[sigma[round][14]]; tem := v[15] xor v[ 0]; v[15] := (tem shr 32) or (tem shl (64-32)); tem := v[12] xor v[ 1]; v[12] := (tem shr 32) or (tem shl (64-32)); tem := v[13] xor v[ 2]; v[13] := (tem shr 32) or (tem shl (64-32)); tem := v[14] xor v[ 3]; v[14] := (tem shr 32) or (tem shl (64-32)); v[10] := v[10] + v[15]; v[11] := v[11] + v[12]; v[ 8] := v[ 8] + v[13]; v[ 9] := v[ 9] + v[14]; tem := v[ 5] xor v[10]; v[ 5] := (tem shr 24) or (tem shl (64-24)); tem := v[ 6] xor v[11]; v[ 6] := (tem shr 24) or (tem shl (64-24)); tem := v[ 7] xor v[ 8]; v[ 7] := (tem shr 24) or (tem shl (64-24)); tem := v[ 4] xor v[ 9]; v[ 4] := (tem shr 24) or (tem shl (64-24)); {---} v[ 0] := (v[ 0] + v[ 5]) + m[sigma[round][ 9]]; v[ 1] := (v[ 1] + v[ 6]) + m[sigma[round][11]]; v[ 2] := (v[ 2] + v[ 7]) + m[sigma[round][13]]; v[ 3] := (v[ 3] + v[ 4]) + m[sigma[round][15]]; tem := v[15] xor v[ 0]; v[15] := (tem shr 16) or (tem shl (64-16)); tem := v[12] xor v[ 1]; v[12] := (tem shr 16) or (tem shl (64-16)); tem := v[13] xor v[ 2]; v[13] := (tem shr 16) or (tem shl (64-16)); tem := v[14] xor v[ 3]; v[14] := (tem shr 16) or (tem shl (64-16)); v[10] := v[10] + v[15]; v[11] := v[11] + v[12]; v[ 8] := v[ 8] + v[13]; v[ 9] := v[ 9] + v[14]; tem := v[ 5] xor v[10]; v[ 5] := (tem shr 63) or (tem shl (64-63)); tem := v[ 6] xor v[11]; v[ 6] := (tem shr 63) or (tem shl (64-63)); tem := v[ 7] xor v[ 8]; v[ 7] := (tem shr 63) or (tem shl (64-63)); tem := v[ 4] xor v[ 9]; v[ 4] := (tem shr 63) or (tem shl (64-63)); end; {finalization} for k:=0 to 7 do begin h[k] := h[k] xor v[k] xor v[k+8]; end; end; end; {---------------------------------------------------------------------------} procedure blake2b_update(var ctx: THashContext; msg: pointer; mlen: longint); {-Add "mlen" bytes from "msg" into the hash} var left,fill: integer; begin with blake2b_ctx(ctx) do begin if mlen > 0 then begin left := c; fill := BLAKE2B_BlockLen - left; if mlen > fill then begin c := 0; if fill>0 then move(msg^, b[left], fill); t[0] := t[0] + BLAKE2B_BlockLen; blake2b_compress(blake2b_ctx(ctx), false); inc(Ptr2Inc(Msg),fill); dec(mlen,fill); while mlen > BLAKE2B_BlockLen do begin move(msg^,b,BLAKE2B_BlockLen); t[0] := t[0] + BLAKE2B_BlockLen; blake2b_compress(blake2b_ctx(ctx), false); {compress (not last)} inc(Ptr2Inc(Msg),BLAKE2B_BlockLen); dec(mlen,BLAKE2B_BlockLen); end; end; if mlen > 0 then begin move(msg^, b[c], mlen); c := c + mlen; end; end; end; end; {---------------------------------------------------------------------------} procedure blake2b_Final(var ctx: THashContext; var Digest: TBlake2BDigest); {-Finalize calculation, generate message digest, clear context} var i: integer; begin with blake2b_ctx(ctx) do begin t[0] := t[0] + c; while c < BLAKE2B_BlockLen do begin {fill up with zeros} b[c] := 0; inc(c); end; blake2b_compress(blake2b_ctx(ctx), true); {final block} {little endian convert and store} fillchar(Digest, sizeof(Digest),0); for i:=0 to outlen-1 do begin Digest[i] := (h[i shr 3] shr (8*(i and 7))) and $FF; end; end; end; {$else} type blake2b_ctx = packed record h: packed array[0..15] of longint; t: packed array[0..3] of longint; b: TBlake2BBlock; c: longint; outlen: longint; fill4: packed array[217..HASHCTXSIZE] of byte; end; type TW64 = packed record L,H: longint; end; TW16 = packed record w0,w1,w2,w3: word end; {$ifdef BIT16} {$ifdef BASM} {---------------------------------------------------------------------------} procedure Add64(var z: TW64; {$ifdef CONST} const {$else} var {$endif} x: TW64); assembler; {-Inc a 64 bit integer} asm les bx,[x] db $66; mov ax,es:[bx] db $66; mov dx,es:[bx+4] les bx,[z] db $66; add es:[bx],ax db $66; adc es:[bx+4],dx end; {---------------------------------------------------------------------------} procedure RotR63(var x: tw64); {-Rotate right 63 bits = rotate left 1} begin asm les bx,[x] db $66; mov ax,es:[bx] db $66; mov dx,es:[bx+4] db $66; shl ax,1 db $66; rcl dx,1 adc ax,0 db $66; mov es:[bx],ax db $66; mov es:[bx+4],dx end; end; {$else} {16-bit compilers without BASM} {---------------------------------------------------------------------------} procedure Add64(var Z: TW64; var X: TW64); {-Inc a 64 bit integer} inline( $8C/$DF/ {mov di,ds } $5E/ {pop si } $1F/ {pop ds } $8B/$04/ {mov ax,[si] } $8B/$5C/$02/ {mov bx,[si+02]} $8B/$4C/$04/ {mov cx,[si+04]} $8B/$54/$06/ {mov dx,[si+06]} $5E/ {pop si } $1F/ {pop ds } $01/$04/ {add [si],ax } $11/$5C/$02/ {adc [si+02],bx} $11/$4C/$04/ {adc [si+04],cx} $11/$54/$06/ {adc [si+06],dx} $8E/$DF); {mov ds,di } {---------------------------------------------------------------------------} procedure RotR63(var x: tw64); {-Rotate right 63 bits = rotate left 1} inline( $8C/$D9/ {mov cx,ds } $5B/ {pop bx } $1F/ {pop ds } $8B/$47/$06/ {mov ax,[bx+06]} $D1/$E0/ {shl ax,1 } $8B/$07/ {mov ax,[bx] } $D1/$D0/ {rcl ax,1 } $89/$07/ {mov [bx],ax } $8B/$47/$02/ {mov ax,[bx+02]} $D1/$D0/ {rcl ax,1 } $89/$47/$02/ {mov [bx+02],ax} $8B/$47/$04/ {mov ax,[bx+04]} $D1/$D0/ {rcl ax,1 } $89/$47/$04/ {mov [bx+04],ax} $8B/$47/$06/ {mov ax,[bx+06]} $D1/$D0/ {rcl ax,1 } $89/$47/$06/ {mov [bx+06],ax} $8E/$D9); {mov ds,cx } {$endif} {$else} {---------------------------------------------------------------------------} procedure Add64(var z: TW64; const x: TW64); assembler; {-Inc a 64 bit integer z := z + x} asm {$ifdef LoadArgs} mov eax,[z] mov edx,[x] {$endif} mov ecx,[edx] add [eax],ecx mov ecx,[edx+4] adc [eax+4],ecx end; {---------------------------------------------------------------------------} procedure RotR63(var x: tw64); assembler; {-Rotate right 63 bits} asm {$ifdef LoadArgs} mov eax,[x] {$endif} mov ecx,[eax] mov edx,[eax+4] shl ecx,1 rcl edx,1 adc ecx,0 mov [eax],ecx mov [eax+4],edx end; {$endif} {---------------------------------------------------------------------------} procedure RotR24(var x: tw64); {-Rotate right 24 bits} var a: packed array[0..7] of byte absolute x; b0,b1,b2: byte; begin b0 := a[0]; b1 := a[1]; b2 := a[2]; a[0] := a[3]; a[1] := a[4]; a[2] := a[5]; a[3] := a[6]; a[4] := a[7]; a[5] := b0; a[6] := b1; a[7] := b2; end; {---------------------------------------------------------------------------} procedure inct01(var ctx: THashContext; cnt: longint); {-Increment byte counter in ctx} begin with blake2b_ctx(ctx) do begin if t[0] < 0 then begin {Overflow if t[0]+cnt changes sign} inc(t[0], cnt); if t[0] >= 0 then inc(t[1]); end else inc(t[0], cnt); end; end; {---------------------------------------------------------------------------} procedure blake2b_compress(var ctx: blake2b_ctx; last: boolean); {-Compression function, "last" indicates last block} var v,m: array[0..15] of tw64; tem: longint; round,k: integer; tw: word; begin {get message} with ctx do begin {init work variables} move(h, v, sizeof(h)); move(blake2b_ivl, v[8], sizeof(h)); v[12].l := v[12].l xor t[0]; {low 64 bits of offset} v[12].h := v[12].h xor t[1]; v[13].l := v[13].l xor t[2]; {high 64 bits} v[13].h := v[13].h xor t[3]; if last then begin v[14].l := not v[14].l; {last block flag set} v[14].h := not v[14].h; end; {get little-endian words} move(b, m, sizeof(m)); {do 12 rounds} for round:=0 to 11 do begin {** EddyHawk speed-ups **} {replaces G64 with partial unroll} {replaces rotr64 by 32 with swap & temp var} { integrates xor-ing into that swapping} {splits 1 BLAKE2b round into quarter-rounds} { regroups them} {further splitting/regroupings, seems a bit better} {moves message addition to the front, seems a bit better} add64(v[0],m[sigma[round][2*0]]); add64(v[1],m[sigma[round][2*1]]); add64(v[2],m[sigma[round][2*2]]); add64(v[3],m[sigma[round][2*3]]); add64(v[0],v[4]); add64(v[1],v[5]); add64(v[2],v[6]); add64(v[3],v[7]); tem := v[12].L xor v[0].L; v[12].L := v[12].H xor v[0].H; v[12].H := tem; tem := v[13].L xor v[1].L; v[13].L := v[13].H xor v[1].H; v[13].H := tem; tem := v[14].L xor v[2].L; v[14].L := v[14].H xor v[2].H; v[14].H := tem; tem := v[15].L xor v[3].L; v[15].L := v[15].H xor v[3].H; v[15].H := tem; add64(v[ 8],v[12]); add64(v[ 9],v[13]); add64(v[10],v[14]); add64(v[11],v[15]); v[4].L := v[4].L xor v[ 8].L; v[5].L := v[5].L xor v[ 9].L; v[6].L := v[6].L xor v[10].L; v[7].L := v[7].L xor v[11].L; v[4].H := v[4].H xor v[ 8].H; v[5].H := v[5].H xor v[ 9].H; v[6].H := v[6].H xor v[10].H; v[7].H := v[7].H xor v[11].H; RotR24(v[4]); RotR24(v[5]); RotR24(v[6]); RotR24(v[7]); {---} add64(v[0],m[sigma[round][2*0+1]]); add64(v[1],m[sigma[round][2*1+1]]); add64(v[2],m[sigma[round][2*2+1]]); add64(v[3],m[sigma[round][2*3+1]]); add64(v[0],v[4]); add64(v[1],v[5]); add64(v[2],v[6]); add64(v[3],v[7]); v[12].L := v[12].L xor v[ 0].L; v[13].L := v[13].L xor v[ 1].L; v[14].L := v[14].L xor v[ 2].L; v[15].L := v[15].L xor v[ 3].L; v[12].H := v[12].H xor v[ 0].H; v[13].H := v[13].H xor v[ 1].H; v[14].H := v[14].H xor v[ 2].H; v[15].H := v[15].H xor v[ 3].H; {WE V0.23: Replace RotR(,16) with word moves} {RotR(v[12],16);} with TW16(v[12]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; {RotR(v[13],16);} with TW16(v[13]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; {RotR(v[14],16);} with TW16(v[14]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; {RotR(v[15],16);} with TW16(v[15]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; add64(v[ 8],v[12]); add64(v[ 9],v[13]); add64(v[10],v[14]); add64(v[11],v[15]); v[4].L := v[4].L xor v[ 8].L; v[5].L := v[5].L xor v[ 9].L; v[6].L := v[6].L xor v[10].L; v[7].L := v[7].L xor v[11].L; v[4].H := v[4].H xor v[ 8].H; v[5].H := v[5].H xor v[ 9].H; v[6].H := v[6].H xor v[10].H; v[7].H := v[7].H xor v[11].H; RotR63(v[4]); RotR63(v[5]); RotR63(v[6]); RotR63(v[7]); {---} add64(v[0],m[sigma[round][2*4]]); add64(v[1],m[sigma[round][2*5]]); add64(v[2],m[sigma[round][2*6]]); add64(v[3],m[sigma[round][2*7]]); add64(v[0],v[5]); add64(v[1],v[6]); add64(v[2],v[7]); add64(v[3],v[4]); tem := v[15].L xor v[0].L; v[15].L := v[15].H xor v[0].H; v[15].H := tem; tem := v[12].L xor v[1].L; v[12].L := v[12].H xor v[1].H; v[12].H := tem; tem := v[13].L xor v[2].L; v[13].L := v[13].H xor v[2].H; v[13].H := tem; tem := v[14].L xor v[3].L; v[14].L := v[14].H xor v[3].H; v[14].H := tem; add64(v[10],v[15]); add64(v[11],v[12]); add64(v[ 8],v[13]); add64(v[ 9],v[14]); v[5].L := v[5].L xor v[10].L; v[6].L := v[6].L xor v[11].L; v[7].L := v[7].L xor v[ 8].L; v[4].L := v[4].L xor v[ 9].L; v[5].H := v[5].H xor v[10].H; v[6].H := v[6].H xor v[11].H; v[7].H := v[7].H xor v[ 8].H; v[4].H := v[4].H xor v[ 9].H; RotR24(v[5]); RotR24(v[6]); RotR24(v[7]); RotR24(v[4]); add64(v[0],m[sigma[round][2*4+1]]); add64(v[1],m[sigma[round][2*5+1]]); add64(v[2],m[sigma[round][2*6+1]]); add64(v[3],m[sigma[round][2*7+1]]); add64(v[0],v[5]); add64(v[1],v[6]); add64(v[2],v[7]); add64(v[3],v[4]); v[15].L := v[15].L xor v[ 0].L; v[12].L := v[12].L xor v[ 1].L; v[13].L := v[13].L xor v[ 2].L; v[14].L := v[14].L xor v[ 3].L; v[15].H := v[15].H xor v[ 0].H; v[12].H := v[12].H xor v[ 1].H; v[13].H := v[13].H xor v[ 2].H; v[14].H := v[14].H xor v[ 3].H; {WE V0.23: Replace RotR(,16) with word moves} {RotR(v[15],16);} with TW16(v[15]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; {RotR(v[12],16);} with TW16(v[12]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; {RotR(v[13],16);} with TW16(v[13]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; {RotR(v[14],16);} with TW16(v[14]) do begin tw := w0; w0 := w1; w1 := w2; w2 := w3; w3 := tw; end; add64(v[10],v[15]); add64(v[11],v[12]); add64(v[ 8],v[13]); add64(v[ 9],v[14]); v[5].L := v[5].L xor v[10].L; v[6].L := v[6].L xor v[11].L; v[7].L := v[7].L xor v[ 8].L; v[4].L := v[4].L xor v[ 9].L; v[5].H := v[5].H xor v[10].H; v[6].H := v[6].H xor v[11].H; v[7].H := v[7].H xor v[ 8].H; v[4].H := v[4].H xor v[ 9].H; RotR63(v[5]); RotR63(v[6]); RotR63(v[7]); RotR63(v[4]); end; {finalization} for k:=0 to 7 do begin h[2*k] := h[2*k] xor v[k].l xor v[k+8].l; h[2*k+1] := h[2*k+1] xor v[k].h xor v[k+8].h; end; end; end; {---------------------------------------------------------------------------} procedure blake2b_update(var ctx: THashContext; msg: pointer; mlen: longint); {-Add "mlen" bytes from "msg" into the hash} var left,fill: integer; begin with blake2b_ctx(ctx) do begin if mlen > 0 then begin left := c; fill := BLAKE2B_BlockLen - left; if mlen > fill then begin c := 0; if fill>0 then move(msg^, b[left], fill); inct01(ctx, BLAKE2B_BlockLen); blake2b_compress(blake2b_ctx(ctx), false); inc(Ptr2Inc(Msg),fill); dec(mlen,fill); while mlen > BLAKE2B_BlockLen do begin move(msg^,b,BLAKE2B_BlockLen); inct01(ctx, BLAKE2B_BlockLen); blake2b_compress(blake2b_ctx(ctx), false); {compress (not last)} inc(Ptr2Inc(Msg),BLAKE2B_BlockLen); dec(mlen,BLAKE2B_BlockLen); end; end; if mlen > 0 then begin move(msg^, b[c], mlen); c := c + mlen; end; end; end; end; {---------------------------------------------------------------------------} procedure blake2b_Final(var ctx: THashContext; var Digest: TBlake2BDigest); {-Finalize calculation, generate message digest, clear context} begin with blake2b_ctx(ctx) do begin inct01(ctx, c); while c < BLAKE2B_BlockLen do begin {fill up with zeros} b[c] := 0; inc(c); end; blake2b_compress(blake2b_ctx(ctx), true); {final block} {little endian convert and store} fillchar(Digest, sizeof(Digest),0); move(h, Digest, outlen); end; end; {$endif} {---------------------------------------------------------------------------} function blake2b_Init(var ctx: THashContext; key: pointer; keylen, diglen: word): integer; {-Initialize context for a digest of diglen bytes; keylen=0: no key} var tb: TBlake2BBlock; begin if (diglen=0) or (diglen > BLAKE2B_MaxDigLen) or (keylen > BLAKE2B_MaxKeyLen) then begin blake2b_Init := -1; {illegal parameters} exit; end; blake2b_Init := 0; fillchar(ctx, sizeof(ctx), 0); with blake2b_ctx(ctx) do begin move(blake2b_ivl, h, sizeof(h)); outlen := diglen; {Fill the lowest 32 bit of h, same for 16/32/64 bit} h[0] := h[0] xor (($01010000) xor (keylen shl 8) xor outlen); if keylen > 0 then begin fillchar(tb, sizeof(tb),0); move(key^, tb, keylen); blake2b_update(ctx, @tb, BLAKE2B_BlockLen); end; end; end; {---------------------------------------------------------------------------} function blake2b_full(var dig: TBlake2BDigest; diglen: word; key: pointer; keylen: word; msg: pointer; mlen: longint): integer; {-Calculate hash digest of Msg with init/update/final} var ctx: THashContext; begin if blake2b_init(ctx, key, keylen, diglen) <> 0 then begin blake2b_full := -1; end else begin blake2b_update(ctx, msg, mlen); blake2b_final(ctx, dig); blake2b_full := 0; end; end; {---------------------------------------------------------------------------} function blake2b_selftest: boolean; {-Return true, if self test is OK} procedure selftest_seq(outp: pbyte; len, seed: integer); var t,a,b: longint; i: integer; begin a := longint($DEAD4BAD) * seed; b := 1; for i:=1 to len do begin t := a+b; a := b; b := t; outp^ := (t shr 24) and $FF; inc(Ptr2Inc(outp)); end; end; const {Grand hash of hash results} blake2b_res: array[0..31] of byte = ( $C2, $3A, $78, $00, $D9, $81, $23, $BD, $10, $F5, $06, $C6, $1E, $29, $DA, $56, $03, $D7, $63, $B8, $BB, $AD, $2E, $73, $7F, $5E, $76, $5A, $7B, $CC, $D4, $75 ); {Parameter sets} b2s_md_len: array[0..3] of integer = (20, 32, 48, 64); b2s_in_len: array[0..5] of integer = (0, 3, 128, 129, 255, 1024); var i,j, outlen, inlen: integer; md, key: TBlake2BDigest; ctx: THashContext; inb: array[0..1023] of byte; begin blake2b_selftest := false; {256-bit hash for testing} if blake2b_init(ctx, nil, 0, 32) <> 0 then exit; for i:=0 to 3 do begin outlen := b2s_md_len[i]; for j:=0 to 5 do begin inlen := b2s_in_len[j]; selftest_seq(pbyte(@inb), inlen, inlen); {unkeyed hash} if blake2b_full(md, outlen, nil, 0, @inb, inlen) <> 0 then exit; blake2b_update(ctx, @md, outlen); {hash the hash} selftest_seq(pbyte(@key), outlen, outlen); {keyed hash} if blake2b_full(md, outlen, @key, outlen, @inb, inlen) <> 0 then exit; blake2b_update(ctx, @md, outlen); {hash the hash} end; end; {Compute and compare the hash of hashes.} blake2b_final(ctx, md); for i:=0 to 31 do begin if md[i] <> blake2b_res[i] then exit; end; blake2b_selftest := true; end; begin {$ifdef HAS_ASSERT} assert(sizeof(blake2b_ctx)=HASHCTXSIZE , '** Invalid sizeof(blake2b_ctx)'); {$endif} end.
unit error; interface procedure FatalError (s: string); procedure LiteError (s: string); procedure Warning (s: string); implementation procedure FatalError (s: string); begin writeln('Fatal error ', s); writeln('program stopped !'); halt; { that's heavy!! } end; procedure LiteError (s: string); begin writeln('a lite error occured in: ', s); writeln('type return to resume.'); readln; end; procedure Warning (s: string); begin writeln('Warning: ', s); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1996,98 Inprise Corporation } { } {*******************************************************} unit DBCGrids; {$R-} interface uses SysUtils, Windows, Messages, Classes, Controls, Forms, Graphics, Menus, DB; type { TDBCtrlGrid } TDBCtrlGrid = class; TDBCtrlGridLink = class(TDataLink) private FDBCtrlGrid: TDBCtrlGrid; protected procedure ActiveChanged; override; procedure DataSetChanged; override; public constructor Create(DBCtrlGrid: TDBCtrlGrid); end; TDBCtrlPanel = class(TWinControl) private FDBCtrlGrid: TDBCtrlGrid; procedure CMControlListChange(var Message: TCMControlListChange); message CM_CONTROLLISTCHANGE; procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST; protected procedure CreateParams(var Params: TCreateParams); override; procedure PaintWindow(DC: HDC); override; public constructor CreateLinked(DBCtrlGrid: TDBCtrlGrid); end; TDBCtrlGridOrientation = (goVertical, goHorizontal); TDBCtrlGridBorder = (gbNone, gbRaised); TDBCtrlGridKey = (gkNull, gkEditMode, gkPriorTab, gkNextTab, gkLeft, gkRight, gkUp, gkDown, gkScrollUp, gkScrollDown, gkPageUp, gkPageDown, gkHome, gkEnd, gkInsert, gkAppend, gkDelete, gkCancel); TPaintPanelEvent = procedure(DBCtrlGrid: TDBCtrlGrid; Index: Integer) of object; TDBCtrlGrid = class(TWinControl) private FDataLink: TDBCtrlGridLink; FPanel: TDBCtrlPanel; FCanvas: TCanvas; FColCount: Integer; FRowCount: Integer; FPanelWidth: Integer; FPanelHeight: Integer; FPanelIndex: Integer; FPanelCount: Integer; FBitmapCount: Integer; FPanelBitmap: HBitmap; FSaveBitmap: HBitmap; FPanelDC: HDC; FOrientation: TDBCtrlGridOrientation; FPanelBorder: TDBCtrlGridBorder; FAllowInsert: Boolean; FAllowDelete: Boolean; FShowFocus: Boolean; FFocused: Boolean; FClicking: Boolean; FSelColorChanged: Boolean; FScrollBarKind: Integer; FSelectedColor: TColor; FOnPaintPanel: TPaintPanelEvent; function AcquireFocus: Boolean; procedure AdjustSize; reintroduce; procedure CreatePanelBitmap; procedure DataSetChanged(Reset: Boolean); procedure DestroyPanelBitmap; procedure DrawPanel(DC: HDC; Index: Integer); procedure DrawPanelBackground(DC: HDC; const R: TRect; Erase, Selected: Boolean); function FindNext(StartControl: TWinControl; GoForward: Boolean; var WrapFlag: Integer): TWinControl; function GetDataSource: TDataSource; function GetEditMode: Boolean; function GetPanelBounds(Index: Integer): TRect; function PointInPanel(const P: TSmallPoint): Boolean; procedure Reset; procedure Scroll(Inc: Integer; ScrollLock: Boolean); procedure ScrollMessage(var Message: TWMScroll); procedure SelectNext(GoForward: Boolean); procedure SetColCount(Value: Integer); procedure SetDataSource(Value: TDataSource); procedure SetEditMode(Value: Boolean); procedure SetOrientation(Value: TDBCtrlGridOrientation); procedure SetPanelBorder(Value: TDBCtrlGridBorder); procedure SetPanelHeight(Value: Integer); procedure SetPanelIndex(Value: Integer); procedure SetPanelWidth(Value: Integer); procedure SetRowCount(Value: Integer); procedure SetSelectedColor(Value: TColor); procedure UpdateDataLinks(Control: TControl; Inserting: Boolean); procedure UpdateScrollBar; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure WMSize(var Message: TMessage); message WM_SIZE; procedure CMChildKey(var Message: TCMChildKey); message CM_CHILDKEY; procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; function GetChildParent: TComponent; override; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure PaintPanel(Index: Integer); virtual; procedure PaintWindow(DC: HDC); override; procedure ReadState(Reader: TReader); override; property Panel: TDBCtrlPanel read FPanel; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoKey(Key: TDBCtrlGridKey); function ExecuteAction(Action: TBasicAction): Boolean; override; procedure GetTabOrderList(List: TList); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; function UpdateAction(Action: TBasicAction): Boolean; override; property Canvas: TCanvas read FCanvas; property EditMode: Boolean read GetEditMode write SetEditMode; property PanelCount: Integer read FPanelCount; property PanelIndex: Integer read FPanelIndex write SetPanelIndex; published property Align; property AllowDelete: Boolean read FAllowDelete write FAllowDelete default True; property AllowInsert: Boolean read FAllowInsert write FAllowInsert default True; property Anchors; property ColCount: Integer read FColCount write SetColCount; property Color; property Constraints; property DataSource: TDataSource read GetDataSource write SetDataSource; property DragCursor; property DragMode; property Enabled; property Font; property Orientation: TDBCtrlGridOrientation read FOrientation write SetOrientation default goVertical; property PanelBorder: TDBCtrlGridBorder read FPanelBorder write SetPanelBorder default gbRaised; property PanelHeight: Integer read FPanelHeight write SetPanelHeight; property PanelWidth: Integer read FPanelWidth write SetPanelWidth; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property TabOrder; property TabStop default True; property RowCount: Integer read FRowCount write SetRowCount; property SelectedColor: TColor read FSelectedColor write SetSelectedColor stored FSelColorChanged default clWindow; property ShowFocus: Boolean read FShowFocus write FShowFocus default True; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnPaintPanel: TPaintPanelEvent read FOnPaintPanel write FOnPaintPanel; property OnStartDrag; end; implementation uses DBConsts; { TDBCtrlGridLink } constructor TDBCtrlGridLink.Create(DBCtrlGrid: TDBCtrlGrid); begin inherited Create; FDBCtrlGrid := DBCtrlGrid; VisualControl := True; RPR; end; procedure TDBCtrlGridLink.ActiveChanged; begin FDBCtrlGrid.DataSetChanged(False); end; procedure TDBCtrlGridLink.DataSetChanged; begin FDBCtrlGrid.DataSetChanged(False); end; { TDBCtrlPanel } constructor TDBCtrlPanel.CreateLinked(DBCtrlGrid: TDBCtrlGrid); begin inherited Create(DBCtrlGrid); ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csDoubleClicks, csOpaque, csReplicatable]; FDBCtrlGrid := DBCtrlGrid; Parent := DBCtrlGrid; end; procedure TDBCtrlPanel.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params.WindowClass do style := style and not (CS_HREDRAW or CS_VREDRAW); end; procedure TDBCtrlPanel.PaintWindow(DC: HDC); var R: TRect; Selected: Boolean; begin with FDBCtrlGrid do begin if FDataLink.Active then begin Selected := (FDataLink.ActiveRecord = FPanelIndex); DrawPanelBackground(DC, Self.ClientRect, True, Selected); FCanvas.Handle := DC; try FCanvas.Font := Font; FCanvas.Brush.Style := bsSolid; FCanvas.Brush.Color := Color; PaintPanel(FDataLink.ActiveRecord); if FShowFocus and FFocused and Selected then begin R := Self.ClientRect; if FPanelBorder = gbRaised then InflateRect(R, -2, -2); FCanvas.Brush.Color := Color; FCanvas.DrawFocusRect(R); end; finally FCanvas.Handle := 0; end; end else DrawPanelBackground(DC, Self.ClientRect, True, csDesigning in ComponentState); end; end; procedure TDBCtrlPanel.CMControlListChange(var Message: TCMControlListChange); begin FDBCtrlGrid.UpdateDataLinks(Message.Control, Message.Inserting); end; procedure TDBCtrlPanel.WMPaint(var Message: TWMPaint); var DC: HDC; PS: TPaintStruct; begin if Message.DC = 0 then begin FDBCtrlGrid.CreatePanelBitmap; try Message.DC := FDBCtrlGrid.FPanelDC; PaintHandler(Message); Message.DC := 0; DC := BeginPaint(Handle, PS); BitBlt(DC, 0, 0, Width, Height, FDBCtrlGrid.FPanelDC, 0, 0, SRCCOPY); EndPaint(Handle, PS); finally FDBCtrlGrid.DestroyPanelBitmap; end; end else PaintHandler(Message); end; procedure TDBCtrlPanel.WMNCHitTest(var Message: TWMNCHitTest); begin if csDesigning in ComponentState then Message.Result := HTCLIENT else Message.Result := HTTRANSPARENT; end; procedure TDBCtrlPanel.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; { TDBCtrlGrid } constructor TDBCtrlGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csOpaque, csDoubleClicks]; TabStop := True; FDataLink := TDBCtrlGridLink.Create(Self); FCanvas := TCanvas.Create; FPanel := TDBCtrlPanel.CreateLinked(Self); FColCount := 1; FRowCount := 3; FPanelWidth := 200; FPanelHeight := 72; FPanelBorder := gbRaised; FAllowInsert := True; FAllowDelete := True; FShowFocus := True; FSelectedColor := Color; AdjustSize; end; destructor TDBCtrlGrid.Destroy; begin FCanvas.Free; FDataLink.Free; FDataLink := nil; inherited Destroy; end; function TDBCtrlGrid.AcquireFocus: Boolean; begin Result := True; if not (Focused or EditMode) then begin SetFocus; Result := Focused; end; end; procedure TDBCtrlGrid.AdjustSize; var W, H: Integer; begin W := FPanelWidth * FColCount; H := FPanelHeight * FRowCount; if FOrientation = goVertical then Inc(W, GetSystemMetrics(SM_CXVSCROLL)) else Inc(H, GetSystemMetrics(SM_CYHSCROLL)); SetBounds(Left, Top, W, H); Reset; end; procedure TDBCtrlGrid.CreatePanelBitmap; var DC: HDC; begin if FBitmapCount = 0 then begin DC := GetDC(0); FPanelBitmap := CreateCompatibleBitmap(DC, FPanel.Width, FPanel.Height); ReleaseDC(0, DC); FPanelDC := CreateCompatibleDC(0); FSaveBitmap := SelectObject(FPanelDC, FPanelBitmap); end; Inc(FBitmapCount); end; procedure TDBCtrlGrid.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_CLIPCHILDREN; WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW); end; end; procedure TDBCtrlGrid.CreateWnd; begin inherited CreateWnd; if FOrientation = goVertical then FScrollBarKind := SB_VERT else FScrollBarKind := SB_HORZ; if not FDataLink.Active then SetScrollRange(Handle, FScrollBarKind, 0, 4, False); UpdateScrollBar; end; procedure TDBCtrlGrid.DataSetChanged(Reset: Boolean); var NewPanelIndex, NewPanelCount: Integer; FocusedControl: TWinControl; R: TRect; begin if csDesigning in ComponentState then begin NewPanelIndex := 0; NewPanelCount := 1; end else if FDataLink.Active then begin NewPanelIndex := FDataLink.ActiveRecord; NewPanelCount := FDataLink.RecordCount; if NewPanelCount = 0 then NewPanelCount := 1; end else begin NewPanelIndex := 0; NewPanelCount := 0; end; FocusedControl := nil; R := GetPanelBounds(NewPanelIndex); if Reset or not HandleAllocated then FPanel.BoundsRect := R else begin FocusedControl := FindControl(GetFocus); if (FocusedControl <> FPanel) and FPanel.ContainsControl(FocusedControl) then FPanel.SetFocus else FocusedControl := nil; if NewPanelIndex <> FPanelIndex then begin SetWindowPos(FPanel.Handle, 0, R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top, SWP_NOZORDER or SWP_NOREDRAW); RedrawWindow(FPanel.Handle, nil, 0, RDW_INVALIDATE or RDW_ALLCHILDREN); end; end; FPanelIndex := NewPanelIndex; FPanelCount := NewPanelCount; FPanel.Visible := FPanelCount > 0; FPanel.Invalidate; if not Reset then begin Invalidate; Update; end; UpdateScrollBar; if (FocusedControl <> nil) and not FClicking and FocusedControl.CanFocus then FocusedControl.SetFocus; end; procedure TDBCtrlGrid.DestroyPanelBitmap; begin Dec(FBitmapCount); if FBitmapCount = 0 then begin SelectObject(FPanelDC, FSaveBitmap); DeleteDC(FPanelDC); DeleteObject(FPanelBitmap); end; end; procedure TDBCtrlGrid.DoKey(Key: TDBCtrlGridKey); var HInc, VInc: Integer; begin if FDataLink.Active then begin if FOrientation = goVertical then begin HInc := 1; VInc := FColCount; end else begin HInc := FRowCount; VInc := 1; end; with FDataLink.DataSet do case Key of gkEditMode: EditMode := not EditMode; gkPriorTab: SelectNext(False); gkNextTab: SelectNext(True); gkLeft: Scroll(-HInc, False); gkRight: Scroll(HInc, False); gkUp: Scroll(-VInc, False); gkDown: Scroll(VInc, False); gkScrollUp: Scroll(-VInc, True); gkScrollDown: Scroll(VInc, True); gkPageUp: Scroll(-FDataLink.BufferCount, True); gkPageDown: Scroll(FDataLink.BufferCount, True); gkHome: First; gkEnd: Last; gkInsert: if FAllowInsert and CanModify then begin Insert; EditMode := True; end; gkAppend: if FAllowInsert and CanModify then begin Append; EditMode := True; end; gkDelete: if FAllowDelete and CanModify then begin Delete; EditMode := False; end; gkCancel: begin Cancel; EditMode := False; end; end; end; end; procedure TDBCtrlGrid.DrawPanel(DC: HDC; Index: Integer); var SaveActive: Integer; R: TRect; begin R := GetPanelBounds(Index); if Index < FPanelCount then begin SaveActive := FDataLink.ActiveRecord; FDataLink.ActiveRecord := Index; FPanel.PaintTo(FPanelDC, 0, 0); FDataLink.ActiveRecord := SaveActive; end else DrawPanelBackground(FPanelDC, FPanel.ClientRect, True, False); BitBlt(DC, R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top, FPanelDC, 0, 0, SRCCOPY); end; procedure TDBCtrlGrid.DrawPanelBackground(DC: HDC; const R: TRect; Erase, Selected: Boolean); var Brush: HBrush; begin if Erase then begin if Selected then FPanel.Color := FSelectedColor else FPanel.Color := Color; Brush := CreateSolidBrush(ColorToRGB(FPanel.Color)); FillRect(DC, R, Brush); DeleteObject(Brush); end; if FPanelBorder = gbRaised then DrawEdge(DC, PRect(@R)^, BDR_RAISEDINNER, BF_RECT); end; function TDBCtrlGrid.GetChildParent: TComponent; begin Result := FPanel; end; procedure TDBCtrlGrid.GetChildren(Proc: TGetChildProc; Root: TComponent); begin FPanel.GetChildren(Proc, Root); end; function TDBCtrlGrid.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TDBCtrlGrid.GetEditMode: Boolean; begin Result := not Focused and ContainsControl(FindControl(GetFocus)); end; function TDBCtrlGrid.GetPanelBounds(Index: Integer): TRect; var Col, Row: Integer; begin if FOrientation = goVertical then begin Col := Index mod FColCount; Row := Index div FColCount; end else begin Col := Index div FRowCount; Row := Index mod FRowCount; end; Result.Left := FPanelWidth * Col; Result.Top := FPanelHeight * Row; Result.Right := Result.Left + FPanelWidth; Result.Bottom := Result.Top + FPanelHeight; end; procedure TDBCtrlGrid.GetTabOrderList(List: TList); begin end; procedure TDBCtrlGrid.KeyDown(var Key: Word; Shift: TShiftState); var GridKey: TDBCtrlGridKey; begin inherited KeyDown(Key, Shift); GridKey := gkNull; case Key of VK_LEFT: GridKey := gkLeft; VK_RIGHT: GridKey := gkRight; VK_UP: GridKey := gkUp; VK_DOWN: GridKey := gkDown; VK_PRIOR: GridKey := gkPageUp; VK_NEXT: GridKey := gkPageDown; VK_HOME: GridKey := gkHome; VK_END: GridKey := gkEnd; VK_RETURN, VK_F2: GridKey := gkEditMode; VK_INSERT: if GetKeyState(VK_CONTROL) >= 0 then GridKey := gkInsert else GridKey := gkAppend; VK_DELETE: if GetKeyState(VK_CONTROL) < 0 then GridKey := gkDelete; VK_ESCAPE: GridKey := gkCancel; end; DoKey(GridKey); end; procedure TDBCtrlGrid.PaintWindow(DC: HDC); var I: Integer; Brush: HBrush; begin if csDesigning in ComponentState then begin FPanel.Update; Brush := CreateHatchBrush(HS_BDIAGONAL, ColorToRGB(clBtnShadow)); SetBkColor(DC, ColorToRGB(Color)); FillRect(DC, ClientRect, Brush); DeleteObject(Brush); for I := 1 to FColCount * FRowCount - 1 do DrawPanelBackground(DC, GetPanelBounds(I), False, False); end else begin CreatePanelBitmap; try for I := 0 to FColCount * FRowCount - 1 do if (FPanelCount <> 0) and (I = FPanelIndex) then FPanel.Update else DrawPanel(DC, I); finally DestroyPanelBitmap; end; end; { When width or height are not evenly divisible by panel size, fill the gaps } if HandleAllocated then begin if (Height <> FPanel.Height * FRowCount) then begin Brush := CreateSolidBrush(ColorToRGB(Color)); FillRect(DC, Rect(0, FPanel.Height * FRowCount, Width, Height), Brush); DeleteObject(Brush); end; if (Width <> FPanel.Width * FColCount) then begin Brush := CreateSolidBrush(ColorToRGB(Color)); FillRect(DC, Rect(FPanelWidth * FColCount, 0, Width, Height), Brush); DeleteObject(Brush); end; end; end; procedure TDBCtrlGrid.PaintPanel(Index: Integer); begin if Assigned(FOnPaintPanel) then FOnPaintPanel(Self, Index); end; function TDBCtrlGrid.PointInPanel(const P: TSmallPoint): Boolean; begin Result := (FPanelCount > 0) and PtInRect(GetPanelBounds(FPanelIndex), SmallPointToPoint(P)); end; procedure TDBCtrlGrid.ReadState(Reader: TReader); begin inherited ReadState(Reader); FPanel.FixupTabList; end; procedure TDBCtrlGrid.Reset; begin if csDesigning in ComponentState then FDataLink.BufferCount := 1 else FDataLink.BufferCount := FColCount * FRowCount; DataSetChanged(True); end; procedure TDBCtrlGrid.Scroll(Inc: Integer; ScrollLock: Boolean); var NewIndex, ScrollInc, Adjust: Integer; begin if FDataLink.Active and (Inc <> 0) then with FDataLink.DataSet do if State = dsInsert then begin UpdateRecord; if Modified then Post else if (Inc < 0) or not EOF then Cancel; end else begin CheckBrowseMode; DisableControls; try if ScrollLock then if Inc > 0 then MoveBy(Inc - MoveBy(Inc + FDataLink.BufferCount - FPanelIndex - 1)) else MoveBy(Inc - MoveBy(Inc - FPanelIndex)) else begin NewIndex := FPanelIndex + Inc; if (NewIndex >= 0) and (NewIndex < FDataLink.BufferCount) then MoveBy(Inc) else if MoveBy(Inc) = Inc then begin if FOrientation = goVertical then ScrollInc := FColCount else ScrollInc := FRowCount; if Inc > 0 then Adjust := ScrollInc - 1 - NewIndex mod ScrollInc else Adjust := 1 - ScrollInc - (NewIndex + 1) mod ScrollInc; MoveBy(-MoveBy(Adjust)); end; end; if (Inc = 1) and EOF and FAllowInsert and CanModify then Append; finally EnableControls; end; end; end; procedure TDBCtrlGrid.ScrollMessage(var Message: TWMScroll); var Key: TDBCtrlGridKey; SI: TScrollInfo; begin if AcquireFocus then begin Key := gkNull; case Message.ScrollCode of SB_LINEUP: Key := gkScrollUp; SB_LINEDOWN: Key := gkScrollDown; SB_PAGEUP: Key := gkPageUp; SB_PAGEDOWN: Key := gkPageDown; SB_TOP: Key := gkHome; SB_BOTTOM: Key := gkEnd; SB_THUMBPOSITION: if FDataLink.Active and FDataLink.DataSet.IsSequenced then begin SI.cbSize := sizeof(SI); SI.fMask := SIF_ALL; GetScrollInfo(Self.Handle, FScrollBarKind, SI); if SI.nTrackPos <= 1 then Key := gkHome else if SI.nTrackPos >= FDataLink.DataSet.RecordCount then Key := gkEnd else begin FDataLink.DataSet.RecNo := SI.nTrackPos; Exit; end; end else begin case Message.Pos of 0: Key := gkHome; 1: Key := gkPageUp; 3: Key := gkPageDown; 4: Key := gkEnd; end; end; end; DoKey(Key); end; end; function TDBCtrlGrid.FindNext(StartControl: TWinControl; GoForward: Boolean; var WrapFlag: Integer): TWinControl; var I, StartIndex: Integer; List: TList; begin List := TList.Create; try StartIndex := 0; I := 0; Result := StartControl; FPanel.GetTabOrderList(List); if List.Count > 0 then begin StartIndex := List.IndexOf(StartControl); if StartIndex = -1 then if GoForward then StartIndex := List.Count - 1 else StartIndex := 0; I := StartIndex; repeat if GoForward then begin Inc(I); if I = List.Count then I := 0; end else begin if I = 0 then I := List.Count; Dec(I); end; Result := List[I]; until (Result.CanFocus and Result.TabStop) or (I = StartIndex); end; WrapFlag := 0; if GoForward then begin if I <= StartIndex then WrapFlag := 1; end else begin if I >= StartIndex then WrapFlag := -1; end; finally List.Free; end; end; procedure TDBCtrlGrid.SelectNext(GoForward: Boolean); var WrapFlag: Integer; ParentForm: TCustomForm; ActiveControl, Control: TWinControl; begin ParentForm := GetParentForm(Self); if ParentForm <> nil then begin ActiveControl := ParentForm.ActiveControl; if ContainsControl(ActiveControl) then begin Control := FindNext(ActiveControl, GoForward, WrapFlag); if not (FDataLink.DataSet.State in dsEditModes) then FPanel.SetFocus; try if WrapFlag <> 0 then Scroll(WrapFlag, False); except ActiveControl.SetFocus; raise; end; if not Control.CanFocus then Control := FindNext(Control, GoForward, WrapFlag); Control.SetFocus; end; end; end; procedure TDBCtrlGrid.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var ScrollWidth, ScrollHeight, NewPanelWidth, NewPanelHeight: Integer; begin ScrollWidth := 0; ScrollHeight := 0; if FOrientation = goVertical then ScrollWidth := GetSystemMetrics(SM_CXVSCROLL) else ScrollHeight := GetSystemMetrics(SM_CYHSCROLL); NewPanelWidth := (AWidth - ScrollWidth) div FColCount; NewPanelHeight := (AHeight - ScrollHeight) div FRowCount; if NewPanelWidth < 1 then NewPanelWidth := 1; if NewPanelHeight < 1 then NewPanelHeight := 1; if (FPanelWidth <> NewPanelWidth) or (FPanelHeight <> NewPanelHeight) then begin FPanelWidth := NewPanelWidth; FPanelHeight := NewPanelHeight; Reset; end; inherited SetBounds(ALeft, ATop, AWidth, AHeight); end; procedure TDBCtrlGrid.SetColCount(Value: Integer); begin if Value < 1 then Value := 1; if Value > 100 then Value := 100; if FColCount <> Value then begin FColCount := Value; AdjustSize; end; end; procedure TDBCtrlGrid.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; UpdateDataLinks(FPanel, True); end; procedure TDBCtrlGrid.SetEditMode(Value: Boolean); var Control: TWinControl; begin if GetEditMode <> Value then if Value then begin Control := FPanel.FindNextControl(nil, True, True, False); if Control <> nil then Control.SetFocus; end else SetFocus; end; procedure TDBCtrlGrid.SetOrientation(Value: TDBCtrlGridOrientation); begin if FOrientation <> Value then begin FOrientation := Value; RecreateWnd; AdjustSize; end; end; procedure TDBCtrlGrid.SetPanelBorder(Value: TDBCtrlGridBorder); begin if FPanelBorder <> Value then begin FPanelBorder := Value; Invalidate; FPanel.Invalidate; end; end; procedure TDBCtrlGrid.SetPanelHeight(Value: Integer); begin if Value < 1 then Value := 1; if Value > 65535 then Value := 65535; if FPanelHeight <> Value then begin FPanelHeight := Value; AdjustSize; end; end; procedure TDBCtrlGrid.SetPanelIndex(Value: Integer); begin if FDataLink.Active and (Value < PanelCount) then FDataLink.DataSet.MoveBy(Value - FPanelIndex); end; procedure TDBCtrlGrid.SetPanelWidth(Value: Integer); begin if Value < 1 then Value := 1; if Value > 65535 then Value := 65535; if FPanelWidth <> Value then begin FPanelWidth := Value; AdjustSize; end; end; procedure TDBCtrlGrid.SetRowCount(Value: Integer); begin if Value < 1 then Value := 1; if Value > 100 then Value := 100; if FRowCount <> Value then begin FRowCount := Value; AdjustSize; end; end; procedure TDBCtrlGrid.SetSelectedColor(Value: TColor); begin if Value <> FSelectedColor then begin FSelectedColor := Value; FSelColorChanged := Value <> Color; Invalidate; FPanel.Invalidate; end; end; procedure TDBCtrlGrid.UpdateDataLinks(Control: TControl; Inserting: Boolean); var I: Integer; DataLink: TDataLink; begin if Inserting and not (csReplicatable in Control.ControlStyle) then DatabaseError(SNotReplicatable); DataLink := TDataLink(Control.Perform(CM_GETDATALINK, 0, 0)); if DataLink <> nil then begin DataLink.DataSourceFixed := False; if Inserting then begin DataLink.DataSource := DataSource; DataLink.DataSourceFixed := True; end; end; if Control is TWinControl then with TWinControl(Control) do for I := 0 to ControlCount - 1 do UpdateDataLinks(Controls[I], Inserting); end; procedure TDBCtrlGrid.UpdateScrollBar; var SIOld, SINew: TScrollInfo; begin if FDatalink.Active and HandleAllocated then with FDatalink.DataSet do begin SIOld.cbSize := sizeof(SIOld); SIOld.fMask := SIF_ALL; GetScrollInfo(Self.Handle, FScrollBarKind, SIOld); SINew := SIOld; if IsSequenced then begin SINew.nMin := 1; SINew.nPage := Self.RowCount * Self.ColCount; SINew.nMax := DWORD(RecordCount) + SINew.nPage - 1; if State in [dsInactive, dsBrowse, dsEdit] then SINew.nPos := RecNo; end else begin SINew.nMin := 0; SINew.nPage := 0; SINew.nMax := 4; if BOF then SINew.nPos := 0 else if EOF then SINew.nPos := 4 else SINew.nPos := 2; end; if (SINew.nMin <> SIOld.nMin) or (SINew.nMax <> SIOld.nMax) or (SINew.nPage <> SIOld.nPage) or (SINew.nPos <> SIOld.nPos) then SetScrollInfo(Self.Handle, FScrollBarKind, SINew, True); end; end; procedure TDBCtrlGrid.WMLButtonDown(var Message: TWMLButtonDown); var I: Integer; P: TPoint; Window: HWnd; begin if FDataLink.Active then begin P := SmallPointToPoint(Message.Pos); for I := 0 to FPanelCount - 1 do if (I <> FPanelIndex) and PtInRect(GetPanelBounds(I), P) then begin FClicking := True; try SetPanelIndex(I); finally FClicking := False; end; P := ClientToScreen(P); Window := WindowFromPoint(P); if IsChild(FPanel.Handle, Window) then begin Windows.ScreenToClient(Window, P); Message.Pos := PointToSmallPoint(P); with TMessage(Message) do SendMessage(Window, Msg, WParam, LParam); Exit; end; Break; end; end; if AcquireFocus then begin if PointInPanel(Message.Pos) then begin EditMode := False; Click; end; inherited; end; end; procedure TDBCtrlGrid.WMLButtonDblClk(var Message: TWMLButtonDblClk); begin if PointInPanel(Message.Pos) then DblClick; inherited; end; procedure TDBCtrlGrid.WMHScroll(var Message: TWMHScroll); begin ScrollMessage(Message); end; procedure TDBCtrlGrid.WMVScroll(var Message: TWMVScroll); begin ScrollMessage(Message); end; procedure TDBCtrlGrid.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TDBCtrlGrid.WMPaint(var Message: TWMPaint); begin PaintHandler(Message); end; procedure TDBCtrlGrid.WMSetFocus(var Message: TWMSetFocus); begin FFocused := True; FPanel.Repaint; end; procedure TDBCtrlGrid.WMKillFocus(var Message: TWMKillFocus); begin FFocused := False; FPanel.Repaint; end; procedure TDBCtrlGrid.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTARROWS or DLGC_WANTCHARS; end; procedure TDBCtrlGrid.WMSize(var Message: TMessage); begin inherited; Invalidate; end; function GetShiftState: TShiftState; begin Result := []; if GetKeyState(VK_SHIFT) < 0 then Include(Result, ssShift); if GetKeyState(VK_CONTROL) < 0 then Include(Result, ssCtrl); if GetKeyState(VK_MENU) < 0 then Include(Result, ssAlt); end; procedure TDBCtrlGrid.CMChildKey(var Message: TCMChildKey); var ShiftState: TShiftState; GridKey: TDBCtrlGridKey; begin with Message do if Sender <> Self then begin ShiftState := GetShiftState; if Assigned(OnKeyDown) then OnKeyDown(Sender, CharCode, ShiftState); GridKey := gkNull; case CharCode of VK_TAB: if not (ssCtrl in ShiftState) and (Sender.Perform(WM_GETDLGCODE, 0, 0) and DLGC_WANTTAB = 0) then if ssShift in ShiftState then GridKey := gkPriorTab else GridKey := gkNextTab; VK_RETURN: if (Sender.Perform(WM_GETDLGCODE, 0, 0) and DLGC_WANTALLKEYS = 0) then GridKey := gkEditMode; VK_F2: GridKey := gkEditMode; VK_ESCAPE: GridKey := gkCancel; end; if GridKey <> gkNull then begin DoKey(GridKey); Result := 1; Exit; end; end; inherited; end; procedure TDBCtrlGrid.CMColorChanged(var Message: TMessage); begin inherited; if not FSelColorChanged then FSelectedColor := Color; end; { Defer action processing to datalink } function TDBCtrlGrid.ExecuteAction(Action: TBasicAction): Boolean; begin Result := inherited ExecuteAction(Action) or (FDataLink <> nil) and FDataLink.ExecuteAction(Action); end; function TDBCtrlGrid.UpdateAction(Action: TBasicAction): Boolean; begin Result := inherited UpdateAction(Action) or (FDataLink <> nil) and FDataLink.UpdateAction(Action); end; end.
unit InputOutputFile_2KH_1; // Файл входных и выходных параметров планетарной передачи 2KH с одинарным сателлитом. // Индексами 1, 2 и 3 обозначены соответственно: солнечная шестерня, сателлиты, корончатое колесо. // Рассматривается планетарная передача с ведущей солнечной шестерней, ведомым водилом // и неподвижным корончатым колесом (редуктор Джеймса). interface Type TInput_PlanetGear_2KH_1 = record P_1: extended; // Мощность ведущей солнечной шестерни [кВт]. Count_sat: byte; // Число сателлитов. i_h: byte; // Передаточное отношение. Omega_1: extended; // Частота вращения солнечной шестерни [об/мин]. ts: extended; // Ресурс [час]. Mark_Steel1, Mark_Steel2, Mark_Steel3: string; // Марка стали. Termobr1, Termobr2, Termobr3: string; // Термообработка. end; TOutput_PlanetGear_2KH_1 = record z1, z2, z3: integer; // Чмсла зубьев. P_2, P_3: extended; // Мощность [кВт]. Omega_2: extended; // Частота вращения сателлитов [об/мин]. Omega_Vod_2: extended; // Частота вращения вала водила [об/мин]. Tp_12, Tp_23: extended; // Расчетный крутящий момент [Н*м]. Th: extended; // Крутящий момент на валу водила [Н*м]. aw: extended; // Межосевое расстояние [мм]. m: extended; // Модуль [мм]. x_1, x_2, x_3: extended; // Коэффициенты смещения. b: extended; // Ширина венца [мм]. da_1, da_2, da_3: extended; // Диаметр вершин [мм]. d_1, d_2, d_3: extended; // Делительный диаметр [мм]. Ft: extended; // Окружное усилие в зацеплении [Н]. Fhv: extended; // Сила, действующая на вал водила [Н]. Fh_2: extended; // Сила, действующая на ось сателлита [Н]. Sigma_H_12, Sigma_H_23: extended; // Рабочее контактное напряжение [МПа]. Sigma_H: extended; // Допускаемое контактное напряжение [МПа]. Sigma_F_1, Sigma_F_2, Sigma_F_3: extended; // Рабочее изгибное напряжение [МПа]. Sigma_F: extended; // Допускаемое изгибное напряжение [МПа]. end; implementation end.
unit Matrices; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, Func, Math; type TMatriz = class private public x,y: integer; M: array of array of real; constructor Create(_x,_y: integer); destructor Destroy(); override; function GetX(): integer; function GetY(): integer; function Transpuesta(): TMatriz; function Determinante(): TRD; function Cofactores(a: TMatriz; r,c: integer): real; function Adjunta(): TMatriz; function Inversa(a: real): TMatriz; function Escalar(a: real): TMatriz; function MPower(a: integer): TMatriz; procedure Print(); end; Operator *(a,b: TMatriz): TMatriz; Operator +(a,b: TMatriz): TMatriz; Operator -(a,b: TMatriz): TMatriz; Operator /(a,b: TMatriz): TMatriz; implementation constructor TMatriz.Create(_x,_y: integer); var i,j: integer; begin Self.x:= _x; Self.y:= _y; SetLength(Self.M,Self.x,Self.y); for i:=0 to x-1 do for j:=0 to y-1 do Self.M[i,j]:= 0; end; destructor TMatriz.Destroy(); begin end; function TMatriz.GetX(): integer; begin Result:= Self.x; end; function TMatriz.GetY(): integer; begin Result:= Self.y; end; function TMatriz.Transpuesta(): TMatriz; var i,j: integer; begin Result:= TMatriz.Create(Self.y,Self.x); for i:=0 to Self.x-1 do for j:=0 to Self.y-1 do Result.M[j,i]:= Self.M[i,j]; end; function TMatriz.Cofactores(a:TMatriz; r,c: integer): real; var i,j,i1,j1: integer; MT: TMatriz; begin MT:= TMatriz.Create(a.x-1,a.x-1); i1:=0; j1:=0; for i:=0 to a.x-1 do begin for j:=0 to a.x-1 do begin if (i<>r) and (j<>c) then begin MT.M[i1,j1]:= a.M[i,j]; j1:= j1+1; if(j1>=(a.x-1)) then begin i1:=i1+1; j1:=0; end; end; end; end; Result:= (Power(-1,r+c))*(MT.Determinante().Value); MT.Destroy(); end; function TMatriz.Determinante(): TRD; var i: integer; begin Result.State:= True; if Self.x <> Self.y then Result.State:= False else if Self.x = 1 then Result.Value:= Self.M[0,0] else if Self.x = 2 then Result.Value:= (Self.M[0,0]*Self.M[1,1])-(Self.M[0,1]*Self.M[1,0]) else begin for i:=0 to Self.x-1 do Result.Value:= Result.Value+(Self.M[0,i]*Self.Cofactores(Self,0,i)); end; end; function TMatriz.Inversa(a: real): TMatriz; var i,j: integer; begin Result:= TMatriz.Create(Self.x,Self.y); for i:=0 to Result.x-1 do for j:=0 to Result.y-1 do Result.M[i,j]:= Self.Cofactores(Self,i,j)/a; Result:= Result.Transpuesta(); end; function TMatriz.Adjunta(): TMatriz; var i,j: integer; begin Result:= TMatriz.Create(Self.x,Self.y); for i:=0 to Result.x-1 do for j:=0 to Result.y-1 do Result.M[i,j]:= Self.Cofactores(Self,i,j); end; function TMatriz.Escalar(a: real): TMatriz; var i,j: integer; begin Result:= TMatriz.Create(Self.x,Self.y); for i:=0 to Result.x-1 do for j:=0 to Result.y-1 do Result.M[i,j]:= Self.M[i,j]*a; end; function TMatriz.MPower(a: integer): TMatriz; var i: integer; begin Result:= Self; for i:=0 to a-2 do Result:= Result*Self; end; procedure TMatriz.Print(); var i,j: integer; begin for i:=0 to x-1 do begin for j:=0 to y-1 do Write(FloatToStr(M[i,j])+' '); Write(LineEnding); end; end; Operator +(a,b: TMatriz): TMatriz; var i,j: integer; begin if ((a.x = b.x) and (a.y = b.y)) then begin Result:= TMatriz.Create(a.x,a.y); for i:=0 to a.x-1 do for j:=0 to a.y-1 do Result.M[i,j]:= a.M[i,j] + b.M[i,j] end else Result:= TMatriz.Create(0,0); end; Operator -(a,b: TMatriz): TMatriz; var i,j: integer; begin if ((a.x = b.x) and (a.y = b.y)) then begin Result:= TMatriz.Create(a.x,a.y); for i:=0 to a.x-1 do for j:=0 to a.y-1 do Result.M[i,j]:= a.M[i,j] - b.M[i,j] end else Result:= TMatriz.Create(0,0); end; Operator *(a,b: TMatriz): TMatriz; var i,j,k: integer; begin if (a.y = b.x) then begin Result:= TMatriz.Create(a.x,b.y); for i:=0 to Result.x-1 do for j:=0 to Result.y-1 do for k:=0 to a.y-1 do Result.M[i,j]:= Result.M[i,j]+(a.M[i,k]*b.M[k,j]); end else begin WriteLn('Order of Matrix are Different'); ShowMessage('Order of Matrix are Different'); Result:= TMatriz.Create(0,0); end; end; Operator /(a,b: TMatriz): TMatriz; var det: TRD; begin det:= b.Determinante(); if(det.State and (det.Value<>0)) then Result:= a*b.Inversa(det.Value); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: FMaterialEditorForm<p> Editor window for a material (with preview).<p> <b>Historique : </b><font size=-1><ul> <li>07/05/10 - Yar - Fixed PolygonMode and texture image class lookup <li>05/10/08 - DanB - Removed Kylix support <li>29/03/07 - DaStr - Renamed LINUX to KYLIX (BugTrackerID=1681585) <li>19/12/06 - DaStr - All comboboxes get their Items using RTTI (thanks to dikoe Kenguru for the reminder and Roman Ganz for the code) <li>03/07/04 - LR - Make change for Linux <li>24/03/00 - Egg - Added Blending <li>06/02/00 - Egg - Creation </ul></font> } unit FMaterialEditorForm; interface {$I GLScene.inc} uses Winapi.Windows, System.Classes, System.TypInfo, VCL.Forms, VCL.ComCtrls, VCL.StdCtrls, VCL.Controls, VCL.Buttons, FRMaterialPreview, FRColorEditor, FRFaceEditor, GLTexture, FRTextureEdit, GLViewer, GLMaterial, GLState; type TMaterialEditorForm = class(TForm) PageControl1: TPageControl; TSFront: TTabSheet; TSBack: TTabSheet; TSTexture: TTabSheet; FEFront: TRFaceEditor; FEBack: TRFaceEditor; GroupBox1: TGroupBox; MPPreview: TRMaterialPreview; BBOk: TBitBtn; BBCancel: TBitBtn; RTextureEdit: TRTextureEdit; CBBlending: TComboBox; Label1: TLabel; Label2: TLabel; CBPolygonMode: TComboBox; procedure OnMaterialChanged(Sender: TObject); private { Private declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; function Execute(AMaterial: TGLMaterial): Boolean; end; function MaterialEditorForm: TMaterialEditorForm; procedure ReleaseMaterialEditorForm; implementation {$R *.dfm} var vMaterialEditorForm: TMaterialEditorForm; function MaterialEditorForm: TMaterialEditorForm; begin if not Assigned(vMaterialEditorForm) then vMaterialEditorForm := TMaterialEditorForm.Create(nil); Result := vMaterialEditorForm; end; procedure ReleaseMaterialEditorForm; begin if Assigned(vMaterialEditorForm) then begin vMaterialEditorForm.Free; vMaterialEditorForm := nil; end; end; // Create // constructor TMaterialEditorForm.Create(AOwner: TComponent); var I: Integer; begin inherited; for i := 0 to Integer(High(TBlendingMode)) do CBBlending.Items.Add(GetEnumName(TypeInfo(TBlendingMode), i)); for i := 0 to Integer(High(TPolygonMode)) do CBPolygonMode.Items.Add(GetEnumName(TypeInfo(TPolygonMode), i)); FEFront.OnChange := OnMaterialChanged; FEBack.OnChange := OnMaterialChanged; RTextureEdit.OnChange := OnMaterialChanged; end; // Execute // function TMaterialEditorForm.Execute(AMaterial: TGLMaterial): Boolean; begin with AMaterial.GetActualPrimaryMaterial do begin FEFront.FaceProperties := FrontProperties; FEBack.FaceProperties := BackProperties; RTextureEdit.Texture := Texture; CBPolygonMode.ItemIndex:=Integer(PolygonMode); CBBlending.ItemIndex := Integer(BlendingMode); end; MPPreview.Material := AMaterial; Result := (ShowModal = mrOk); if Result then with AMaterial.GetActualPrimaryMaterial do begin FrontProperties := FEFront.FaceProperties; BackProperties := FEBack.FaceProperties; Texture := RTextureEdit.Texture; BlendingMode := TBlendingMode(CBBlending.ItemIndex); PolygonMode := TPolygonMode(CBPolygonMode.ItemIndex); end; end; // OnMaterialChanged // procedure TMaterialEditorForm.OnMaterialChanged(Sender: TObject); begin with MPPreview.Material do begin FrontProperties := FEFront.FaceProperties; BackProperties := FEBack.FaceProperties; Texture := RTextureEdit.Texture; BlendingMode := TBlendingMode(CBBlending.ItemIndex); PolygonMode := TPolygonMode(CBPolygonMode.ItemIndex); end; MPPreview.GLSceneViewer.Invalidate; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ finalization ReleaseMaterialEditorForm; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLSpline<p> Cubic spline interpolation functions<p> <b>History : </b><font size=-1><ul> <li>10/12/14 - PW - Renamed Spline unit to GLSpline <li>30/12/12 - PW - Restored CPP compatibility with record arrays <li>08/07/04 - LR - Removed ../ from the GLScene.inc <li>16/07/02 - Egg - Added methods to access slope per axis <li>28/05/00 - Egg - Javadocisation, minor changes & optimizations, Renamed TSpline to TCubicSpline, added W component and a bunch of helper methods <li>20/05/00 - RoC - Created, based on the C source code from Eric </ul></font> } unit GLSpline; interface uses GLVectorGeometry; {$i GLScene.inc} type TCubicSplineMatrix = array of array [0..3] of Single; // TCubicSpline // {: 3D cubic spline handler class.<p> This class allows to describe and calculate values of a time-based, three-dimensionnal cubic spline.<p> Cubic spline pass through all given points and tangent on point N is given by the (N-1) to (N+1) vector.<p> Note : X, Y & Z are actually interpolated independently. } TCubicSpline = class (TObject) private { Private Declarations } matX, matY, matZ, matW : TCubicSplineMatrix; FNb : Integer; public { Public Declarations } {: Creates the spline and declares interpolation points.<p> Time references go from 0 (first point) to nb-1 (last point), the first and last reference matrices respectively are used when T is used beyond this range.<p> Note : "nil" single arrays are accepted, in this case the axis is disabled and calculus will return 0 (zero) for this component. } constructor Create(const X, Y, Z, W : PFloatArray; const nb : Integer); {$ifdef CLR}unsafe;{$endif} destructor Destroy; override; {: Calculates X component at time t.<p> } function SplineX(const t : Single): Single; {: Calculates Y component at time t.<p> } function SplineY(const t : single): Single; {: Calculates Z component at time t.<p> } function SplineZ(const t : single): Single; {: Calculates W component at time t.<p> } function SplineW(const t : single): Single; {: Calculates X and Y components at time t.<p> } procedure SplineXY(const t : single; var X, Y : Single); {: Calculates X, Y and Z components at time t.<p> } procedure SplineXYZ(const t : single; var X, Y, Z : Single); {: Calculates X, Y, Z and W components at time t.<p> } procedure SplineXYZW(const t : single; var X, Y, Z, W : Single); {: Calculates affine vector at time t.<p> } function SplineAffineVector(const t : single) : TAffineVector; overload; {: Calculates affine vector at time t.<p> } procedure SplineAffineVector(const t : single; var vector : TAffineVector); overload; {: Calculates vector at time t.<p> } function SplineVector(const t : single) : TVector; overload; {: Calculates vector at time t.<p> } procedure SplineVector(const t : single; var vector : TVector); overload; {: Calculates X component slope at time t.<p> } function SplineSlopeX(const t : Single): Single; {: Calculates Y component slope at time t.<p> } function SplineSlopeY(const t : single): Single; {: Calculates Z component slope at time t.<p> } function SplineSlopeZ(const t : single): Single; {: Calculates W component slope at time t.<p> } function SplineSlopeW(const t : single): Single; {: Calculates the spline slope at time t. } function SplineSlopeVector(const t : single) : TAffineVector; overload; {: Calculates the intersection of the spline with the YZ plane.<p> Returns True if an intersection was found. } function SplineIntersecYZ(X: Single; var Y, Z: Single): Boolean; {: Calculates the intersection of the spline with the XZ plane.<p> Returns True if an intersection was found. } function SplineIntersecXZ(Y: Single; var X, Z: Single): Boolean; {: Calculates the intersection of the spline with the XY plane.<p> Returns True if an intersection was found. } function SplineIntersecXY(Z: Single; var X, Y: Single): Boolean; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // VECCholeskyTriDiagResol // procedure VECCholeskyTriDiagResol(const b : array of Single; const nb : Integer; var Result : array of Single); var Y, LDiag, LssDiag : array of Single; i, k, Debut, Fin: Integer; begin Debut:=0; Fin:=nb-1; Assert(Length(b)>0); SetLength(LDiag, nb); SetLength(LssDiag, nb-1); LDiag[Debut]:=1.4142135; // = sqrt(2) LssDiag[Debut]:=1.0/1.4142135; for K:=Debut+1 to Fin-1 do begin LDiag[K]:=Sqrt(4-LssDiag[K-1]*LssDiag[K-1]); LssDiag[K]:=1.0/LDiag[K]; end; LDiag[Fin]:=Sqrt(2-LssDiag[Fin-1]*LssDiag[Fin-1]); SetLength(Y, nb); Y[Debut]:=B[Debut]/LDiag[Debut]; for I:=Debut+1 to Fin do Y[I]:=(B[I]-Y[I-1]*LssDiag[I-1])/LDiag[I]; Assert(Length(Result)=nb); Result[Fin]:=Y[Fin]/LDiag[Fin]; for i:=Fin-1 downto Debut do Result[I]:=(Y[I]-Result[I+1]*LssDiag[I])/LDiag[I]; end; // MATInterpolationHermite // procedure MATInterpolationHermite(const ordonnees : PFloatArray; const nb : Integer; var Result : TCubicSplineMatrix); {$ifdef CLR}unsafe;{$endif} var a, b, c, d : Single; i, n : Integer; bb, deriv : array of Single; begin Result:=nil; if Assigned(Ordonnees) and (nb>0) then begin n:=nb-1; SetLength(bb, nb); bb[0]:=3*(ordonnees[1]-ordonnees[0]); bb[n]:=3*(ordonnees[n]-ordonnees[n-1]); for i:=1 to n-1 do bb[I]:=3*(ordonnees[I+1]-ordonnees[I-1]); SetLength(deriv, nb); VECCholeskyTriDiagResol(bb, nb, deriv); SetLength(Result, n); for i:=0 to n-1 do begin a:=ordonnees[I]; b:=deriv[I]; c:=3*(ordonnees[I+1]-ordonnees[I])-2*deriv[I]-deriv[I+1]; d:=-2*(ordonnees[I+1]-ordonnees[I])+deriv[I]+deriv[I+1]; Result[I][3]:=a+I*(I*(c-I*d)-b); Result[I][2]:=b+I*(3*I*d-2*c); Result[I][1]:=c-3*I*d; Result[I][0]:=d; end; end; end; // MATValeurSpline // function MATValeurSpline(const spline : TCubicSplineMatrix; const x : Single; const nb : Integer) : Single; var i : Integer; begin if Length(Spline)>0 then begin if x<=0 then i:=0 else if x>nb-1 then i:=nb-1 else i:=Integer(Trunc(x)); { TODO : the following line looks like a bug... } if i=(nb-1) then Dec(i); Result:=((spline[i][0]*x+spline[i][1])*x+spline[i][2])*x+spline[i][3]; end else Result:=0; end; // MATValeurSplineSlope // function MATValeurSplineSlope(const spline : TCubicSplineMatrix; const x : Single; const nb : Integer) : Single; var i : Integer; begin if Length(Spline)>0 then begin if x<=0 then i:=0 else if x>nb-1 then i:=nb-1 else i:=Integer(Trunc(x)); { TODO : the following line looks like a bug... } if i=(nb-1) then Dec(i); Result:=(3*spline[i][0]*x+2*spline[i][1])*x+spline[i][2]; end else Result:=0; end; // ------------------ // ------------------ TCubicSpline ------------------ // ------------------ // Create // constructor TCubicSpline.Create(const X, Y, Z, W: PFloatArray; const nb : Integer); {$ifdef CLR}unsafe;{$endif} begin inherited Create; MATInterpolationHermite(X, nb, matX); MATInterpolationHermite(Y, nb, matY); MATInterpolationHermite(Z, nb, matZ); MATInterpolationHermite(W, nb, matW); FNb:=nb; end; // Destroy // destructor TCubicSpline.Destroy; begin inherited Destroy; end; // SplineX // function TCubicSpline.SplineX(const t : single): Single; begin Result:=MATValeurSpline(MatX, t, FNb); end; // SplineY // function TCubicSpline.SplineY(const t : single): Single; begin Result:=MATValeurSpline(MatY, t, FNb); end; // SplineZ // function TCubicSpline.SplineZ(const t : single): Single; begin Result:=MATValeurSpline(MatZ, t, FNb); end; // SplineW // function TCubicSpline.SplineW(const t : single): Single; begin Result:=MATValeurSpline(MatW, t, FNb); end; // SplineXY // procedure TCubicSpline.SplineXY(const t : single; var X, Y : Single); begin X:=MATValeurSpline(MatX, T, FNb); Y:=MATValeurSpline(MatY, T, FNb); end; // SplineXYZ // procedure TCubicSpline.SplineXYZ(const t : single; var X, Y, Z : Single); begin X:=MATValeurSpline(MatX, T, FNb); Y:=MATValeurSpline(MatY, T, FNb); Z:=MATValeurSpline(MatZ, T, FNb); end; // SplineXYZW // procedure TCubicSpline.SplineXYZW(const t : single; var X, Y, Z, W : Single); begin X:=MATValeurSpline(MatX, T, FNb); Y:=MATValeurSpline(MatY, T, FNb); Z:=MATValeurSpline(MatZ, T, FNb); W:=MATValeurSpline(MatW, T, FNb); end; // SplineAffineVector // function TCubicSpline.SplineAffineVector(const t : single) : TAffineVector; begin Result.V[0]:=MATValeurSpline(MatX, t, FNb); Result.V[1]:=MATValeurSpline(MatY, t, FNb); Result.V[2]:=MATValeurSpline(MatZ, t, FNb); end; // SplineAffineVector // procedure TCubicSpline.SplineAffineVector(const t : single; var vector : TAffineVector); begin vector.V[0]:=MATValeurSpline(MatX, t, FNb); vector.V[1]:=MATValeurSpline(MatY, t, FNb); vector.V[2]:=MATValeurSpline(MatZ, t, FNb); end; // SplineVector // function TCubicSpline.SplineVector(const t : single) : TVector; begin Result.V[0]:=MATValeurSpline(MatX, t, FNb); Result.V[1]:=MATValeurSpline(MatY, t, FNb); Result.V[2]:=MATValeurSpline(MatZ, t, FNb); Result.V[3]:=MATValeurSpline(MatW, t, FNb); end; // SplineVector // procedure TCubicSpline.SplineVector(const t : single; var vector : TVector); begin vector.V[0]:=MATValeurSpline(MatX, t, FNb); vector.V[1]:=MATValeurSpline(MatY, t, FNb); vector.V[2]:=MATValeurSpline(MatZ, t, FNb); vector.V[3]:=MATValeurSpline(MatW, t, FNb); end; // SplineSlopeX // function TCubicSpline.SplineSlopeX(const t : Single): Single; begin Result:=MATValeurSplineSlope(MatX, t, FNb); end; // SplineSlopeY // function TCubicSpline.SplineSlopeY(const t : single): Single; begin Result:=MATValeurSplineSlope(MatY, t, FNb); end; // SplineSlopeZ // function TCubicSpline.SplineSlopeZ(const t : single): Single; begin Result:=MATValeurSplineSlope(MatZ, t, FNb); end; // SplineSlopeW // function TCubicSpline.SplineSlopeW(const t : single): Single; begin Result:=MATValeurSplineSlope(MatW, t, FNb); end; // SplineSlopeVector // function TCubicSpline.SplineSlopeVector(const t : single) : TAffineVector; begin Result.V[0]:=MATValeurSplineSlope(MatX, t, FNb); Result.V[1]:=MATValeurSplineSlope(MatY, t, FNb); Result.V[2]:=MATValeurSplineSlope(MatZ, t, FNb); end; // SplineIntersecYZ // function TCubicSpline.SplineIntersecYZ(X: Single; var Y, Z: Single): Boolean; var Sup, Inf, Mid : Single; SSup, Sinf, Smid : Single; begin Result:=False; Sup:=FNb; Inf:=0.0; Ssup:=SplineX(Sup); Sinf:=SplineX(Inf); if SSup>Sinf then begin if (SSup<X) or (Sinf>X) then Exit; while Abs(SSup-Sinf)>1e-4 do begin Mid:=(Sup+Inf)*0.5; SMid:=SplineX(Mid); if X<SMid then begin SSup:=SMid; Sup:=Mid; end else begin Sinf:=SMid; Inf:=Mid; end; end; Y:=SplineY((Sup+Inf)*0.5); Z:=SplineZ((Sup+Inf)*0.5); end else begin if (Sinf<X) or (SSup>X) then Exit; while Abs(SSup-Sinf)>1e-4 do begin Mid:=(Sup+Inf)*0.5; SMid:=SplineX(Mid); if X<SMid then begin Sinf:=SMid; Inf:=Mid; end else begin SSup:=SMid; Sup:=Mid; end; end; Y:=SplineY((Sup+Inf)*0.5); Z:=SplineZ((Sup+Inf)*0.5); end; Result:=True; end; // SplineIntersecXZ // function TCubicSpline.SplineIntersecXZ(Y: Single; var X, Z: Single): Boolean; var Sup, Inf, Mid : Single; SSup, Sinf, Smid : Single; begin Result:=False; Sup:=FNb; Inf:=0.0; Ssup:=SplineY(Sup); Sinf:=SplineY(Inf); if SSup>Sinf then begin if (SSup<Y) or (Sinf>Y) then Exit; while Abs(SSup-Sinf)>1e-4 do begin Mid:=(Sup+Inf)*0.5; SMid:=SplineY(Mid); if Y<SMid then begin SSup:=SMid; Sup:=Mid; end else begin Sinf:=SMid; Inf:=Mid; end; end; X:=SplineX((Sup+Inf)*0.5); Z:=SplineZ((Sup+Inf)*0.5); end else begin if (Sinf<Y) or (SSup>Y) then Exit; while Abs(SSup-Sinf)>1e-4 do begin Mid:=(Sup+Inf)*0.5; SMid:=SplineY(Mid); if Y<SMid then begin Sinf:=SMid; Inf:=Mid; end else begin SSup:=SMid; Sup:=Mid; end; end; X:=SplineX((Sup+Inf)*0.5); Z:=SplineZ((Sup+Inf)*0.5); end; Result:=True; end; // SplineIntersecXY // function TCubicSpline.SplineIntersecXY(Z: Single; var X, Y: Single): Boolean; var Sup, Inf, Mid : Single; SSup, Sinf, Smid : Single; begin Result:=False; Sup:=FNb; Inf:=0.0; Ssup:=SplineZ(Sup); Sinf:=SplineZ(Inf); if SSup>Sinf then begin if (SSup<Z) or (Sinf>Z) then Exit; while Abs(SSup-Sinf)>1e-4 do begin Mid:=(Sup+Inf)*0.5; SMid:=SplineZ(Mid); if Z<SMid then begin SSup:=SMid; Sup:=Mid; end else begin Sinf:=SMid; Inf:=Mid; end; end; X:=SplineX((Sup+Inf)*0.5); Y:=SplineY((Sup+Inf)*0.5); end else begin if (Sinf<Z) or (SSup>Z) then Exit; while Abs(SSup-Sinf)>1e-4 do begin Mid:=(Sup+Inf)*0.5; SMid:=SplineZ(Mid); if Z<SMid then begin Sinf:=SMid; Inf:=Mid; end else begin SSup:=SMid; Sup:=Mid; end; end; X:=SplineX((Sup+Inf)*0.5); Y:=SplineY((Sup+Inf)*0.5); end; Result:=True; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids; type TForm1 = class(TForm) StringGrid1: TStringGrid; LabeledEdit1: TLabeledEdit; Button1: TButton; Button2: TButton; Button3: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; // структура type TSchoolboy = record // имя FirstName : string; // фамилия LastName : string; // год YearOfStudy : string; // буква класса ClassLetter : string; // средний бал Assessment : real; end; var // динамический массив структур schoolboys : array of TSchoolboy; // количество записей count : integer; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin // при создание формы устанавливаем имена // фиксированных колонок таблицы StringGrid1.ColCount:=7; StringGrid1.Cells[0,0] := 'Имя'; StringGrid1.Cells[1,0] := 'Фамилия'; StringGrid1.Cells[2,0] := 'Год обучения'; StringGrid1.Cells[3,0] := 'Буква класса'; StringGrid1.Cells[4,0] := 'Средний бал'; StringGrid1.Cells[5,0] := 'ср. бал >4'; StringGrid1.Cells[6,0] := 'ср. бал >4.5'; end; procedure TForm1.Button1Click(Sender: TObject); var // текстовый файл f: TextFile; // итератор i: integer; begin // открытие файла на чтение AssignFile(f, './input.txt'); Reset(f); // обнуляем количество записей в файле count := 0; // читаем файл до конца while not Eof(f) do begin // увеличиваем счетчик количества записей Inc(count); // устанавливаем новый размер структур SetLength(schoolboys, count + 1); // считываем построчно имя фамилию и т.д. ReadLn(f, schoolboys[count].FirstName); ReadLn(f, schoolboys[count].LastName); ReadLn(f, schoolboys[count].YearOfStudy); ReadLn(f, schoolboys[count].ClassLetter); ReadLn(f, schoolboys[count].Assessment); end; // после окончания считывния закрываем файл CloseFile(f); // -------------------- // выводим содержимое на форму // количество строк в таблице StringGrid1.RowCount := count+1; // заполняем таблицу данными со структуры for i := 1 to count do begin StringGrid1.Cells[0,i] := schoolboys[i].FirstName; StringGrid1.Cells[1,i] := schoolboys[i].LastName; StringGrid1.Cells[2,i] := schoolboys[i].YearOfStudy; StringGrid1.Cells[3,i] := schoolboys[i].ClassLetter; StringGrid1.Cells[4,i] := FormatFloat('0.00', schoolboys[i].Assessment); end; end; procedure TForm1.FormDestroy(Sender: TObject); begin // при разрушении формы высвобождаем память // выделенную под массив структур schoolboys := nil; end; procedure TForm1.Button3Click(Sender: TObject); var // итератор и счетчик кол-во отличников i, c : Integer; begin // обнуляем счетчик c := 0; // проходим циклом по всем структурам for i := 1 to count do begin // если средний бал текущего учениека // выше нежели 4 if schoolboys[i].Assessment >= 4.0 then begin // то увеличиваем кол-во отличников // на еденицу Inc(c); StringGrid1.Cells[5,i] := '#####'; if schoolboys[i].Assessment >= 4.5 then StringGrid1.Cells[6,i] := '#####'; end; end; // выводим кол-во отличников в ячейку на форме LabeledEdit1.Text := IntToStr(c); end; procedure TForm1.Button2Click(Sender: TObject); var // текстовый файл f: TextFile; // итератор i : Integer; begin // открываем файл на запись AssignFile(f, './output.txt'); Rewrite(f); // проходим циклом по всем структурам for i := 1 to count do begin // если средниц бал выше 4,5 // то сохраним этого учениека в файл g if schoolboys[i].Assessment >= 4.5 then begin // записываем все в одну строку через пробел Write(f, schoolboys[i].FirstName, ' '); Write(f, schoolboys[i].LastName, ' '); Write(f, schoolboys[i].YearOfStudy, ' '); Write(f, schoolboys[i].ClassLetter, ' '); // в конце записываем оценку и переходим на новую строку файла WriteLn(f, schoolboys[i].Assessment, ' '); end; end; // закрываем файл CloseFile(f); end; end.
unit BinToInt_1; interface implementation function TryBinToInt(const BinString: string; out Value: Int64): Boolean; var i, c: Int32; Digit: Char; begin Value := 0; c := Length(BinString); if c = 0 then Exit(False); for i := Low(string) to c - 1 do begin Digit := BinString[i]; case Digit of '0':; '1': Value := Value + 1; else Exit(False); end; if i < c - 1 then Value := Value shl 1; end; end; var i: Int64; procedure Test; begin TryBinToInt('0', i); Assert(i = %0); TryBinToInt('01', i); Assert(i = %01); TryBinToInt('11', i); Assert(i = %11); TryBinToInt('1011', i); Assert(i = %1011); TryBinToInt('10111101010101001', i); Assert(i = %10111101010101001); TryBinToInt('1010101111001101111011110001001000110100010101100111100010010000', i); Assert(i = $ABCDEF1234567890); end; initialization Test(); finalization end.
unit Entities; interface uses SysUtils; type MemLeakError = class(Exception); TRefObject = class public constructor Create; destructor Destroy; override; class threadvar RefCount: Integer; end; TPerson = class(TRefObject) const DATETIME_FORMAT = 'dd/mm/yyyy'; strict private FFirstName: string; FLastName: string; FBirthDay: TDateTime; function GetAge: LongWord; public constructor Create(const FirstName: string; LastName: string; const BirthDay: TDateTime); overload; constructor Create(const FirstName: string; LastName: string; const BirthDay: string); overload; property FirstName: string read FFirstName; property LastName: string read FLastName; property BirthDay: TDateTime read FBirthDay; property Age: LongWord read GetAge; end; TTwit = class(TRefObject) strict private FText: string; FAuthor: string; public property Author: string read FAuthor; property Text: string read FText; end; implementation { TPerson } constructor TPerson.Create(const FirstName: string; LastName: string; const BirthDay: TDateTime); begin inherited Create; FFirstName := FirstName; FLastName := LastName; FBirthDay := BirthDay; end; constructor TPerson.Create(const FirstName: string; LastName: string; const BirthDay: string); begin inherited Create; FFirstName := FirstName; FLastName := LastName; end; function TPerson.GetAge: LongWord; begin Result := 0; end; { TRefObject } constructor TRefObject.Create; begin AtomicIncrement(RefCount) end; destructor TRefObject.Destroy; begin AtomicDecrement(RefCount) end; end.
unit NewImage; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ExtCtrls; type TMouseEnterEvent = procedure (Sender: TObject) of object; TMouseLeaveEvent = procedure (Sender: TObject) of object; TNewImage = class(TImage) private FOnMouseEnter: TMouseEnterEvent; FOnMouseLeave: TMouseLeaveEvent; procedure CMMouseEnter (var message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave (var message: TMessage); message CM_MOUSELEAVE; protected public published property OnMouseEnter: TMouseEnterEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave: TMouseLeaveEvent read FOnMouseLeave write FOnMouseLeave; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TNewImage]); end; { TNewImage } procedure TNewImage.CMMouseEnter(var message: TMessage); begin if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; procedure TNewImage.CMMouseLeave(var message: TMessage); begin if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; end.
unit MagicBrushFirstComplect; interface uses Windows, MagicBrush, Graphics; { Простые кисти первый комплект, будет предпологаться что кисти будут добавлятся комплектами Версия 1.0 } type TGradientBrush = class(TMagicBrush) FRemeberColor: TColor; // Запоминаем начальное значение цвета public constructor Create(aCanvas: TCanvas);override; procedure Draw(X, Y: Integer); override; procedure RefreshBrush(); override; end; implementation { TGradientBrush } constructor TGradientBrush.Create(aCanvas: TCanvas); begin inherited Create(aCanvas); ActiveColor := clRed; Width := 10; Name:= 'Gradient brush'; FRemeberColor:= ActiveColor; end; procedure TGradientBrush.Draw(X, Y: Integer); const DivParams = 5; var aRed,aGreen, aBlue: Byte; aCurrent: Byte; begin aRed := GetRValue(FCurrentValue); aGreen := GetGValue(FCurrentValue); aBlue := GetBValue(FCurrentValue); if (aRed >= aGreen) and (aRed >= aBlue ) then begin aCurrent := aRed - 1; if aCurrent <= 0 then begin ActiveColor := RGB(0, aGreen, aBlue); end else begin ActiveColor := RGB(aCurrent, aGreen, aBlue); end; end else if (aGreen >= aRed) and (aGreen >= aBlue ) then begin aCurrent := aGreen - 1; if aCurrent <= 0 then begin ActiveColor := RGB(aRed, 0, aBlue); end else begin ActiveColor := RGB(aRed, aCurrent, aBlue); end; end else if (aBlue >= aRed) and (aBlue >= aGreen ) then begin aCurrent := aBlue - 1; if aCurrent <= 0 then begin ActiveColor := RGB(aRed, aGreen, 0); end else begin ActiveColor := RGB(aRed, aGreen, aCurrent); end; end else begin ActiveColor := RGB(aRed, aGreen , aBlue); end; if (ISFirstCall) then begin ISFirstCall := False; Canvas.MoveTo(X,Y); end; Canvas.LineTo(X,Y); end; procedure TGradientBrush.RefreshBrush; begin inherited; ActiveColor := FRemeberColor; end; end.
unit AddUserPageMod; interface uses Windows, Messages, SysUtils, Classes, HTTPApp, WebModu, HTTPProd, CompProd, PagItems, SiteProd, MidItems, WebForm, WebAdapt, WebComp; type TAddUserPageModule = class(TWebPageModule) Adapter: TAdapter; AddUser: TAdapterAction; Name: TAdapterField; Password: TAdapterField; PasswordVerify: TAdapterField; Messages: TAdapterField; UpdateUser: TAdapterAction; DeleteUser: TAdapterAction; trvlsAccessRights: TStringsValuesList; AccessRights: TAdapterField; UserListAdapter: TAdapter; UserName: TAdapterField; UserRights: TAdapterField; PageProducer1: TPageProducer; procedure AddUserExecute(Sender: TObject; Params: TStrings); procedure WebPageModuleCreate(Sender: TObject); procedure NameGetValue(Sender: TObject; var Value: Variant); procedure MessagesGetValue(Sender: TObject; var Value: Variant); procedure WebPageModuleActivate(Sender: TObject); procedure UpdateUserExecute(Sender: TObject; Params: TStrings); procedure DeleteUserExecute(Sender: TObject; Params: TStrings); procedure UserNameGetValue(Sender: TObject; var Value: Variant); procedure UserRightsGetValue(Sender: TObject; var Value: Variant); procedure UserListAdapterIterateRecords(Sender: TObject; Action: TIteratorMethod; var EOF: Boolean); private FLastUserName: string; FMessageValue: string; FCurrentIndex: Integer; public { Public declarations } end; function AddUserPageModule: TAddUserPageModule; implementation {$R *.dfm} {*.html} uses WebReq, WebCntxt, AdaptReq, WebFact, Variants, MainPageMod, SiteComp, WebUsers; resourcestring rBlankName = 'The name is blank.'; rPassBlank = 'The password is blank.'; rPassDontMatch = 'The passwords do not match.'; rUserExists = 'The user %s already exists. Please choose another name.'; rUserSuccessAdded = 'User %s successfully added.'; rRootWarning = 'Warning: you are using the root account with the default password!'; rUnknownUser = 'Unknown user to set password for.'; rBlankNewPass = 'New password is blank.'; rCantFindUser = 'The user %s can not be found to be set the password!'; rUserUpdated = 'User %s successfully updated.'; rCantFindUserToDelete = 'The user %s can not be found to be deleted!'; rUserDeleted = 'User %s successfully deleted.'; rAddUserTitle = 'Add/Modify Users'; rAddUserDescript = 'Add, delete and modify users.'; function AddUserPageModule: TAddUserPageModule; begin Result := TAddUserPageModule(WebContext.FindModuleClass(TAddUserPageModule)); end; procedure TAddUserPageModule.AddUserExecute(Sender: TObject; Params: TStrings); var Value: IActionFieldValue; StrName: string; StrPass: string; StrPassVerify: string; StrRights: string; DontAddUser: boolean; WebUser: TWebUserItem; begin DontAddUser := False; try Value := Name.ActionValue; if Assigned(Value) then StrName := Value.Values[0]; Value := Password.ActionValue; if Assigned(Value) then StrPass := Value.Values[0]; Value := PasswordVerify.ActionValue; if Assigned(Value) then StrPassVerify := Value.Values[0]; Value := AccessRights.ActionValue; if Assigned(Value) then StrRights := Value.Values[0] else StrRights := ''; // Make sure the name isn't empty if Trim(StrName) = '' then begin Adapter.Errors.AddError(Exception.Create(rBlankName)); DontAddUser := True; end; if StrPass = '' then begin Adapter.Errors.AddError(Exception.Create(rPassBlank)); DontAddUser := True; end; if StrPass <> StrPassVerify then begin Adapter.Errors.AddError(Exception.Create(rPassDontMatch)); DontAddUser := True; end; // Exit if an error happened above, after filling in what the // user already put in. if DontAddUser then begin FLastUserName := StrName; // Filled in with the NameGetValue event // Don't fill in the password for security reasons Exit; end; // Check to see if that user already exists WebUser := MainPageModule.PersistWebUserList.UserItems.FindUserName(StrName); if WebUser <> nil then begin Adapter.Errors.AddError(Exception.CreateFmt(rUserExists, [StrName])); end else begin // Add the user to the main page's user list WebUser := MainPageModule.PersistWebUserList.UserItems.Add as TWebUserItem; WebUser.UserName := StrName; WebUser.Password := StrPass; WebUser.AccessRights := StrRights; MainPageModule.SaveUserList; FMessageValue := Format(rUserSuccessAdded, [StrName]); end; except on E: Exception do Adapter.Errors.AddError(E); end; end; procedure TAddUserPageModule.WebPageModuleCreate(Sender: TObject); begin FLastUserName := ''; FMessageValue := ''; end; procedure TAddUserPageModule.NameGetValue(Sender: TObject; var Value: Variant); begin Value := FLastUserName; end; procedure TAddUserPageModule.MessagesGetValue(Sender: TObject; var Value: Variant); begin Value := FMessageValue; end; procedure TAddUserPageModule.WebPageModuleActivate(Sender: TObject); var WebUserItem: TWebUserItem; begin // Show a warning if they are running as "root" with the default password (root) with MainPageModule do begin if not VarIsEmpty(EndUserSessionAdapter.UserID) then begin WebUserItem := PersistWebUserList.UserItems.FindUserID(EndUserSessionAdapter.UserId); if WebUserItem <> nil then if (WebUserItem.UserName = 'root') and (WebUserItem.Password = 'root') then { do not localize } FMessageValue := rRootWarning; end; end; end; procedure TAddUserPageModule.UpdateUserExecute(Sender: TObject; Params: TStrings); var Value: IActionFieldValue; StrName: string; StrPassword: string; StrRights: string; WebUser: TWebUserItem; begin try Value := Name.ActionValue; if Assigned(Value) then StrName := Value.Values[0] else StrName := ''; if StrName = '' then raise Exception.Create(rUnknownUser); Value := AccessRights.ActionValue; if Assigned(Value) then StrRights := Value.Values[0] else StrRights := ''; Value := Password.ActionValue; if Assigned(Value) then StrPassword := Value.Values[0] else StrPassword := ''; WebUser := MainPageModule.PersistWebUserList.UserItems.FindUserName(StrName); if WebUser = nil then raise Exception.CreateFmt(rCantFindUser, [StrName]); if StrPassword <> '' then WebUser.Password := StrPassword; if StrRights <> '' then WebUser.AccessRights := StrRights; MainPageModule.SaveUserList; FMessageValue := Format(rUserUpdated, [StrName]); except on E: Exception do Adapter.Errors.AddError(E); end; end; procedure TAddUserPageModule.DeleteUserExecute(Sender: TObject; Params: TStrings); var Value: IActionFieldValue; StrName: string; WebUser: TWebUserItem; begin try StrName := ''; Value := Name.ActionValue; if Assigned(Value) then StrName := Value.Values[0]; WebUser := MainPageModule.PersistWebUserList.UserItems.FindUserName(StrName); if WebUser = nil then raise Exception.CreateFmt(rCantFindUserToDelete, [StrName]); MainPageModule.PersistWebUserList.UserItems.Delete(WebUser.Index); MainPageModule.SaveUserList; FMessageValue := Format(rUserDeleted, [StrName]); except on E: Exception do Adapter.Errors.AddError(E); end; end; procedure TAddUserPageModule.UserNameGetValue(Sender: TObject; var Value: Variant); begin Value := MainPageModule.PersistWebUserList.Users[FCurrentIndex].UserName; end; procedure TAddUserPageModule.UserRightsGetValue(Sender: TObject; var Value: Variant); begin Value := MainPageModule.PersistWebUserList.Users[FCurrentIndex].AccessRights; end; procedure TAddUserPageModule.UserListAdapterIterateRecords(Sender: TObject; Action: TIteratorMethod; var EOF: Boolean); begin case Action of itStart, itEnd: FCurrentIndex := 0; itNext: Inc(FCurrentIndex); end; EOF := FCurrentIndex >= MainPageModule.PersistWebUserList.UserItems.Count; end; initialization if WebRequestHandler <> nil then WebRequestHandler.AddWebModuleFactory(TWebPageModuleFactory.Create(TAddUserPageModule, TWebPageInfo.Create([wpPublished, wpLoginRequired], '.html', '', rAddUserTitle, rAddUserDescript, 'Administrator' {ViewAccess}), crOnDemand, caCache)); end.
unit UBAGlobals; {$OPTIMIZATION OFF} {$define debug} interface uses Classes, ORNet, uConst, ORFn, Sysutils, Dialogs, Windows, Messages, rOrders; type {Problem List Record Used To Add New DX From SignOrders Form } TBAPLRec = class(TObject) constructor Create(PLlist:TStringList); function BuildProblemListDxEntry(pDxCode:string):TStringList; function FMToDateTime(FMDateTime: string): TDateTime; end; {patient qualifiers} TBAPLPt=class(TObject) public PtVAMC:string; PtDead:string; PtBid:string; PtServiceConnected:boolean; PtAgentOrange:boolean; PtRadiation:boolean; PtEnvironmental:boolean; PtHNC:boolean; PtMST:boolean; PtSHAD:boolean; PtCL: boolean; constructor Create(Alist:TStringList); function GetGMPDFN(dfn:string;name:String):string; public function rpcInitPt(const PatientDFN: string): TStrings ; procedure LoadPatientParams(AList:TstringList); end; TBAGlobals = class(TObject) private FOrderNum: string; protected public constructor Create; property OrderNum: string read FOrderNum write FOrderNum; procedure AddBAPCEDiag(DiagStr:string); procedure ClearBAPCEDiagList; end; TBADxRecord = class(TObject) public FExistingRecordID: string; FOrderID: string; FBADxCode: string; //Primary Dx FBASecDx1: string; //Secondary Dx 1 FBASecDx2: string; //Secondary Dx 2 FBASecDx3: string; //Secondary Dx 3 FDxDescCode: string; FDxDesc1: string; FDxDesc2: string; FDxDesc3: string; FTreatmentFactors: string; end; TBACopiedOrderFlags = class public OrderID: string; end; TBATreatmentFactorsInRec = class(TObject) public FBAOrderID: string; FBAEligible: string; FBATFactors: string; end; TBAUnsignedBillingRec = class(TObject) public FBAOrderID: string; FBASTSFlags: string; FBADxCode: string; FBASecDx1: string; FBASecDx2: string; FBASecDx3: string; end; TBAConsultOrderRec = class(TObject) public FBAOrderID: string; FBADxCode: string; FBASecDx1: string; FBASecDx2: string; FBASecDx3: string; FBATreatmentFactors: string; end; TBAClearedBillingRec = class(TObject) public FBAOrderID: string; FBASTSFlags: string; FBADxCode: string; FBASecDx1: string; FBASecDx2: string; FBASecDx3: string; end; TBAFactorsRec = class(TObject) public FBAFactorActive : boolean; FBAFactorSC : string; FBAFactorMST : string; FBAFactorAO : string; FBAFactorIR : string; FBAFactorEC : string; FBAFactorHNC : string; FBAFactorCV : string; FBAFactorSHAD : string; FBAFactorCL: string; end; TBAPLFactorsIN = class(TOBject) public FPatientID : string; // UProblems.piece 1 FBADxText : string; // UProblems.piece 2 FBADxCode : string; // UProblems.piece 3 FBASC : string; // UProblems.piece 5 FBASC_YN : string; // UProblems.piece 6 FBATreatFactors : string; //(......) end; TBACBStsFlagsIN = class(TOBject) // Y/N/U public CB_Sts_Flags :string; // CB_SC :string; CB_AO :string; CB_IR :string; CB_EC :string; CB_MST :string; CB_HNC :string; CB_CV :string; CB_SHAD :string; end; procedure PutBADxListForOrder(var thisRecord: TBADxRecord; thisOrderID: string); //BAPHII 1.3.1 procedure CopyDxRecord(sourceOrderID: string; targetOrderID: string); //BAPHII 1.3.1 function GetPrimaryDx(thisOrderID: string) : string; //BAPHII 1.3.1 function tempDxNodeExists(thisOrderID: string) : boolean; function GetDxNodeIndex(thisOrderID: string) : smallint; function DiagnosesMatch(var List1: TStringList; var List2: TStringList) : boolean; function CountSelectedOrders(const Caller: smallint) : smallint; function CompareOrderDx(const Caller: smallint) : boolean; procedure GetBADxListForOrder(var thisRetVal: TBADxRecord; thisOrderID: string); procedure DestroyDxList; procedure SetBADxList; procedure SimpleAddTempDxList(thisOrderID: string); procedure SetBADxListForOrder(thisRec: TBADxRecord; thisOrderID: string); function AllSelectedDxBlank(const Caller: smallint) : boolean; function SecondaryDxFull(thisOrderID: string) : boolean; procedure AddSecondaryDx(thisOrderID: string; thisDxCode: string); procedure InitializeNewDxRec(var thisDxRec: TBADxRecord); procedure InitializeConsultOrderRec(var thisDxRec: TBAConsultOrderRec); procedure InitializeUnsignedOrderRec(var thisUnsignedRec: TBAUnsignedBillingRec); procedure InitializeTFactorsInRec(var thisTFactorsRecIn: TBATreatmentFactorsInRec); procedure BACopyOrder(sourceOrderList: TStringList); //BAPHII 1.3.2 procedure CopyTreatmentFactorsDxsToCopiedOrder(pSourceOrderID:string; pTargetOrderID:string); //BAPHII 1.3.2 procedure CopyTreatmentFactorsDxsToRenewedOrder; //BAPHII 1.3.2 function GetTFCIForOrder(thisIndex: integer) : string; //BAPHII 1.3.2 procedure CopyTFCIToTargetOrder(thisTargetOrderID: string; thisCheckBoxStatus: string); procedure ResetOrderID(fromID: string; toID: string); procedure RemoveOrderFromDxList(thisOrderID: string); function IsUserNurseProvider(pUserID: int64): boolean; function GetPatientTFactors(pOrderList:TStringList): String; var BAGlobals : TBAGlobals; BAPLPt : TBAPLPt; BAPLRec : TBAPLRec; PLlist : TStringList; BADiagnosisList : TStringList; BALocation : integer; BAPCEDiagList : TStringList; BAOrderIDList : TStringList; tempDxList : TList; globalDxRec : TBADxRecord; UnsignedBillingRec : TBAUnsignedBillingRec; ClearedBillingRec : TBAClearedBillingRec; ConsultOrderRec : TBAConsultOrderRec; BAFactorsInRec : TBATreatmentFactorsInRec; BAFactorsRec : TBAFactorsRec; BAOrderList : TStringList; UpdatedBAOrderList: TStringList; ChangeItemOrderNum: string; i : integer; OrderIDList : TStringList; OrderBillableList : TStrings; BAOrderID : string; BILLING_AWARE : boolean; BAtmpOrderList : TStringList; BAFlagsIN : string; BAFlagsOUT : TStringList; SourceOrderID : string; //BAPHII 1.3.2 TargetOrderID : string; //BAPHII 1.3.2 BACopiedOrderFlags: TStringList; //BAPHII 1.3.2 BANurseConsultOrders: TStringList; // Used to display Dx's on grids Dx1 : string; Dx2 : string; Dx3 : string; Dx4 : string; TFactors : string; SC,AO,IR : string; MST, HNC, CV, SHD, EC, CL: string; PLFactorsIndexes : TStringList; BAHoldPrimaryDx : string; // used to verify primart dx has been changed. BAPrimaryDxChanged: boolean; NonBillableOrderList : TStringList; // contains reference to those selected orders that are non billable OrderListSCEI : TSTringList; // OrderID Exists SCEI are required. UnsignedOrders : TStringList; // List of Orders when "don't sign" action BAUnSignedOrders : TStringList; // OrderID^StsFlags ie., 12345^NNNNNNN BATFHints : TStringList; BASelectedList : TStringList; // contains list of orders selected for signature. BAConsultDxList: TStringList; // contains dx^code^DxRequired(consults Only) selected for consults. BAConsultPLFlags: TStringList; // orderid^flags contains TF's if dx is selected from Problem list and Problem had TF associated. BAFWarningShown: boolean; // flag used to determine if Inactive ICD Code has been shown. BAPersonalDX: boolean; BADeltedOrders: TStringList; implementation uses fBALocalDiagnoses, fOrdersSign, fReview, uCore, rCore, rPCE, uPCE, UBAConst, UBAMessages, UBACore, VAUtils; procedure RemoveOrderFromDxList(thisOrderID: string); { This routine written for CQ4589. Called from fOrdersDC.ExecuteDCOrders(). } var i: integer; begin if tempDxList.Count > 0 then for i := 0 to tempDxList.Count-1 do if tempDxNodeExists(thisOrderID) then if ((TBADxRecord(tempDxList[i]).FOrderID = thisOrderID) and (tempDxList[i] <> nil)) then begin //tempDxList.Items[i] := nil; //remove reference to this item, effectively deleting it from the list (see Delphi help) BACopiedOrderFlags.Clear; UBAGlobals.SourceOrderID := ''; UBAGlobals.TargetOrderID := ''; tempDxList.Delete(i); //remove this item from the CIDC Dx list end; end; procedure ResetOrderID(fromID: string; toID: string); var i: integer; begin for i := 0 to tempDxList.Count-1 do begin if TBADxRecord(tempDxList[i]).FOrderID = fromID then TBADxRecord(tempDxList[i]).FOrderID := toID; end; end; function GetTFCIForOrder(thisIndex: integer) : string; { Retrieve BA flags for 'thisOrderID', and convert them to CPRS type uSignItems.StsChar array. } begin Result := BACopiedOrderFlags[thisIndex]; end; procedure CopyTFCIToTargetOrder(thisTargetOrderID: string; thisCheckBoxStatus: string); var i: integer; begin for i := 0 to tempDxList.Count - 1 do if TBADxRecord(tempDxList[i]).FOrderID = thisTargetOrderID then TBADxRecord(tempDxList[i]).FTreatmentFactors := thisCheckBoxStatus; end; procedure BACopyOrder(sourceOrderList: TStringList); begin { Removed, no longer used } end; procedure CopyTreatmentFactorsDxsToCopiedOrder(pSourceOrderID:string; pTargetOrderID:string); { BAPHII 1.3.2 } var sourceOrderList: TStringList; sourceOrderID: TStringList; targetOrderIDLst: TStringList; begin //Retrieve TF's/CI's from SOURCE Order sourceOrderList := TStringList.Create; targetOrderIDLst := TStringList.Create; sourceOrderList.Clear; targetOrderIDLst.Clear; sourceOrderID := TStringList.Create; sourceOrderID.Clear; sourceOrderID.Add(Piece(pSourceOrderID, ';', 1)); targetOrderIDLst.Add(pTargetOrderID); { if targetORderID is not billable do not create entry in BADXRecord - List fix HDS00003130} rpcNonBillableOrders(targetOrderIDLst); if IsOrderBillable(pTargetOrderID) then begin tCallV(sourceOrderList, 'ORWDBA4 GETTFCI', [sourceOrderID]); BACopyOrder(sourceOrderList); end; end; procedure CopyTreatmentFactorsDxsToRenewedOrder; { BAPHII 1.3.2 } var sourceOrderList: TStringList; sourceOrderID: TStringList; targetOrderList: TStringList; begin //Retrieve TF's/CI's from SOURCE Order sourceOrderList := TStringList.Create; sourceOrderList.Clear; sourceOrderID := TStringList.Create; sourceOrderID.Clear; targetOrderList := TStringList.Create; targetOrderList.Clear; sourceOrderID.Add(Piece(UBAGlobals.sourceOrderID, ';', 1)); { if targetORderID is not billable do not create entry in BADXRecord - List fix HDS00003130} rpcNonBillableOrders(targetOrderList); if IsOrderBillable(UBAGLobals.TargetOrderID) then begin tCallV(sourceOrderList, 'ORWDBA4 GETTFCI', [sourceOrderID]); BACopyOrder(sourceOrderList); //BAPHII 1.3.2 end; end; procedure PutBADxListForOrder(var thisRecord: TBADxRecord; thisOrderID: string); { //existingRecord //targetOrderID } var i: integer; thisRec: TBADxRecord; begin if UBAGlobals.tempDxNodeExists(thisOrderID) then begin if Assigned(tempDxList) then try for i := 0 to (tempDxList.Count - 1) do begin thisRec := TBADxRecord(tempDxList.Items[i]); if Assigned(thisRec) then if (thisRec.FOrderID = thisOrderID) then begin thisRec.FBADxCode := thisRecord.FBADxCode; thisRec.FBASecDx1 := thisRecord.FBASecDx1; thisRec.FBASecDx2 := thisRecord.FBASecDx2; thisRec.FBASecDx3 := thisRecord.FBASecDx3; thisRec.FTreatmentFactors := thisRecord.FTreatmentFactors; end; end; except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.PutBADxListForOrder()');{$endif} raise; end; end; end; end; procedure CopyDxRecord(sourceOrderID: string; targetOrderID: string); { BAPHII 1.3.1 Copy contents of one TBADxRecord to another. If target record does NOT exist, then add it to the Dx list. If target record DOES exist, then change its contents to those of source record. } var thisRecord: TBADxRecord; thatRecord: TBADxRecord; billingInfo: TstringList; orderList: TStringList; begin thisRecord := TBADxRecord.Create; thatRecord := TBADxRecord.Create; billingInfo := TStringList.Create; orderList := TStringList.Create; if Assigned(billingInfo) then billingInfo.Clear; if Assigned(orderList) then orderList.Clear; if tempDxNodeExists(sourceOrderID) then GetBADxListForOrder(thisRecord, sourceOrderID); //load data from source if not tempDxNodeExists(targetOrderID) then begin SimpleAddTempDxList(targetOrderID); orderList.Add(sourceOrderID); billingInfo := rpcRetrieveSelectedOrderInfo(orderList); if billingInfo.Count > 0 then begin thisRecord.FBADxCode := Piece(billingInfo.Strings[0],U,4) + U + Piece(billingInfo.Strings[0],U,3); thisRecord.FBASecDx1 := Piece(billingInfo.Strings[0],U,6) + U + Piece(billingInfo.Strings[0],U,5); thisRecord.FBASecDx2 := Piece(billingInfo.Strings[0],U,8) + U + Piece(billingInfo.Strings[0],U,7); thisRecord.FBASecDx3 := Piece(billingInfo.Strings[0],U,10) + U + Piece(billingInfo.Strings[0],U,9); if thisRecord.FBADxCode = CARET then thisRecord.FBADxCode := DXREC_INIT_FIELD_VAL; if thisRecord.FBASecDx1 = CARET then thisRecord.FBASecDx1 := DXREC_INIT_FIELD_VAL ; if thisRecord.FBASecDx2 = CARET then thisRecord.FBASecDx2 := DXREC_INIT_FIELD_VAL ; if thisRecord.FBASecDx3 = CARET then thisRecord.FBASecDx3 := DXREC_INIT_FIELD_VAL ; end else PutBADxListForOrder(thisRecord, targetOrderID); //copy source data to temporary record with thatRecord do begin FOrderID := targetOrderID; FBADxCode := thisRecord.FBADxCode; FBASecDx1 := thisRecord.FBASecDx1; FBASecDx2 := thisRecord.FBASecDx2; FBASecDx3 := thisRecord.FBASecDx3; PutBADxListForOrder(thatRecord, targetOrderID); end; end; end; function GetPrimaryDx(thisOrderID: string) : string; { BAPHII 1.3.1 } var retVal: TBADxRecord; begin retVal := TBADxRecord.Create; GetBADxListForOrder(retVal, thisOrderID); Result := retVal.FBADxCode; end; function AllSelectedDxBlank(const Caller: smallint) : boolean; { var i: smallint; selectedOrderID: string; } begin Result := true; case Caller of F_ORDERS_SIGN: begin try { Removed, no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.AllSelectedDxBlank() - F_ORDERS_SIGN');{$endif} raise; end; end; end; F_REVIEW: begin try { Removed, no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.AllSelectedDxBlank() - F_REVIEW');{$endif} raise; end; end; end; end; //case end; function GetDxNodeIndex(thisOrderID: string) : smallint; var i: integer; thisRec: TBADxRecord; begin Result := 0; if Assigned(tempDxList) then try for i := 0 to (tempDxList.Count - 1) do begin thisRec := TBADxRecord(tempDxList.Items[i]); if Assigned(thisRec) then if (thisRec.FOrderID = thisOrderID) then Result := i; end; except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.GetDxNodeIndex()');{$endif} raise; end; end; end; function DiagnosesMatch(var List1: TStringList; var List2: TStringList) : boolean; var i: smallint; begin Result := false; // If the number of Dx's in the lists differs, then bail if (List1.Count <> List2.Count) then begin Result := false; Exit; end; List1.Sort; List2.Sort; try for i := 0 to (List1.Count - 1) do if (List1.Strings[i] <> List2.Strings[i]) then Result := false else Result := true; except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.DiagnosesMatch()');{$endif} raise; end; end; end; function CountSelectedOrders(const Caller: smallint) : smallint; var //i: integer; selectedOrders: smallint; begin selectedOrders := 0; // How many orders selected? case Caller of F_ORDERS_SIGN: begin try { Removed, no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.CountSelectedOrders() - F_ORDERS_SIGN');{$endif} raise; end; end; end; F_REVIEW: begin try { Removed no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.CountSelectedOrders() - F_REVIEW');{$endif} raise; end; end; end; end; //case Result := selectedOrders; end; function CompareOrderDx(const Caller: smallint) : boolean; var //i: integer; firstSelectedID: string; //thisOrderID: string; firstDxRec: TBADxRecord; //compareDxRec: TBADxRecord; thisStringList: TStringList; thatStringList: TStringList; begin Result := false; firstSelectedID := ''; firstDxRec := nil; firstDxRec := TBADxRecord.Create; thisStringList := TStringList.Create; thisStringList.Clear; thatStringList := TStringList.Create; thatStringList.Clear; case Caller of F_ORDERS_SIGN: begin try { Removed, no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.CompareOrderDx() - F_ORDERS_SIGN');{$endif} raise; end; end; end; F_REVIEW: begin try { Removed, no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.CompareOrderDx() - F_REVIEW');{$endif} raise; end; end; end; end; //case firstDxRec := TBADxRecord.Create; InitializeNewDxRec(firstDxRec); GetBADxListForOrder(firstDxRec, firstSelectedID); // first string to compare thisStringList.Add(firstDxRec.FBADxCode); thisStringList.Add(firstDxRec.FBASecDx1); thisStringList.Add(firstDxRec.FBASecDx2); thisStringList.Add(firstDxRec.FBASecDx3); case Caller of F_ORDERS_SIGN: begin try { Removed, no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.CompareOrderDx() - F_ORDERS_SIGN');{$endif} raise; end; end; end; F_REVIEW: begin try { Removed, no longer used with this form } except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.CompareOrderDx() - F_REVIEW');{$endif} raise; end; end; end; end; //case if Assigned(thisStringList) then FreeAndNil(thisStringList); if Assigned(thatStringList) then FreeAndNil(thatStringList); end; procedure GetBADxListForOrder(var thisRetVal: TBADxRecord; thisOrderID: string); var i: integer; thisRec: TBADxRecord; begin if UBAGlobals.tempDxNodeExists(thisOrderID) then begin if Assigned(tempDxList) then for i := 0 to (tempDxList.Count - 1) do begin thisRec := TBADxRecord(tempDxList.Items[i]); if Assigned(thisRec) then if (thisRec.FOrderID = thisOrderID) then begin with thisRetVal do begin FOrderID := thisRec.FOrderID; FBADxCode := StringReplace(thisrec.FBADxCode,'^',':',[rfReplaceAll]); FBASecDx1 := StringReplace(thisrec.FBASecDx1,'^',':',[rfReplaceAll]); FBASecDx2 := StringReplace(thisrec.FBASecDx2,'^',':',[rfReplaceAll]);; FBASecDx3 := StringReplace(thisrec.FBASecDx3,'^',':',[rfReplaceAll]); end; end; end; end; end; procedure DestroyDxList; var i: integer; begin if Assigned(tempDxList) then for i := 0 to pred(UBAGlobals.tempDxList.Count) do TObject(tempDxList[i]).Free; tempDxList := nil; FreeAndNil(tempDxList); end; procedure SimpleAddTempDxList(thisOrderID: string); var tempDxRec: TBADxRecord; begin frmBALocalDiagnoses.LoadTempRec(tempDxRec, thisOrderID); UBAGlobals.tempDxList.Add(TBADxRecord(tempDxRec)); end; procedure SetBADxList; var i: smallint; begin if not Assigned(UBAGlobals.tempDxList) then begin UBAGlobals.tempDxList := TList.Create; UBAGlobals.tempDxList.Count := 0; end else begin //Kill the old Dx list for i := 0 to pred(UBAGlobals.tempDxList.Count) do TObject(UBAGlobals.tempDxList[i]).Free; UBAGlobals.tempDxList := nil; //Create new Dx list for newly selected patient if not Assigned(UBAGlobals.tempDxList) then begin UBAGlobals.tempDxList := TList.Create; UBAGlobals.tempDxList.Count := 0; end; end; end; procedure SetBADxListForOrder(thisRec: TBADxRecord; thisOrderID: string); var i: integer; foundRec: TBADxRecord; begin if UBAGlobals.tempDxNodeExists(thisOrderID) then begin foundRec := TBADxRecord.Create; if Assigned(tempDxList) then try for i := 0 to (tempDxList.Count - 1) do begin foundRec := TBADxRecord(tempDxList.Items[i]); if Assigned(thisRec) then if (thisOrderID = foundRec.FOrderID) then begin with foundRec do begin FOrderID := thisRec.FOrderID; FBADxCode := thisRec.FBADxCode; FBASecDx1 := thisRec.FBASecDx1; FBASecDx2 := thisRec.FBASecDx2; FBASecDx3 := thisRec.FBASecDx3; PutBADxListForOrder(foundRec, thisOrderID); end; Break; end; end; except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.SetBADxListForOrder()');{$endif} raise; end; end; end; end; function SecondaryDxFull(thisOrderID: string) : boolean; var i: integer; thisRec: TBADxRecord; begin Result := false; try for i := 0 to tempDxList.Count - 1 do begin thisRec := TBADxRecord(tempDxList.Items[i]); if Assigned(thisRec) then if thisRec.FOrderID = thisOrderID then begin if (thisRec.FBADxCode <> UBAConst.DXREC_INIT_FIELD_VAL) then if (thisRec.FBASecDx1 <> UBAConst.DXREC_INIT_FIELD_VAL) then if (thisRec.FBASecDx2 <> UBAConst.DXREC_INIT_FIELD_VAL) then if (thisRec.FBASecDx3 <> UBAConst.DXREC_INIT_FIELD_VAL) then Result := true; end; end; except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.SecondaryDxFull()');{$endif} raise; end; end; end; procedure AddSecondaryDx(thisOrderID: string; thisDxCode: string); // Add a Secondary Dx to the first open slot in DxRec, if there IS an open slot var thisRec: TBADxRecord; i: integer; begin try for i := 0 to tempDxList.Count - 1 do begin thisRec := TBADxRecord(tempDxList.Items[i]); if thisRec.FOrderID = thisOrderID then begin if (thisRec.FBASecDx1 = UBAConst.DXREC_INIT_FIELD_VAL) then thisRec.FBASecDx1 := thisDxCode else if (thisRec.FBASecDx2 = UBAConst.DXREC_INIT_FIELD_VAL) then thisRec.FBASecDx2 := thisDxCode else if (thisRec.FBASecDx3 = UBAConst.DXREC_INIT_FIELD_VAL) then thisRec.FBASecDx3 := thisDxCode; end end; except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.AddSecondaryDx()');{$endif} raise; end; end; end; procedure InitializeConsultOrderRec(var thisDxRec: TBAConsultOrderRec); begin with thisDxRec do begin FBAOrderID := UBAConst.DXREC_INIT_FIELD_VAL; FBADxCode := UBAConst.DXREC_INIT_FIELD_VAL; FBASecDx1 := UBAConst.DXREC_INIT_FIELD_VAL; FBASecDx2 := UBAConst.DXREC_INIT_FIELD_VAL; FBASecDx3 := UBAConst.DXREC_INIT_FIELD_VAL; FBATreatmentFactors:= UBAConst.DXREC_INIT_FIELD_VAL; end; end; procedure InitializeNewDxRec(var thisDxRec: TBADxRecord); begin with thisDxRec do begin FExistingRecordID := UBAConst.DXREC_INIT_FIELD_VAL; FOrderID := UBAConst.DXREC_INIT_FIELD_VAL; FBADxCode := UBAConst.DXREC_INIT_FIELD_VAL; FBASecDx1 := UBAConst.DXREC_INIT_FIELD_VAL; FBASecDx2 := UBAConst.DXREC_INIT_FIELD_VAL; FBASecDx3 := UBAConst.DXREC_INIT_FIELD_VAL; end; end; procedure InitializeUnsignedOrderRec(var thisUnsignedRec: TBAUnsignedBillingRec); begin with thisUnsignedRec do begin FBAOrderID := UNSIGNED_REC_INIT_FIELD_VAL; FBASTSFlags := UNSIGNED_REC_INIT_FIELD_VAL; FBADxCode := UNSIGNED_REC_INIT_FIELD_VAL; FBASecDx1 := UNSIGNED_REC_INIT_FIELD_VAL; FBASecDx2 := UNSIGNED_REC_INIT_FIELD_VAL; FBASecDx3 := UNSIGNED_REC_INIT_FIELD_VAL; end; end; procedure InitializeTFactorsInRec(var thisTFactorsRecIn: TBATreatmentFactorsInRec); begin with thisTFactorsRecIn do begin FBAOrderID := UNSIGNED_REC_INIT_FIELD_VAL; FBAEligible := UNSIGNED_REC_INIT_FIELD_VAL; FBATFactors := UNSIGNED_REC_INIT_FIELD_VAL; end; end; constructor TBAGlobals.Create; begin inherited Create; end; // This procedure is called from uPCE.pas only -- do not delete..... procedure TBAGlobals.AddBAPCEDiag(DiagStr:string); begin if (BAPCEDiagList.Count <= 0) then BAPCEDiagList.Add('^Encounter Diagnoses'); BAPCEDiagList.Add(DiagStr); end; procedure TBAGlobals.ClearBAPCEDiagList; begin BAPCEDiagList.Clear; end; constructor TBAPLRec.Create; begin inherited Create; end; function TBAPLRec.BuildProblemListDxEntry(pDxCode:string): TStringList; // StringList used to store DX Codes selected from Encounter Form var BADxIEN: string; BAProviderStr, BAProviderName : string; AList: TStringList; begin // Build Problem List record to be saved for selection. PLlist := TStringList.Create; AList := TStringList.Create; AList.Clear; PLlist.Clear; BALocation := Encounter.Location; BAProviderStr := IntToStr(Encounter.Provider); BAProviderName := Encounter.ProviderName; BADxIEN := sCallV('ORWDBA7 GETIEN9', [Piece(pDxCode,U,1)]); BAPLPt.LoadPatientParams(AList); //BAPLPt.PtVAMC PLlist.Add('GMPFLD(.01)='+'"' +BADxIEN+ '^'+Piece(pDxCode,U,1)+'"'); PLlist.Add('GMPFLD(.03)=' +'"'+'0^' +'"'); PLlist.Add('GMPFLD(.05)=' + '"' +'^'+Piece(pDxCode,U,2)+ '"'); PLlist.Add('GMPFLD(.08)=' + '"'+ '^'+FloatToStr(FMToday)+'"'); PLlist.Add('GMPFLD(.12)=' + '"' + 'A^ACTIVE'+ '"'); PLlist.Add('GMPFLD(.13)=' + '"' + '^'+ '"'); PLlist.Add('GMPFLD(1.01)=' + '"'+ Piece(pDxCode,U,2) + '"'); PLlist.Add('GMPFLD(1.02)=' + '"'+'P' + '"'); PLlist.Add('GMPFLD(1.03)=' + '"'+ BAProviderStr + '^'+ BAProviderName + '"'); PLlist.Add('GMPFLD(1.04)=' + '"'+ BAProviderStr + '^' + BAProviderName + '"'); PLlist.Add('GMPFLD(1.05)=' + '"'+ BAProviderStr + '^' + BAProviderName + '"'); PLlist.Add('GMPFLD(1.08)=' +'"' + IntToStr(BALocation) + '^' + Encounter.LocationName + '"'); PLlist.Add('GMPFLD(1.09)=' + '"'+ FloatToStr(FMToday) +'"'); PLlist.Add('GMPFLD(10,0)=' + '"'+'0'+ '"'); Result := PLlist; end; function TBAPLRec.FMToDateTime(FMDateTime: string): TDateTime; var x, Year: string; begin { Note: TDateTime cannot store month only or year only dates } x := FMDateTime + '0000000'; if Length(x) > 12 then x := Copy(x, 1, 12); if StrToInt(Copy(x, 9, 4)) > 2359 then x := Copy(x, 1, 7) + '.2359'; Year := IntToStr(17 + StrToInt(Copy(x,1,1))) + Copy(x,2,2); x := Copy(x,4,2) + '/' + Copy(x,6,2) + '/' + Year + ' ' + Copy(x,9,2) + ':' + Copy(x,11,2); Result := StrToDateTime(x); end; {-------------------------- TPLPt Class ----------------------} constructor TBAPLPT.Create(Alist:TStringList); var i: integer; begin for i := 0 to AList.Count - 1 do case i of 0: PtVAMC := Copy(Alist[i], 1, 999); 1: PtDead := Alist[i]; 2: PtServiceConnected := (Alist[i] = '1'); 3: PtAgentOrange := (Alist[i] = '1'); 4: PtRadiation := (Alist[i] = '1'); 5: PtEnvironmental := (Alist[i] = '1'); 6: PtBid := Alist[i]; 7: PtHNC := (Alist[i] = '1'); 8: PtMST := (Alist[i] = '1'); 9: PtSHAD := (Alist[i] = '1'); 10: PtCL := (Alist[i] = '1'); end; end; function TBAPLPt.GetGMPDFN(dfn:string;name:string):string; begin Result := dfn + u + name + u + PtBID + u + PtDead; end; procedure TBAPLPt.LoadPatientParams(AList:TstringList); begin FastAssign(rpcInitPt(Patient.DFN), AList); BAPLPt := TBAPLPt.create(Alist); end; function TBAPLPt.rpcInitPt(const PatientDFN: string): TStrings ; //*DFN* begin CallV('ORQQPL INIT PT',[PatientDFN]); Result := RPCBrokerV.Results; end ; function tempDxNodeExists(thisOrderID: string) : boolean; // Returns true if a node with the specified Order ID exists, false otherwise. var i: integer; thisRec: TBADxRecord; begin Result := false; if Assigned(tempDxList) then try for i := 0 to (tempDxList.Count - 1) do begin thisRec := TBADxRecord(tempDxList.Items[i]); if Assigned(thisRec) then if (thisRec.FOrderID = thisOrderID) then begin Result := true; Break; end; end; except on EListError do begin {$ifdef debug}ShowMsg('EListError in UBAGlobals.tempDxNodeExists()');{$endif} raise; end; end; end; // HDS00003380 function IsUserNurseProvider(pUserID: int64):boolean; begin Result := False; if BILLING_AWARE then begin if (pUserID <> 0) and PersonHasKey(pUserID, 'PROVIDER') then if (uCore.User.OrderRole = OR_NURSE) then Result := True; end; end; function GetPatientTFactors(pOrderList:TStringList):String; begin Result := ''; Result := sCallV('ORWDBA1 SCLST',[Patient.DFN,pOrderList]); end; Initialization BAPrimaryDxChanged := False; BAFWarningShown := False; BAPersonalDX := False; BAHoldPrimaryDx := DXREC_INIT_FIELD_VAL; NonBillableOrderList := TStringList.Create; BAPCEDiagList := TStringList.Create; OrderListSCEI := TStringList.Create; BAOrderList := TStringList.Create; UnSignedOrders := TStringList.Create; BAOrderIDList := TStringList.Create; BAUnSignedOrders := TStringList.Create; BATFHints := TStringList.Create; BAFactorsRec := TBAFactorsRec.Create; BAFactorsInRec := TBATreatmentFactorsInRec.Create; BASelectedList := TStringList.Create; PLFactorsIndexes := TStringList.Create; BAtmpOrderList := TStringList.Create; BACopiedOrderFlags := TStringList.Create; //BAPHII 1.3.2 OrderIDList := TStringList.Create; BAConsultDxList := TStringList.Create; BAConsultPLFlags := TStringList.Create; BANurseConsultOrders := TStringList.Create; BADeltedOrders := TStringList.Create; BAConsultDxList.Clear; NonBillableOrderList.Clear; OrderListSCEI.Clear; UnSignedOrders.Clear; BAOrderIDList.Clear; BAUnSignedOrders.Clear; BATFHints.Clear; PLFactorsIndexes.Clear; BASelectedList.Clear; BAtmpOrderList.Clear; OrderIDList.Clear; BAConsultPLFlags.Clear; BAPCEDiagList.Clear; BANurseConsultOrders.Clear; BADeltedOrders.Clear; end.
unit UntSmServicos; interface uses System.Classes, System.JSON, System.JSON.Readers, System.JSON.Types, System.NetEncoding, Web.HTTPApp, Datasnap.DSHTTPWebBroker, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Stan.StorageJSON, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.DB, Data.DBXPlatform, UntSrvMetodosGerais, ULGTDataSetHelper, Restaurantes.Utils, //Classe de conexão Restaurantes.Servidor.Connection; type {$MethodInfo ON} TSmServicos = class(TDataModule) qryExportar: TFDQuery; qryAuxiliar: TFDQuery; private { Private declarations } public { Public declarations } {Estabelecimentos} function Estabelecimentos(const AID: string): TJSONArray; //Get - SELECT function AcceptEstabelecimentos(const AID : string): TJSONArray; //Put - UPDATE TABELA function UpdateEstabelecimentos : TJSONArray; //Post - INSERT INTO function CancelEstabelecimentos (const AID : string): TJSONArray; //Delete - DELETE {Categorias} function Categorias(const AEstabelecimento: string): TJSONArray; //Get function AcceptCategorias(const AID: Integer): TJSONArray; //Put function UpdateCategorias: TJSONArray; //Post function CancelCategorias(const AID: string): TJSONArray; //Delete {Cardapios} function Cardapios(const ACategoria, AEstabelecimento: string): TJSONArray; //Get function AcceptCardapios(const AID: string) : TJSONArray; //Put function UpdateCardapios: TJSONArray; //Post function CancelCardapios(const AID: string): TJSONArray; //Delete {Pedidos} function Pedidos(const AUsuario: Integer; APedidoMobile: Integer = 0): TJSONArray; //Get - SELECT function AcceptPedidos(const AID_Usuario, AID_Pedido_Mobile: Integer; AEstabelecimento: String = 'N'): TJSONArray; //Put - UPDATE TABELA function UpdatePedidos: TJSONArray; //Post - INSERT INTO function AtualizarStatus(const AUsuario: Integer): TJSONArray; function ItensPedido(const AIDPedido, AIDEstabelecimento: Integer): TJSONArray; end; {$MethodInfo OFF} var SmServicos: TSmServicos; implementation uses System.SysUtils; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TsmEstabelecimentos } function TSmServicos.AcceptCategorias(const AID: Integer): TJSONArray; begin end; function TSmServicos.AcceptCardapios(const AID: string): TJSONArray; begin end; function TSmServicos.AcceptEstabelecimentos (const AId : string): TJSONArray; var lModulo : TWebmodule; lJARequisicao : TJSONArray; lJObj : TJSONObject; lSR : TStringReader; lJR : TJsonTextReader; lFields : TStringList; lValues : TStringList; lUpdate : TStringList; lLinha : TStringBuilder; I : Integer; J : Integer; lRows : integer; lInStream : TStringStream; lOutStream : TMemoryStream; lImagem64 : TStringList; begin //Result := 'PUT - Delphi'; lModulo := GetDataSnapWebModule; if (lModulo.Request.Content.IsEmpty) or (aID.IsEmpty) then begin GetInvocationMetadata().ResponseCode := 204; Abort end; lJARequisicao := TJSONObject.ParseJSONValue( TEncoding.ASCII.GetBytes(lModulo.Request.Content), 0) as TJSONArray; Result := TJSONArray.Create; lJObj := TJSONObject.Create; lUpdate := TStringList.Create; lFields := TStringList.Create; lValues := TStringList.Create; lLinha := TStringBuilder.Create; lImagem64 := TStringList.Create; lRows := 0; try qryExportar.Connection := TConexaoDados.Connection; for I := 0 to lJARequisicao.Count -1 do begin lSR := TStringReader.Create(lJARequisicao.Items[i].ToJSON); lJR := TJsonTextReader.Create(lSR); lLinha.Clear; lFields.Clear; lValues.Clear; lLinha.Append('UPDATE CURSO.ESTABELECIMENTOS SET '); while lJR.Read do begin if lJR.TokenType = TJsonToken.PropertyName then begin if not lJR.Value.ToString.IsEmpty then begin if lFields.IndexOf(lJR.Value.ToString) = -1 then lFields.Append(lJR.Value.ToString); lJR.Read; if lJR.TokenType in [TJsonToken.String, TJsonToken.Date] then //System.JSON.Types; begin if lJR.TokenType = TJsonToken.Date then lValues.Append(QuotedStr(FormatDateTime('dd.mm.yyyy', StrToDate(lJR.Value.ToString)))) else if UpperCase(lJR.Value.ToString) <> 'NULL' then lValues.Append(QuotedStr(lJR.Value.ToString)) else lValues.Append(lJR.Value.ToString); end else lValues.Append(lJR.Value.ToString.Replace(',','.')); end; end; end; for J := 0 to lFields.Count -1 do begin if not lFields[j].IsEmpty then begin if LowerCase(lFields[j]) = 'foto_logotipo' then begin lImagem64.Add(lValues[j]); lValues[j] := ':PIMAGEM'; end; if j <> lFields.Count -1 then lLinha.Append(lFields[j] + ' = ' + lValues[j] + ', ') else lLinha.Append(lFields[j] + ' = ' + lValues[j]); end; end; lLinha.Append(' WHERE ID = :PID'); lUpdate.Append(lLinha.ToString+';'); end; TConexaoDados.Connection.TxOptions.AutoCommit := False; if not TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.StartTransaction; try for I := 0 to Pred(lUpdate.Count) do begin lInStream := TStringStream.Create(lImagem64[i]); lInStream.Position := 0; lOutStream := TMemoryStream.Create; TNetEncoding.Base64.Decode(lInStream, lOutStream); lOutStream.Position := 0; qryExportar.SQL.Clear; qryExportar.SQL.Append(lUpdate[I]); qryExportar.Params.CreateParam(ftInteger, 'PID', ptInput); qryExportar.ParamByName('PID').AsInteger := aId.ToInteger(); qryExportar.Params.CREATEPARAM(ftBlob, 'PIMAGEM', ptInput); qryExportar.ParamByName('pImagem').LoadFromStream(lOutStream, ftBlob); //qryExportar.SQL.SaveToFile('accept.txt'); lRows := qryExportar.ExecSQL(lUpdate[I]); lJObj.AddPair('Linhas afetadas', TJSONNumber.Create(lRows)); lInStream.Free; lOutStream.Free; end; if TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.CommitRetaining; TConexaoDados.Connection.TxOptions.AutoCommit := True; Result.AddElement(lJObj); if lRows > 0 then GetInvocationMetadata().ResponseCode := 200 else GetInvocationMetadata().ResponseCode := 204; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToJSON); except on E: Exception do begin TConexaoDados.Connection.Rollback; raise end; end; finally lUpdate.Free; lFields.Free; lValues.Free; lLinha.Free; lJR.Free; lSR.Free; end; end; function TSmServicos.AcceptPedidos(const AID_Usuario, AID_Pedido_Mobile: Integer; AEstabelecimento: String = 'N'): TJSONArray; const SQL_PEDIDO = 'SELECT ID, STATUS FROM CURSO.PEDIDOS ' + 'WHERE ' + ' ID_USUARIO = :PID_USUARIO ' + ' AND ID_PEDIDO_MOBILE = :PID_PEDIDO_MOBILE '; UPD_PEDIDO = 'UPDATE CURSO.PEDIDOS ' + 'SET ' + ' ID_USUARIO = :PID_USUARIO , ' + ' ID_ESTABELECIMENTO = :PID_ESTABELECIMENTO , ' + ' DATA = :PDATA , ' + ' STATUS = :PSTATUS , ' + ' VALOR_PEDIDO = :PVALOR_PEDIDO , ' + ' ID_PEDIDO_MOBILE = :PID_PEDIDO_MOBILE ' + 'WHERE ' + ' ID_USUARIO = :PID_USUARIO ' + ' AND ID_PEDIDO_MOBILE = :PID_PEDIDO_MOBILE '; SQL_ITEM_PEDIDO = 'SELECT ID FROM CURSO.ITENS_PEDIDO ' + 'WHERE ' + ' ID_PEDIDO_MOBILE = :PID_PEDIDO_MOBILE ' + ' AND ID_USUARIO = :PID_USUARIO ' + ' AND ID_ITEM_PEDIDO_MOBILE = :PID_ITEM_PEDIDO_MOBILE '; UPD_ITENS_PEDIDO = 'UPDATE CURSO.ITENS_PEDIDO ' + 'SET ' + ' STATUS = :PSTATUS ' + 'WHERE ' + ' ID_PEDIDO_MOBILE = :PID_PEDIDO_MOBILE ' + ' AND ID_USUARIO = :PID_USUARIO ' + ' AND ID_ITEM_PEDIDO_MOBILE = :PID_ITEM_PEDIDO_MOBILE '; INS_ITENS_PEDIDO = 'INSERT INTO CURSO.ITENS_PEDIDO ' + '( ' + ' ID_PEDIDO , ' + ' QTDE , ' + ' VALOR_UNITARIO , ' + ' ID_CARDAPIO , ' + ' ID_PEDIDO_MOBILE , ' + ' STATUS , ' + ' ID_ITEM_PEDIDO_MOBILE , ' + ' ID_USUARIO ' + ') ' + 'VALUES ' + '( ' + ' :PID_PEDIDO , ' + ' :PQTDE , ' + ' :PVALOR_UNITARIO , ' + ' :PID_CARDAPIO , ' + ' :PID_PEDIDO_MOBILE , ' + ' :PSTATUS , ' + ' :PID_ITEM_PEDIDO_MOBILE , ' + ' :PID_USUARIO ' + '); '; var lModulo : TWebModule; lJARequisicao : TJSONArray; LValores : TJSONValue; jPedido : TJSONValue; jItens : TJSONValue; lJOBJ : TJSONObject; //Pedidos iID_Pedido_Servidor : Integer; iId_Estabelecimento : Integer; dData : TDateTime; fValor_Pedido : Double; sStatus : String; //Itens pedido iQtde : Integer; fValor_Unitario : Double; iId_Cardapio : Integer; iID_Item_Pedido_Mobile : Integer; sStatus_Item : string; //Auxiliares I : Integer; J : Integer; arrItens : Integer; begin lModulo := GetDataSnapWebModule; if lModulo.Request.Content.IsEmpty then begin GetInvocationMetaData().ResponseCode := 204; Abort; end; lJARequisicao := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lModulo.Request.Content), 0) as TJSONArray; try try qryAuxiliar.Connection := TConexaoDados.Connection; qryExportar.Connection := TConexaoDados.Connection; TConexaoDados.Connection.TxOptions.AutoCommit := False; if not TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.StartTransaction; for LVAlores in lJARequisicao do begin jPedido := LValores.GetValue<TJSONArray>('pedido'); for I := 0 to Pred((jPedido as TJSONArray).Count) do begin iId_Estabelecimento := (jPedido as TJSONArray).Items[I].GetValue<integer>('id_estabelecimento'); dData := StrToDateTime((jPedido as TJSONArray).Items[I].GetValue<string>('data')); fValor_Pedido := (jPedido as TJSONArray).Items[I].GetValue<double>('valor_pedido'); sStatus := (jPedido as TJSONArray).Items[I].GetValue<string>('status_pedido'); //Resgatar o ID do Pedido Atual - Alterado qryAuxiliar.Active := False; qryAuxiliar.SQL.Clear; qryAuxiliar.SQL.Text := SQL_PEDIDO; qryAuxiliar.ParamByName('PID_USUARIO').AsIntegers[0] := AID_Usuario; qryAuxiliar.ParamByName('PID_PEDIDO_MOBILE').AsIntegers[0] := AID_Pedido_Mobile; qryAuxiliar.Active := True; iID_Pedido_Servidor := qryAuxiliar.FieldByName('ID').AsInteger; if (qryAuxiliar.FieldByName('STATUS').AsString[1] in ['P', 'M', 'F', 'C', 'X']) and not (AEstabelecimento.Equals('S')) then begin lJOBJ := TJSONObject.Create; lJOBJ.AddPair('Mensagem', 'O pedido não pôde ser alterado. Consulte o estabelecimento!'); Result := TJSONArray.Create; Result.AddElement(lJOBJ); GetInvocationMetaData().ResponseCode := 202; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToJSON()); TConexaoDados.Connection.Rollback; exit; end; //A = ABERTO (NÃO ENVIADO DO CLIENTE PARA O SERVIDOR) //G = AGUARDANDO (AGUARDANDO QUALQUER STATUS) //E = ENVIADO (CLIENTE PARA SERVIDOR) //R = RECEBIDO (RECEBIDO NO RESTAURANTE) //P = PREPARO (PREPARANDO NO RESTAURANTE) //M = MOTOBOY (ENVIADO DO RESTAURANTE PARA O CLIENTE) //F = FECHADO (ENTREGUE - O MOTOBOY RETORNOU E DEU BAIXA NO RESTAURANTE) //C = CANCELADO (PELO CLIENTE OU RESTAURANTE) //X = EXCLUÍDO (ITEM DE PEDIDO EXCLUÍDO) qryAuxiliar.Active := False; //Atualização de Pedidos qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Text := UPD_PEDIDO; qryExportar.Params.ArraySize := 1; qryExportar.ParamByName('PID_USUARIO').AsIntegers[0] := AID_Usuario; qryExportar.ParamByName('PID_ESTABELECIMENTO').AsIntegers[0] := iId_Estabelecimento; qryExportar.ParamByName('PDATA').AsDateTimes[0] := dData; qryExportar.ParamByName('PSTATUS').AsStrings[0] := sStatus; qryExportar.ParamByName('PVALOR_PEDIDO').AsFloats[0] := (FormatFloat('###,###,##0.00', fValor_Pedido)).ToDouble(); qryExportar.ParamByName('PID_PEDIDO_MOBILE').AsIntegers[0] := AID_Pedido_Mobile; qryExportar.Execute(1, 0); //Atualiação dos Itens do Pedido (jPedido as TJSONArray).Items[I].TryGetValue('itens', jItens); //jItens := (jPedido as TJSONArray).Items[I].GetValue<TJSONArray>('itens'); if Assigned(jItens) then begin arrItens := (jItens as TJSONArray).Count; for J := 0 to Pred((jItens as TJSONArray).Count) do begin iQtde := (jItens as TJSONArray).Items[J].GetValue<integer>('qtde'); fValor_Unitario := (FormatFloat('###,###,##0.00', (jItens as TJSONArray).Items[J].GetValue<double>('valor_unitario'))).ToDouble(); iId_Cardapio := (jItens as TJSONArray).Items[J].GetValue<integer>('id_cardapio'); sStatus_Item := (jItens as TJSONArray).Items[J].GetValue<string>('status_item'); iID_Item_Pedido_Mobile := (jItens as TJSONArray).Items[J].GetValue<integer>('id_item_pedido_mobile'); //Localiza o item na base. Se existir, altera, senão insere qryAuxiliar.Active := False; qryAuxiliar.SQL.Clear; qryAuxiliar.SQL.Text := SQL_ITEM_PEDIDO; qryAuxiliar.ParamByName('PID_PEDIDO_MOBILE').AsIntegers[0] := AID_Pedido_Mobile; qryAuxiliar.ParamByName('PID_USUARIO').AsIntegers[0] := AID_Usuario; qryAuxiliar.ParamByName('PID_ITEM_PEDIDO_MOBILE').AsIntegers[0] := iID_Item_Pedido_Mobile; qryAuxiliar.Active := True; if not qryAuxiliar.IsEmpty then //Se o item FOR encontrado, ou seja, existir....faz o update no banco begin //Update no Item qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Text := UPD_ITENS_PEDIDO; qryExportar.Params.ArraySize := 1; qryExportar.ParamByName('PSTATUS').AsStrings[0] := sStatus_Item; qryExportar.ParamByName('PID_PEDIDO_MOBILE').AsIntegers[0] := AID_Pedido_Mobile; qryExportar.ParamByName('PID_USUARIO').AsIntegers[0] := AID_Usuario; qryExportar.ParamByName('PID_ITEM_PEDIDO_MOBILE').AsIntegers[0] := iID_Item_Pedido_Mobile; qryExportar.Execute(1, 0); end else //Se o item NÃO for encontrado, ou seja, NÃO existir...adiciona o novo registro begin //Insert do Item qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Text := INS_ITENS_PEDIDO; qryExportar.Params.ArraySize := 1; qryExportar.ParamByName('PID_PEDIDO').AsIntegers[0] := iID_Pedido_Servidor; qryExportar.ParamByName('PID_PEDIDO_MOBILE').AsIntegers[0] := AID_Pedido_Mobile; qryExportar.ParamByName('PID_ITEM_PEDIDO_MOBILE').AsIntegers[0] := iID_Item_Pedido_Mobile; qryExportar.ParamByName('PSTATUS').AsStrings[0] := sStatus_Item; qryExportar.ParamByName('PQTDE').AsIntegers[0] := iQtde; qryExportar.ParamByName('PVALOR_UNITARIO').AsFloats[0] := fValor_Unitario; qryExportar.ParamByName('PID_CARDAPIO').AsIntegers[0] := iId_Cardapio; qryExportar.ParamByName('PID_USUARIO').AsIntegers[0] := AID_Usuario; qryExportar.Execute(1, 0); end; end; end; end; end; if TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.CommitRetaining; TConexaoDados.Connection.TxOptions.AutoCommit := True; lJOBJ := TJSONObject.Create; lJOBJ.AddPair('Mensagem', 'Pedido alterado com sucesso!'); Result := TJSONArray.Create; Result.AddElement(lJOBJ); GetInvocationMetaData().ResponseCode := 201; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToJSON()); except on E:Exception do begin TConexaoDados.Connection.Rollback; raise; end; end; finally end; end; function TSmServicos.AtualizarStatus(const AUsuario: Integer): TJSONArray; const _SQL = 'SELECT * FROM CURSO.PEDIDOS WHERE ' + ' STATUS IN ("A", "G", "E", "R", "P", "M") ' + ' AND ID_USUARIO = :PUSUARIO '; begin qryExportar.Connection := TConexaoDados.Connection; qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Add(_SQL); qryExportar.ParamByName('PUSUARIO').AsInteger := AUsuario; qryExportar.Active := True; if qryExportar.IsEmpty then Result := TJSONArray.Create('Mensagem', 'Nenhum pedido encontrado.') else Result := qryExportar.DataSetToJSON; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToString); end; function TSmServicos.CancelCardapios(const AID: string): TJSONArray; begin // end; function TSmServicos.CancelCategorias(const AID: string): TJSONArray; begin // end; function TSmServicos.CancelEstabelecimentos(const AId : string): TJSONArray; const _SQL = 'DELETE FROM ESTABELECIMENTOS WHERE ID = :PID'; var lJob : TJSONObject; lRows : integer; begin //Result := 'DELETE - Delphi'; qryExportar.Connection := TConexaoDados.Connection; Result := TJSONArray.Create; lJob := TJSONObject.Create; lRows := 0; if not AID.IsEmpty then begin qryExportar.SQL.Clear; qryExportar.SQL.Append(_SQL); qryExportar.Params.CreateParam(ftInteger, 'pID', ptInput); qryExportar.ParamByName('pID').AsInteger := AId.ToInteger(); lRows := qryExportar.ExecSQL(_SQL); end else GetInvocationMetadata().ResponseCode := 204; lJob.AddPair('Linhas afetadas', TJSONNumber.Create(lRows)); Result.AddElement(lJob); TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToJSON); end; function TSmServicos.Cardapios(const ACategoria, AEstabelecimento: string): TJSONArray; const _SQL = 'SELECT ' + ' ID , ' + ' ID_ESTABELECIMENTO , ' + ' ID_CATEGORIA , ' + ' NOME , ' + ' INGREDIENTES , ' + ' PRECO ' + 'FROM CURSO.CARDAPIOS ' + 'WHERE ' + ' ID_CATEGORIA = :ID_CATEGORIA AND ' + ' ID_ESTABELECIMENTO = :ID_ESTABELECIMENTO '; begin qryExportar.Connection := TConexaoDados.Connection; qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Text := _SQL; qryExportar.ParamByName('ID_CATEGORIA').AsInteger := ACategoria.ToInteger(); qryExportar.ParamByName('ID_ESTABELECIMENTO').AsInteger := AEstabelecimento.ToInteger(); qryExportar.Active := True; if qryExportar.IsEmpty then Result := TJSONArray.Create('Mensagem', 'Nenhum cardápio encontrado.') else Result := qryExportar.DataSetToJSON; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToString); end; function TSmServicos.Categorias(const AEstabelecimento: string): TJSONArray; const _SQL = 'SELECT ' + ' CI.ID, ' + ' CI.DESCRICAO ' + 'FROM ' + ' CURSO.CATEGORIA_ITEM CI ' + ' INNER JOIN CURSO.CARDAPIOS CA ' + ' ON CA.ID_CATEGORIA = CI.ID ' + 'WHERE ' + ' CA.ID_ESTABELECIMENTO = :ID_ESTABELECIMENTO ' + 'GROUP BY ' + ' CI.DESCRICAO '; begin qryExportar.Connection := TConexaoDados.Connection; qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Text := _SQL; qryExportar.ParamByName('ID_ESTABELECIMENTO').AsInteger := AEstabelecimento.ToInteger(); qryExportar.Active := True; if qryExportar.IsEmpty then Result := TJSONArray.Create('Mensagem', 'Nenhuma categoria encontrada.') else Result := qryExportar.DataSetToJSON; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToString); end; function TSmServicos.Estabelecimentos(const AId : string): TJSONArray; const _SQL = 'SELECT * FROM CURSO.ESTABELECIMENTOS'; begin //Result := 'GET - Delphi' qryExportar.Connection := TConexaoDados.Connection; qryExportar.Close; if AId.IsEmpty then qryExportar.Open(_SQL) else begin qryExportar.SQL.Clear; qryExportar.SQL.Add(_SQL); qryExportar.SQL.Add(' WHERE ID = :PID'); qryExportar.Params.CreateParam(ftInteger, 'PID', ptInput); qryExportar.ParamByName('PID').AsInteger := aId.ToInteger(); qryExportar.Open(); end; if qryExportar.IsEmpty then Result := TJSONArray.Create('Mensagem', 'Nenhum estabelecimento encontrado.') else Result := qryExportar.DataSetToJSON; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToString); end; function TSmServicos.ItensPedido(const AIDPedido, AIDEstabelecimento: Integer): TJSONArray; const _SQL = 'SELECT * FROM ' + ' CURSO.ITENS_PEDIDO IT ' + ' INNER JOIN CURSO.PEDIDOS PE ' + ' ON IT.ID_PEDIDO = PE.ID ' + 'WHERE ' + ' PE.ID = :PID ' + ' AND PE.ID_ESTABELECIMENTO = :PID_ESTABELECIMENTO '; begin //Result := 'GET - Delphi' qryExportar.Connection := TConexaoDados.Connection; qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Add(_SQL); qryExportar.ParamByName('PID').AsInteger := AIDPedido; qryExportar.ParamByName('PID_ESTABELECIMENTO').AsInteger := AIDEstabelecimento; qryExportar.Active := True; if qryExportar.IsEmpty then Result := TJSONArray.Create('Mensagem', 'Nenhum item de pedido encontrado.') else Result := qryExportar.DataSetToJSON; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToString); end; function TSmServicos.Pedidos(const AUsuario: Integer; APedidoMobile: Integer = 0): TJSONArray; const _SQL = 'SELECT * FROM CURSO.PEDIDOS'; begin //Result := 'GET - Delphi' qryExportar.Connection := TConexaoDados.Connection; qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Add(_SQL); qryExportar.SQL.Add(' WHERE ID_USUARIO = :PUSUARIO'); qryExportar.Params.CreateParam(ftInteger, 'PUSUARIO', ptInput); qryExportar.ParamByName('PUSUARIO').AsInteger := AUsuario; if not (APedidoMobile = 0) then begin qryExportar.SQL.Add(' AND '); qryExportar.SQL.Add(' ID_PEDIDO_MOBILE = :PPEDIDO_MOBILE'); qryExportar.Params.CreateParam(ftInteger, 'PPEDIDO_MOBILE', ptInput); qryExportar.ParamByName('PPEDIDO_MOBILE').AsInteger := APedidoMobile; end; qryExportar.Active := True; if qryExportar.IsEmpty then Result := TJSONArray.Create('Mensagem', 'Nenhum pedido encontrado.') else Result := qryExportar.DataSetToJSON; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToString); end; function TSmServicos.UpdateCardapios: TJSONArray; var lModulo : TWebmodule; lJARequisicao : TJSONArray; lJObj : TJSONObject; lSR : TStringReader; lJR : TJsonTextReader; lFields : TStringList; lValues : TStringList; lInsert : TStringList; lLinha : TStringBuilder; I : Integer; J : Integer; lInStream : TStringStream; lOutStream : TMemoryStream; lImagem64 : TStringList; begin //Result := 'POST Delphi'; lModulo := GetDataSnapWebModule; if lModulo.Request.Content.IsEmpty then begin GetInvocationMetadata().ResponseCode := 204; Abort; end; lJARequisicao := TJSONObject.ParseJSONValue( TEncoding.ASCII.GetBytes(lModulo.Request.Content), 0) as TJSONArray; Result := TJSONArray.Create; lJObj := TJSONObject.Create; lInsert := TStringList.Create; lFields := TStringList.Create; lValues := TStringList.Create; lLinha := TStringBuilder.Create; lImagem64 := TStringList.Create; try qryExportar.Connection := TConexaoDados.Connection; for I := 0 to Pred(lJARequisicao.Count) do begin lSR := TStringReader.Create(lJARequisicao.Items[I].ToJSON); lJR := TJsonTextReader.Create(lSR); lLinha.Clear; lFields.Clear; lValues.Clear; lLinha.Append('INSERT INTO CURSO.CARDAPIOS('); //Preenche os Campos while lJR.Read do begin if lJR.TokenType = TJsonToken.PropertyName then begin if not lJR.Value.ToString.IsEmpty then begin if lFields.IndexOf(lJR.Value.ToString) = -1 then lFields.Append(lJR.Value.ToString); lJR.Read; if lJR.TokenType in [TJsonToken.String, TJsonToken.Date] then //System.JSON.Types; begin if lJR.TokenType = TJsonToken.Date then lValues.Append(QuotedStr(FormatDateTime('dd.mm.yyyy',StrToDate(lJR.Value.ToString)))) else if UpperCase(lJR.Value.ToString) <> 'NULL' then lValues.Append(QuotedStr(lJR.Value.ToString)) else lValues.Append(lJR.Value.ToString); end else lValues.Append(lJR.Value.ToString.Replace(',','.')); end; end; end; for J := 0 to Pred(lFields.Count) do begin if not lFields[j].IsEmpty then begin if j <> lFields.Count -1 then lLinha.Append(lFields[j] + ', ') else lLinha.Append(lFields[j]); end; end; lLinha.Append(') VALUES ('); //Preenche os valores for J := 0 to lValues.Count -1 do begin if not lValues[j].IsEmpty then begin if LowerCase(lFields[j]) = 'foto_logotipo' then begin lImagem64.Add(lValues[j]); lValues[j] := ':PIMAGEM'; end; if j <> lValues.Count -1 then lLinha.Append(lValues[j] + ', ') else lLinha.Append(lValues[j]); end; end; lInsert.Append(lLinha.ToString + ');'); end; //Inicia a transação TConexaoDados.Connection.TxOptions.AutoCommit := False; if not TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.StartTransaction; try for I := 0 to Pred(lInsert.Count) do begin //lInStream := TStringStream.Create(lImagem64[i]); //lInStream.Position := 0; //lOutStream := TMemoryStream.Create; //TNetEncoding.Base64.Decode(lInStream, lOutStream); //lOutStream.Position := 0; qryExportar.SQL.Clear; qryExportar.SQL.Append(lInsert[I]); //qryExportar.Params.CreateParam(ftBlob, 'PIMAGEM', ptInput); //qryExportar.ParamByName('PIMAGEM').LoadFromStream(lOutStream, ftBlob); qryExportar.ExecSQL; lJObj.AddPair('ID', TConexaoDados.Connection.GetLastAutoGenValue('cardapios')); lInStream.Free; lOutStream.Free; end; if TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.CommitRetaining; TConexaoDados.Connection.TxOptions.AutoCommit := True; Result.AddElement(lJObj); GetInvocationMetadata().ResponseCode := 201; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToJSON); except on E: Exception do begin TConexaoDados.Connection.Rollback; raise; end; end; finally lInsert.Free; lFields.Free; lValues.Free; lLinha.Free; lJR.Free; lSR.Free; end; end; function TSmServicos.UpdateCategorias: TJSONArray; begin end; function TSmServicos.UpdateEstabelecimentos: TJSONArray; var lModulo : TWebmodule; lJARequisicao : TJSONArray; lJObj : TJSONObject; lSR : TStringReader; lJR : TJsonTextReader; lFields : TStringList; lValues : TStringList; lInsert : TStringList; lLinha : TStringBuilder; I : Integer; J : Integer; lInStream : TStringStream; lOutStream : TMemoryStream; lImagem64 : TStringList; begin //Result := 'POST Delphi'; lModulo := GetDataSnapWebModule; if lModulo.Request.Content.IsEmpty then begin GetInvocationMetadata().ResponseCode := 204; Abort; end; lJARequisicao := TJSONObject.ParseJSONValue( TEncoding.ASCII.GetBytes(lModulo.Request.Content), 0) as TJSONArray; Result := TJSONArray.Create; lJObj := TJSONObject.Create; lInsert := TStringList.Create; lFields := TStringList.Create; lValues := TStringList.Create; lLinha := TStringBuilder.Create; lImagem64 := TStringList.Create; try qryExportar.Connection := TConexaoDados.Connection; for I := 0 to Pred(lJARequisicao.Count) do begin lSR := TStringReader.Create(lJARequisicao.Items[I].ToJSON); lJR := TJsonTextReader.Create(lSR); lLinha.Clear; lFields.Clear; lValues.Clear; lLinha.Append('INSERT INTO CURSO.ESTABELECIMENTOS('); //Preenche os Campos while lJR.Read do begin if lJR.TokenType = TJsonToken.PropertyName then begin if not lJR.Value.ToString.IsEmpty then begin if lFields.IndexOf(lJR.Value.ToString) = -1 then lFields.Append(lJR.Value.ToString); lJR.Read; if lJR.TokenType in [TJsonToken.String, TJsonToken.Date] then //System.JSON.Types; begin if lJR.TokenType = TJsonToken.Date then lValues.Append(QuotedStr(FormatDateTime('dd.mm.yyyy',StrToDate(lJR.Value.ToString)))) else if UpperCase(lJR.Value.ToString) <> 'NULL' then lValues.Append(QuotedStr(lJR.Value.ToString)) else lValues.Append(lJR.Value.ToString); end else lValues.Append(lJR.Value.ToString.Replace(',','.')); end; end; end; for J := 0 to Pred(lFields.Count) do begin if not lFields[j].IsEmpty then begin if j <> lFields.Count -1 then lLinha.Append(lFields[j] + ', ') else lLinha.Append(lFields[j]); end; end; lLinha.Append(') VALUES ('); //Preenche os valores for J := 0 to lValues.Count -1 do begin if not lValues[j].IsEmpty then begin (* if LowerCase(lFields[j]) = 'foto_logotipo' then begin lImagem64.Add(lValues[j]); lValues[j] := ':PIMAGEM'; end; *) if j <> lValues.Count -1 then lLinha.Append(lValues[j] + ', ') else lLinha.Append(lValues[j]); end; end; lInsert.Append(lLinha.ToString + ');'); end; //Inicia a transação TConexaoDados.Connection.TxOptions.AutoCommit := False; if not TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.StartTransaction; try for I := 0 to Pred(lInsert.Count) do begin // lInStream := TStringStream.Create(lImagem64[i]); // lInStream.Position := 0; // lOutStream := TMemoryStream.Create; // TNetEncoding.Base64.Decode(lInStream, lOutStream); // lOutStream.Position := 0; qryExportar.SQL.Clear; qryExportar.SQL.Append(lInsert[I]); // qryExportar.Params.CreateParam(ftBlob, 'PIMAGEM', ptInput); // qryExportar.ParamByName('PIMAGEM').LoadFromStream(lOutStream, ftBlob); qryExportar.ExecSQL; lJObj.AddPair('ID', TConexaoDados.Connection.GetLastAutoGenValue('estabelecimentos')); lInStream.Free; lOutStream.Free; end; if TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.CommitRetaining; TConexaoDados.Connection.TxOptions.AutoCommit := True; Result.AddElement(lJObj); GetInvocationMetadata().ResponseCode := 201; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToJSON); except on E: Exception do begin TConexaoDados.Connection.Rollback; raise; end; end; finally lInsert.Free; lFields.Free; lValues.Free; lLinha.Free; lJR.Free; lSR.Free; end; end; function TSmServicos.UpdatePedidos: TJSONArray; const INS_PEDIDO = 'INSERT INTO CURSO.PEDIDOS ' + '( ' + ' ID_USUARIO , ' + ' ID_ESTABELECIMENTO , ' + ' DATA , ' + ' STATUS , ' + ' VALOR_PEDIDO , ' + ' ID_PEDIDO_MOBILE ' + ') ' + 'VALUES ' + '( ' + ' :ID_USUARIO , ' + ' :ID_ESTABELECIMENTO , ' + ' :DATA , ' + ' :STATUS , ' + ' :VALOR_PEDIDO , ' + ' :ID_PEDIDO_MOBILE ' + '); '; INS_ITENS_PEDIDO = 'INSERT INTO CURSO.ITENS_PEDIDO ' + '( ' + ' ID_PEDIDO , ' + ' QTDE , ' + ' VALOR_UNITARIO , ' + ' ID_CARDAPIO , ' + ' ID_PEDIDO_MOBILE ' + ') ' + 'VALUES ' + '( ' + ' :ID_PEDIDO , ' + ' :QTDE , ' + ' :VALOR_UNITARIO , ' + ' :ID_CARDAPIO , ' + ' :ID_PEDIDO_MOBILE ' + '); '; var lModulo : TWebModule; lJARequisicao : TJSONArray; LValores : TJSONValue; jPedido : TJSONValue; jItens : TJSONValue; lJOBJ : TJSONObject; //Pedidos iId_Pedido_Mobile : Integer; iId_Usuario : Integer; iId_Estabelecimento : Integer; dData : TDateTime; fValor_Pedido : Double; //Itens pedido iQtde : Integer; fValor_Unitario : Double; iId_Cardapio : Integer; //Auxiliares I : Integer; J : Integer; arrItens : Integer; iID_PedidoGerado : Integer; begin lModulo := GetDataSnapWebModule; if lModulo.Request.Content.IsEmpty then begin GetInvocationMetaData().ResponseCode := 204; Abort; end; lJARequisicao := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lModulo.Request.Content), 0) as TJSONArray; try qryExportar.Connection := TConexaoDados.Connection; TConexaoDados.Connection.TxOptions.AutoCommit := False; if not TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.StartTransaction; for LVAlores in lJARequisicao do begin jPedido := LValores.GetValue<TJSONArray>('pedido'); for I := 0 to Pred((jPedido as TJSONArray).Count) do begin iId_Pedido_Mobile := (jPedido as TJSONArray).Items[I].GetValue<integer>('id_pedido_mobile'); iId_Usuario := (jPedido as TJSONArray).Items[I].GetValue<integer>('id_usuario'); iId_Estabelecimento := (jPedido as TJSONArray).Items[I].GetValue<integer>('id_estabelecimento'); dData := StrToDateTime((jPedido as TJSONArray).Items[I].GetValue<string>('data')); fValor_Pedido := (jPedido as TJSONArray).Items[I].GetValue<double>('valor_pedido'); //Update de Pedidos qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Text := INS_PEDIDO; qryExportar.ParamByName('ID_USUARIO').AsInteger := iId_Usuario; qryExportar.ParamByName('ID_ESTABELECIMENTO').AsInteger := iId_Estabelecimento; qryExportar.ParamByName('DATA').AsDateTime := dData; qryExportar.ParamByName('STATUS').AsString := 'E'; qryExportar.ParamByName('VALOR_PEDIDO').AsFloat := (FormatFloat('###,###,##0.00', fValor_Pedido)).ToDouble(); qryExportar.ParamByName('ID_PEDIDO_MOBILE').AsInteger := iId_Pedido_Mobile; qryExportar.ExecSQL; iID_PedidoGerado := TConexaoDados.Connection.GetLastAutoGenValue('ID'); //Inclusão dos itens do pedido jItens := (jPedido as TJSONArray).Items[I].GetValue<TJSONArray>('itens'); arrItens := (jItens as TJSONArray).Count; qryExportar.Active := False; qryExportar.SQL.Clear; qryExportar.SQL.Text := INS_ITENS_PEDIDO; qryExportar.Params.ArraySize := arrItens; for J := 0 to Pred((jItens as TJSONArray).Count) do begin iQtde := (jItens as TJSONArray).Items[J].GetValue<integer>('qtde'); fValor_Unitario := (FormatFloat('###,###,##0.00', (jItens as TJSONArray).Items[J].GetValue<double>('valor_unitario'))).ToDouble(); iId_Cardapio := (jItens as TJSONArray).Items[J].GetValue<integer>('id_cardapio'); qryExportar.ParamByName('ID_PEDIDO').AsIntegers[J] := iID_PedidoGerado; qryExportar.ParamByName('QTDE').AsIntegers[J] := iQtde; qryExportar.ParamByName('VALOR_UNITARIO').AsFloats[J] := fValor_Unitario; qryExportar.ParamByName('ID_CARDAPIO').AsIntegers[J] := iId_Cardapio; qryExportar.ParamByName('ID_PEDIDO_MOBILE').AsIntegers[J] := iId_Pedido_Mobile; end; qryExportar.Execute(arrItens, 0); end; end; if TConexaoDados.Connection.InTransaction then TConexaoDados.Connection.CommitRetaining; TConexaoDados.Connection.TxOptions.AutoCommit := True; lJOBJ := TJSONObject.Create; lJOBJ.AddPair('Mensagem', 'Pedido enviado com sucesso!'); Result := TJSONArray.Create; Result.AddElement(lJOBJ); GetInvocationMetaData().ResponseCode := 201; TUtils.FormatarJSON(GetInvocationMetadata().ResponseCode, Result.ToJSON()); except on E:Exception do begin TConexaoDados.Connection.Rollback; raise; end; end; end; end.
unit uBotConversa; interface uses System.Classes, Vcl.ExtCtrls, uTInject; type TTipoUsuario = (tpCliente, tpAdm); TSituacaoConversa = (saIndefinido, saNova, saEmAtendimento, saEmEspera, saInativa, saFinalizada, saAtendente); TBotConversa = class; TNotifyConversa = procedure(Conversa: TBotConversa) of object; TBotConversa = class(TComponent) private //Enumerado FTipoUsuario: TTipoUsuario; FSituacao: TSituacaoConversa; //Propriedades FID: String; FTelefone: String; FIDMensagem: Extended; FNome: String; FEtapa: Integer; FPergunta: String; FResposta: String; FLat : Extended; FLng : Extended; FTempoInatividade: Integer; //Objeto FTimerSleep: TTimer; //Notifys Eventos FOnSituacaoAlterada: TNotifyConversa; FOnRespostaRecebida: TNotifyConversa; //curso --> FItensPizza : TStringList; FIDPedido : integer; FEnderecoCliente : string; FTipo : string; FFormaPGT : string; FIDInc : integer; FMaiorValor : currency; FPrimeiroSabor : string; FType : string; //<-- procedure TimerSleepExecute(Sender: TObject); procedure SetSituacao(const Value: TSituacaoConversa); procedure SetTempoInatividade(const Value: Integer); public //Construtores destrutores constructor Create(AOwner: TComponent); override; destructor Destroy; override; property TipoUsuario: TTipoUsuario read FTipoUsuario write FTipoUsuario default tpCliente; property Situacao: TSituacaoConversa read FSituacao write SetSituacao default saIndefinido; property ID: String read FID write FID; property Telefone: String read FTelefone write FTelefone; property IDMensagem: Extended read FIDMensagem write FIDMensagem; property Nome: String read FNome write FNome; property Etapa: Integer read FEtapa write FEtapa default 0; property Pergunta: String read FPergunta write FPergunta; property Resposta: String read FResposta write FResposta; property Lat: Extended read FLat write FLat; property Lng: Extended read FLng write FLng; //curso --> property Items : TStringList read FItensPizza write FItensPizza; property IDPedido : integer read FIDPedido write FIDPedido; property EnderecoCliente : string read FEnderecoCliente write FEnderecoCliente; property Tipo : string read FTipo write FTipo; property FormaPGT : string read FFormaPGT write FFormaPGT; property IDInc : integer read FIDInc write FIDInc; property MaiorValor : currency read FMaiorValor write FMaiorValor; property PrimeiroSabor : string read FPrimeiroSabor write FPrimeiroSabor; //<-- property TempoInatividade: Integer read FTempoInatividade write SetTempoInatividade; property OnSituacaoAlterada: TNotifyConversa read FOnSituacaoAlterada write FOnSituacaoAlterada; property OnRespostaRecebida: TNotifyConversa read FOnRespostaRecebida write FOnRespostaRecebida; property &type : string read FType write FType; procedure ReiniciarTimer; end; implementation uses System.SysUtils; { TBotConversa } constructor TBotConversa.Create(AOwner: TComponent); begin inherited Create(AOwner); //Prepara Timer FTimerSleep := TTimer.Create(Self); with FTimerSleep do begin Enabled := False; Interval := TempoInatividade; OnTimer := TimerSleepExecute; end; end; destructor TBotConversa.Destroy; begin FTimerSleep.Free; inherited Destroy; end; procedure TBotConversa.SetSituacao(const Value: TSituacaoConversa); begin //DoChange if FSituacao <> Value then begin FSituacao := Value; //Habilita Time se situacao ativa. if FSituacao <> saAtendente then begin FTimerSleep.Enabled := FSituacao = saEmAtendimento; if Assigned( OnSituacaoAlterada ) then OnSituacaoAlterada(Self); end; end; end; procedure TBotConversa.SetTempoInatividade(const Value: Integer); begin FTempoInatividade := Value; FTimerSleep.Interval := FTempoInatividade; end; procedure TBotConversa.TimerSleepExecute(Sender: TObject); begin Self.Situacao := saInativa; end; procedure TBotConversa.ReiniciarTimer; begin //Se estiver em atendimento reinicia o timer de inatividade if Situacao in [saNova, saEmAtendimento, saAtendente] then begin FTimerSleep.Enabled := False; FTimerSleep.Enabled := True; end; end; end.
unit UnFuncoesAuxiliares; interface uses Windows,SysUtils, DB, Vcl.StdCtrls, StrUtils, Vcl.Forms, Vcl.Controls, FireDAC.Comp.Client,Classes,FireDAC.Comp.DataSet, IniFiles, System.Math; procedure CriarForm(aClasseForm:TComponentClass; aForm: TForm);overload; procedure SetarFoco(Objeto: TWinControl); {Retira todos os espaços e converte para extended} function StrToExt(S:string):Extended; {Converte string para inteiro, caso haja algum exceção retorn a zero} function CSI(ValorTexto:string):Integer; {Retira todos os espaços e converte para currency} function CSV(S:string):Currency; function AlinharEsquerda(aTexto: string; aTamanho: Integer; aCaracter : String = ' '): string; function AlinharCentralizado(aTexto: string; aTamanho: Integer; aCaracter : String = ' '): string; function AlinharDireita(aTexto: string; aTamanho: Integer; aCaracter : String = ' '): string; {converte hexadecimal para inteiro} function HexToInt(HexStr: String): Integer; {Remove todos os espeços da string} function AllTrim(ptexto:string):string; {retira todos os acentos da string} function TiraAcento(Texto:string): string; {preenche uma string com zeros a esquerda ou a direita dependendo do terceiro parametro} function StrZero(Texto : string; Tamanho : Integer; AEsquerda: Boolean=true) : string; function FormataNumero(S:string):string; {valida cnpj} function CnpjValido(ParCnpj : string) : boolean; {valida cpf} function CpfValido(ParCpf : string) : boolean; {retorna a descrição do estado quando passado a sigla} function GetDescricaoUF(ASigla: string): String; {retorna o MacAddress da maquina} function MacAddress: string; {recebe um codigo de tamanho 7 e retorna o codigo com seu digito, complementando o ean8 } function getReferenciaDV(aCodigo: String):string; function getDivisao(aValor1, aValor2 :Extended):Extended; function getPercentual(aValor1, aValor2 :Extended):Extended; function iff(aCondicao : boolean; aResultTrue, aResultFalse : string):string; function FormataCpfCnpj(aTexto: string): string; procedure EscreverIni(aSecao, aChave, aValor: String); function LerArquivoIni(aSecao, aChave: String):String; function validaC1(aCmc7: string):boolean; function validaC2(frase:String; C:integer):boolean; function validaC3(frase:String; C:integer):boolean; function Modulo10(Valor: String): string; function Valida_CMC7(Entrada:String) : Boolean; Function SoNumero(S:String):String; function isNumber(S: string): Boolean; function ValorExtenso(Valor :Currency) :String; function mcx_Ajusta(Valor :String) :String; function mcx_Centenas(Valor :Integer) :String; function mcx_Dezenas(Valor :Integer) :String; function mcx_Unidades(Valor :Integer) :String; function CalcularIdade(aDataNasc: Tdate): integer; function ano_bisexto(aInt_ano: Integer): Boolean; function ultimo_dia_mes(aInt_ano, aInt_mes: Integer): Integer; implementation uses UnVariaveisGlobais; procedure SetarFoco(Objeto: TWinControl); begin TWinControl(Objeto).SetFocus; if Objeto.InheritsFrom(TCustomEdit) then TCustomEdit(Objeto).SelectAll; end; function StrToExt(S:string):Extended; var v : string; i,t : Integer; begin try v := S; t := length(v); for i:=1 to t do if v[i]= FormatSettings.ThousandSeparator then v[i]:=' '; Result:= StrToFloat(AllTrim(v)); except Result:=0; end; end; function AllTrim(ptexto:string):string; var temp : string; begin temp := ptexto; while Pos(' ', temp) > 0 do begin Delete(temp,Pos(' ', temp),1); end; result:=temp; end; function CSI(ValorTexto:string):Integer; begin try Result:= StrToInt(AllTrim(ValorTexto)); except Result:=0; end; end; function CSV(S:string):Currency; var v : string; i,t : Integer; begin try if Trim(S) <> EmptyStr then begin v := S; t := length(v); for i:=1 to t do if v[i]= FormatSettings.ThousandSeparator then v[i]:=' '; Result:= StrToCurr(AllTrim(v)); end else Result:= 0; except Result:=0; end; end; function AlinharEsquerda(aTexto: string; aTamanho: Integer; aCaracter : String = ' '): string; var aStrTemp : String; begin aStrTemp := Trim(aTexto); while Length(aStrTemp) < aTamanho do begin aStrTemp := aStrTemp + aCaracter; end; Result := aStrTemp; end; // para texto centralizado function AlinharCentralizado(aTexto: string; aTamanho: Integer; aCaracter : String = ' '): string; var aStrTemp : String; aPosicao1, aPosicao2 : integer; begin aStrTemp := Trim(aTexto); aPosicao2:= (aTamanho - Length(aStrTemp)) div 2; for aPosicao1 := 1 to aPosicao2 do aStrTemp := aCaracter + aStrTemp; while Length(aStrTemp) < aTamanho do aStrTemp := aStrTemp + aCaracter; Result := aStrTemp; end; // para texto a direita function AlinharDireita(aTexto: string; aTamanho: Integer; aCaracter : String = ' '): string; var aStrTemp : String; begin aStrTemp := Trim(aTexto); while Length(aStrTemp) < aTamanho do begin aStrTemp := aCaracter + aStrTemp; end; Result := copy(aStrTemp,1,aTamanho); end; function CnpjValido(ParCnpj : string) : boolean; var Digito1,Digito2 : integer; Soma : LongInt; cnpj : string; begin Result := False; cnpj := ParCnpj; if (StrToExt(cnpj) > 99999999999999) or (StrToExt(cnpj)=0) then exit; cnpj := FormatFloat('00000000000000',StrToExt(cnpj)); { calcula o 1o. dígito } Soma := (CSI(cnpj[01]) * 5) + (CSI(cnpj[02]) * 4) + (CSI(cnpj[03]) * 3) + (CSI(cnpj[04]) * 2) + (CSI(cnpj[05]) * 9) + (CSI(cnpj[06]) * 8) + (CSI(cnpj[07]) * 7) + (CSI(cnpj[08]) * 6) + (CSI(cnpj[09]) * 5) + (CSI(cnpj[10]) * 4) + (CSI(cnpj[11]) * 3) + (CSI(cnpj[12]) * 2); Soma := Soma * 10; Digito1 := Soma mod 11; if Digito1 = 10 then Digito1 := 0; { compara o resultado com o 1o. digito informado } if Digito1 = CSI(cnpj[13]) then begin { se correto ... } { calcula o 2o. dígito } Soma := (CSI(cnpj[01]) * 6) + (CSI(cnpj[02]) * 5) + (CSI(cnpj[03]) * 4) + (CSI(cnpj[04]) * 3) + (CSI(cnpj[05]) * 2) + (CSI(cnpj[06]) * 9) + (CSI(cnpj[07]) * 8) + (CSI(cnpj[08]) * 7) + (CSI(cnpj[09]) * 6) + (CSI(cnpj[10]) * 5) + (CSI(cnpj[11]) * 4) + (CSI(cnpj[12]) * 3) + (CSI(cnpj[13]) * 2); Soma := Soma * 10; Digito2 := Soma mod 11; if Digito2 = 10 then Digito2 := 0; { compara o resultado com o 2o. digito informado } if Digito2 = CSI(cnpj[14]) then begin { se correto ... } { retorna cnpj válido } cnpjValido := true; end; end; end; function CpfValido(ParCpf : string) : boolean; var Digito1,Digito2 : integer; Soma : LongInt; Cpf : string; begin Result := False; Cpf := ParCpf; if (StrToExt(Cpf) > 99999999999) or (StrToExt(Cpf)=0) then exit; Cpf := FormatFloat('00000000000',StrToExt(Cpf)); { calcula o 1o. dígito } Soma := (CSI(Cpf[01]) * 10) + (CSI(Cpf[02]) * 09) + (CSI(Cpf[03]) * 08) + (CSI(Cpf[04]) * 07) + (CSI(Cpf[05]) * 06) + (CSI(Cpf[06]) * 05) + (CSI(Cpf[07]) * 04) + (CSI(Cpf[08]) * 03) + (CSI(Cpf[09]) * 02); Soma := Soma * 10; Digito1 := Soma mod 11; if Digito1 = 10 then Digito1 := 0; { compara o resultado com o 1o. digito informado } if Digito1 = CSI(Cpf[10]) then begin { se correto ... } { calcula o 2o. dígito } Soma := (CSI(Cpf[01]) * 11) + (CSI(Cpf[02]) * 10) + (CSI(Cpf[03]) * 09) + (CSI(Cpf[04]) * 08) + (CSI(Cpf[05]) * 07) + (CSI(Cpf[06]) * 06) + (CSI(Cpf[07]) * 05) + (CSI(Cpf[08]) * 04) + (CSI(Cpf[09]) * 03) + (CSI(Cpf[10]) * 02); Soma := Soma * 10; Digito2 := Soma mod 11; if Digito2 = 10 then Digito2 := 0; { compara o resultado com o 2o. digito informado } if Digito2 = CSI(Cpf[11]) then begin { se correto ... } { retorna Cpf válido } Result := true; end; end; end; function GetDescricaoUF(ASigla: string): String; begin if ASigla = 'AC' then Result := 'AC - Acre' else if Asigla = 'AL' then Result := 'AL - Alagoas' else if Asigla = 'AP' then Result := 'AP - Amapá' else if Asigla = 'AM' then Result := 'AM - Amazonas' else if Asigla = 'BA' then Result := 'BA - Bahia' else if Asigla = 'CE' then Result := 'CE - Ceará' else if Asigla = 'DF' then Result := 'DF - Distrito Federal' else if Asigla = 'GO' then Result := 'GO - Goiás' else if Asigla = 'ES' then Result := 'ES - Espírito Santo' else if Asigla = 'MA' then Result := 'MA - Maranhão' else if Asigla = 'MT' then Result := 'MT - Mato Grosso' else if Asigla = 'MS' then Result := 'MS - Mato Grosso do Sul' else if Asigla = 'MG' then Result := 'MG - Minas Gerais' else if Asigla = 'PA' then Result := 'PA - Pará' else if Asigla = 'PB' then Result := 'PB - Paraiba' else if Asigla = 'PR' then Result := 'PR - Paraná' else if Asigla = 'PE' then Result := 'PE - Pernambuco' else if Asigla = 'PI' then Result := 'PI - Piauí' else if Asigla = 'RJ' then Result := 'RJ - Rio de Janeiro' else if Asigla = 'RN' then Result := 'RN - Rio Grande do Norte' else if Asigla = 'RS' then Result := 'RS - Rio Grande do Sul' else if Asigla = 'RO' then Result := 'RO - Rondônia' else if Asigla = 'RR' then Result := 'RR - Rorâima' else if Asigla = 'SP' then Result := 'SP - São Paulo' else if Asigla = 'SC' then Result := 'SC - Santa Catarina' else if Asigla = 'SE' then Result := 'SE - Sergipe' else if Asigla = 'TO' then Result := 'TO - Tocantins'; end; procedure CriarForm(aClasseForm:TComponentClass; aForm: TForm);overload; begin try Application.CreateForm(aClasseForm,aForm); aForm.ShowModal; finally FreeAndNil(aForm); end; end; function MacAddress: string; var Lib: Cardinal; Func: function(GUID: PGUID): Longint; stdcall; GUID1, GUID2: TGUID; begin Result := ''; Lib := LoadLibrary('rpcrt4.dll'); if Lib <> 0 then begin @Func := GetProcAddress(Lib, 'UuidCreateSequential'); if Assigned(Func) then begin if (Func(@GUID1) = 0) and (Func(@GUID2) = 0) and (GUID1.D4[2] = GUID2.D4[2]) and (GUID1.D4[3] = GUID2.D4[3]) and (GUID1.D4[4] = GUID2.D4[4]) and (GUID1.D4[5] = GUID2.D4[5]) and (GUID1.D4[6] = GUID2.D4[6]) and (GUID1.D4[7] = GUID2.D4[7]) then begin Result := IntToHex(GUID1.D4[2], 2) + '-' + IntToHex(GUID1.D4[3], 2) + '-' + IntToHex(GUID1.D4[4], 2) + '-' + IntToHex(GUID1.D4[5], 2) + '-' + IntToHex(GUID1.D4[6], 2) + '-' + IntToHex(GUID1.D4[7], 2); end; end; end; end; function HexToInt(HexStr: String): Integer; var i: Integer; b: Byte; begin i := 0; Result := 0; HexStr := UpperCase(HexStr); while (Length(HexStr) > 0) do begin b := 0; case HexStr[Length(HexStr)] of '1'..'9': b := Ord(HexStr[Length(HexStr)]) - $30; 'A'..'F': b := Ord(HexStr[Length(HexStr)]) - $37; end; Result := Result + b shl i; Inc(i, 4); Delete(HexStr, Length(HexStr), 1); end; end; function getReferenciaDV(aCodigo: String):string; var ean_xx : integer; ean_Co, aCod, DV : string; begin DV := ''; aCod := RightStr(aCodigo,7); try Ean_Co := FormatFloat('0000000000000',StrToInt64(Trim(aCod))); except Result := ''; exit; end; ean_xx := StrToInt(Ean_Co[01]) * 3 + StrToInt(Ean_Co[02]) + StrToInt(Ean_Co[03]) * 3 + StrToInt(Ean_Co[04]) + StrToInt(Ean_Co[05]) * 3 + StrToInt(Ean_Co[06]) + StrToInt(Ean_Co[07]) * 3 + StrToInt(Ean_Co[08]) + StrToInt(Ean_Co[09]) * 3 + StrToInt(Ean_Co[10]) + StrToInt(Ean_Co[11]) * 3 + StrToInt(Ean_Co[12]) + StrToInt(Ean_Co[13]) * 3 ; DV := IntToStr((ean_xx div 10 + 1)*10 - ean_xx); if StrToInt(DV) > 9 then DV := '0'; Result := DV; end; function CalcularDigitoEAN13(aCodigo : string) : string; var ean_xx : integer; ean_Co : string; begin try Ean_Co := FormatFloat('0000000000000',StrToInt64(Trim(aCodigo))); except Result := ''; exit; end; ean_xx := StrToInt(Ean_Co[01]) * 3 + StrToInt(Ean_Co[02]) + StrToInt(Ean_Co[03]) * 3 + StrToInt(Ean_Co[04]) + StrToInt(Ean_Co[05]) * 3 + StrToInt(Ean_Co[06]) + StrToInt(Ean_Co[07]) * 3 + StrToInt(Ean_Co[08]) + StrToInt(Ean_Co[09]) * 3 + StrToInt(Ean_Co[10]) + StrToInt(Ean_Co[11]) * 3 + StrToInt(Ean_Co[12]) + StrToInt(Ean_Co[13]) * 3 ; Result := IntToStr((ean_xx div 10 + 1)*10 - ean_xx); if StrToInt(Result) > 9 then Result := '0'; end; function TiraAcento(Texto:string): string; const ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ'; SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU'; var IntTmp : Integer; begin For IntTmp := 1 to Length(Texto) do begin if Pos(Texto[IntTmp],ComAcento) > 0 then begin Texto[IntTmp] := SemAcento[Pos(Texto[IntTmp],ComAcento)]; end; end; Result := Texto; end; function StrZero( Texto : string; Tamanho : Integer; AEsquerda : Boolean=true ) : string; var FStrTmp : string; begin FStrTmp := AllTrim(Texto); while Length(FStrTmp) < Tamanho do begin if AEsquerda then FStrTmp := '0' + FStrTmp Else FStrTmp := FStrTmp + '0'; end; Result := FStrTmp; end; function FormataNumero(S:string):string; procedure RetiraCaracteres(var Str:string); var i:Integer; Aux:string; begin i:=1; Aux:=''; while i<=length(str) do begin if str[i] in ['-','0'..'9'] then Aux:=Aux+str[i]; i:=i+1; end; Str:=Aux; end; var A,B:Char; begin if Trim(S) = '' then exit; A:=Copy(S,Length(S)-2,1)[1]; B:=Copy(S,Length(S)-1,1)[1]; if (not(A in ['0'..'9'])) or (not(B in ['0'..'9'])) then begin RetiraCaracteres(S); if not(A in ['0'..'9']) then Insert(FormatSettings.DecimalSeparator,S,Length(S)-1) else Insert(FormatSettings.DecimalSeparator,S,Length(S)); end; Result:=S; end; function getDivisao(aValor1, aValor2 :Extended):Extended; begin Result := 0; if (aValor1 > 0) and (aValor2 > 0) then Result := aValor1 / aValor2; end; function getPercentual(aValor1, aValor2 :Extended):Extended; begin Result := getDivisao(aValor1, aValor2) * 100; end; function iff(aCondicao: boolean; aResultTrue, aResultFalse : string):string; begin Result := ''; if aCondicao then Result := aResultTrue else Result := aResultFalse; end; function FormataCpfCnpj(aTexto: string): string; var aTextoFormatado : string; begin Result := ''; aTextoFormatado := ''; if Trim(aTexto) <> EmptyStr then begin if length(trim(aTexto)) = 14 then begin aTextoFormatado := copy(aTexto,1,3)+'.'+copy(aTexto,4,3)+'.'+copy(aTexto,7,3)+'/'+copy(aTexto,10,3)+'-'+copy(aTexto,13,2); end else if length(trim(aTexto)) <= 11 then begin if length(trim(aTexto)) < 11 then begin aTextoFormatado := FormatFloat('00000000000', StrToInt64(aTextoFormatado)); end; aTextoFormatado := copy(aTexto,1,3)+'.'+copy(aTexto,4,3)+'.'+copy(aTexto,7,3)+'-'+copy(aTexto,10,2); end; Result := aTextoFormatado; end; end; procedure EscreverIni(aSecao, aChave, aValor: String); var aArqIni : TIniFile; begin aArqIni := TIniFile.Create(pPathArquivoIni); aArqIni.WriteString(aSecao, aChave, aValor); aArqIni.Free; end; function LerArquivoIni(aSecao, aChave: String):String; var aArqIni : TIniFile; begin Result := ''; aArqIni := TIniFile.Create(pPathArquivoIni); Result := aArqIni.ReadString(aSecao, aChave, ''); aArqIni.Free; end; {passar os campos compensação, banco e agencia concatenados} function validaC1(aCmc7: string):boolean; var i,soma,num:integer; frase: String; C: Integer; begin frase := Copy(Trim(aCmc7), 9,3) + Copy(Trim(aCmc7), 1,7); C := StrToInt(Copy(Trim(aCmc7), 19,1)); if length(aCmc7) < 30 then validaC1 := False else begin Soma := 0; num := 8; for i:= 1 to length(frase) do begin Soma := Soma + (StrToInt(frase[i]) * num); Inc(num); if num = 10 then num := 2; end; Soma := Soma mod 11; validaC1 := False; if C = Soma then validaC1 := true; end; end; { passar o campo conta corrente com uma string de 10 posicoes } function validaC2(frase:String; C:integer):boolean; var i,soma,num:integer; begin if length(frase)=0 then validaC2:=false else begin soma:=0; num:=11; for I:=1 to Length(frase) do begin soma:=soma+(strtoint(frase[i])*num); dec(num); end; soma:=soma mod 11; if (soma=0) or (soma=1) then soma:=0 else soma:=11-soma; validaC2:=false; if C=soma then validaC2:=true; end; end; {passar o campo Numero do Chequecom uma string de 6 posicoes} function validaC3(frase:String; C:integer):boolean; var i,soma,num:integer; begin if length(frase)=0 then validaC3:=false else begin soma:=0; num:=7; for I:=1 to Length(frase) do begin soma:=soma+(strtoint(frase[i])*num); dec(num); end; soma:=soma mod 11; if (soma=0) or (soma=1) then soma:=0 else soma:=11-soma; validaC3:=false; if C=soma then validaC3:=true; end; end; function Modulo10(Valor: String): string; { Rotina usada para cálculo de alguns dígitos verificadores Pega-se cada um dos dígitos contidos no parâmetro VALOR, da direita para a esquerda e multiplica-se por 2121212... Soma-se cada um dos subprodutos. Caso algum dos subprodutos tenha mais de um dígito, deve-se somar cada um dos dígitos. (Exemplo: 7*2 = 14 >> 1+4 = 5) Divide-se a soma por 10. Faz-se a operação 10-Resto da divisão e devolve-se o resultado dessa operação como resultado da função Modulo10. Obs.: Caso o resultado seja maior que 9, deverá ser substituído por 0 (ZERO). } var Auxiliar : string; Contador, Peso : integer; Digito : integer; begin Auxiliar := ''; Peso := 2; for Contador := Length(Valor) downto 1 do begin Auxiliar := IntToStr(StrToInt(Valor[Contador]) * Peso) + Auxiliar; if Peso = 1 then Peso := 2 else Peso := 1; end; Digito := 0; for Contador := 1 to Length(Auxiliar) do begin Digito := Digito + StrToInt(Auxiliar[Contador]); end; Digito := 10 - (Digito mod 10); if (Digito > 9) then Digito := 0; Result := IntToStr(Digito); end; function Valida_CMC7(Entrada:String) : Boolean; var campo1, campo2, campo3 : String; begin Entrada := SoNumero(Entrada); campo1 := Copy(entrada,1,7); campo2 := Copy(entrada,9,10); campo3 := Copy(entrada,20,10); Result := True; if Modulo10(campo1) <> Copy(Entrada,19,1) then Result := False Else if Modulo10(campo2) <> Copy(Entrada,8,1) then Result := False Else if Modulo10(campo3) <> Copy(Entrada,30,1) then Result := False; end; function SoNumero(S: String): String; var StrAux : String; i,intAux : Integer; begin Try StrAux := S; intAux := length(StrAux); for i:=1 to intAux do begin if Pos(StrAux[i],'0123456789') = 0 then begin StrAux[i]:=' '; end; end; Result:= AllTrim(StrAux); except Result:=''; end; end; function isNumber(S: string): Boolean; var I: Integer; begin Result := True; for I := 1 to Length(S) do begin if not (S[I] in ['0'..'9']) then begin Result := False; Break; end; end; end; function ValorExtenso(Valor :Currency) :String; var StrValores, StrPart, StrValor, PartDec :String; i, Parcela, Posicao :Integer; begin StrValores := 'trilhão '+'trilhões '+'bilhão '+'bilhões '+ 'milhão '+'milhões '+'mil '+'mil '; //Formata o valor corretamente... StrValor := CurrToStr(Valor); Posicao := Pos(',',StrValor); if Posicao > 0 then begin PartDec := Copy(StrValor,Posicao+1,2); if Length(PartDec) < 2 then begin StrValor := StrValor+'0'; PartDec := PartDec +'0'; end; StrValor := StringReplace(StrValor,',','',[rfReplaceAll]); end else begin PartDec := '00'; StrValor := StrValor+PartDec; end; while Length(StrValor) < 17 do StrValor := '0'+StrValor; //Fim da formatação... for i := 1 to 5 do begin StrPart := Copy(StrValor,((i-1)*3)+1,3); Parcela := StrToInt(StrPart); if Parcela = 1 then Posicao := 1 else Posicao := 10; if Parcela > 0 then begin if Length(Result) > 0 then Result := Result+' e '; Result := Result+mcx_Centenas(Parcela); Result := Result+TrimRight(Copy(StrValores,((i-1)*18)+Posicao,9)); if not i = 5 then Result := Result+' '; end; end; if Length(Result) > 0 then if Int(Valor) = 1 then Result := Result+'real ' else Result := Result+' reais '; Parcela := StrToInt(PartDec); if Parcela > 0 then begin if Length(Result) > 0 then Result := Result+' e '; if Parcela = 1 then Result := Result+'um centavo' else Result := Result+mcx_Dezenas(Parcela)+'centavos'; end; Result := mcx_Ajusta(Result); end; function mcx_Ajusta(Valor :String) :String; begin Valor := Trim(StringReplace(Valor,' ',' ',[rfReplaceAll])); if Pos('um mil ',Valor) = 1 then Valor := StringReplace(Valor,'um mil','mil',[rfReplaceAll]); if (Copy(Valor,Length(Valor)-8,9) = 'tos reais') or (Copy(Valor,Length(Valor)-8,9) = 'mil reais') then begin Result := Valor; Exit; end; //Ajusta milhares Valor := StringReplace(Valor,'mil e cento' ,'mil cento' ,[rfReplaceAll]); Valor := StringReplace(Valor,'mil e duzentos' ,'mil duzentos' ,[rfReplaceAll]); Valor := StringReplace(Valor,'mil e trezentos' ,'mil trezentos' ,[rfReplaceAll]); Valor := StringReplace(Valor,'mil e quatrocentos','mil quatrocentos',[rfReplaceAll]); Valor := StringReplace(Valor,'mil e quinhentos' ,'mil quinhentos' ,[rfReplaceAll]); Valor := StringReplace(Valor,'mil e seiscentos' ,'mil seiscentos' ,[rfReplaceAll]); Valor := StringReplace(Valor,'mil e setecentos' ,'mil setecentos' ,[rfReplaceAll]); Valor := StringReplace(Valor,'mil e oitocentos' ,'mil oitocentos' ,[rfReplaceAll]); Valor := StringReplace(Valor,'mil e novecentos' ,'mil novecentos' ,[rfReplaceAll]); //Ajusta trilhões, bilhões e milhões Valor := StringReplace(Valor,'ão reais' ,'ão de reais' ,[rfReplaceAll]); Valor := StringReplace(Valor,'ões reais','ões de reais',[rfReplaceAll]); //Retorna valor Result := Valor; end; function mcx_Centenas(Valor :Integer) :String; var StrValor, StrDig :String; begin if Valor = 100 then Result := 'cem ' else begin Result := ''; StrDig := '00'+IntToStr(Valor); StrDig := Copy(StrDig,Length(StrDig)-2,3); StrValor := 'cento '+'duzentos '+'trezentos '+ 'quatrocentos'+'quinhentos '+'seiscentos '+ 'setecentos '+'oitocentos '+'novecentos '; if StrToInt(StrDig[1]) > 0 then Result := TrimRight(Copy(StrValor,((StrToInt(StrDig[1])-1)*12)+1,12))+' '; if StrToInt(Copy(StrDig,2,2)) > 0 then begin if Length(Result) > 0 then Result := Result+'e '; Result := Result+mcx_Dezenas(StrToInt(Copy(StrDig,2,2))) end; end; end; function mcx_Dezenas(Valor :Integer) :String; var StrValor, StrDig :String; begin if Valor < 20 then Result := mcx_Unidades(Valor) else begin Result := ''; StrDig := '00'+IntToStr(Valor); StrDig := Copy(StrDig,Length(StrDig)-1,2); StrValor := 'vinte '+'trinta '+'quarenta '+'cinquenta'+ 'sessenta '+'setenta '+'oitenta '+'noventa '; Result := TrimRight(Copy(StrValor,((StrToInt(StrDig[1])-2)*9)+1,9))+' '; if StrToInt(StrDig[2]) > 0 then Result := Result+'e '+mcx_Unidades(StrToInt(StrDig[2])); end; end; function mcx_Unidades(Valor :Integer) :String; const StrValor :Array[0..18] of pChar = ('um','dois','três','quatro','cinco','seis', 'sete','oito','nove','dez','onze','doze', 'treze','quatorze','quinze','dezesseis', 'dezessete','dezoito','dezenove'); begin Result := StrValor[Valor-1]+' '; end; function CalcularIdade(aDataNasc: Tdate): integer; var anoN, mes, dia : word; anoA, mesA, diaA : word; begin Decodedate(aDataNasc,anoN,mes,dia ); Decodedate(Date,anoA,mesA,diaA ); if (mesA > mes) or ((mesA = mes) and (dia >= dia)) then Result := anoA - anoN else Result := anoA - anoN - 1; end; function ano_bisexto(aInt_ano: Integer): Boolean; begin //Verifica se o ano é bissexto Result := (aInt_ano mod 4 = 0) and ((aInt_ano mod 100 <> 0) or (aInt_ano mod 400 = 0)); //Também pode-se usar a função “IsLeapYear(Year: Word): Boolean”, //existente em SysUtils end; function ultimo_dia_mes(aInt_ano, aInt_mes: Integer): Integer; const dia_mes: array[1..12] of Integer = (31,28,31,30,31,30,31,31,30,31,30,31); begin Result := dia_mes[aInt_mes]; if (aInt_mes = 2) and ano_bisexto(aInt_ano) then Inc(Result); end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } { Copyright and license exceptions noted in source } { } {*******************************************************} unit Posix.SysTime; {$WEAKPACKAGEUNIT} {$HPPEMIT NOUSINGNAMESPACE} interface uses Posix.Base, Posix.SysTypes, Posix.Time; {$HPPEMIT '#include <sys/time.h>' } {$IFDEF MACOS} {$I osx/SysTimeTypes.inc} {$ELSEIF defined(LINUX)} {$I linux/SysTimeTypes.inc} {$ELSEIF defined(ANDROID)} {$I android/SysTimeTypes.inc} {$ENDIF} type time_t = Posix.SysTypes.time_t; {$EXTERNALSYM time_t} suseconds_t = Posix.SysTypes.suseconds_t; {$EXTERNALSYM suseconds_t} cmpTimerType = (cmpGreater, cmpGreaterEqual, cmpEquals, cmpLess, cmpLessEqual); procedure timerclear(var a: timeval); inline; {$EXTERNALSYM timerclear} function timerisset(a: timeval):boolean; inline; {$EXTERNALSYM timerisset} function timercmp(a, b: timeval; op: cmpTimerType): boolean; inline; {$EXTERNALSYM timercmp} procedure timeradd(a, b: timeval; var res: timeval); inline; {$EXTERNALSYM timeradd} procedure timersub(a, b: timeval; var res: timeval); inline; {$EXTERNALSYM timersub} {$I SysTimeAPI.inc} implementation procedure timerclear(var a: timeval); begin a.tv_sec := 0; a.tv_usec := 0; end; function timerisset(a: timeval):boolean; begin Result := (a.tv_sec <> 0) or (a.tv_usec <> 0); end; function timercmp(a, b: timeval; op: cmpTimerType): boolean; begin Result := False; if a.tv_sec = b.tv_sec then begin case op of cmpGreater: result := a.tv_usec > b.tv_usec; cmpGreaterEqual: result := a.tv_usec >= b.tv_usec; cmpEquals: result := a.tv_usec = b.tv_usec; cmpLess: result := a.tv_usec < b.tv_usec; cmpLessEqual: result := a.tv_usec <= b.tv_usec; end; end else begin case op of cmpGreater: result := a.tv_sec > b.tv_sec; cmpGreaterEqual: result := a.tv_sec >= b.tv_sec; cmpEquals: result := a.tv_sec = b.tv_sec; cmpLess: result := a.tv_sec < b.tv_sec; cmpLessEqual: result := a.tv_sec <= b.tv_sec; end; end; end; procedure timeradd(a, b: timeval; var res: timeval); begin res.tv_sec := a.tv_sec + b.tv_sec; res.tv_usec := a.tv_usec + b.tv_usec; if res.tv_usec >= 1000000 then begin res.tv_usec := res.tv_usec - 1000000; res.tv_sec := res.tv_sec +1; end; end; procedure timersub(a, b: timeval; var res: timeval); begin res.tv_sec := a.tv_sec - b.tv_sec; res.tv_usec := a.tv_usec - b.tv_usec; if res.tv_usec < 0 then begin res.tv_usec := res.tv_usec + 1000000; res.tv_sec := res.tv_sec - 1; end; end; end.
unit JAScene; {$mode objfpc}{$H+} {$i JA.inc} interface uses {amiga} exec, agraphics, JATypes, JAMath, JAList, JALog, JARender, JAPalette, JACell, JASpatial, JANode; type TJAScene = record Name : string; Nodes : PJAList; {LinkedList of all Nodes} Toys : PJAList; {LinkedList of all Toys} Lights : PJAList; {LinkedList of all Lights} RootNode : PJANode; {Root Node of SceneGraph} RootCell : PJACell; {Root Cell of QuadTree} Camera : PJANode; {The active camera for this scene} {viewport dimensions} ViewWidth : SInt16; ViewWidthDiv2 : SInt16; ViewHeight : SInt16; ViewHeightDiv2 : SInt32; ViewVecDiv2 : TVec2; MousePosition : TVec2; {The camera-scene-space mouse position} SceneLink : TJASceneLink; end; PJAScene = ^TJAScene; function JASceneCreate(AName : string; AViewWidth, AViewHeight : SInt16) : PJAScene; function JASceneDestroy(AScene : PJAScene) : boolean; function JASceneUpdate(AScene : PJAScene; ADelta : Float32) : Float32; function JASceneRender(AScene : PJAScene) : Float32; {Render a given stage/pass of all nodes except lights} function JASceneRenderPass(AScene : PJAScene; ARenderPass : SInt16) : Float32; {Render a given stage/pass of all lights} function JASceneRenderLightPass(AScene : PJAScene; ARenderPass : SInt16) : Float32; {Render All Shadows for a Given Light} function JASceneRenderShadowPass(AScene : PJAScene; ALight : PJANode) : FLoat32; function JASceneRenderGrid(AScene : PJAScene) : Float32; function JASceneRenderCameraPosition(AScene : PJAScene) : Float32; function JAScenePointToCoord(AScene : PJAScene; APoint : TVec2SInt32) : TVec2; function JASceneCoordToPoint(AScene : PJAScene; ACoord : TVec2) : TVec2SInt32; procedure JASceneOnNodeCreate(AScene : pointer; ANode : PJANode); procedure JASceneOnNodeDestroy(AScene : pointer; ANode : PJANode); implementation function JASceneCreate(AName : string; AViewWidth, AViewHeight : SInt16) : PJAScene; begin Log('JASceneCreate','Creating Scene'); Result := PJAScene(JAMemGet(SizeOf(TJAScene))); JANodeRoot := nil; JANodeCamera := nil; JANodeLight0 := nil; with Result^ do begin Name := AName; {Store viewport dimensions} ViewWidth := AViewWidth; ViewWidthDiv2 := AViewWidth div 2; ViewHeight := AViewHeight; ViewHeightDiv2 := AViewHeight Div 2; ViewVecDiv2 := Vec2(ViewWidthDiv2, ViewHeightDiv2); {Setup Node List} Nodes := JAListCreate(); {Setup Toy List} Toys := JAListCreate(); {Setup Light List} Lights := JAListCreate(); JANodeLights := Lights; {Store Global Reference} SceneLink.Scene := Result; SceneLink.OnNodeCreate := @JASceneOnNodeCreate; SceneLink.OnNodeDestroy := @JASceneOnNodeDestroy; {Setup Root Cell} RootCell := JACellCreate(); {Setup Camera} {NOTE : This Camera 'Node' is not created in the SceneGraph} Camera := JANodeCreate(JANode_Camera, @Result^.SceneLink); {Set the Render ViewMatrix to the Camera Matrix} {$IFDEF JA_SCENE_MAT3} JARenderViewMatrix := Camera^.Spatial.WorldMatrix; {$ENDIF} MousePosition := Vec2Zero; JANodeRoot := RootNode; JANodeCamera := Camera; {Setup Root Node} RootNode := JANodeCreate(JANode_Root, @Result^.SceneLink); //JASceneGenerateBackgroundStars(Result); end; end; function JASceneDestroy(AScene : PJAScene) : boolean; begin Log('JASceneDestroy','Destroying Scene'); with AScene^ do begin SetLength(Name, 0); JANodeDestroy(RootNode); JAListDestroy(Lights); JANodeLights := nil; JANodeDestroy(Camera); JACellDestroy(RootCell); JAListDestroy(Toys); JAListDestroy(Nodes); end; JAMemFree(AScene,SizeOf(TJAScene)); Result := true; end; function JASceneUpdate(AScene : PJAScene; ADelta : Float32) : Float32; begin {$IFDEF JA_SCENE_MAT3} {Set the Render ViewMatrix to the Camera (View) Matrix and offset by window middle (projection) matrix} JARenderViewMatrix := Mat3Translation(AScene^.ViewVecDiv2) * AScene^.Camera^.Spatial.WorldMatrixInverse; JARenderModelMatrix := Mat3Identity; JARenderMVP := JARenderViewMatrix;// * JARenderModelMatrix; {we know it's an identity matrix here} {$ENDIF} Result += JANodeUpdateRecurse(AScene^.RootNode, ADelta); Result := 0.0; end; function JASceneRender(AScene : PJAScene) : Float32; var I : SInt16; begin Result := 0.0; //Result += JASceneRenderBackgroundStars(AScene); {$ifdef JA_RENDER_GRID} Result += JASceneRenderGrid(AScene); {$endif} {Draw SceneSpace Mouse Position} //JARenderLine(AScene^.Camera^.Spatial.WorldPosition, AScene^.MousePosition); {SetDrMd(JARenderRasterPort, JAM1); SetWriteMask(JARenderRasterPort, %11000); {Disable Planes 1-5} SetAPen(JARenderRasterPort, 24); {Clear the Extra-Half-Brite bit} //SetAPen(JARenderRasterPort, 32); {Set the Extra-Half-Brite bit} RectFill(JARenderRasterPort, JARenderClipRect.Left, JARenderClipRect.Top, JARenderClipRect.Right, JARenderClipRect.Bottom); SetWrMsk(JARenderRasterPort, %00000111); { Enable Planes 1-5} //SetAPen(JARenderRasterPort, 1); //Restore Black Pen} {$IFDEF JA_ENABLE_SHADOW} {Render Lights} for I := 0 to JARenderPassCount-1 do begin JASceneRenderLightPass(AScene, I); end; {$ENDIF} {Render Scene Nodes} Result += JANodeRenderRecurse(AScene^.RootNode); {Render Camera Position} JASceneRenderCameraPosition(AScene); end; function JASceneRenderPass(AScene: PJAScene; ARenderPass: SInt16): Float32; begin {Render Lights} JASceneRenderLightPass(AScene, ARenderPass); end; function JASceneRenderLightPass(AScene: PJAScene; ARenderPass: SInt16): Float32; var I : SInt16; ItemLight : PJAListItem; begin {Render Lights} Result := 0; ItemLight := AScene^.Lights^.Head^.Next; while (ItemLight<>AScene^.Lights^.Tail) do begin {Render Light Cones in Multiple passes to allow penumbra regions to blend better} Result += JANodeRenderPass(PJANode(ItemLight^.Data), ARenderPass); {Render All Shadows for this Light} ItemLight := ItemLight^.Next; end; end; function JASceneRenderShadowPass(AScene: PJAScene; ALight: PJANode): FLoat32; begin end; function JASceneRenderGrid(AScene : PJAScene) : Float32; var GridRect : TJRectSInt32; DivisionMajor : SInt32; DivisionMinor : SInt32; GridPos : TVec2SInt32; begin Result := 0; JARenderModelMatrix := Mat3Identity; GridRect := JRectSInt32(-400,-400,400,400); DivisionMajor := 400; DivisionMinor := 200; {Minor Divisions} SetAPen(JARenderRasterPort, Palette^.PenGreen); GridPos.X := GridRect.Left; while GridPos.X <= GridRect.Right do begin if (GridPos.X+400) mod DivisionMajor <> 0 then JARenderLine(Vec2(GridPos.X,GridRect.Top), Vec2(GridPos.X,GridRect.Bottom)); GridPos.X += DivisionMinor; end; GridPos.Y := GridRect.Top; while GridPos.Y <= GridRect.Bottom do begin if (GridPos.Y+400) mod DivisionMajor <> 0 then JARenderLine(Vec2(GridRect.Left,GridPos.Y), Vec2(GridRect.Right,GridPos.Y)); GridPos.Y += DivisionMinor; end; SetAPen(JARenderRasterPort, Palette^.PenWhite); {Major Divisions} GridPos.X := GridRect.Left; while GridPos.X <= GridRect.Right do begin JARenderLine(Vec2(GridPos.X,GridRect.Top), Vec2(GridPos.X,GridRect.Bottom)); GridPos.X += DivisionMajor; end; GridPos.Y := GridRect.Top; while GridPos.Y <= GridRect.Bottom do begin JARenderLine(Vec2(GridRect.Left,GridPos.Y), Vec2(GridRect.Right,GridPos.Y)); GridPos.Y += DivisionMajor; end; end; function JASceneRenderCameraPosition(AScene : PJAScene) : Float32; begin {$IFDEF JA_SCENE_MAT3} JARenderModelMatrix := AScene^.Camera^.Spatial.WorldMatrix; JARenderMVP := JARenderViewMatrix * JARenderModelMatrix; {$ENDIF} JARenderLine(Vec2(-5,0), Vec2(5,0)); JARenderLine(Vec2(0,-5), Vec2(0,5)); Result := 0; end; function JAScenePointToCoord(AScene : PJAScene; APoint : TVec2SInt32) : TVec2; begin {$IFDEF JA_SCENE_MAT3} Result := Vec2DotMat3Affine(vec2(APoint.X,APoint.Y) - AScene^.ViewVecDiv2, AScene^.Camera^.Spatial.WorldMatrix); {$ENDIF} end; function JASceneCoordToPoint(AScene : PJAScene; ACoord : TVec2) : TVec2SInt32; var Vec : TVec2; begin {$IFDEF JA_SCENE_MAT3} Vec := Vec2DotMat3Affine(ACoord, AScene^.Camera^.Spatial.WorldMatrixInverse) + AScene^.ViewVecDiv2; {$ENDIF} Result := Vec2SInt32(round(Vec.X),round(Vec.Y)); end; procedure JASceneOnNodeCreate(AScene: pointer; ANode: PJANode); var ListItem : PJAListItem; begin Log('JASceneOnNodeCreate','Create [%s]',[JANodeRootPath(ANode)]); case ANode^.NodeType of JANode_Light : begin ListItem := JAListItemCreate(); ListItem^.Data := ANode; JAListPushTail(PJAScene(AScene)^.Lights, ListItem); end; end; end; procedure JASceneOnNodeDestroy(AScene: pointer; ANode: PJANode); begin Log('JASceneOnNodeDestroy','Destroy [%s]',[JANodeRootPath(ANode)]); end; end.
unit dec_1; interface implementation var i8: int8; u8: uint8; i16: int16; u16: uint16; i32: int32; u32: uint32; i64: int64; u64: uint64; procedure Init; begin i8 := 100; u8 := 100; i16 := 100; u16 := 100; i32 := 100; u32 := 100; i64 := 100; u64 := 100; end; procedure Test1; begin dec(i8); dec(u8); dec(i16); dec(u16); dec(i32); dec(u32); dec(i64); dec(u64); end; procedure Test2; begin dec(i8, 0); dec(u8, 1); dec(i16, 2); dec(u16, 3); dec(i32, 4); dec(u32, 5); dec(i64, 6); dec(u64, 7); end; procedure Test3; var D: Int32; begin D := 10; dec(i8, D); dec(u8, D); dec(i16, D); dec(u16, D); dec(i32, D); dec(u32, D); dec(i64, D); dec(u64, D); end; initialization Init(); Test1(); Test2(); Test3(); finalization Assert(i8 = 89); Assert(u8 = 88); Assert(i16 = 87); Assert(u16 = 86); Assert(i32 = 85); Assert(u32 = 84); Assert(i64 = 83); Assert(u64 = 82); end.
unit Principal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, ulkJSON, IdHashMessageDigest, ExtCtrls; type TForm1 = class(TForm) BitBtn1: TBitBtn; IdHTTP: TIdHTTP; BitBtn2: TBitBtn; edtURL: TEdit; lblEndereco: TLabel; lblUsuario: TLabel; edtUsuario: TEdit; lblSenha: TLabel; edtSenha: TEdit; lblClientId: TLabel; edtClientId: TEdit; edtClientSecret: TEdit; lblClientSecret: TLabel; pnlVersao: TPanel; procedure BitBtn1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FToken : string; function GerarToken(): String; function MD5(const texto: string): string; function ObterVersao(): string; public { Public declarations } end; var Form1: TForm1; implementation uses Wcrypt2; {$R *.dfm} procedure TForm1.BitBtn1Click(Sender: TObject); begin ShowMessage(GerarToken); Self.pnlVersao.Caption := 'Versão: ' + Self.ObterVersao(); end; {--------------------------------------------------------------------} { Plataforma: Delphi 7 / Indy {--------------------------------------------------------------------} function TForm1.GerarToken(): String; var lHTTP : TIdHTTP; lParametros : TStringStream; lRetorno : TStringStream; js: TlkJSONobject; lRetornoAux : string; lNounce: Integer; begin lRetornoAux:= ''; lHTTP := TIdHTTP.Create(nil); js:= TlkJSONobject.Create(); lNounce := 55; lParametros := TStringStream.Create('client_id=' + Self.edtClientId.Text + '&'+ 'client_secret=' + Self.edtClientSecret.Text + '&'+ 'grant_type=password&'+ 'username=' + Self.edtUsuario.Text + '&'+ 'nonce=' + IntToStr(lNounce) + '&'+ 'password=' + Self.MD5(Self.edtUsuario.Text + IntToStr(lNounce) + Self.edtSenha.Text)); lRetorno := TStringStream.Create(''); try lHTTP.Request.ContentType := 'application/x-www-form-urlencoded'; lHTTP.Post(edtURL.Text + '/oauth/token', lParametros, lRetorno); js := TlkJSON.ParseText(lRetorno.DataString) as TlkJSONobject; except on E: Exception do ShowMessage(E.Message); end; lHTTP.Free; lParametros.Free; lRetornoAux:= lRetornoAux + 'access_token = ' + Copy(VarToStr(js.Field['access_token'].Value), 1, 50) + '...' + #10 + #13; lRetornoAux:= lRetornoAux + 'token_type = ' + VarToStr(js.Field['token_type'].Value) + #10 + #13; lRetornoAux:= lRetornoAux + 'refresh_token = ' + VarToStr(js.Field['refresh_token'].Value) + #10 + #13; lRetornoAux:= lRetornoAux + 'as:client_id = ' + VarToStr(js.Field['as:client_id'].Value) + #10 + #13; lRetornoAux:= lRetornoAux + 'userName = ' + VarToStr(js.Field['userName'].Value) + #10 + #13; lRetornoAux:= lRetornoAux + '.issued = ' + VarToStr(js.Field['.issued'].Value) + #10 + #13; lRetornoAux:= lRetornoAux + '.expires = ' + VarToStr(js.Field['.expires'].Value) + #10 + #13; FToken:= VarToStr(js.Field['access_token'].Value); Result := lRetornoAux; end; function TForm1.MD5(const texto: string): string; var hCryptProvider: HCRYPTPROV; hHash: HCRYPTHASH; bHash: array[0..$7f] of Byte; dwHashLen: DWORD; pbContent: PByte; i: Integer; begin dwHashLen := 16; pbContent := Pointer(PChar(texto)); Result := ''; if CryptAcquireContext(@hCryptProvider, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT or CRYPT_MACHINE_KEYSET) then begin if CryptCreateHash(hCryptProvider, CALG_MD5, 0, 0, @hHash) then begin if CryptHashData(hHash, pbContent, Length(texto), 0) then begin if CryptGetHashParam(hHash, HP_HASHVAL, @bHash[0], @dwHashLen, 0) then begin for i := 0 to dwHashLen - 1 do begin Result := Result + Format('%.2x', [bHash[i]]); end; end; end; CryptDestroyHash(hHash); end; CryptReleaseContext(hCryptProvider, 0); end; Result := AnsiLowerCase(Result); end; procedure TForm1.BitBtn2Click(Sender: TObject); var lHTTP : TIdHTTP; lParametros : TStringStream; js: TlkJSONobject; lRetorno : TStringStream; begin lHTTP := TIdHTTP.Create(nil); lParametros := TStringStream.Create('{' + ' "Identificador": "",' + ' "Enderecos": [' + ' {' + '"CEP": "22060020",' + ' "CodigoSuframa": "",' + ' "Complemento": "",' + ' "IdentificadorBairro": "00A00001R7",' + ' "IdentificadorCidade": "00A000059E",' + ' "IdentificadorTipoLogradouro": "",' + ' "InscricaoEstadual": "",' + ' "NomeLogradouro": "RUA LEOPOLDO MIGUEZ n 99/202",' + ' "NumeroLogradouro": "",' + ' "Observacao": "11020258",' + ' "PessoasContato": [' + ' {' + '"ContatoPrincipal": true,' + ' "Email": "email@globo.com",' + ' "Identificador": "",' + ' "Nome": "Pessoa de contato inserida pela API",' + ' "PaginaInternet": "",' + ' "TipoCadastro": "I",' + ' "TelefoneCelular": "(0021)99999-9999",' + ' "TelefoneFixo": "(0021)11111-111"' + ' }' + ' ],' + ' "SiglaUnidadeFederativa": "RJ",' + ' "TipoCadastro": "I",' + ' "Tipos": {' + ' "Cobranca": true,' + ' "Comercial": true,' + ' "Correspondencia": true,' + ' "Entrega": true,' + ' "Principal": true,' + ' "Residencial": true' + ' },' + ' "Codigo": "01"' + ' }' + ' ],' + ' "IdentificadorRepresentantePrincipal": "",' + ' "Tipo": "F",' + ' "Codigo": "",' + ' "CpfCnpj": "01234567894",' + ' "DataNascimento": "1980-04-26T00:00:00:000Z",' + ' "Nome": "",' + ' "NomeCurto": ""' + '}'); lRetorno := TStringStream.Create(''); try try lHTTP.Request.CustomHeaders.Values['Authorization'] := 'bearer ' + FToken; lHTTP.Request.ContentType := 'application/json'; lHTTP.Post(edtURL.Text + '/api/clientes', lParametros, lRetorno); js := TlkJSON.ParseText(lRetorno.DataString) as TlkJSONobject; ShowMessage('Cliente cadastrado com sucesso. ' + #13#10 + 'Identificador: ' + js.Field['ListaObjetos'].Child[0].Field['Identificador'].Value + #13#10 + 'Código de chamada: ' + js.Field['ListaObjetos'].Child[0].Field['Codigo'].Value); except on E: EIdHTTPProtocolException do begin ShowMessage(IntToStr(E.ErrorCode )); ShowMessage(E.Message); ShowMessage(E.ErrorMessage); end; on E: Exception do begin ShowMessage(E.Message); end; end; finally lRetorno.Free(); end; end; procedure TForm1.FormCreate(Sender: TObject); begin Randomize; end; function TForm1.ObterVersao: string; var lHTTP : TIdHTTP; js: TlkJSONobject; lRetorno : TStringStream; begin lRetorno := TStringStream.Create(''); try lHTTP := TIdHTTP.Create(nil); lHTTP.Request.CustomHeaders.Values['Authorization'] := 'bearer ' + FToken; lHTTP.Request.ContentType := 'application/json'; lHTTP.Get(edtURL.Text + '/api/versao', lRetorno); js := TlkJSON.ParseText(lRetorno.DataString) as TlkJSONobject; Result := js.Field['ListaObjetos'].Child[0].Field['VersaoCompleta'].Value; finally lRetorno.Free(); end; end; end.
unit IdDsnRegister; {$I IdCompilerDefines.inc} interface uses {$IFDEF VCL6ORABOVE}DesignIntf, DesignEditors;{$ELSE}Dsgnintf;{$ENDIF} type TIdPropEdBinding = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure SetValue(const Value: string); override; end; // Procs procedure Register; implementation uses Classes, IdDsnBaseCmpEdt, IdBaseComponent, IdDsnPropEdBinding, IdGlobal, IdComponent, IdMessage, {Since we are removing New Design-Time part, we remove the "New Message Part Editor"} {IdDsnNewMessagePart, } IdStack, IdSocketHandle, IdTCPServer, IdUDPServer, {$IFDEF Linux} QControls, QForms, QStdCtrls, QButtons, QExtCtrls, QActnList {$ELSE} Controls, Forms, StdCtrls, Buttons, ExtCtrls, ActnList {$ENDIF} ; const MessagePartsType : array[0..1] of String = ('TIdAttachment', 'TIdText'); {Do not Localize} procedure TIdPropEdBinding.Edit; begin inherited; with TIdPropEdBindingEntry.Create(nil) do try SetList(Value); if ShowModal = mrOk then Value := GetList; finally Free; end; end; function TIdPropEdBinding.GetAttributes: TPropertyAttributes; begin result := [paDialog]; end; function TIdPropEdBinding.GetValue: string; var IdSockets: TIdSocketHandles; i: integer; sep: string; begin IdSockets := TIdSocketHandles(GetOrdValue); result := ''; sep := ''; {Do not Localize} for i := 0 to IdSockets.Count - 1 do begin result := result + sep + MakeBindingStr(IdSockets[i].IP, IdSockets[i].Port); sep := ','; {Do not Localize} end; end; procedure TIdPropEdBinding.SetValue(const Value: string); var IdSockets: TIdSocketHandles; s: string; sl: TStringList; i, j: integer; begin inherited; IdSockets := TIdSocketHandles(GetOrdValue); IdSockets.BeginUpdate; IdSockets.Clear; sl := TStringList.Create; try sl.CommaText := Value; for i := 0 to sl.Count - 1 do with TIdSocketHandle.Create(IdSockets) do begin s := sl[i]; j := IndyPos(':', s); {Do not Localize} IP := Copy(s, 1, j - 1); Port := GStack.WSGetServByName(Copy(s, j+1, Length(s))); end; finally sl.Free; IdSockets.EndUpdate; end; end; procedure Register; begin RegisterPropertyEditor(TypeInfo(TIdSocketHandles), TIdTCPServer, '', TIdPropEdBinding); {Do not Localize} RegisterPropertyEditor(TypeInfo(TIdSocketHandles), TIdUDPServer, '', TIdPropEdBinding); {Do not Localize} RegisterComponentEditor(TIdBaseComponent, TIdBaseComponentEditor); // RegisterComponentEditor ( TIdMessage, TIdMessageComponentEdit); } end; end.
{*************************************************************** * * Project : TimeServer * Unit Name: Main * Purpose : Demonstrates basic use of the TimeServer * Date : 21/01/2001 - 15:12:26 * History : * ****************************************************************} unit Main; interface uses {$IFDEF Linux} QGraphics, QForms, QControls, QDialogs, QStdCtrls, {$ELSE} windows, messages, graphics, controls, forms, dialogs, stdctrls, {$ENDIF} SysUtils, Classes, IdComponent, IdTCPServer, IdTimeServer, IdBaseComponent; type TfrmMain = class(TForm) IdTimeServer1: TIdTimeServer; Label1: TLabel; lblStatus: TLabel; procedure FormActivate(Sender: TObject); procedure IdTimeServer1Connect(AThread: TIdPeerThread); procedure IdTimeServer1Disconnect(AThread: TIdPeerThread); private public end; var frmMain: TfrmMain; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} // No Code required - TimeServer is functional as is. procedure TfrmMain.FormActivate(Sender: TObject); begin try IdTimeServer1.Active := True; except ShowMessage('Permission Denied. Cannot bind reserved port due to security reasons'); Application.Terminate; end; end; procedure TfrmMain.IdTimeServer1Connect(AThread: TIdPeerThread); begin lblStatus.caption := '[ Client connected ]'; end; procedure TfrmMain.IdTimeServer1Disconnect(AThread: TIdPeerThread); begin lblStatus.caption := '[ idle ]'; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 定义系统经常使用的一此类,常驻内存 //主要实现: //-----------------------------------------------------------------------------} unit untEasyUtilClasses; interface uses Windows, Classes; type //插件类 PPLugin = ^TPlugin; TPlugin = record FileName: string; //插件文件 EName: string; //英文名 CName: string; //中文名 image1: string; //图片 image2: string; //点击时图片 iOrder: Integer; //序号 Flag : string; //标志符 end; implementation end.
unit FIToolkit.Logger.Types; interface uses System.Generics.Collections; type TLogTimestamp = type TDateTime; TLogItem = (liMessage, liSection, liMethod); TLogItems = set of TLogItem; TLogMsgSeverity = type Word; TLogMsgType = ( lmNone, // lower bound lmDebug, lmInfo, lmWarning, lmError, lmFatal, lmExtreme // upper bound ); TLogMsgTypeDescription = TPair<TLogMsgType, String>; TLogMsgTypeDescriptions = record strict private FItems : array [TLogMsgType] of String; private function GetItem(Index : TLogMsgType) : String; function GetMaxItemLength : Integer; procedure SetItem(Index : TLogMsgType; const Value : String); public constructor Create(const Descriptions : array of TLogMsgTypeDescription); property Items[Index : TLogMsgType] : String read GetItem write SetItem; default; property MaxItemLength : Integer read GetMaxItemLength; end; implementation uses System.SysUtils, System.Math; { TLogMsgTypeDescriptions } constructor TLogMsgTypeDescriptions.Create(const Descriptions : array of TLogMsgTypeDescription); var Desc : TLogMsgTypeDescription; begin for Desc in Descriptions do FItems[Desc.Key] := Desc.Value; end; function TLogMsgTypeDescriptions.GetItem(Index : TLogMsgType) : String; begin Result := FItems[Index]; end; function TLogMsgTypeDescriptions.GetMaxItemLength : Integer; var LMT : TLogMsgType; begin Result := 0; for LMT := Low(TLogMsgType) to High(TLogMsgType) do Result := Max(Result, FItems[LMT].Length); end; procedure TLogMsgTypeDescriptions.SetItem(Index : TLogMsgType; const Value : String); begin FItems[Index] := Value; end; end.
unit UMainForm; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, CheckLst, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.Jpeg, // GLScene GLTexture, GLCadencer, GLWin32Viewer, GLScene, GLPostEffects, GLGraph, GLUtils, GLContext, GLVectorGeometry, GLGeomObjects, GLCoordinates, GLObjects, GLVectorFileObjects, GLSimpleNavigation, GLCrossPlatform, GLMaterial, GLBaseClasses, // GlScene shaders GLSLPostBlurShader, CGPostTransformationShader, // FileFormats TGA, GLFileMD2, GLFileMS3D, GLFile3DS; type TPostShaderDemoForm = 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; TurnPitchrollCheckBox: TCheckBox; Panel2: TPanel; ShaderCheckListBox: TCheckListBox; Label1: TLabel; BigBlurThicknessCheckbox: TCheckBox; GLSimpleNavigation1: TGLSimpleNavigation; PostShaderHolder: TGLPostShaderHolder; procedure FormCreate(Sender: TObject); procedure CadencerProgress(Sender: TObject; const deltaTime, newTime: double); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure LightCubeProgress(Sender: TObject; const deltaTime, newTime: Double); procedure BigBlurThicknessCheckboxClick(Sender: TObject); procedure ShaderCheckListBoxClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var PostShaderDemoForm: TPostShaderDemoForm; BlurShader: TGLSLPostBlurShader; TransformationShader: TGLCGPostTransformationShader; implementation {$R *.dfm} procedure TPostShaderDemoForm.FormCreate(Sender: TObject); begin // First load models. SetGLSceneMediaDir(); Fighter.LoadFromFile('waste.md2'); //Fighter Fighter.SwitchToAnimation(0, True); Fighter.AnimationMode := aamLoop; Fighter.Scale.Scale(2); Teapot.LoadFromFile('Teapot.3ds'); //Teapot (no texture coordinates) Teapot.Scale.Scale(0.8); Sphere_big.LoadFromFile('Sphere_big.3DS'); Sphere_big.Scale.Scale(70); Sphere_little.LoadFromFile('Sphere_little.3ds'); Sphere_little.Scale.Scale(4); // Then load textures. MaterialLibrary.LibMaterialByName('Earth').Material.Texture.Image.LoadFromFile('Earth.jpg'); MaterialLibrary.LibMaterialByName('Fighter').Material.Texture.Image.LoadFromFile('Waste.jpg'); MaterialLibrary.LibMaterialByName('Noise').Material.Texture.Image.LoadFromFile('Flare1.bmp'); // Blur Shader BlurShader := TGLSLPostBlurShader.Create(Self); PostShaderHolder.Shaders.Add.Shader := BlurShader; ShaderCheckListBox.Items.AddObject('Blur Shader', BlurShader); ShaderCheckListBox.Checked[0] := True; // Transformation Shader TransformationShader := TGLCGPostTransformationShader.Create(Self); TransformationShader.TransformationTexture := MaterialLibrary.LibMaterialByName('Noise').Material.Texture; PostShaderHolder.Shaders.Add.Shader := TransformationShader; ShaderCheckListBox.Items.AddObject('Transformation Shader', TransformationShader); ShaderCheckListBox.Checked[1] := True; end; procedure TPostShaderDemoForm.CadencerProgress(Sender: TObject; const deltaTime, newTime: double); begin Viewer.Invalidate; if TurnPitchrollCheckBox.Checked then begin Fighter.Roll(20 * deltaTime); Sphere_big.Pitch(40 * deltaTime); Sphere_big.Turn(40 * deltaTime); Sphere_little.Roll(40 * deltaTime); Teapot.Roll(-20 * deltaTime); end; end; procedure TPostShaderDemoForm.LightCubeProgress(Sender: TObject; const deltaTime, newTime: Double); begin if LightMovingCheckBox.Checked then LightCube.MoveObjectAround(Camera.TargetObject, sin(NewTime) * deltaTime * 10, deltaTime * 20); end; procedure TPostShaderDemoForm.BigBlurThicknessCheckboxClick(Sender: TObject); begin if BigBlurThicknessCheckbox.Checked then BlurShader.Threshold := 0.005 else BlurShader.Threshold := 0.2; end; procedure TPostShaderDemoForm.ShaderCheckListBoxClick(Sender: TObject); var I: Integer; begin if ShaderCheckListBox.Items.Count <> 0 then for I := 0 to ShaderCheckListBox.Items.Count - 1 do TGLShader(ShaderCheckListBox.Items.Objects[I]).Enabled := ShaderCheckListBox.Checked[I]; end; procedure TPostShaderDemoForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Cadencer.Enabled := False; end; end.
uses megacrt,gui; {---------------------------------------------------------------- GUI.TPU --- msgbox(color_titulo,'titulo', color_texto,color_bordes,color_fondo, string_especial,botones_a_escojer). String especial: xs:='Hola | uno dos |!| Esto es para|^decir que| |'; | nueva ! linea ^ centra- linea linea con raya lizado blanco Los botones_a_escojer se el numero que devuelve la funcion en la variable de string_especial depende de los divisores. Devuelven los valores: ' Ok | Cancel | Retry ' .... Esc='0' '1' '2' '3' .... Cuando veas un numero menor de 16 dentro de un texto a imprimir, 'Hola '#14'mundo' esto cambia el color al que pongas. Asi, pone 'Hola ' del color antes escojido y continua de color 14 (amarillo). -----------------------------------------------------------------} var bs,cs : string; txt : text; client : string; {*****************************************************************************} begin {color(red,blue); cls('±');} get_screen(screen1); mouse_on; cursor_off; help('Dale a '#1'[Enter]'#0'/Usa el mouse. '#1'[Ctrl]+[flechas]'#0' o mouse mueve caja. '); bs:=' | ¨Quiere continuar? | '; msgbox(ltgreen,' Batch file... ',yellow,white,blue,bs,' Si | Cancelar '); mouse_hide; put_screen(screen1); if (bs='0') or (bs='2') then halt(1); end.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit RouteCollectionIntf; interface {$MODE OBJFPC} uses RouterIntf; type (*!------------------------------------------------ * interface for any class that can set route handler * for various http verb * * This interface will be deprecated. You should use IRouter * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) IRouteCollection = interface(IRouter) ['{382B4D2E-0061-4727-8C79-291FCD39F798}'] end; implementation end.
unit KromOGLUtils; interface uses dglOpenGL, Forms, Windows, SysUtils; procedure SetRenderFrame(RenderFrame: HWND; out h_DC: HDC; out h_RC: HGLRC); procedure SetRenderFrameAA(DummyFrame, RenderFrame: HWND; AntiAliasing: Byte; out h_DC: HDC; out h_RC: HGLRC); implementation function SetDCPixelFormat(h_DC: HDC; PixelFormat: Integer): Boolean; var nPixelFormat: Integer; PixelDepth: Integer; pfd: TPixelFormatDescriptor; begin PixelDepth := 32; //32bpp is common with pfd do begin nSize := SizeOf(TPIXELFORMATDESCRIPTOR); // Size Of This Pixel Format Descriptor nVersion := 1; // The version of this data structure dwFlags := PFD_DRAW_TO_WINDOW // Buffer supports drawing to window or PFD_SUPPORT_OPENGL // Buffer supports OpenGL drawing or PFD_DOUBLEBUFFER; // Supports double buffering iPixelType := PFD_TYPE_RGBA; // RGBA color format cColorBits := PixelDepth; // OpenGL color depth cRedBits := 0; // Number of red bitplanes cRedShift := 0; // Shift count for red bitplanes cGreenBits := 0; // Number of green bitplanes cGreenShift := 0; // Shift count for green bitplanes cBlueBits := 0; // Number of blue bitplanes cBlueShift := 0; // Shift count for blue bitplanes cAlphaBits := 0; // Not supported cAlphaShift := 0; // Not supported cAccumBits := 0; // No accumulation buffer cAccumRedBits := 0; // Number of red bits in a-buffer cAccumGreenBits := 0; // Number of green bits in a-buffer cAccumBlueBits := 0; // Number of blue bits in a-buffer cAccumAlphaBits := 0; // Number of alpha bits in a-buffer cDepthBits := 16; // Specifies the depth of the depth buffer cStencilBits := 8; // Turn off stencil buffer cAuxBuffers := 0; // Not supported iLayerType := PFD_MAIN_PLANE; // Ignored bReserved := 0; // Number of overlay and underlay planes dwLayerMask := 0; // Ignored dwVisibleMask := 0; // Transparent color of underlay plane dwDamageMask := 0; // Ignored end; if PixelFormat = 0 then nPixelFormat := ChoosePixelFormat(h_DC, @pfd) else nPixelFormat := PixelFormat; if nPixelFormat = 0 then begin MessageBox(0, 'Unable to find a suitable pixel format', 'Error', MB_OK or MB_ICONERROR); Result := false; Exit; end; //Even with known pixel format we still need to supply some PFD structure if not SetPixelFormat(h_DC, nPixelFormat, @pfd) then begin MessageBox(0, 'Unable to set the pixel format', 'Error', MB_OK or MB_ICONERROR); Result := false; Exit; end; Result := true; end; function GetMultisamplePixelFormat(h_DC: HDC; AntiAliasing: Byte): Integer; var pixelFormat: Integer; ValidFormat: Boolean; NumFormats: GLUint; iAttributes: array of GLint; begin Result := 0; if not WGL_ARB_multisample or not Assigned(wglChoosePixelFormatARB) then Exit; SetLength(iAttributes, 21); iAttributes[0] := WGL_DRAW_TO_WINDOW_ARB; iAttributes[1] := 1; iAttributes[2] := WGL_SUPPORT_OPENGL_ARB; iAttributes[3] := 1; iAttributes[4] := WGL_ACCELERATION_ARB; iAttributes[5] := WGL_FULL_ACCELERATION_ARB; iAttributes[6] := WGL_COLOR_BITS_ARB; iAttributes[7] := 24; iAttributes[8] := WGL_ALPHA_BITS_ARB; iAttributes[9] := 8; iAttributes[10] := WGL_DEPTH_BITS_ARB; iAttributes[11] := 16; iAttributes[12] := WGL_STENCIL_BITS_ARB; iAttributes[13] := 0; iAttributes[14] := WGL_DOUBLE_BUFFER_ARB; iAttributes[15] := 1; iAttributes[16] := WGL_SAMPLE_BUFFERS_ARB; iAttributes[17] := 1; iAttributes[18] := WGL_SAMPLES_ARB; iAttributes[19] := AntiAliasing; iAttributes[20] := 0; //Try to find mode with slightly worse AA before giving up repeat iAttributes[19] := AntiAliasing; ValidFormat := wglChoosePixelFormatARB(h_dc, @iAttributes[0], nil, 1, @pixelFormat, @NumFormats); if ValidFormat and (NumFormats >= 1) then begin Result := pixelFormat; Exit; end; AntiAliasing := AntiAliasing div 2; until(AntiAliasing < 2); end; procedure SetContexts(RenderFrame: HWND; PixelFormat: Integer; out h_DC: HDC; out h_RC: HGLRC); begin h_DC := GetDC(RenderFrame); if h_DC = 0 then begin MessageBox(HWND(nil), 'Unable to get a device context', 'Error', MB_OK or MB_ICONERROR); Exit; end; if not SetDCPixelFormat(h_DC, PixelFormat) then Exit; h_RC := wglCreateContext(h_DC); if h_RC = 0 then begin MessageBox(HWND(nil), 'Unable to create an OpenGL rendering context', 'Error', MB_OK or MB_ICONERROR); Exit; end; if not wglMakeCurrent(h_DC, h_RC) then begin MessageBox(HWND(nil), 'Unable to activate OpenGL rendering context', 'Error', MB_OK or MB_ICONERROR); Exit; end; end; procedure SetRenderFrame(RenderFrame: HWND; out h_DC: HDC; out h_RC: HGLRC); begin InitOpenGL; SetContexts(RenderFrame, 0, h_DC, h_RC); ReadExtensions; ReadImplementationProperties; end; {The key problem is this: the function we use to get WGL extensions is, itself, an OpenGL extension. Thus like any OpenGL function, it requires an OpenGL context to call it. So in order to get the functions we need to create a context, we have to... create a context. Fortunately, this context does not need to be our final context. All we need to do is create a dummy context to get function pointers, then use those functions directly. Unfortunately, Windows does not allow recreation of a rendering context within a single HWND. We must destroy previous HWND context and create final HWND context after we are finished with the dummy context.} procedure SetRenderFrameAA(DummyFrame, RenderFrame: HWND; AntiAliasing: Byte; out h_DC: HDC; out h_RC: HGLRC); var PixelFormat: Integer; begin InitOpenGL; SetContexts(DummyFrame, 0, h_DC, h_RC); ReadExtensions; ReadImplementationProperties; PixelFormat := GetMultisamplePixelFormat(h_DC, AntiAliasing); wglMakeCurrent(h_DC, 0); wglDeleteContext(h_RC); SetContexts(RenderFrame, PixelFormat, h_DC, h_RC); ReadExtensions; ReadImplementationProperties; end; end.
unit fActivateDeactivate; interface uses Windows, Messages, SysUtils, StrUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ExtCtrls, ORCtrls,ORFn, rCore, uCore, oRNet, Math, fOrders, ORClasses, rOrders, fMeds, rMeds, VA508AccessibilityManager; type TfrmActivateDeactive = class(TfrmAutoSz) TActivate: TButton; TDeactive: TButton; Memo1: TMemo; TCancel: TButton; procedure TActivateClick(Sender: TObject); procedure TDeactiveClick(Sender: TObject); procedure TCancelClick(Sender: TObject); private { Private declarations } procedure GetOriginalOrders(OrderID: TStringList; var OriginalOrder: TORStringList); procedure DCOriginalOrder(OrderID: string); procedure BuildForm(Str1: String); function PromptForm(Text: String): String; public { Public declarations } procedure fActivateDeactive(OrderID: TStringList); overload; procedure fActivateDeactive(OrderID: TStringList; AList: TListBox); overload; end; var frmActivateDeactive: TfrmActivateDeactive; Act: Boolean; Deact: Boolean; CancelProcess: Boolean; implementation {$R *.dfm} { TfrmActivateDeactive } procedure TfrmActivateDeactive.BuildForm(Str1: String); var str: string; begin with frmActivateDeactive do begin str := 'This order is in a pending status. If this pending order is discontinued, the original order will still be active.'; str := str + CRLF + CRLF + str1; str := str + CRLF + CRLF + 'Click:'; str := str + CRLF + ' "DC BOTH" to discontinue both orders '; str := str + CRLF + ' "DC Pending Order" to discontinue only the pending order and return the original order back to an active status '; str := str + CRLF + ' "Cancel - No Action Taken" to stop the discontinue process '; Memo1.ReadOnly := False; Memo1.Text := str; Memo1.ReadOnly := True; end; ResizeAnchoredFormToFont(frmActivateDeactive); frmActivateDeactive.ShowModal; frmActivateDeactive.Release; end; procedure TfrmActivateDeactive.fActivateDeactive(OrderID: TStringList); var i,Pos: integer; tmpArr: TORStringList; ActDeact: string; AnOrder: TOrder; begin //called from order tab tmpArr := TORStringList.Create; GetOriginalOrders(OrderID,tmpArr); with forders.frmOrders.lstOrders do for i := 0 to items.Count-1 do if Selected[i] then begin AnOrder := TOrder(Items.Objects[i]); Pos := tmpArr.IndexOfPiece(AnOrder.ID,U,1); if Pos > -1 then begin ActDeact := PromptForm(AnOrder.Text); if ActDeact = 'D' then AnOrder.DCOriginalOrder := True; if ActDeact = 'A' then AnOrder.DCOriginalOrder := False; if ActDeact = 'C' then Selected[i] := False; end; end; end; procedure TfrmActivateDeactive.fActivateDeactive(OrderID: TStringList; AList: TListBox); var i,Pos: integer; tmpArr: TORStringList; ActDeact: String; AMed: TMedListRec; AnOrder: TOrder; begin //called from Med tab tmpArr := TORStringList.Create; GetOriginalOrders(OrderID,tmpArr); AnOrder := TOrder.Create; with AList do for i := 0 to items.Count-1 do if Selected[i] then begin AMed := TMedListRec(Items.Objects[i]); if AMed = nil then Continue; Pos := tmpArr.IndexOfPiece(AMed.OrderID,U,1); if Pos > -1 then begin ActDeact := PromptForm(Alist.Items.Strings[i]); if ActDeact = 'D' then begin AnOrder := GetOrderByIFN(Piece(tmpArr.Strings[Pos],U,1)); DCOriginalOrder(AnOrder.ID); //AnOrder.DCOriginalOrder := True; end; if ActDeact = 'A' then AnOrder.DCOriginalOrder := False; if ActDeact = 'C' then Selected[i] := False; end; end; end; procedure TfrmActivateDeactive.GetOriginalOrders(OrderID: TStringList; var OriginalOrder: TORStringList); var i: integer; aTmpList: TStringList; begin aTmpList := TStringList.Create; try CallVistA('ORWDX1 DCREN', [OrderID], aTmpList); for i := 0 to aTmpList.Count-1 do OriginalOrder.Add(aTmpList[i]); finally FreeAndNil(aTmpList); end; end; function TfrmActivateDeactive.PromptForm(Text: String): String; begin frmActivateDeactive := TfrmActivateDeactive.create(Application); BuildForm(Text); if Deact = True then Result := 'D'; if Act = True then Result := 'A'; if CancelProcess = True then Result := 'C'; end; procedure TfrmActivateDeactive.TActivateClick(Sender: TObject); begin inherited; Act := True; Deact := False; CancelProcess := False; frmActivateDeactive.Close; end; procedure TfrmActivateDeactive.TDeactiveClick(Sender: TObject); begin inherited; Act := False; Deact := True; CancelProcess := False; frmActivateDeactive.Close; end; procedure TfrmActivateDeactive.TCancelClick(Sender: TObject); begin inherited; Act := False; Deact := False; CancelProcess := True; frmActivateDeactive.Close; end; procedure TfrmActivateDeactive.DCOriginalOrder(OrderID: string); begin CallVistA('ORWDX1 DCORIG', [OrderID]); end; end.
unit uIParser; {$I ..\Include\IntXLib.inc} interface uses {$IFDEF DELPHI} Generics.Collections, {$ENDIF DELPHI} {$IFDEF FPC} fgl, {$ENDIF FPC} uIntX, uIntXLibTypes; type /// <summary> /// Parser class interface. /// </summary> IIParser = interface(IInterface) ['{933EE4BE-5EC3-4E51-8EBB-033D0E10F793}'] /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">Number as string.</param> /// <param name="numberBase">Number base.</param> /// <param name="charToDigits">Char->digit dictionary.</param> /// <param name="checkFormat">Check actual format of number (0 or ("$" or "0x") at start).</param> /// <returns>Parsed object.</returns> function Parse(const value: String; numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>; checkFormat: Boolean) : TIntX; overload; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">Number as string.</param> /// <param name="startIndex">Index inside string from which to start.</param> /// <param name="endIndex">Index inside string on which to end.</param> /// <param name="numberBase">Number base.</param> /// <param name="charToDigits">Char->digit dictionary.</param> /// <param name="digitsRes">Resulting digits.</param> /// <returns>Parsed integer length.</returns> function Parse(const value: String; startIndex: Integer; endIndex: Integer; numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>; digitsRes: TIntXLibUInt32Array): UInt32; overload; end; implementation end.
unit RXMain; { This program provides an example of how to use the TreeView and ListView components in a fashion similar to the Microsoft Windows Explorer. It is not intended to be a fully functional resource viewer. } interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExeImage, StdCtrls, Buttons, ExtCtrls, ComCtrls, Menus, RXMisc, HexDump, ImgList; type TMainForm = class(TForm) StatusBar: TStatusBar; TreeViewPanel: TPanel; Panel1: TPanel; ImageViewer: TImage; ListView: TListView; TreeView: TTreeView; Splitter: TPanel; Notebook: TNotebook; ListViewPanel: TPanel; ListViewCaption: TPanel; FileOpenDialog: TOpenDialog; FileSaveDialog: TSaveDialog; MainMenu: TMainMenu; miFile: TMenuItem; miFileExit: TMenuItem; miFileSave: TMenuItem; miFileOpen: TMenuItem; miView: TMenuItem; miViewStatusBar: TMenuItem; miViewLargeIcons: TMenuItem; miViewSmallIcons: TMenuItem; miViewList: TMenuItem; miViewDetails: TMenuItem; miHelp: TMenuItem; miHelpAbout: TMenuItem; Small: TImageList; Large: TImageList; StringViewer: TMemo; procedure FileExit(Sender: TObject); procedure FileOpen(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ListViewEnter(Sender: TObject); procedure SaveResource(Sender: TObject); procedure SelectListViewType(Sender: TObject); procedure ShowAboutBox(Sender: TObject); procedure ToggleStatusBar(Sender: TObject); procedure TreeViewChange(Sender: TObject; Node: TTreeNode); procedure SplitterMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SplitterMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SplitterMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ViewMenuDropDown(Sender: TObject); procedure NotebookEnter(Sender: TObject); procedure FormDestroy(Sender: TObject); private FExeFile: TExeImage; HexDump: THexDump; SplitControl: TSplitControl; procedure LoadResources(ResList: TResourceList; Node: TTreeNode); procedure DisplayResources; procedure UpdateViewPanel; procedure UpdateListView(ResList: TResourceList); procedure UpdateStatusLine(ResItem: TResourceItem); end; var MainForm: TMainForm; implementation uses About, RXTypes; {$R *.DFM} {$R RXIMAGES.RES} const itBitmap: TResType = ImgList.rtBitmap; // Reference for duplicate identifier ImageMap: array[TResourceType] of Byte = (2,4,5,3,2,2,2,2,2,2,2,2,2,2,2,2,2); ResFiltMap: array[TResourceType] of Byte = (1,4,2,3,1,1,1,1,1,1,1,1,1,1,1,1,1); SNoResSelected = 'No resource selected'; SFormCaption = 'Resource Explorer'; SSaveFilter = 'Other Resource (*.*)|*.*|Bitmaps (*.BMP)|*.BMP|'+ 'Icons (*.ICO)|*.ICO|Cursor (*.CUR)|*.CUR'; SOpenFilter = 'Executable File Images (*.EXE;*.DLL)|*.EXE;*.DLL|'+ 'All Files (*.*)|*.*'; { Utility Functions } procedure Error(const ErrMsg: string); begin raise Exception.Create(ErrMsg); end; procedure ErrorFmt(const ErrMsg: string; Params: array of const); begin raise Exception.Create(format(ErrMsg, Params)); end; function Confirm(const AMsg: String): Boolean; begin Result := MessageDlg(AMsg, mtConfirmation, mbYesNoCancel, 0) = idYes; end; { Non Event Handlers } procedure TMainForm.LoadResources(ResList: TResourceList; Node: TTreeNode); var I: Integer; CNode: TTreeNode; begin for I := 0 to ResList.Count - 1 do with ResList[I] do begin CNode := TreeView.Items.AddChildObject(Node, Name, ResList[I]); if IsList then begin CNode.SelectedIndex := 1; LoadResources(List, CNode); end else begin CNode.ImageIndex := ImageMap[ResList[I].ResType]; CNode.SelectedIndex := CNode.ImageIndex; end; end; end; procedure TMainForm.DisplayResources; begin ListView.Items.Clear; TreeView.Selected := nil; TreeView.Items.Clear; LoadResources(FExeFile.Resources, nil); Caption := Format('%s - %s', [SFormCaption, AnsiLowerCaseFileName(FExeFile.FileName)]); with TreeView do begin SetFocus; Selected := Items[0]; end; end; procedure TMainForm.UpdateViewPanel; var R: TResourceItem; begin with TreeView do begin if Visible and Assigned(Selected) then begin R := TResourceItem(Selected.Data); if R.IsList then UpdateListView(R.List) else begin case R.ResType of rtBitmap, rtIconEntry, rtCursorEntry: begin ImageViewer.Picture.Assign(R); Notebook.PageIndex := 1; end; rtString, rtMenu: begin StringViewer.Lines.Assign(R); StringViewer.SelStart := 0; Notebook.PageIndex := 2; end else begin HexDump.Address := R.RawData; HexDump.DataSize := R.Size; Notebook.PageIndex := 3; end; end; end; UpdateStatusLine(R); end; end; end; procedure TMainForm.UpdateListView(ResList: TResourceList); var I: Integer; begin ListView.Items.Clear; for I := 0 to ResList.Count-1 do with ResList[I], ListView.Items.Add do begin Data := ResList[I]; Caption := Name; SubItems.Add(Format('%.7x', [Offset])); SubItems.Add(Format('%.5x', [Size])); ImageIndex := ImageMap[ResType]; end; Notebook.PageIndex := 0; end; procedure TMainForm.UpdateStatusLine(ResItem: TResourceItem); begin if ResItem.IsList then begin ListViewCaption.Caption := ' '+TreeView.Selected.Text; StatusBar.Panels[0].Text := Format(' %d object(s)', [ListView.Items.Count]); StatusBar.Panels[1].Text := Format(' Offset: %x', [ResItem.Offset]); end else with ResItem do begin ListViewCaption.Caption := Format(' %s: %s', [ResTypeStr, Name]); StatusBar.Panels[0].Text := ''; StatusBar.Panels[1].Text := Format(' Offset: %x Size: %x', [Offset, Size]); end; end; { Form Initialization } procedure TMainForm.FormCreate(Sender: TObject); begin SplitControl := TSplitControl.Create(Self); HexDump := CreateHexDump(TWinControl(NoteBook.Pages.Objects[3])); FileOpenDialog.Filter := SOpenFilter; FileSaveDialog.Filter := SSaveFilter; Small.ResourceLoad(itBitmap, 'SmallImages', clOlive); Large.ResourceLoad(itBitmap, 'LargeImages', clOlive); Notebook.PageIndex := 0; if (ParamCount > 0) and FileExists(ParamStr(1)) then begin Show; FExeFile := TExeImage.CreateImage(Self, ParamStr(1)); DisplayResources; end; end; { Menu Event Handlers } procedure TMainForm.FileOpen(Sender: TObject); var TmpExeFile: TExeImage; begin with FileOpenDialog do begin if not Execute then Exit; TmpExeFile := TExeImage.CreateImage(Self, FileName); if Assigned(FExeFile) then FExeFile.Destroy; FExeFile := TmpExeFile; DisplayResources; end; end; procedure TMainForm.FileExit(Sender: TObject); begin Close; end; procedure TMainForm.ListViewEnter(Sender: TObject); begin with ListView do if (Items.Count > 1) and (Selected = nil) then begin Selected := Items[0]; ItemFocused := Selected; end; end; procedure TMainForm.SaveResource(Sender: TObject); var ResItem: TResourceitem; function TreeViewResourceSelected: Boolean; begin Result := Assigned(TreeView.Selected) and Assigned(TreeView.Selected.Data) and not TResourceItem(TreeView.Selected.Data).IsList; if Result then ResItem := TResourceItem(TreeView.Selected.Data); end; function ListViewResourceSelected: Boolean; begin Result := Assigned(ListView.Selected) and Assigned(ListView.Selected.Data) and not TResourceItem(ListView.Selected.Data).IsList; if Result then ResItem := TResourceItem(ListView.Selected.Data); end; begin if TreeViewResourceSelected or ListViewResourceSelected then with FileSaveDialog do begin FilterIndex := ResFiltMap[ResItem.ResType]; if Execute then ResItem.SaveToFile(FileName) end else Error(SNoResSelected); end; procedure TMainForm.SelectListViewType(Sender: TObject); begin ListView.ViewStyle := TViewStyle(TComponent(Sender).Tag); end; procedure TMainForm.ShowAboutBox(Sender: TObject); begin About.ShowAboutBox; end; procedure TMainForm.ToggleStatusBar(Sender: TObject); begin StatusBar.Visible := not StatusBar.Visible; end; procedure TMainForm.TreeViewChange(Sender: TObject; Node: TTreeNode); begin UpdateViewPanel; end; procedure TMainForm.ViewMenuDropDown(Sender: TObject); var I: Integer; begin miViewStatusBar.Checked := StatusBar.Visible; for I := 0 to miView.Count-1 do with miView.Items[I] do if GroupIndex = 1 then Checked := (Tag = Ord(ListView.ViewStyle)); end; procedure TMainForm.SplitterMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbLeft) and (Shift = [ssLeft]) then SplitControl.BeginSizing(Splitter, TreeViewPanel); end; procedure TMainForm.SplitterMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin with SplitControl do if Sizing then ChangeSizing(X, Y); end; procedure TMainForm.SplitterMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin with SplitControl do if Sizing then EndSizing; end; procedure TMainForm.NotebookEnter(Sender: TObject); var Page: TWinControl; begin with NoteBook do begin Page := TWinControl(Pages.Objects[PageIndex]); if (Page.ControlCount > 0) and (Page.Controls[0] is TWinControl) then TWinControl(Page.Controls[0]).SetFocus; end; end; procedure TMainForm.FormDestroy(Sender: TObject); begin SplitControl.Free; end; end.
unit uQuestionInfo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, xQuestionInfo, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.StdCtrls, FMX.Controls.Presentation, FMX.TabControl; type TfQuestionInfo = class(TForm) pnl3: TPanel; btnOK: TButton; btnCancel: TButton; tbcntrl1: TTabControl; tbtm1: TTabItem; tbtm2: TTabItem; edtQuestionName: TEdit; lbl3: TLabel; mmoQuestionDescribe: TMemo; mmoQuestionRemark: TMemo; lbl2: TLabel; lbl1: TLabel; private { Private declarations } protected FInfo : TQuestionInfo; public { Public declarations } /// <summary> /// 显示信息 /// </summary> procedure ShowInfo(AInfo : TQuestionInfo); virtual; /// <summary> /// 保存信息 /// </summary> procedure SaveInfo; virtual; end; var fQuestionInfo: TfQuestionInfo; implementation {$R *.fmx} { TfQuestionInfo } procedure TfQuestionInfo.SaveInfo; begin if Assigned(FInfo) then begin FInfo.QName := edtQuestionName.Text; FInfo.QDescribe := mmoQuestionDescribe.Text; FInfo.QRemark1 := mmoQuestionRemark.Text; end; end; procedure TfQuestionInfo.ShowInfo(AInfo: TQuestionInfo); begin if Assigned(AInfo) then begin FInfo := AInfo; edtQuestionName.Text := FInfo.QName; mmoQuestionDescribe.Text := FInfo.QDescribe; mmoQuestionRemark.Text := FInfo.QRemark1; end; end; end.
unit IdHeaderList; interface uses Classes; type TIdHeaderList = class(TStringList) protected FNameValueSeparator: string; FCaseSensitive: Boolean; FUnfoldLines: Boolean; FFoldLines: Boolean; FFoldLinesLength: Integer; procedure DeleteFoldedLines(Index: Integer); function FoldLine(AString: string): TStringList; procedure FoldAndInsert(AString: string; Index: Integer); function GetName(Index: Integer): string; function GetValue(const Name: string): string; procedure SetValue(const Name, Value: string); function GetValueFromLine(ALine: Integer): string; function GetNameFromLine(ALine: Integer): string; public constructor Create; procedure Extract(const AName: string; ADest: TStrings); function IndexOfName(const Name: string): Integer; reintroduce; property Names[Index: Integer]: string read GetName; property Values[const Name: string]: string read GetValue write SetValue; property NameValueSeparator: string read FNameValueSeparator write FNameValueSeparator; property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive; property UnfoldLines: Boolean read FUnfoldLines write FUnfoldLines; property FoldLines: Boolean read FFoldLines write FFoldLines; property FoldLength: Integer read FFoldLinesLength write FFoldLinesLength; end; implementation uses IdGlobal , SysUtils; const LWS = [#9, ' ']; function FoldWrapText(const Line, BreakStr: string; BreakChars: TSysCharSet; MaxCol: Integer): string; const QuoteChars = ['"']; var Col, Pos: Integer; LinePos, LineLen: Integer; BreakLen, BreakPos: Integer; QuoteChar, CurChar: Char; ExistingBreak: Boolean; begin Col := 1; Pos := 1; LinePos := 1; BreakPos := 0; QuoteChar := ' '; ExistingBreak := False; LineLen := Length(Line); BreakLen := Length(BreakStr); Result := ''; while Pos <= LineLen do begin CurChar := Line[Pos]; if CurChar in LeadBytes then begin Inc(Pos); Inc(Col); end else if CurChar = BreakStr[1] then begin if QuoteChar = ' ' then begin ExistingBreak := AnsiSameText(BreakStr, Copy(Line, Pos, BreakLen)); if ExistingBreak then begin Inc(Pos, BreakLen - 1); BreakPos := Pos; end; end end else if CurChar in BreakChars then begin if QuoteChar = ' ' then BreakPos := Pos end else if CurChar in QuoteChars then if CurChar = QuoteChar then QuoteChar := ' ' else if QuoteChar = ' ' then QuoteChar := CurChar; Inc(Pos); Inc(Col); if not (QuoteChar in QuoteChars) and (ExistingBreak or ((Col > MaxCol) and (BreakPos > LinePos))) then begin Col := Pos - BreakPos; Result := Result + Copy(Line, LinePos, BreakPos - LinePos + 1); if not (CurChar in QuoteChars) then while (Pos <= LineLen) and (Line[Pos] in BreakChars + [#13, #10]) do Inc(Pos); if not ExistingBreak and (Pos < LineLen) then Result := Result + BreakStr; Inc(BreakPos); LinePos := BreakPos; ExistingBreak := False; end; end; Result := Result + Copy(Line, LinePos, MaxInt); end; constructor TIdHeaderList.Create; begin inherited Create; FNameValueSeparator := ': '; FCaseSensitive := False; FUnfoldLines := True; FFoldLines := True; FFoldLinesLength := 78; end; procedure TIdHeaderList.DeleteFoldedLines(Index: Integer); begin Inc(Index); while (Index < Count) and ((Length(Get(Index)) > 0) and (Get(Index)[1] = ' ') or (Get(Index)[1] = #9)) do begin Delete(Index); end; end; procedure TIdHeaderList.Extract(const AName: string; ADest: TStrings); var idx: Integer; begin if not Assigned(ADest) then Exit; for idx := 0 to Count - 1 do begin if AnsiSameText(AName, GetNameFromLine(idx)) then begin ADest.Add(GetValueFromLine(idx)); end; end; end; procedure TIdHeaderList.FoldAndInsert(AString: string; Index: Integer); var strs: TStringList; idx: Integer; begin strs := FoldLine(AString); try idx := strs.Count - 1; Put(Index, strs[idx]); Dec(idx); while (idx > -1) do begin Insert(Index, strs[idx]); Dec(idx); end; finally FreeAndNil(strs); end; end; function TIdHeaderList.FoldLine(AString: string): TStringList; var s: string; begin Result := TStringList.Create; try s := FoldWrapText(AString, EOL + ' ', LWS, FFoldLinesLength); while s <> '' do begin Result.Add(TrimRight(Fetch(s, EOL))); end; finally end; end; function TIdHeaderList.GetName(Index: Integer): string; var P: Integer; begin Result := Get(Index); P := IndyPos(FNameValueSeparator, Result); if P <> 0 then begin SetLength(Result, P - 1); end else begin SetLength(Result, 0); end; Result := Result; end; function TIdHeaderList.GetNameFromLine(ALine: Integer): string; var p: Integer; begin Result := Get(ALine); if not FCaseSensitive then begin Result := UpperCase(Result); end; P := IndyPos(TrimRight(FNameValueSeparator), Result); Result := Copy(Result, 1, P - 1); end; function TIdHeaderList.GetValue(const Name: string): string; begin Result := GetValueFromLine(IndexOfName(Name)); end; function TIdHeaderList.GetValueFromLine(ALine: Integer): string; var Name: string; begin if ALine >= 0 then begin Name := GetNameFromLine(ALine); Result := Copy(Get(ALine), Length(Name) + 2, MaxInt); if FUnfoldLines then begin Inc(ALine); while (ALine < Count) and ((Length(Get(ALine)) > 0) and (Get(ALine)[1] in LWS)) do begin if (Result[Length(Result)] in LWS) then begin Result := Result + TrimLeft(Get(ALine)) end else begin Result := Result + ' ' + TrimLeft(Get(ALine)) end; inc(ALine); end; end; end else begin Result := ''; end; Result := TrimLeft(Result); end; function TIdHeaderList.IndexOfName(const Name: string): Integer; var S: string; begin for Result := 0 to Count - 1 do begin S := GetNameFromLine(Result); if (AnsiSameText(S, Name)) then begin Exit; end; end; Result := -1; end; procedure TIdHeaderList.SetValue(const Name, Value: string); var I: Integer; begin I := IndexOfName(Name); if Value <> '' then begin if I < 0 then begin I := Add(''); end; if FFoldLines then begin DeleteFoldedLines(I); FoldAndInsert(Name + FNameValueSeparator + Value, I); end else begin Put(I, Name + FNameValueSeparator + Value); end; end else begin if I >= 0 then begin if FFoldLines then begin DeleteFoldedLines(I); end; Delete(I); end; end; end; end.