text
stringlengths
14
6.51M
program simpleimage; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} { Project : simpleimage Title : program to show the use of a simple Intuition Image. Source : RKRM } {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF} {$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF} {$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF} Uses Exec, AmigaDOS, intuition, Utility, {$IFDEF AMIGA} systemvartags, {$ENDIF} CHelpers, Trinity; const MYIMAGE_LEFT = (0); MYIMAGE_TOP = (0); MYIMAGE_WIDTH = (24); MYIMAGE_HEIGHT = (10); MYIMAGE_DEPTH = (1); {* This is the image data. It is a one bit-plane open rectangle which is 24 ** pixels wide and 10 high. Make sure that it is in CHIP memory, or allocate ** a block of chip memory with a call like this: AllocMem(data_size,MEMF_CHIP), ** and then copy the data to that block. See the Exec chapter on Memory ** Allocation for more information on AllocMem(). *} myImageDataData : Array[0..Pred(20)] of UWORD = ( $FFFF, $FF00, $C000, $0300, $C000, $0300, $C000, $0300, $C000, $0300, $C000, $0300, $C000, $0300, $C000, $0300, $C000, $0300, $FFFF, $FF00 ); // FPC Note: Small workaround to accomodate all supported platforms MyImageData : Pointer = @MyImageDataData; {* ** main routine. Open required library and window and draw the images. ** This routine opens a very simple window with no IDCMP. See the ** chapters on "Windows" and "Input and Output Methods" for more info. ** Free all resources when done. *} procedure Main(argc: integer; argv: PPChar); var win : PWindow; myImage : TImage; begin {$IFDEF MORPHOS} IntuitionBase := PIntuitionBase(OpenLibrary('intuition.library', 37)); if (IntuitionBase <> Nil) then {$ENDIF} begin if (nil <> SetAndGet(win, OpenWindowTags(nil, [ TAG_(WA_Width) , 200, TAG_(WA_Height) , 100, TAG_(WA_RMBTrap) , TAG_(TRUE), TAG_END ]))) then begin myImage.LeftEdge := MYIMAGE_LEFT; myImage.TopEdge := MYIMAGE_TOP; myImage.Width := MYIMAGE_WIDTH; myImage.Height := MYIMAGE_HEIGHT; myImage.Depth := MYIMAGE_DEPTH; myImage.ImageData := myImageData; myImage.PlanePick := $1; //* use first bit-plane */ myImage.PlaneOnOff := $0; //* clear all unused planes */ myImage.NextImage := nil; //* Draw the 1 bit-plane image into the first bit-plane (color 1) */ DrawImage(win^.RPort, @myImage, 10, 10); //* Draw the same image at a new location */ DrawImage(win^.RPort, @myImage, 100, 10); {* Wait a bit, then quit. ** In a real application, this would be an event loop, like the ** one described in the Intuition Input and Output Methods chapter. *} DOSDelay(200); CloseWindow(win); end; end; {$IFDEF MORPHOS} CloseLibrary(PLibrary(IntuitionBase)); {$ENDIF} end; {$IFDEF ENDIAN_LITTLE} Var index : Integer; {$ENDIF} begin // FPC Note: // Small workaround to accomodate all supported platforms // Amiga requires image data to be stored into ChipMem // AROS doesn't use the chipmem concept for imagedata anymore // MorphOS ? {$IFDEF ENDIAN_LITTLE} // Intuition expects image data in Big Endian format, so accomodate For Index := Low(MyImageDataData) to High(MyImageDataData) do MyImageDataData[index] := Swap(MyImageDataData[index]); {$ENDIF} {$IFDEF AMIGA} // Intuition expects image data to be located into chipmem (on m68k) // so lets transfer the declared imagery to chip mem. MyImageData := ExecAllocMem(SizeOf(MyImageDataData), MEMF_CHIP); Move(MyImageDataData[0], MyImagedata^, SizeOf(MyImageDataData)); {$ENDIF} Main(ArgC, ArgV); {$IFDEF AMIGA} // Dont forget to release the allocated chip memory. ExecFreeMem(MyImageData, SizeOf(MyImageDataData)); {$ENDIF} end.
{ @abstract(This file is part of the PWIG tool, Pascal Wrapper and Interface Generator.) @author(Tomas Krysl) Copyright (c) 2020 Tomas Krysl<BR><BR> <B>License:</B><BR> This code is licensed under BSD 3-Clause Clear License, see file License.txt or https://spdx.org/licenses/BSD-3-Clause-Clear.html. } unit pwig_ridl; {$mode delphi} interface uses Classes, SysUtils, PWIGGen; type { TPWIGGenRIDL } TPWIGGenRIDL = class(TPWIGGenerator) private FFlags: string; FIndent: string; procedure IncIndent; procedure DecIndent; procedure ClearFlags; procedure AddFlag(AFlag: Boolean; const AFlagText: string); procedure WriteBracketBegin; procedure WriteBracketEnd; procedure WriteCurlyBegin; procedure WriteCurlyEnd; procedure WriteSpace; property Flags: string read FFlags; property Indent: string read FIndent; protected F: TextFile; function GetDescription: string; override; function GetName: string; override; function InterfaceToString(AIntf: TPWIGInterface): string; virtual; function TypeToString(AType: TPWIGType; AUseEnums: Boolean = True): string; virtual; procedure WriteElementProps(AElement: TPWIGElement); virtual; procedure WriteAliasProps(AAlias: TPWIGAlias); virtual; procedure WriteEnumProps(AEnum: TPWIGEnum); virtual; procedure WriteMethod(AMethod: TPWIGMethod; AGetter, ACallingConv: Boolean); virtual; procedure WriteInterfaceProps(AIntf: TPWIGInterface); virtual; procedure WriteClassProps(AClass: TPWIGClass); virtual; public constructor Create(AOwner: TPWIG); override; procedure SaveCalleeFiles(const AFileName: string); override; procedure SaveCallerFiles(const AFileName: string); override; end; implementation uses KFunctions; { TPWIGGenRIDL } constructor TPWIGGenRIDL.Create(AOwner: TPWIG); begin inherited Create(AOwner); FIndent := ''; end; procedure TPWIGGenRIDL.IncIndent; begin FIndent := FIndent + ' '; end; procedure TPWIGGenRIDL.DecIndent; begin Delete(FIndent, 1, 2); end; procedure TPWIGGenRIDL.ClearFlags; begin FFlags := ''; end; procedure TPWIGGenRIDL.AddFlag(AFlag: Boolean; const AFlagText: string); begin if AFlag then begin if FFlags <> '' then FFlags := FFlags + ', '; FFlags := FFlags + AFlagText; end; end; function TPWIGGenRIDL.InterfaceToString(AIntf: TPWIGInterface): string; begin if AIntf.FlagDispEvents then Result := 'dispinterface' else Result := 'interface'; end; function TPWIGGenRIDL.TypeToString(AType: TPWIGType; AUseEnums: Boolean): string; begin Result := ''; case AType.BaseType of btLongInt: Result := 'long'; btLongWord: Result := 'unsigned long'; btSmallInt: Result := 'short'; btWord: Result := 'unsigned short'; btInt64: Result := '__int64'; btUInt64: Result := 'unsigned __int64'; btSingle: Result := 'single'; btDouble: Result := 'double'; btUnicodeString: Result := 'BSTR'; btRawByteString: Result := 'LPSTR'; // memory management not supported by COM! btCurrency: Result := 'CURRENCY'; btDateTime: Result := 'DATE'; btEnum: if AUseEnums then Result := 'enum ' + FPWIG.Enums.FindName(AType.CustomTypeGUID, AType.CustomTypeName) else Result := 'unsigned long'; btAlias: Result := FPWIG.Aliases.FindName(AType.CustomTypeGUID, AType.CustomTypeName); btInterface: Result := FPWIG.Interfaces.FindName(AType.CustomTypeGUID, AType.CustomTypeName) + '*'; end; end; procedure TPWIGGenRIDL.WriteBracketBegin; begin Writeln(F, Indent, '['); IncIndent; end; procedure TPWIGGenRIDL.WriteBracketEnd; begin DecIndent; Writeln(F, Indent, ']'); end; procedure TPWIGGenRIDL.WriteCurlyBegin; begin Writeln(F, Indent, '{'); IncIndent; end; procedure TPWIGGenRIDL.WriteCurlyEnd; begin DecIndent; Writeln(F, Indent, '};'); end; procedure TPWIGGenRIDL.WriteSpace; begin Writeln(F); end; function TPWIGGenRIDL.GetDescription: string; begin Result := 'RIDL (Delphi version of COM IDL). Usable in Delphi.'; end; function TPWIGGenRIDL.GetName: string; begin Result := 'RIDL'; end; procedure TPWIGGenRIDL.SaveCalleeFiles(const AFileName: string); var LIntf: TPWIGInterface; LCls: TPWIGClass; LAlias: TPWIGAlias; LEnum: TPWIGEnum; begin AssignFile(F, AFileName); try try Rewrite(F); // write file header (warning etc.) Writeln(F, Indent, '// ************************************************************************ //'); Writeln(F, Indent, '// WARNING'); Writeln(F, Indent, '// -------'); Writeln(F, Indent, '// This file was generated by PWIG. Do not edit.'); Writeln(F, Indent, '// File generated on ', DateTimeToStr(Now)); WriteSpace; // write library props WriteElementProps(FPWIG); // begin to write library Writeln(F, Indent, 'library ', FPWIG.Name); WriteCurlyBegin; WriteSpace; // write library imports // now hardcoded, later might be automated when needed Writeln(F, Indent, 'importlib("stdole2.tlb");'); WriteSpace; // write interface and class forward declarations for LIntf in FPWIG.Interfaces do Writeln(F, Indent, InterfaceToString(LIntf), ' ', LIntf.Name, ';'); for LCls in FPWIG.Classes do Writeln(F, Indent, 'coclass ', LCls.Name, ';'); WriteSpace; // write enums for LEnum in FPWIG.Enums do WriteEnumProps(LEnum); // write aliases for LAlias in FPWIG.Aliases do WriteAliasProps(LAlias); // write interfaces for LIntf in FPWIG.Interfaces do WriteInterfaceProps(LIntf); // write classes for LCls in FPWIG.Classes do WriteClassProps(LCls); // finish WriteCurlyEnd; Writeln('RIDL file generated: ', AFileName); except Writeln('Could not generate RIDL file: ', AFileName); end; finally CloseFile(F); end; end; procedure TPWIGGenRIDL.SaveCallerFiles(const AFileName: string); begin // nothing to do, caller must import type library from registry, write notice Writeln('RIDL generator cannot output caller wrappers, register and import type library instead!'); end; procedure TPWIGGenRIDL.WriteElementProps(AElement: TPWIGElement); begin WriteBracketBegin; if AElement.GUID <> '' then Writeln(F, Indent, 'uuid(', XMLGUIDToGUIDNoCurlyBraces(AElement.GUID), '),'); if AElement.Description <> '' then Writeln(F, Indent, 'helpstring("', AElement.Description, '"),'); if AElement.Version <> '' then Writeln(F, Indent, 'version(', AElement.Version, '),'); if (AElement is TPWIGInterface) and TPWIGInterface(AElement).FlagDual then Writeln(F, Indent, 'dual,'); if (AElement is TPWIGInterface) and TPWIGInterface(AElement).FlagOleAutomation then Writeln(F, Indent, 'oleautomation,'); WriteBracketEnd; end; procedure TPWIGGenRIDL.WriteAliasProps(AAlias: TPWIGAlias); begin WriteElementProps(AAlias); Writeln(F, Indent, 'typedef ', TypeToString(AAlias.AliasedType), ' ', AAlias.Name, ';'); WriteSpace; end; procedure TPWIGGenRIDL.WriteEnumProps(AEnum: TPWIGEnum); var I: Integer; Elem: TPWIGEnumElement; begin WriteElementProps(AEnum); Writeln(F, Indent, 'enum ', AEnum.Name); WriteCurlyBegin; for I := 0 to AEnum.Elements.Count - 1 do begin Elem := AEnum.Elements[I]; Write(F, Indent, Elem.Name, ' = ', Elem.Value); if I < AEnum.Elements.Count - 1 then Writeln(F, ',') else Writeln(F); end; WriteCurlyEnd; WriteSpace; end; procedure TPWIGGenRIDL.WriteMethod(AMethod: TPWIGMethod; AGetter, ACallingConv: Boolean); var I: Integer; Param: TPWIGParam; S: string; begin // always HRESULT and stdcall if ACallingConv then S := '_stdcall' else S := ''; Write(F, Indent, 'HRESULT', ' ', S, ' ', AMethod.Name, '('); if AMethod.Params.Count = 0 then Writeln(F, 'void);') else begin for I := 0 to AMethod.Params.Count - 1 do begin Param := AMethod.Params[I]; if AMethod is TPWIGProperty then begin // all params are [in] except last one which is [out, retval] for a getter if not AGetter or (I < AMethod.Params.Count - 1) then Write(F, '[in] ', TypeToString(Param.ParamType, TPWIGProperty(AMethod).PropertyType = ptWriteOnly), ' ', Param.Name) else Write(F, '[out, retval] ', TypeToString(Param.ParamType, TPWIGProperty(AMethod).PropertyType = ptWriteOnly), '* ', Param.Name); end else begin // write param flags as specified ClearFlags; AddFlag(Param.FlagInput, 'in'); AddFlag(Param.FlagOutput, 'out'); AddFlag(Param.FlagRetVal, 'retval'); if Param.FlagOutput then S := '*' else S := ''; if Flags = '' then AddFlag(True, 'in'); Write(F, '[', Flags, '] ', TypeToString(Param.ParamType), S, ' ', Param.Name) end; if I < AMethod.Params.Count - 1 then Write(F, ', ') else Writeln(F, ');'); end; end; end; procedure TPWIGGenRIDL.WriteInterfaceProps(AIntf: TPWIGInterface); procedure WriteMethods; var Method: TPWIGMethod; Id: string; begin if AIntf.FlagDispEvents then Writeln(F, Indent, 'methods:'); for Method in AIntf.Methods do begin Id := IntToHexStr(Method.Id, 8, '0x', '', False); Writeln(F, Indent, '[id(', Id, ')]'); WriteMethod(Method, False, not AIntf.FlagDispEvents); end; end; procedure WriteProperties; var Prop: TPWIGProperty; Id: string; begin if AIntf.FlagDispEvents then Writeln(F, Indent, 'properties:'); for Prop in AIntf.Properties do begin Id := IntToHexStr(Prop.Id, 8, '0x', '', False); if Prop.PropertyType in [ptReadOnly, ptReadWrite] then begin // write getter Writeln(F, Indent, '[propget, id(', Id, ')]'); WriteMethod(Prop, True, not AIntf.FlagDispEvents); end; if Prop.PropertyType in [ptWriteOnly, ptReadWrite] then begin // write setter Writeln(F, Indent, '[propput, id(', Id, ')]'); WriteMethod(Prop, False, not AIntf.FlagDispEvents); end; end; end; begin WriteElementProps(AIntf); Write(F, Indent, InterfaceToString(AIntf), ' ', AIntf.Name); if AIntf.FlagDispEvents or (AIntf.BaseInterface = '') then Writeln(F) else Writeln(F, ': ', AIntf.BaseInterface); WriteCurlyBegin; if AIntf.FlagDispEvents then begin WriteProperties; WriteMethods; end else begin WriteMethods; WriteProperties; end; WriteCurlyEnd; WriteSpace; end; procedure TPWIGGenRIDL.WriteClassProps(AClass: TPWIGClass); var Ref: TPWIGInterfaceRef; LIntf: TPWIGInterface; begin WriteElementProps(AClass); Writeln(F, Indent, 'coclass', ' ', AClass.Name); WriteCurlyBegin; for Ref in AClass.InterfaceRefs do begin LIntf := FPWIG.Interfaces.Find(Ref.RefGUID, Ref.RefName); if LIntf <> nil then begin ClearFlags; AddFlag(Ref.FlagDefault, 'default'); AddFlag(Ref.FlagSource, 'source'); Writeln(F, Indent, '[', Flags, '] ', InterfaceToString(LIntf), ' ', LIntf.Name, ';'); end; end; WriteCurlyEnd; WriteSpace; end; end.
{ ClickForms (C) Copyright 1998 - 2009, Bradford Technologies, Inc. All Rights Reserved. } unit ULinkCommentsForm; interface uses ActnList, Classes, Controls, ExtCtrls, StdCtrls, UForms; type TFormLinkComments = class(TAdvancedForm) actCancel: TAction; actOK: TAction; btnCancel: TButton; btnOK: TButton; fldAsk: TCheckBox; fldHeading: TEdit; lblHeading: TLabel; pnlHeading: TPanel; slHeading: TActionList; procedure actCancelExecute(Sender: TObject); procedure actOKUpdate(Sender: TObject); procedure btnOKKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnOKClick(Sender: TObject); private FKeyDown : word; function GetAsk: String; procedure SetAsk(const Value: String); function GetHeading: String; procedure SetHeading(const Value: String); published property Ask: String read GetAsk write SetAsk; property Heading: String read GetHeading write SetHeading; end; implementation uses SysUtils; const kSpaceKey = $20; {$R *.dfm} procedure TFormLinkComments.actCancelExecute(Sender: TObject); begin actCancel.Enabled := True; end; procedure TFormLinkComments.actOKUpdate(Sender: TObject); begin actOK.Enabled := (fldHeading.Text <> ''); end; function TFormLinkComments.GetAsk: String; begin if fldAsk.Checked then Result := 'No' else Result := 'Yes'; end; procedure TFormLinkComments.SetAsk(const Value: String); begin fldAsk.Checked := SameText(Value, 'No'); end; function TFormLinkComments.GetHeading: String; begin Result := fldHeading.Text; end; procedure TFormLinkComments.SetHeading(const Value: String); begin if (Value <> fldHeading.Text) then fldHeading.Text := Value; end; procedure TFormLinkComments.btnOKKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin //Trap key down case Key of kSpaceKey: FKeyDown := kSpaceKey; else FKeyDown := Key; end; end; procedure TFormLinkComments.btnOKClick(Sender: TObject); begin if FKeyDown = kSpaceKey then begin ModalResult := mrNone; FKeyDown := 0; //reset the key end else ModalResult := mrOK; end; end.
unit lamwtoolsoptions; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, LazIDEIntf, LCLVersion, IDEOptionsIntf{, IDEOptEditorIntf}; implementation uses {$if (lcl_fullversion > 1090000) } IDEOptEditorIntf, {$endif} LamwSettings; {$R *.lfm} type { TFormLamwToolsOptions } TFormLamwToolsOptions = class(TAbstractIDEOptionsEditor) Label1: TLabel; private public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function SupportedOptionsClass: TAbstractIDEOptionsClass; override; function GetTitle: string; override; procedure Setup({%H-}ADialog: TAbstractOptionsEditorDialog); override; procedure ReadSettings({%H-}AOptions: TAbstractIDEOptions); override; procedure WriteSettings({%H-}AOptions: TAbstractIDEOptions); override; end; { TFormLamwToolsOptions } constructor TFormLamwToolsOptions.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TFormLamwToolsOptions.Destroy; begin inherited Destroy; end; class function TFormLamwToolsOptions.SupportedOptionsClass: TAbstractIDEOptionsClass; begin Result := nil; end; function TFormLamwToolsOptions.GetTitle: string; begin Result := '[LAMW] Android Module Wizard'; end; procedure TFormLamwToolsOptions.Setup(ADialog: TAbstractOptionsEditorDialog); begin //localization end; procedure TFormLamwToolsOptions.ReadSettings(AOptions: TAbstractIDEOptions); begin // end; procedure TFormLamwToolsOptions.WriteSettings(AOptions: TAbstractIDEOptions); begin // end; initialization RegisterIDEOptionsEditor(GroupEnvironment, TFormLamwToolsOptions, 2000); end.
{******************************************************************************* * * * ksMailChimp - MailChimp Interface * * * * https://github.com/gmurt/ksMailChimp * * * * Copyright 2020 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 ksMailChimp; interface uses System.Generics.Collections, JsonDataObjects, System.Net.HttpClient, Classes, System.Net.HttpClientComponent, System.Net.URLClient; type TPostEvent = reference to procedure(Sender: TObject; AEmail: string; ASuccess: Boolean; AError: string); IMailChimpContact = interface ['{7E7B3A83-42A6-4BC4-988D-53969C63AE92}'] function GetEmail: string; function GetFirstName: string; function GetLastName: string; procedure UploadJson(AJson: TJSONObject); procedure SetEmail(const Value: string); procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); property Firstname: string read GetFirstName write SetFirstName; property LastName: string read GetLastName write SetLastName; property Email: string read GetEmail write SetEmail; end; IMailChimpAudience = interface ['{70A2D93B-D8A2-4E1D-93A8-AF2DD155A42C}'] function GetID: string; function GetMemberCount: integer; function GetName: string; procedure SetID(const Value: string); procedure SetName(const Value: string); procedure LoadFromJson(AJson: string); overload; procedure LoadFromJson(AJson: TJsonObject); overload; property ID: string read GetID write SetID; property Name: string read GetName write SetName; property MemberCount: integer read GetMemberCount; end; TMailChimpContactList = class(TList<IMailChimpContact>) public procedure UploadJson(AJson: TJSONObject); procedure AddMember(AFirstname, ASurname, AEmail: string); end; TMailChimpAudienceList = class(TList<IMailChimpAudience>) public function AddAudience: IMailChimpAudience; function IndexOfListID(AId: string): integer; procedure LoadFromJson(AJson: string); end; IksMailChimp = interface ['{F0CB2B37-BF05-44A4-81E4-AAD31190DF25}'] procedure AddContact(AAudienceID: string; AContact: IMailChimpContact; AOnPost: TPostEvent); procedure AddContacts(AAudienceID: string; AContacts: TMailChimpContactList); procedure GetAudienceList(AAudienceList: TMailChimpAudienceList); end; function CreateMailChimp(AApiKey: string): IksMailChimp; function CreateMailChimpContact(AFirstname, ALastname, AEmail: string): IMailChimpContact; implementation uses System.NetEncoding, SysUtils; { TContact } type TMailChimpContact = class(TInterfacedObject, IMailChimpContact) private FFirstname: string; FLastname: string; FEmail: string; function GetEmail: string; function GetFirstName: string; function GetLastName: string; procedure SetEmail(const Value: string); procedure SetFirstName(const Value: string); procedure SetLastName(const Value: string); protected procedure UploadJson(AJson: TJSONObject); property Firstname: string read GetFirstName write SetFirstName; property LastName: string read GetLastName write SetLastName; property Email: string read GetEmail write SetEmail; end; TMailChimpAudience = class(TInterfacedObject, IMailChimpAudience) private FId: string; FName: string; FMemberCount: integer; function GetID: string; function GetMemberCount: integer; function GetName: string; procedure SetID(const Value: string); procedure SetName(const Value: string); public procedure LoadFromJson(AJson: string); overload; procedure LoadFromJson(AJson: TJsonObject); overload; property ID: string read GetID write SetID; property Name: string read GetName write SetName; property MemberCount: integer read GetMemberCount; end; TksMailChimp = class(TInterfacedObject, IksMailChimp) private FApiKey: string; FHttp: TNetHTTPClient; FDatacenter: string; function Post(AResource, AData: string): string; public constructor Create(AApiKey: string); destructor Destroy; override; procedure AddContact(AAudienceID: string; AContact: IMailChimpContact; AOnPost: TPostEvent); procedure AddContacts(AAudienceID: string; AContacts: TMailChimpContactList); procedure GetAudienceList(AAudienceList: TMailChimpAudienceList); end; function CreateMailChimp(AApiKey: string): IksMailChimp; begin Result := TksMailChimp.Create(AApiKey); end; function CreateMailChimpContact(AFirstname, ALastname, AEmail: string): IMailChimpContact; begin Result := TMailChimpContact.Create; Result.Firstname := AFirstname; Result.LastName := ALastname; Result.Email := Trim(LowerCase(AEmail)); end; function TMailChimpContact.GetEmail: string; begin Result := FEmail; end; function TMailChimpContact.GetFirstName: string; begin Result := FFirstname; end; function TMailChimpContact.GetLastName: string; begin Result := FLastname; end; procedure TMailChimpContact.SetEmail(const Value: string); begin FEmail := Value; end; procedure TMailChimpContact.SetFirstName(const Value: string); begin FFirstname := Value; end; procedure TMailChimpContact.SetLastName(const Value: string); begin FLastname := Value; end; procedure TMailChimpContact.UploadJson(AJson: TJSONObject); begin AJson.S['email_address'] := Email.ToLower; AJson.S['status'] := 'subscribed'; AJson.O['merge_fields'].S['FNAME'] := FFirstname; AJson.O['merge_fields'].S['LNAME'] := FLastname; end; { TMailChimpContactList } procedure TMailChimpContactList.AddMember(AFirstname, ASurname, AEmail: string); var AContact: IMailChimpContact; begin AContact := TMailChimpContact.Create; AContact.Firstname := AFirstname; AContact.LastName := ASurname; AContact.Email := AEmail; Add(AContact); end; function TksMailChimp.Post(AResource, AData: string): string; var AStream: TStringStream; AResponse: IHTTPResponse; begin AStream := TStringStream.Create(AData, TEncoding.UTF8); try FHttp.CustomHeaders['Authorization'] := 'Basic '+ TNetEncoding.Base64.Encode('apiUser:'+FApiKey); AResponse := FHttp.Post('https://'+FDatacenter+'.api.mailchimp.com/3.0/'+AResource, AStream); Result := AResponse.ContentAsString; finally AStream.Free; end; end; procedure TksMailChimp.AddContact(AAudienceID: string; AContact: IMailChimpContact; AOnPost: TPostEvent); var AJson: TJSONObject; AArray: TJsonArray; AUploadJson: TJsonObject; AResult: TJsonObject; begin AJson := TJsonObject.Create; try AArray := AJson.A['members']; AUploadJson := TJsonObject.Create; AContact.UploadJson(AUploadJson); AArray.Add(AUploadJson); AResult := TJsonObject.Parse(Post('lists/'+AAudienceID, AJson.ToJSON)) as TJsonObject; try if Assigned(AOnPost) then begin if AResult.I['error_count'] > 0 then AOnPost(Self, AContact.Email, False, AResult.A['errors'][0].S['error']) else AOnPost(Self, AContact.Email, True, ''); end; finally AResult.Free; end; finally AJson.Free; end; end; procedure TksMailChimp.GetAudienceList(AAudienceList: TMailChimpAudienceList); var AData: string; AObj: TJSONObject; AArray: TJSONArray; begin AAudienceList.Clear; FHttp.CustomHeaders['Authorization'] := 'Basic '+ TNetEncoding.Base64.Encode('apiUser:'+FApiKey); AData := FHttp.Get('https://'+FDataCenter+'.api.mailchimp.com/3.0/lists/').ContentAsString; AObj := TJSONObject.Parse(AData) as TJSONObject; try AArray := AObj.A['lists']; AAudienceList.LoadFromJson(AArray.ToJSON); finally AObj.Free; end; end; { TMailChimp } function StrBefore(ASubStr, AStr: string): string; begin Result := AStr; if Pos(ASubStr, AStr) > 0 then Result := Copy(AStr, 1, Pos(ASubStr, AStr)); end; function StrAfter(ASubStr, AStr: string): string; begin Result := AStr; if Pos(ASubStr, AStr) > 0 then Result := Copy(AStr, Pos(ASubStr, AStr)+1, Length(AStr)); end; constructor TksMailChimp.Create(AApiKey: string); begin FHttp := TNetHTTPClient.Create(nil); FApiKey := StrBefore('-', AApiKey); FDataCenter := StrAfter('-', AApiKey); if Pos('|', FDatacenter) > 0 then FDatacenter := StrBefore('|', FDatacenter); end; destructor TksMailChimp.Destroy; begin FHttp.Free; inherited; end; procedure TksMailChimp.AddContacts(AAudienceID: string; AContacts: TMailChimpContactList); var AJson: TJSONObject; AArray: TJsonArray; AUploadJson: TJsonObject; AResult: TJsonObject; AUploadContacts: TMailChimpContactList; begin AUploadContacts := TMailChimpContactList.Create; try while AContacts.Count > 0 do begin AUploadContacts.Add(AContacts.ExtractAt(0)); if (AUploadContacts.Count >= 500) or (AContacts.Count = 0) then begin AJson := TJsonObject.Create; AUploadContacts.UploadJson(AJson); AResult := TJsonObject.Parse(Post('lists/'+AAudienceID, AJson.ToJSON)) as TJsonObject; try AUploadContacts.Clear; finally AResult.Free; AJson.Free; end; end; end; finally AUploadContacts.Free; end; end; procedure TMailChimpContactList.UploadJson(AJson: TJSONObject); var AArray: TJsonArray; AObj: TJsonObject; ACont: IMailChimpContact; begin AArray := AJson.A['members']; for ACont in Self do begin AObj := TJsonObject.Create; ACont.UploadJson(AObj); AArray.Add(AObj); end; end; { TMailChimpAudience } function TMailChimpAudience.GetID: string; begin Result := FId; end; function TMailChimpAudience.GetMemberCount: integer; begin Result := FMemberCount; end; function TMailChimpAudience.GetName: string; begin Result := FName; end; procedure TMailChimpAudience.LoadFromJson(AJson: TJsonObject); var AStats: TJSONObject; begin FId := AJson.Values['id'].Value; FName := AJson.Values['name'].Value; AStats := AJson.O['stats'] as TJSONObject; FMemberCount := StrToIntDef(AStats.S['member_count'], 0); end; procedure TMailChimpAudience.SetID(const Value: string); begin FId := Value; end; procedure TMailChimpAudience.SetName(const Value: string); begin FName := Value; end; procedure TMailChimpAudience.LoadFromJson(AJson: string); var AObj: TJSONObject; begin AObj := TJSONObject.Parse(AJson) as TJSONObject; try LoadFromJson(AObj); finally AObj.Free; end; end; { TMailChimpAudienceList } function TMailChimpAudienceList.AddAudience: IMailChimpAudience; begin Result := TMailChimpAudience.Create; Add(Result); end; function TMailChimpAudienceList.IndexOfListID(AId: string): integer; var ICount: integer; begin Result := -1; for ICount := 0 to Count-1 do begin if Items[ICount].ID = AId then begin Result := ICount; Exit; end; end; end; procedure TMailChimpAudienceList.LoadFromJson(AJson: string); var AArray: TJSONArray; AList: TJSONObject; begin AArray := TJsonObject.Parse(AJson) as TJSONArray; try for AList in AArray do AddAudience.LoadFromJson(AList); finally AArray.Free; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls,BasicDataAccess_TLB,DataServer_TLB, Spin; type TForm1 = class(TForm) Panel1: TPanel; Label1: TLabel; edHost: TEdit; Label2: TLabel; edServer: TEdit; Label3: TLabel; edUser: TEdit; Label4: TLabel; edPassword: TEdit; btnConnect: TButton; PageControl1: TPageControl; tsSQL: TTabSheet; tsResult: TTabSheet; mmSQL: TMemo; btnExec: TButton; rdBrowse: TRadioButton; rbPrint: TRadioButton; sePerReading: TSpinEdit; Label5: TLabel; btnNext: TButton; btnClear: TButton; mmResult: TRichEdit; edBinding: TEdit; Label6: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnConnectClick(Sender: TObject); procedure btnExecClick(Sender: TObject); procedure btnNextClick(Sender: TObject); procedure btnClearClick(Sender: TObject); private { Private declarations } DataServer : ITestData; Dataset : IHDataset; Render : IHResultRender; procedure readData; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); begin DataServer := CoTestData.Create; end; procedure TForm1.FormDestroy(Sender: TObject); begin Render := nil; Dataset := nil; DataServer := nil; end; procedure TForm1.btnConnectClick(Sender: TObject); begin DataServer.connect(edHost.text,edServer.text,edUser.text,edPassword.text); if DataServer.Connected then begin btnConnect.Enabled := false; btnExec.Enabled := true; end; end; procedure TForm1.btnExecClick(Sender: TObject); begin mmResult.Lines.Clear; Dataset := DataServer.exec(mmSQL.lines.text); if rbPrint.Checked then begin Render := Dataset.getRender(rtPrint); Render.prepare(0,edBinding.text); end else begin Render := Dataset.getRender(rtBrowse); Render.prepare('grid',edBinding.text); end; readData; end; procedure TForm1.readData; begin if Render<>nil then begin mmResult.Lines.add(Render.getData(sePerReading.value)); btnNext.enabled := not Render.eof; end; end; procedure TForm1.btnNextClick(Sender: TObject); begin readData; end; procedure TForm1.btnClearClick(Sender: TObject); begin mmResult.Lines.Clear; end; end.
{******************************************************************************* * * * ksTypes - ksComponents Base classes and types * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2015 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 forthe specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksTypes; interface {$I ksComponents.inc} {$R glyphs.res} uses Classes, FMX.Controls, FMX.Objects, FMX.Types, FMX.StdCtrls, FMX.Graphics, System.UITypes, Types, System.UIConsts, System.Generics.Collections, FMX.InertialMovement; type TksSound = (ksMailNew, ksMailSent, ksVoiceMail, ksBeep, ksMessageReceived, ksMessageSent, ksCameraShutter); IksBaseComponent = interface ['{23FAF7AC-205E-4F03-924D-DA5C7D663777}'] end; IksSystemSound = interface(IKsBaseComponent) ['{CF3A9726-6F3B-4029-B5CD-EB763DB0D2C5}'] procedure Play(ASound: TksSound); end; TksControl = class(TControl, IksBaseComponent); TksComponent = class(TFmxObject); TksRoundRect = class(TRoundRect); TksBaseSpeedButton = class(TSpeedButton); TksBaseTabControl = class(TksComponent) protected procedure AddTab; virtual; abstract; end; TksAccessoryType = (atNone, atMore, atCheckmark, atDetail, atEllipses, atFlag, atBack, atRefresh, atAction, atPlay, atRewind, atForward, atPause, atStop, atAdd, atPrior, atNext, atArrowUp, atArrowDown, atArrowLeft, atArrowRight, atReply, atSearch, atBookmarks, atTrash, atOrganize, atCamera, atCompose, atInfo, atPagecurl, atDetails, atRadioButton, atRadioButtonChecked, atCheckBox, atCheckBoxChecked, atUserDefined1, atUserDefined2, atUserDefined3); //--------------------------------------------------------------------------------------- // TksTableViewAccessoryImage TksTableViewAccessoryImage = class(TBitmap) private FColor: TAlphaColor; procedure SetColor(const Value: TAlphaColor); public procedure SetBitmap(ASource: TBitmap); procedure DrawToCanvas(ACanvas: TCanvas; ADestRect: TRectF; const AStretch: Boolean = True); property Color: TAlphaColor read FColor write SetColor default claNull; end; //--------------------------------------------------------------------------------------- // TksTableViewAccessoryImageList TksTableViewAccessoryImageList = class(TObjectList<TksTableViewAccessoryImage>) private FImageScale: single; FImageMap: TBitmap; FActiveStyle: TFmxObject; procedure AddEllipsesAccessory; procedure AddFlagAccessory; procedure CalculateImageScale; function GetAccessoryFromResource(AStyleName: string; const AState: string = ''): TksTableViewAccessoryImage; procedure Initialize; public constructor Create; destructor Destroy; override; function GetAccessoryImage(AAccessory: TksAccessoryType): TksTableViewAccessoryImage; procedure DrawAccessory(ACanvas: TCanvas; ARect: TRectF; AAccessory: TksAccessoryType; AStroke, AFill: TAlphaColor); property Images[AAccessory: TksAccessoryType]: TksTableViewAccessoryImage read GetAccessoryImage; default; property ImageMap: TBitmap read FImageMap; property ImageScale: single read FImageScale; end; TksAniCalc = class(TAniCalculations) public procedure UpdatePosImmediately; end; var AUnitTesting: Boolean; procedure PlaySystemSound(ASound: TksSound); overload; procedure PlaySystemSound(ASoundID: integer); overload; implementation uses ksCommon, SysUtils, FMX.Styles, FMX.Styles.Objects, Math, ksSystemSound; // ------------------------------------------------------------------------------ procedure PlaySystemSound(ASound: TksSound); var AObj: TksSystemSound; begin AObj := TksSystemSound.Create; AObj.Play(ASound); end; procedure PlaySystemSound(ASoundID: integer); overload; var AObj: TksSystemSound; begin AObj := TksSystemSound.Create; AObj.Play(ASoundID); end; { TksTableViewAccessoryImageList } function TksTableViewAccessoryImageList.GetAccessoryImage(AAccessory: TksAccessoryType): TksTableViewAccessoryImage; begin if Count = 0 then Initialize; Result := Items[Ord(AAccessory)]; end; procedure TksTableViewAccessoryImageList.AddEllipsesAccessory; var AAcc: TksTableViewAccessoryImage; ARect: TRectF; ASpacing: single; ASize: single; begin AAcc := TksTableViewAccessoryImage.Create; AAcc.SetSize(Round(32 * GetScreenScale), Round(32 * GetScreenScale)); ASize := 7 * GetScreenScale; ASpacing := (AAcc.Width - (3 * ASize)) / 2; AAcc.Clear(claNull); AAcc.Canvas.BeginScene; try AAcc.Canvas.Fill.Color := claSilver; ARect := RectF(0, 0, ASize, ASize); OffsetRect(ARect, 0, (AAcc.Height - ARect.Height) / 2); AAcc.Canvas.FillEllipse(ARect, 1); OffsetRect(ARect, ASize+ASpacing, 0); AAcc.Canvas.FillEllipse(ARect, 1); OffsetRect(ARect, ASize+ASpacing, 0); AAcc.Canvas.FillEllipse(ARect, 1); finally AAcc.Canvas.EndScene; end; Add(AAcc); end; procedure TksTableViewAccessoryImageList.AddFlagAccessory; var AAcc: TksTableViewAccessoryImage; ARect: TRectF; s: single; r1, r2: TRectF; begin s := GetScreenScale; AAcc := TksTableViewAccessoryImage.Create; AAcc.SetSize(Round(32 * s), Round(32 * s)); AAcc.Clear(claNull); ARect := RectF(0, 0, AAcc.Width, AAcc.Height); ARect.Inflate(0-(AAcc.Width / 4), 0-(AAcc.Height / 7)); AAcc.Canvas.BeginScene; try r1 := ARect; r2 := ARect; r2.Top := ARect.Top+(ARect.Height/12); r2.Left := r2.Left; r2.Height := ARect.Height / 2; AAcc.Canvas.stroke.Color := claSilver; AAcc.Canvas.Stroke.Thickness := s*2; AAcc.Canvas.Fill.Color := claSilver; AAcc.Canvas.FillRect(r2, 0, 0, AllCorners, 1); AAcc.Canvas.DrawLine(r1.TopLeft, PointF(r1.Left, r1.Bottom), 1); finally AAcc.Canvas.EndScene; end; Add(AAcc); end; procedure TksTableViewAccessoryImageList.CalculateImageScale; begin if FImageScale = 0 then begin FImageScale := Min(Trunc(GetScreenScale), 3); {$IFDEF MSWINDOWS} FImageScale := 1; {$ENDIF} end; end; constructor TksTableViewAccessoryImageList.Create; begin inherited Create(True); FImageScale := 0; FImageMap := TBitmap.Create; end; destructor TksTableViewAccessoryImageList.Destroy; begin FreeAndNil(FImageMap); if FActiveStyle <> nil then FreeAndNil(FActiveStyle); inherited; end; procedure TksTableViewAccessoryImageList.DrawAccessory(ACanvas: TCanvas; ARect: TRectF; AAccessory: TksAccessoryType; AStroke, AFill: TAlphaColor); begin //AState := ACanvas.SaveState; try //ACanvas.IntersectClipRect(ARect); if AFill <> claNull then begin ACanvas.Fill.Color := AFill; ACanvas.Fill.Kind := TBrushKind.Solid; ACanvas.FillRect(ARect, 0, 0, AllCorners, 1); end; GetAccessoryImage(AAccessory).DrawToCanvas(ACanvas, ARect, False); //ACanvas.Stroke.Color := AStroke; //ACanvas.DrawRect(ARect, 0, 0, AllCorners, 1); finally // ACanvas.RestoreState(AState); end; end; function TksTableViewAccessoryImageList.GetAccessoryFromResource (AStyleName: string; const AState: string = ''): TksTableViewAccessoryImage; var AStyleObj: TStyleObject; AImgRect: TBounds; AIds: TStrings; r: TRectF; ABitmapLink: TBitmapLinks; AImageMap: TBitmap; begin CalculateImageScale; Result := TksTableViewAccessoryImage.Create; AIds := TStringList.Create; try AIds.Text := StringReplace(AStyleName, '.', #13, [rfReplaceAll]); if AUnitTesting then begin if FActiveStyle = nil then FActiveStyle := TStyleManager.ActiveStyle(Nil); AStyleObj := TStyleObject(FActiveStyle) end else AStyleObj := TStyleObject(TStyleManager.ActiveStyle(nil)); while AIds.Count > 0 do begin AStyleObj := TStyleObject(AStyleObj.FindStyleResource(AIds[0])); AIds.Delete(0); end; if AStyleObj <> nil then begin if FImageMap.IsEmpty then begin AImageMap := ((AStyleObj as TStyleObject).Source.MultiResBitmap.Bitmaps[FImageScale]); FImageMap.SetSize(Round(AImageMap.Width), Round(AImageMap.Height)); FImageMap.Clear(claNull); FImageMap.Canvas.BeginScene; try FImageMap.Canvas.DrawBitmap(AImageMap, RectF(0, 0, AImageMap.Width, AImageMap.Height), RectF(0, 0, FImageMap.Width, FImageMap.Height), 1, True); finally FImageMap.Canvas.EndScene; end; end; ABitmapLink := nil; if AStyleObj = nil then Exit; if (AStyleObj.ClassType = TCheckStyleObject) then begin if AState = 'checked' then ABitmapLink := TCheckStyleObject(AStyleObj).ActiveLink else ABitmapLink := TCheckStyleObject(AStyleObj).SourceLink end; if ABitmapLink = nil then ABitmapLink := AStyleObj.SourceLink; {$IFDEF XE8_OR_NEWER} AImgRect := ABitmapLink.LinkByScale(FImageScale, True).SourceRect; {$ELSE} AImgRect := ABitmapLink.LinkByScale(FImageScale).SourceRect; {$ENDIF} Result.SetSize(Round(AImgRect.Width), Round(AImgRect.Height)); Result.Clear(claNull); Result.Canvas.BeginScene; r := AImgRect.Rect; Result.Canvas.DrawBitmap(FImageMap, r, RectF(0, 0, Result.Width, Result.Height), 1, True); Result.Canvas.EndScene; end; finally {$IFDEF NEXTGEN} FreeAndNil(AIds); {$ELSE} AIds.Free; {$ENDIF} end; end; procedure TksTableViewAccessoryImageList.Initialize; var ICount: TksAccessoryType; begin for ICount := Low(TksAccessoryType) to High(TksAccessoryType) do begin case ICount of atNone: Add(GetAccessoryFromResource('none')); atMore: Add(GetAccessoryFromResource('listviewstyle.accessorymore')); atCheckmark: Add(GetAccessoryFromResource('listviewstyle.accessorycheckmark')); atDetail: Add(GetAccessoryFromResource('listviewstyle.accessorydetail')); atEllipses: AddEllipsesAccessory; atFlag: AddFlagAccessory; atBack: Add(GetAccessoryFromResource('backtoolbutton.icon')); atRefresh: Add(GetAccessoryFromResource('refreshtoolbutton.icon')); atAction: Add(GetAccessoryFromResource('actiontoolbutton.icon')); atPlay: Add(GetAccessoryFromResource('playtoolbutton.icon')); atRewind: Add(GetAccessoryFromResource('rewindtoolbutton.icon')); atForward: Add(GetAccessoryFromResource('forwardtoolbutton.icon')); atPause: Add(GetAccessoryFromResource('pausetoolbutton.icon')); atStop: Add(GetAccessoryFromResource('stoptoolbutton.icon')); atAdd: Add(GetAccessoryFromResource('addtoolbutton.icon')); atPrior: Add(GetAccessoryFromResource('priortoolbutton.icon')); atNext: Add(GetAccessoryFromResource('nexttoolbutton.icon')); atArrowUp: Add(GetAccessoryFromResource('arrowuptoolbutton.icon')); atArrowDown: Add(GetAccessoryFromResource('arrowdowntoolbutton.icon')); atArrowLeft: Add(GetAccessoryFromResource('arrowlefttoolbutton.icon')); atArrowRight: Add(GetAccessoryFromResource('arrowrighttoolbutton.icon')); atReply: Add(GetAccessoryFromResource('replytoolbutton.icon')); atSearch: Add(GetAccessoryFromResource('searchtoolbutton.icon')); atBookmarks: Add(GetAccessoryFromResource('bookmarkstoolbutton.icon')); atTrash: Add(GetAccessoryFromResource('trashtoolbutton.icon')); atOrganize: Add(GetAccessoryFromResource('organizetoolbutton.icon')); atCamera: Add(GetAccessoryFromResource('cameratoolbutton.icon')); atCompose: Add(GetAccessoryFromResource('composetoolbutton.icon')); atInfo: Add(GetAccessoryFromResource('infotoolbutton.icon')); atPagecurl: Add(GetAccessoryFromResource('pagecurltoolbutton.icon')); atDetails: Add(GetAccessoryFromResource('detailstoolbutton.icon')); atRadioButton: Add(GetAccessoryFromResource('radiobuttonstyle.background')); atRadioButtonChecked: Add(GetAccessoryFromResource('radiobuttonstyle.background', 'checked')); atCheckBox: Add(GetAccessoryFromResource('checkboxstyle.background')); atCheckBoxChecked: Add(GetAccessoryFromResource('checkboxstyle.background', 'checked')); atUserDefined1: Add(GetAccessoryFromResource('userdefined1')); atUserDefined2: Add(GetAccessoryFromResource('userdefined2')); atUserDefined3: Add(GetAccessoryFromResource('userdefined3')); end; end; // generate our own ellipses accessory... end; // ------------------------------------------------------------------------------ { TksAccessoryImage } procedure TksTableViewAccessoryImage.DrawToCanvas(ACanvas: TCanvas; ADestRect: TRectF; const AStretch: Boolean = True); var r: TRectF; begin r := ADestRect; if AStretch = False then begin r := RectF(0, 0, Width / GetScreenScale, Height / GetScreenScale); OffsetRect(r, ADestRect.Left, ADestRect.Top); OffsetRect(r, (ADestRect.Width-r.Width)/2, (ADestRect.Height-r.Height)/2); end; ACanvas.DrawBitmap(Self, RectF(0, 0, Width, Height), r, 1, True); end; procedure TksTableViewAccessoryImage.SetBitmap(ASource: TBitmap); var AScale: single; begin AScale := Min(Trunc(GetScreenScale), 3); Assign(ASource); Resize(Round(32 * AScale), Round(32 * AScale)); end; procedure TksTableViewAccessoryImage.SetColor(const Value: TAlphaColor); begin if FColor <> Value then begin FColor := Value; ReplaceOpaqueColor(Value); end; end; { TksAniCalc } procedure TksAniCalc.UpdatePosImmediately; begin inherited UpdatePosImmediately(True); end; initialization AUnitTesting := False; finalization end.
unit TSTOSbtp.JSon; interface Uses Windows, Classes, SysUtils, TSTOSbtpIntf, OJSonObject; Type IJSonSbtpSubVariable = Interface(ISbtpSubVariable) ['{4B61686E-29A0-2112-B5E0-8DDF1D6E1570}'] Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); End; IJSonSbtpSubVariables = Interface(ISbtpSubVariables) ['{4B61686E-29A0-2112-8E1B-6C44BED9C401}'] Function Get(Index : Integer) : IJSonSbtpSubVariable; Procedure Put(Index : Integer; Const Item : IJSonSbtpSubVariable); Function Add() : IJSonSbtpSubVariable; OverLoad; Function Add(Const AItem : IJSonSbtpSubVariable) : Integer; OverLoad; Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property Items[Index : Integer] : IJSonSbtpSubVariable Read Get Write Put; Default; End; IJSonSbtpVariable = Interface(ISbtpVariable) ['{4B61686E-29A0-2112-9C89-BE78BEE78E3A}'] Function GetSubItem() : IJSonSbtpSubVariables; Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property SubItem : IJSonSbtpSubVariables Read GetSubItem; End; IJSonSbtpVariables = Interface(ISbtpVariables) ['{4B61686E-29A0-2112-B529-E4F15EB72F02}'] Function Get(Index : Integer) : IJSonSbtpVariable; Procedure Put(Index : Integer; Const Item : IJSonSbtpVariable); Function Add() : IJSonSbtpVariable; OverLoad; Function Add(Const AItem : IJSonSbtpVariable) : Integer; OverLoad; Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property Items[Index : Integer] : IJSonSbtpVariable Read Get Write Put; Default; End; IJSonSbtpHeader = Interface(ISbtpHeader) ['{4B61686E-29A0-2112-81A0-415C4648A005}'] Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); End; IJSonSbtpFile = Interface(ISbtpFile) ['{4B61686E-29A0-2112-99E7-7C1B3CE0F0A4}'] Function GetHeader() : IJSonSbtpHeader; Function GetItem() : IJSonSbtpVariables; Function GetAsJSon() : String; Procedure SetAsJSon(Const AJSon : String); Property Header : IJSonSbtpHeader Read GetHeader; Property Item : IJSonSbtpVariables Read GetItem; Property AsJSon : String Read GetAsJSon Write SetAsJSon; End; (******************************************************************************) TJSonSbtpFile = Class(TObject) Public Class Function CreateSbtpFile() : IJSonSbtpFile; OverLoad; Class Function CreateSbtpFile(Const AJSonString : String) : IJSonSbtpFile; OverLoad; End; Implementation Uses Dialogs, OJsonUtils, HsJSonFormatterEx, HsInterfaceEx, TSTOSbtpImpl; Type TJSonSbtpSubVariable = Class(TSbtpSubVariable, IJSonSbtpSubVariable) Protected Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property VariableName : String Read GetVariableName Write SetVariableName; Property VariableData : String Read GetVariableData Write SetVariableData; End; TJSonSbtpSubVariables = Class(TSbtpSubVariables, IJSonSbtpSubVariables) Protected Function GetItemClass() : TInterfacedObjectExClass; OverRide; Function Get(Index : Integer) : IJSonSbtpSubVariable; OverLoad; Procedure Put(Index : Integer; Const Item : IJSonSbtpSubVariable); OverLoad; Function Add() : IJSonSbtpSubVariable; OverLoad; Function Add(Const AItem : IJSonSbtpSubVariable) : Integer; OverLoad; Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property Items[Index : Integer] : IJSonSbtpSubVariable Read Get Write Put; Default; End; TJSonSbtpVariable = Class(TSbtpVariable, IJSonSbtpVariable) Protected Function GetSubItemClass() : TSbtpSubVariablesClass; OverRide; Function GetSubItem() : IJSonSbtpSubVariables; OverLoad; Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property VariableType : String Read GetVariableType Write SetVariableType; Property SubItem : IJSonSbtpSubVariables Read GetSubItem; End; TJSonSbtpVariables = Class(TSbtpVariables, IJSonSbtpVariables) Protected Function GetItemClass() : TInterfacedObjectExClass; OverRide; Function Get(Index : Integer) : IJSonSbtpVariable; OverLoad; Procedure Put(Index : Integer; Const Item : IJSonSbtpVariable); OverLoad; Function Add() : IJSonSbtpVariable; OverLoad; Function Add(Const AItem : IJSonSbtpVariable) : Integer; OverLoad; Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property Items[Index : Integer] : IJSonSbtpVariable Read Get Write Put; Default; End; TJSonSbtpHeader = Class(TSbtpHeader, IJSonSbtpHeader) Protected Procedure SaveJSon(AJSon : IJSonObject); Procedure LoadJSon(AJSon : IJSonObject); Property Header : String Read GetHeader Write SetHeader; Property HeaderPadding : Word Read GetHeaderPadding Write SetHeaderPadding; End; TJSonSbtpFileImpl = Class(TSbtpFile, IJSonSbtpFile) Protected Function GetHeaderClass() : TSbtpHeaderClass; OverRide; Function GetItemClass() : TSbtpVariablesClass; OverRide; Function GetHeader() : IJSonSbtpHeader; OverLoad; Function GetItem() : IJSonSbtpVariables; OverLoad; Function GetAsJSon() : String; Procedure SetAsJSon(Const AJSon : String); Property Header : IJSonSbtpHeader Read GetHeader; Property Item : IJSonSbtpVariables Read GetItem; End; Class Function TJSonSbtpFile.CreateSbtpFile() : IJSonSbtpFile; Begin Result := TJSonSbtpFileImpl.Create(); End; Class Function TJSonSbtpFile.CreateSbtpFile(Const AJSonString : String) : IJSonSbtpFile; Begin Result := TJSonSbtpFileImpl.Create(); Result.AsJSon := AJSonString; End; (******************************************************************************) Procedure TJSonSbtpSubVariable.SaveJSon(AJSon : IJSonObject); Begin With AJSon.OpenObject() Do Try Text('Name', VariableName); Text('Data', VariableData); Finally AJSon.CloseObject(); End; End; Procedure TJSonSbtpSubVariable.LoadJSon(AJSon : IJSonObject); Var lToken : TCustomJSONReaderToken; lCurPairName : String; Begin If AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttOpenObject) Then While AJSon.ReadNextToken(lToken) And (lToken.TokenType <> ttCloseObject) Do Case lToken.TokenType Of ttPairName : Begin lCurPairName := lToken.PairName; If AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttValue) Then Case lToken.ValueType Of vtString : Begin If SameText(lCurPairName, 'Name') Then VariableName := lToken.StringValue Else If SameText(lCurPairName, 'Data') Then VariableData := lToken.StringValue; End; End; End; End; End; Function TJSonSbtpSubVariables.GetItemClass() : TInterfacedObjectExClass; Begin Result := TJSonSbtpSubVariable; End; Function TJSonSbtpSubVariables.Get(Index : Integer) : IJSonSbtpSubVariable; Begin Result := InHerited Items[Index] As IJSonSbtpSubVariable; End; Procedure TJSonSbtpSubVariables.Put(Index : Integer; Const Item : IJSonSbtpSubVariable); Begin InHerited Items[Index] := Item; End; Function TJSonSbtpSubVariables.Add() : IJSonSbtpSubVariable; Begin Result := InHerited Add() As IJSonSbtpSubVariable; End; Function TJSonSbtpSubVariables.Add(Const AItem : IJSonSbtpSubVariable) : Integer; Begin Result := InHerited Add(AItem); End; Procedure TJSonSbtpSubVariables.SaveJSon(AJSon : IJSonObject); Var X : Integer; Begin With AJSon.OpenArray('SubVariable') Do Try For X := 0 To Count - 1 Do Items[X].SaveJSon(AJSon); Finally AJSon.CloseArray(); End; End; Procedure TJSonSbtpSubVariables.LoadJSon(AJSon : IJSonObject); Var lToken : TCustomJSONReaderToken; Begin If AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttOpenArray) Then While AJSon.LastToken.TokenType <> ttCloseArray Do Begin Add().LoadJSon(AJSon); AJSon.ReadNextToken(lToken); End; End; Function TJSonSbtpVariable.GetSubItemClass() : TSbtpSubVariablesClass; Begin Result := TJSonSbtpSubVariables; End; Function TJSonSbtpVariable.GetSubItem() : IJSonSbtpSubVariables; Begin Result := InHerited GetSubItem() As IJSonSbtpSubVariables; End; Procedure TJSonSbtpVariable.SaveJSon(AJSon : IJSonObject); Begin With AJSon.OpenObject() Do Try Text('Type', VariableType); SubItem.SaveJSon(AJSon); Finally AJSon.CloseObject(); End; End; Procedure TJSonSbtpVariable.LoadJSon(AJSon : IJSonObject); Var lToken : TCustomJSONReaderToken; Begin If AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttOpenObject) Then While AJSon.ReadNextToken(lToken) And (lToken.TokenType <> ttCloseObject) Do Case lToken.TokenType Of ttPairName : Begin If SameText(lToken.PairName, 'Type') And AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttValue) And (lToken.ValueType = vtString) Then VariableType := lToken.StringValue Else If SameText(lToken.PairName, 'SubVariable') Then SubItem.LoadJSon(AJSon); End; End; End; Function TJSonSbtpVariables.GetItemClass() : TInterfacedObjectExClass; Begin Result := TJSonSbtpVariable; End; Function TJSonSbtpVariables.Get(Index : Integer) : IJSonSbtpVariable; Begin Result := InHerited Items[Index] As IJSonSbtpVariable; End; Procedure TJSonSbtpVariables.Put(Index : Integer; Const Item : IJSonSbtpVariable); Begin InHerited Items[Index] := Item; End; Function TJSonSbtpVariables.Add() : IJSonSbtpVariable; Begin Result := InHerited Add() As IJSonSbtpVariable; End; Function TJSonSbtpVariables.Add(Const AItem : IJSonSbtpVariable) : Integer; Begin Result := InHerited Add(AItem); End; Procedure TJSonSbtpVariables.SaveJSon(AJSon : IJSonObject); Var X : Integer; Begin With AJSon.OpenArray('SbtpVariable') Do Try For X := 0 To Count - 1 Do Items[X].SaveJSon(AJSon); Finally AJSon.CloseArray(); End; End; Procedure TJSonSbtpVariables.LoadJSon(AJSon : IJSonObject); Var lToken : TCustomJSONReaderToken; Begin If AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttOpenArray) Then While AJSon.LastToken.TokenType <> ttCloseArray Do Begin Add().LoadJSon(AJSon); AJSon.ReadNextToken(lToken); End; End; Procedure TJSonSbtpHeader.SaveJSon(AJSon : IJSonObject); Begin With AJSon.OpenObject('SbtpHeader') Do Try Text('FileSig', Header); Number('Padding', HeaderPadding); Finally AJSon.CloseObject(); End; End; Procedure TJSonSbtpHeader.LoadJSon(AJSon : IJSonObject); Var lToken : TCustomJSONReaderToken; lCurPairName : String; Begin If AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttOpenObject) Then While AJSon.ReadNextToken(lToken) And (lToken.TokenType <> ttCloseObject) Do Begin Case lToken.TokenType Of ttPairName : Begin lCurPairName := lToken.PairName; If AJSon.ReadNextToken(lToken) And (lToken.TokenType = ttValue) Then Case lToken.ValueType Of vtString : Begin If SameText(lCurPairName, 'FileSig') Then Header := lToken.StringValue; End; vtNumber : Begin If SameText(lCurPairName, 'Padding') Then HeaderPadding := lToken.IntegerValue; End; End; End; End; End; End; Function TJSonSbtpFileImpl.GetHeaderClass() : TSbtpHeaderClass; Begin Result := TJSonSbtpHeader; End; Function TJSonSbtpFileImpl.GetItemClass() : TSbtpVariablesClass; Begin Result := TJSonSbtpVariables; End; Function TJSonSbtpFileImpl.GetHeader() : IJSonSbtpHeader; Begin Result := InHerited GetHeader() As IJSonSbtpHeader; End; Function TJSonSbtpFileImpl.GetItem() : IJSonSbtpVariables; Begin Result := InHerited GetItem() As IJSonSbtpVariables; End; Function TJSonSbtpFileImpl.GetAsJSon() : String; Var lWriter : IJSonObject; Begin lWriter := TJSonObject.Create(); Try With lWriter.OpenObject() Do Try Header.SaveJSon(lWriter); Item.SaveJSon(lWriter); Finally CloseObject(); End; Result := FormatJSonData(lWriter.AsJSon); Finally lWriter := Nil; End; End; Procedure TJSonSbtpFileImpl.SetAsJSon(Const AJSon : String); Var lReader : IJSonObject; lToken : TCustomJSONReaderToken; Begin Header.Clear(); Item.Clear(); lReader := TJSonObject.Create(); Try lReader.InitString(AJSon); If lReader.ReadNextToken(lToken) And (lToken.TokenType = ttOpenObject) Then While lReader.ReadNextToken(lToken) And (lToken.TokenType <> ttCloseObject) Do Begin Case lToken.TokenType Of ttPairName : Begin If SameText(lToken.PairName, 'SbtpHeader') Then Header.LoadJSon(lReader) Else If SameText(lToken.PairName, 'SbtpVariable') Then Item.LoadJSon(lReader); End; End; End; Finally lReader := Nil; End; End; End.
program Hasil_Studi; { I.S. : Pengguna memasukkan banyaknya mahasiswa (m), banyaknya mata kuliah (n) } { F.S. : Menampilkan hasil studi setiap mahasiswa } uses crt; const MaksMhs = 50; MaksMK = 5; type RecordMhs = record NIM : integer; Nama : string; IPK : real; end; RecordMK = record KodeMK : string; NamaMK : string; SKS : integer; end; LarikMhs = array[1..MaksMhs] of RecordMhs; LarikMK = array[1..MaksMK] of RecordMK; MatriksNilai = array[1..MaksMhs, 1..MaksMK] of integer; MatriksIndeks = array[1..MaksMhs, 1..MaksMK] of char; MatriksMutu = array[1..MaksMhs, 1..MaksMK] of integer; { variabel global } var Mhs : LarikMhs; MK : LarikMK; Nilai : MatriksNilai; Indeks : MatriksIndeks; Mutu : MatriksMutu; M, N : integer; function IndeksNilai(Nilai : integer) : char; begin case(Nilai) of 80..100 : IndeksNilai := 'A'; 70..79 : IndeksNilai := 'B'; 60..69 : IndeksNilai := 'C'; 50..59 : IndeksNilai := 'D'; 0..49 : IndeksNilai := 'E'; end; end; { end function } procedure IsiData(var M, N : integer; var Mhs : LarikMhs; var MK : LarikMK); var i, j : integer; begin write('Banyaknya Mahasiswa : '); readln(M); write('Banyaknya Mata Kuliah : '); readln(N); clrscr; { memasukkan data mahasiswa } window(1, 1, 40, 30); writeln('Daftar Mahasiswa'); writeln('-------------------------------------'); writeln('| No | NIM | Nama Mahasiswa |'); writeln('====================================='); for i := 1 to M do begin gotoxy( 1, i + 4); write('| | | |'); gotoxy( 3, i + 4); write(i); gotoxy( 8, i + 4); readln(Mhs[i].NIM); gotoxy(20, i + 4); readln(Mhs[i].Nama); end; writeln('-------------------------------------'); writeln; { memasukkan data mata kuliah } window(41, 1, 120, 30); writeln('Daftar Mata Kuliah'); writeln('--------------------------------------------------'); writeln('| No | Kode Mata Kuliah | Nama Mata Kuliah | SKS |'); writeln('=================================================='); for j := 1 to N do begin gotoxy( 1, j + 4); writeln('| | | | |'); gotoxy( 3, j + 4); write(j); gotoxy( 8, j + 4); readln(MK[j].KodeMK); gotoxy(27, j + 4); readln(MK[j].NamaMK); gotoxy(46, j + 4); readln(MK[j].SKS); end; writeln('--------------------------------------------------'); write('Tekan Enter untuk melanjutkan!'); readln; end; { end procedure } procedure IsiNilai(M, N : integer; Mhs : LarikMhs; MK : LarikMK; var Nilai : MatriksNilai); var i, j : integer; begin window(1, 1, 120, 30); textbackground(7); textcolor(0); clrscr; gotoxy(50, 1); writeln('Pengisian Nilai Mahasiswa'); gotoxy(50, 2); writeln('-------------------------'); { menampilkan data kode mk dan nim } gotoxy( 1, 4); write('NIM'); gotoxy(12, 4); write('Kode Mata Kuliah'); for i := 1 to M do begin for j := 1 to N do begin textcolor(blue); gotoxy(j * 12, 5); write(MK[j].KodeMK); end; gotoxy(1, i + 5); write(Mhs[i].NIM); end; textcolor(0); { mengisi nilai matriks } for i := 1 to M do begin for j := 1 to N do begin gotoxy(j * 12 + 3, i + 5); readln(Nilai[i, j]); end; end; end; procedure TampilIndeks(Nilai : MatriksNilai; M, N : integer; var Indeks : MatriksIndeks); var i, j : integer; begin for i := 1 to M do begin for j := 1 to N do begin Indeks[i, j] := IndeksNilai(Nilai[i, j]); gotoxy(j * 12 + 3, i + 5); clreol; write(Indeks[i, j]); delay(300); end; end; writeln; write('Tekan Enter untuk melanjutkan!'); readln; end; { end procedure } function HitungMutu(Indeks : char; SKS : integer) : integer; begin if(Indeks = 'A') then HitungMutu := 4 * SKS else if(Indeks = 'B') then HitungMutu := 3 * SKS else if(Indeks = 'C') then HitungMutu := 2 * SKS else if(Indeks = 'D') then HitungMutu := 1 * SKS else HitungMutu := 0; end; function HitungIPK(i, M, N : integer; Mutu : MatriksMutu; MK : LarikMK) : real; var Mt, Sk, j : integer; begin { menghitung total mutu } Mt := 0; for j := 1 to N do begin Mt := Mt + Mutu[i, j]; end; { menghitung total sks } Sk := 0; for j := 1 to N do begin Sk := Sk + MK[j].SKS; end; HitungIPK := Mt / Sk; end; procedure TampilHasilStudi(M, N : integer; Mhs : LarikMhs; MK : LarikMK; Indeks : MatriksIndeks; var Mutu : MatriksMutu); var i, j, k, l : integer; begin clrscr; gotoxy(25, 1); writeln('HASIL STUDI MAHASISWA TEKNIK INFORMATIKA UNIKOM SEBANYAK ', M, ' MAHASISWA'); gotoxy(25, 2); writeln('===================================================================='); l := 1; for i := 1 to M do begin textcolor(red); gotoxy( 1, l + 3); for k := 1 to 120 do begin write('-'); end; gotoxy(53, l + 3); write('Mahasiswa Ke-', i); textcolor(black); gotoxy( 1, l + 4); write('NIM : ', Mhs[i].NIM); gotoxy( 1, l + 5); write('Nama : ', Mhs[i].Nama); gotoxy( 1, l + 6); write('-----------------------------------------------------------'); gotoxy( 1, l + 7); write('| No | Kode Mata Kuliah | Nama Mata Kuliah | SKS | Indeks |'); gotoxy( 1, l + 8); write('==========================================================='); for j := 1 to N do begin gotoxy( 1, j + (l + 8)); gotoxy( 1, j + (l + 8)); write('| | | | | |'); gotoxy( 3, j + (l + 8)); write(j); gotoxy( 8, j + (l + 8)); write(MK[j].KodeMK); gotoxy(27, j + (l + 8)); write(MK[j].NamaMK); gotoxy(46, j + (l + 8)); write(MK[j].SKS); gotoxy(54, j + (l + 8)); write(Indeks[i, j]); Mutu[i, j] := HitungMutu(Indeks[i, j], MK[j].SKS); end; gotoxy( 1, (l + 9) + N); write('-----------------------------------------------------------'); gotoxy( 1, (l + 10) + N); write('IPK : ', HitungIPK(i, M, N, Mutu, MK):0:1); l := (l * 10) + N; end; end; { end procedure } { program utama } begin IsiData(M, N, Mhs, MK); IsiNilai(M, N, Mhs, MK, Nilai); TampilIndeks(Nilai, M, N, Indeks); TampilHasilStudi(M, N, Mhs, MK, Indeks, Mutu); readln; end.
unit fmBase; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AppEvnts; type TfBase = class(TForm) procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private procedure InsideComponentEnabled(component: TComponent; const enabled: boolean); procedure InsideComponent(component: TComponent); protected procedure DoShow; override; procedure SetEnabled(Value: Boolean); override; public constructor Create(AOwner: TComponent); override; procedure Loaded; override; end; implementation {$R *.dfm} uses ExtCtrls; type TControlCracked = class(TControl) public property Font; end; constructor TfBase.Create(AOwner: TComponent); begin Screen.Cursor := crHourGlass; inherited Create(AOwner); end; procedure TfBase.DoShow; begin inherited DoShow; Screen.Cursor := crDefault; end; procedure TfBase.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfBase.InsideComponent(component: TComponent); var i, num: integer; begin if component is TCustomPanel then TCustomPanel(component).ParentBackground := false; num := component.ComponentCount - 1; for i:=0 to num do begin InsideComponent(component.Components[i]); end; end; procedure TfBase.InsideComponentEnabled(component: TComponent; const enabled: boolean); var i, num: integer; begin if component is TControl then begin TControl(component).Enabled := enabled; if enabled then TControlCracked(component).Font.Color := component.Tag else begin component.Tag := TControlCracked(component).Font.Color; TControlCracked(component).Font.Color := clGrayText; end; end; num := component.ComponentCount - 1; for i:=0 to num do begin InsideComponentEnabled(component.Components[i], enabled); end; end; procedure TfBase.Loaded; var i: integer; begin inherited Loaded; for i:=0 to ComponentCount - 1 do begin InsideComponent(Components[i]); end; end; procedure TfBase.SetEnabled(Value: Boolean); var i: integer; begin inherited; for i:=0 to ComponentCount - 1 do begin InsideComponentEnabled(Components[i], Value); end; end; end.
unit ChapterListModel; interface type TChapterListModel = class public chapter_content_decompress_length6: Cardinal; chapter_content_decompresss_offset5: Cardinal; chapter_data_block_offset4: Cardinal; chapter_data_type3: Word; chapter_index1: Cardinal; chapter_level2: Word; chapter_name_data8: string; chapter_name_header_length: Cardinal; chapter_name_length7: Cardinal; chaptermodellenth: Cardinal; constructor Create; end; implementation constructor TChapterListModel.Create; begin self.chapter_name_header_length := $18; self.chaptermodellenth := 8; end; end.
unit uRecipeEmail; interface uses Classes, RegularExpressions, uDemo, uRecipe; type TRecipeEmail = class(TRecipe) public class function Description: String; override; function Pattern: String; override; function Options: TRegexOptions; override; procedure GetInputs(const Inputs: TStrings); override; end; implementation { TRecipeEmail } class function TRecipeEmail.Description: String; begin Result := 'Recipes\Email Address'; end; {$REGION} /// <B>Source</B>: http://www.regexlib.com/REDetails.aspx?regexp_id=980 /// <B>Author</B>: Micah Duke /// /// This will validate most legal email addresses, even allows for some /// discouraged but perfectly legal characters in local part; allows IP domains /// with optional []; keeps final tld at a minmum of 2 chars; non capturing /// groups for efficiency function TRecipeEmail.Pattern: String; begin Result := '^(?:[a-zA-Z0-9_''^&/+-])+(?:\.(?:[a-zA-Z0-9_''^&/+-])+)*@' + '(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}' + '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+' + '(?:[a-zA-Z]){2,}\.?)$'; end; function TRecipeEmail.Options: TRegexOptions; begin Result := [roIgnoreCase]; end; procedure TRecipeEmail.GetInputs(const Inputs: TStrings); begin Inputs.Add('you.me.hello@somewhere.else.cc'); Inputs.Add('joe_smith@here.com.'); Inputs.Add('me@[24.111.232.1]'); Inputs.Add('.me.you@here.com'); Inputs.Add('.murat@62.59.114.103.nl'); Inputs.Add('test_case@here*555%there.com'); end; {$ENDREGION} initialization RegisterDemo(TRecipeEmail); end.
unit UdwsDataBaseTests; interface uses Classes, SysUtils, dwsXPlatformTests, dwsComp, dwsCompiler, dwsExprs, dwsErrors, dwsDataBaseLibModule, dwsXPlatform, dwsSymbols, dwsUtils, dwsGUIDDatabase; type TdwsDataBaseTests = class (TTestCase) private FTests : TStringList; FCompiler : TDelphiWebScript; FDataBaseLib : TdwsDatabaseLib; public procedure SetUp; override; procedure TearDown; override; procedure Execution; procedure Compilation; published procedure CompilationNormal; procedure CompilationWithMapAndSymbols; procedure ExecutionNonOptimized; procedure ExecutionOptimized; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------ // ------------------ TdwsDataBaseTests ------------------ // ------------------ // SetUp // procedure TdwsDataBaseTests.SetUp; begin FTests:=TStringList.Create; CollectFiles(ExtractFilePath(ParamStr(0))+'DatabaseLib'+PathDelim, '*.pas', FTests); FCompiler:=TDelphiWebScript.Create(nil); FDataBaseLib:=TdwsDatabaseLib.Create(nil); FDataBaseLib.Script:=FCompiler; end; // TearDown // procedure TdwsDataBaseTests.TearDown; begin FDataBaseLib.Free; FCompiler.Free; FTests.Free; end; // Compilation // procedure TdwsDataBaseTests.Compilation; var source : TStringList; i : Integer; prog : IdwsProgram; begin source:=TStringList.Create; try for i:=0 to FTests.Count-1 do begin source.LoadFromFile(FTests[i]); prog:=FCompiler.Compile(source.Text); CheckEquals('', prog.Msgs.AsInfo, FTests[i]); end; finally source.Free; end; end; // CompilationNormal // procedure TdwsDataBaseTests.CompilationNormal; begin FCompiler.Config.CompilerOptions:=[coOptimize]; Compilation; end; // CompilationWithMapAndSymbols // procedure TdwsDataBaseTests.CompilationWithMapAndSymbols; begin FCompiler.Config.CompilerOptions:=[coSymbolDictionary, coContextMap, coAssertions]; Compilation; end; // ExecutionNonOptimized // procedure TdwsDataBaseTests.ExecutionNonOptimized; begin FCompiler.Config.CompilerOptions:=[coAssertions]; Execution; end; // ExecutionOptimized // procedure TdwsDataBaseTests.ExecutionOptimized; begin FCompiler.Config.CompilerOptions:=[coOptimize, coAssertions]; Execution; end; // Execution // procedure TdwsDataBaseTests.Execution; var source, expectedResult : TStringList; i : Integer; prog : IdwsProgram; exec : IdwsProgramExecution; resultText, resultsFileName : String; begin source:=TStringList.Create; expectedResult:=TStringList.Create; try for i:=0 to FTests.Count-1 do begin source.LoadFromFile(FTests[i]); prog:=FCompiler.Compile(source.Text); CheckEquals('', prog.Msgs.AsInfo, FTests[i]); exec:=prog.Execute; resultText:=exec.Result.ToString; if exec.Msgs.Count>0 then resultText:=resultText+#13#10'>>>> Error(s): '#13#10+exec.Msgs.AsInfo; resultsFileName:=ChangeFileExt(FTests[i], '.txt'); if FileExists(resultsFileName) then begin expectedResult.LoadFromFile(resultsFileName); CheckEquals(expectedResult.Text, resultText, FTests[i]); end else CheckEquals('', resultText, FTests[i]); CheckEquals('', exec.Msgs.AsInfo, FTests[i]); end; finally expectedResult.Free; source.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterTest('LibModules', TdwsDataBaseTests); end.
unit uDGCtrlUtils; interface uses SysUtils, fmx.Controls, Classes, fmx.Forms, IniFiles; // this is the array of properties, the names are case sensitive const CONTROL_PROPS: array[0..4] of string = ('Left', 'Top', 'Width', 'Height', 'Visible'); (* you can also add more properties like Caption increase the length of array by 1 from 4 to 5 const CONTROL_PROPS: array[0..5] of string = ('Left', 'Top', 'Width', 'Height', 'Visible', 'Caption'); and add Caption in the array *) procedure SaveControls(toIniFile: TIniFile; fromForm: TForm); procedure LoadControls(fromIniFIle: TIniFile; toForm: TForm); procedure SaveControlsToFile(const FileName: string; fromForm: TForm); procedure LoadControlsFromFile(const FileName: string; toForm: TForm); implementation uses TypInfo; procedure SaveControls(toIniFile: TIniFile; fromForm: TForm); var i, j : integer; obj : TComponent; s, sec : string; begin // store the section sec := fromForm.Name; // for each component on form for i := 0 to fromForm.ComponentCount -1 do begin // get it's reference into obj obj := fromForm.Components[i]; // for each property defined in array for j := Low(CONTROL_PROPS) to High(CONTROL_PROPS) do // check if component has that property using RTTI if IsPublishedProp(obj, CONTROL_PROPS[j]) then begin // format the string ComponentName.Property s := Format('%s.%s', [obj.Name, CONTROL_PROPS[j]]); // write data to ini file toIniFile.WriteString(sec, s, GetPropValue(obj, CONTROL_PROPS[j])); end;// if IsPublishedProp(obj, CONTROL_PROPS[j]) then begin end;// for i := 0 to fromForm.ComponentCount -1 do begin end; procedure LoadControls(fromIniFIle: TIniFile; toForm: TForm); var i, j : integer; obj : TComponent; s, sec, value : string; begin // store the section sec := toForm.Name; // for each component on form for i := 0 to toForm.ComponentCount -1 do begin // get it's reference into obj obj := toForm.Components[i]; // for each property defined in array for j := Low(CONTROL_PROPS) to High(CONTROL_PROPS) do // check if component has that property using RTTI if IsPublishedProp(obj, CONTROL_PROPS[j]) then begin // format the string ComponentName.Property s := Format('%s.%s', [obj.Name, CONTROL_PROPS[j]]); // read data from ini file value := fromIniFIle.ReadString(sec, s, EmptyStr); // check if value is not '' (EmptyStr) if value <> EmptyStr then // set the property SetPropValue(obj, CONTROL_PROPS[j], value); end;// if IsPublishedProp(obj, CONTROL_PROPS[j]) then begin end;// for i := 0 to fromForm.ComponentCount -1 do begin end; procedure SaveControlsToFile(const FileName: string; fromForm: TForm); var ini : TIniFile; begin ini := TIniFile.Create(FileName); SaveControls(ini, fromForm); FreeAndNil(ini); end; procedure LoadControlsFromFile(const FileName: string; toForm: TForm); var ini : TIniFile; begin ini := TIniFile.Create(FileName); LoadControls(ini, toForm); FreeAndNil(ini); end; end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 2000 by Stephen L. Moshier Contributors: * Sergey Bochkanov (ALGLIB project). Translation from C to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit chisquaredistr; interface uses Math, Sysutils, Ap, gammafunc, normaldistr, igammaf; function ChiSquareDistribution(v : Double; x : Double):Double; function ChiSquareCDistribution(v : Double; x : Double):Double; function InvChiSquareDistribution(v : Double; y : Double):Double; implementation (************************************************************************* Chi-square distribution Returns the area under the left hand tail (from 0 to x) of the Chi square probability density function with v degrees of freedom. x - 1 | | v/2-1 -t/2 P( x | v ) = ----------- | t e dt v/2 - | | 2 | (v/2) - 0 where x is the Chi-square variable. The incomplete gamma integral is used, according to the formula y = chdtr( v, x ) = igam( v/2.0, x/2.0 ). The arguments must both be positive. ACCURACY: See incomplete gamma function Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 2000 by Stephen L. Moshier *************************************************************************) function ChiSquareDistribution(v : Double; x : Double):Double; begin Assert(AP_FP_Greater_Eq(x,0) and AP_FP_Greater_Eq(v,1), 'Domain error in ChiSquareDistribution'); Result := IncompleteGamma(v/Double(2.0), x/Double(2.0)); end; (************************************************************************* Complemented Chi-square distribution Returns the area under the right hand tail (from x to infinity) of the Chi square probability density function with v degrees of freedom: inf. - 1 | | v/2-1 -t/2 P( x | v ) = ----------- | t e dt v/2 - | | 2 | (v/2) - x where x is the Chi-square variable. The incomplete gamma integral is used, according to the formula y = chdtr( v, x ) = igamc( v/2.0, x/2.0 ). The arguments must both be positive. ACCURACY: See incomplete gamma function Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 2000 by Stephen L. Moshier *************************************************************************) function ChiSquareCDistribution(v : Double; x : Double):Double; begin Assert(AP_FP_Greater_Eq(x,0) and AP_FP_Greater_Eq(v,1), 'Domain error in ChiSquareDistributionC'); Result := IncompleteGammaC(v/Double(2.0), x/Double(2.0)); end; (************************************************************************* Inverse of complemented Chi-square distribution Finds the Chi-square argument x such that the integral from x to infinity of the Chi-square density is equal to the given cumulative probability y. This is accomplished using the inverse gamma integral function and the relation x/2 = igami( df/2, y ); ACCURACY: See inverse incomplete gamma function Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 2000 by Stephen L. Moshier *************************************************************************) function InvChiSquareDistribution(v : Double; y : Double):Double; begin Assert(AP_FP_Greater_Eq(y,0) and AP_FP_Less_Eq(y,1) and AP_FP_Greater_Eq(v,1), 'Domain error in InvChiSquareDistribution'); Result := 2*InvIncompleteGammaC(Double(0.5)*v, y); end; end.
unit uBase85; {$ZEROBASEDSTRINGS ON} interface uses System.SysUtils, System.Classes, System.StrUtils, uBase, uUtils; type IBase85 = interface ['{A230687D-2037-482C-B207-E543683B5ED4}'] function Encode(data: TArray<Byte>): String; function Decode(const data: String): TArray<Byte>; function EncodeString(const data: String): String; function DecodeToString(const data: String): String; function GetBitsPerChars: Double; property BitsPerChars: Double read GetBitsPerChars; function GetCharsCount: UInt32; property CharsCount: UInt32 read GetCharsCount; function GetBlockBitsCount: Integer; property BlockBitsCount: Integer read GetBlockBitsCount; function GetBlockCharsCount: Integer; property BlockCharsCount: Integer read GetBlockCharsCount; function GetAlphabet: String; property Alphabet: String read GetAlphabet; function GetSpecial: Char; property Special: Char read GetSpecial; function GetHaveSpecial: Boolean; property HaveSpecial: Boolean read GetHaveSpecial; function GetEncoding: TEncoding; procedure SetEncoding(value: TEncoding); property Encoding: TEncoding read GetEncoding write SetEncoding; function GetPrefixPostfix: Boolean; procedure SetPrefixPostfix(value: Boolean); property PrefixPostfix: Boolean read GetPrefixPostfix write SetPrefixPostfix; end; TBase85 = class(TBase, IBase85) strict private function GetPrefixPostfix: Boolean; procedure SetPrefixPostfix(value: Boolean); procedure EncodeBlock(count: Integer; sb: TStringBuilder; encodedBlock: TArray<Byte>; tuple: UInt32); procedure DecodeBlock(bytes: Integer; decodedBlock: TArray<Byte>; tuple: UInt32); protected class var FPrefixPostfix: Boolean; public const DefaultAlphabet = '!"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstu'; DefaultSpecial = Char(0); Pow85: Array [0 .. 4] of UInt32 = (85 * 85 * 85 * 85, 85 * 85 * 85, 85 * 85, 85, 1); Prefix = '<~'; Postfix = '~>'; constructor Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _prefixPostfix: Boolean = False; _textEncoding: TEncoding = Nil); function Encode(data: TArray<Byte>): String; override; function Decode(const data: String): TArray<Byte>; override; property PrefixPostfix: Boolean read GetPrefixPostfix write SetPrefixPostfix; end; implementation constructor TBase85.Create(const _Alphabet: String = DefaultAlphabet; _Special: Char = DefaultSpecial; _prefixPostfix: Boolean = False; _textEncoding: TEncoding = Nil); begin Inherited Create(85, _Alphabet, _Special, _textEncoding); FHaveSpecial := False; PrefixPostfix := _prefixPostfix; BlockBitsCount := 32; BlockCharsCount := 5; end; function TBase85.GetPrefixPostfix: Boolean; begin result := FPrefixPostfix; end; procedure TBase85.SetPrefixPostfix(value: Boolean); begin FPrefixPostfix := value; end; {$OVERFLOWCHECKS OFF} function TBase85.Encode(data: TArray<Byte>): String; var encodedBlock: TArray<Byte>; decodedBlockLength, count, resultLength: Integer; sb: TStringBuilder; tuple: UInt32; b: Byte; temp: Double; begin SetLength(encodedBlock, 5); decodedBlockLength := 4; temp := Length(data) * (Length(encodedBlock) / decodedBlockLength); resultLength := Trunc(temp); if (PrefixPostfix) then resultLength := resultLength + Length(Prefix) + Length(Postfix); sb := TStringBuilder.Create(resultLength); try if (PrefixPostfix) then begin sb.Append(Prefix); end; count := 0; tuple := 0; for b in data do begin if (count >= (decodedBlockLength - 1)) then begin tuple := tuple or b; if (tuple = 0) then begin sb.Append('z') end else begin EncodeBlock(Length(encodedBlock), sb, encodedBlock, tuple); tuple := 0; count := 0; end; end else begin tuple := tuple or (UInt32(b shl (24 - (count * 8)))); Inc(count); end; end; if (count > 0) then begin EncodeBlock(count + 1, sb, encodedBlock, tuple); end; if (PrefixPostfix) then begin sb.Append(Postfix); end; result := sb.ToString; finally sb.Free; end; end; {$OVERFLOWCHECKS OFF} function TBase85.Decode(const data: String): TArray<Byte>; var dataWithoutPrefixPostfix: String; ms: TMemoryStream; count, encodedBlockLength, i: Integer; processChar: Boolean; tuple: LongWord; decodedBlock: TArray<Byte>; c: Char; begin if TUtils.isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; dataWithoutPrefixPostfix := data; if (PrefixPostfix) then begin if not(TUtils.StartsWith(dataWithoutPrefixPostfix, Prefix) or TUtils.EndsWith(dataWithoutPrefixPostfix, Postfix)) then begin raise Exception.Create (Format('ASCII85 encoded data should begin with "%s" and end with "%s"', [Prefix, Postfix])); end; dataWithoutPrefixPostfix := Copy(dataWithoutPrefixPostfix, Length(Prefix) + 1, Length(dataWithoutPrefixPostfix) - Length(Prefix) - Length(Postfix)); end; ms := TMemoryStream.Create; try count := 0; tuple := UInt32(0); encodedBlockLength := 5; SetLength(decodedBlock, 4); for c in dataWithoutPrefixPostfix do begin Case AnsiIndexStr(c, ['z']) of 0: begin if (count <> 0) then begin raise Exception.Create ('The character ''z'' is invalid inside an ASCII85 block.'); end; decodedBlock[0] := 0; decodedBlock[1] := 0; decodedBlock[2] := 0; decodedBlock[3] := 0; ms.Write(decodedBlock, 0, Length(decodedBlock)); processChar := False; end else begin processChar := True; end; end; if (processChar) then begin tuple := tuple + UInt32(FInvAlphabet[Ord(c)]) * Pow85[count]; Inc(count); if (count = encodedBlockLength) then begin DecodeBlock(Length(decodedBlock), decodedBlock, tuple); ms.Write(decodedBlock, 0, Length(decodedBlock)); tuple := 0; count := 0; end; end; end; if (count <> 0) then begin if (count = 1) then begin raise Exception.Create ('The last block of ASCII85 data cannot be a single byte.'); end; dec(count); tuple := tuple + Pow85[count]; DecodeBlock(count, decodedBlock, tuple); for i := 0 to Pred(count) do begin ms.Write(decodedBlock[i], 1); end; end; ms.Position := 0; SetLength(result, ms.Size); ms.Read(result[0], ms.Size); finally ms.Free; end; end; {$OVERFLOWCHECKS OFF} procedure TBase85.EncodeBlock(count: Integer; sb: TStringBuilder; encodedBlock: TArray<Byte>; tuple: UInt32); var i: Integer; begin i := Pred(Length(encodedBlock)); while i >= 0 do begin encodedBlock[i] := Byte(tuple mod 85); tuple := tuple div 85; dec(i); end; i := 0; while i < count do begin sb.Append(DefaultAlphabet[encodedBlock[i]]); Inc(i); end; end; procedure TBase85.DecodeBlock(bytes: Integer; decodedBlock: TArray<Byte>; tuple: LongWord); var i: Integer; begin for i := 0 to Pred(bytes) do begin decodedBlock[i] := Byte(tuple shr (24 - (i * 8))); end; end; end.
unit LocationService; interface uses Androidapi.JNI.Location, Androidapi.JNIBridge, FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText; type TLocationService = class(TObject) private public class function CheckLocationEnable(): Boolean; end; implementation // Comprueba que esté disponible la localización en android (en iOS no hará falta) class function TLocationService.CheckLocationEnable(): Boolean; var locationManager : JLocationManager; begin locationManager := TJLocationManager.Wrap( ((SharedActivity.getSystemService(TJContext.JavaClass.LOCATION_SERVICE)) as ILocalObject).GetObjectID); Result := false; // Con que una de las dos localizaciones funcione, devolverá true if locationManager.isProviderEnabled(TJLocationManager.JavaClass.GPS_PROVIDER) then Result := true else if locationManager.isProviderEnabled(TJLocationManager.JavaClass.NETWORK_PROVIDER) then Result := true; end; end.
unit ULanguageExtensionTests; interface {$I dws.inc} uses {$IFDEF WINDOWS} Windows, {$ENDIF}Classes, SysUtils, dwsStack, dwsXPlatformTests, dwsComp, dwsCompiler, dwsExprs, dwsDataContext, dwsTokenizer, dwsXPlatform, dwsFileSystem, dwsErrors, dwsUtils, Variants, dwsSymbols, dwsPascalTokenizer, dwsStrings, dwsJSON, dwsLanguageExtension; type TLanguageExtensionTests = class (TTestCase) private FCompiler : TDelphiWebScript; public procedure SetUp; override; procedure TearDown; override; published procedure AutoExternalValues; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ type TAutoExternalValues = class (TdwsLanguageExtension) public function FindUnknownName(compiler : TdwsCompiler; const name : UnicodeString) : TSymbol; override; end; TCallableAutoExternal = class(TdwsCallable) protected procedure Call(exec : TdwsProgramExecution; func : TFuncSymbol); override; end; TAutoExternalValuesExtension = class (TdwsCustomLangageExtension) protected function CreateExtension : TdwsLanguageExtension; override; end; // CreateExtension // function TAutoExternalValuesExtension.CreateExtension : TdwsLanguageExtension; begin Result:=TAutoExternalValues.Create; end; // Call // procedure TCallableAutoExternal.Call(exec : TdwsProgramExecution; func : TFuncSymbol); begin exec.Stack.WriteStrValue_BaseRelative(func.Result.StackAddr, func.Name); end; // FindUnknownName // function TAutoExternalValues.FindUnknownName(compiler : TdwsCompiler; const name : UnicodeString) : TSymbol; var externalSym : TExternalVarSymbol; readFunc : TFuncSymbol; call : TCallableAutoExternal; begin externalSym:=TExternalVarSymbol.Create(name, compiler.CurrentProg.TypString); compiler.CurrentProg.Table.AddSymbol(externalSym); call:=TCallableAutoExternal.Create(nil); readFunc:=TFuncSymbol.Create('_get_'+name, fkFunction, 0); readFunc.Executable:=call; readFunc.Typ:=compiler.CurrentProg.TypString; call._Release; externalSym.ReadFunc:=readFunc; Result:=externalSym; end; // ------------------ // ------------------ TLanguageExtensionTests ------------------ // ------------------ // SetUp // procedure TLanguageExtensionTests.SetUp; begin FCompiler:=TDelphiWebScript.Create(nil); end; // TearDown // procedure TLanguageExtensionTests.TearDown; begin FCompiler.Free; end; // AutoExternalValues // procedure TLanguageExtensionTests.AutoExternalValues; var custom : TAutoExternalValuesExtension; prog : IdwsProgram; exec : IdwsProgramExecution; begin custom:=TAutoExternalValuesExtension.Create(nil); try custom.Script:=FCompiler; prog:=FCompiler.Compile( 'PrintLn(Hello);'#13#10 +'PrintLn(World);'#13#10); CheckEquals('', prog.Msgs.AsInfo); exec:=prog.Execute; CheckEquals('_get_Hello'#13#10'_get_World'#13#10, exec.Result.ToString); finally custom.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterTest('LanguageExtensionTests', TLanguageExtensionTests); end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Copyright (c) 1992-2007 The University of Tennessee. All rights reserved. Contributors: * Sergey Bochkanov (ALGLIB project). Translation from FORTRAN to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit estnorm; interface uses Math, Sysutils, Ap; procedure IterativeEstimate1Norm(N : AlglibInteger; var V : TReal1DArray; var X : TReal1DArray; var ISGN : TInteger1DArray; var EST : Double; var KASE : AlglibInteger); function DemoIterativeEstimate1Norm(const A : TReal2DArray; N : AlglibInteger):Double; implementation (************************************************************************* Matrix norm estimation The algorithm estimates the 1-norm of square matrix A on the assumption that the multiplication of matrix A by the vector is available (the iterative method is used). It is recommended to use this algorithm if it is hard to calculate matrix elements explicitly (for example, when estimating the inverse matrix norm). The algorithm uses back communication for multiplying the vector by the matrix. If KASE=0 after returning from a subroutine, its execution was completed successfully, otherwise it is required to multiply the returned vector by matrix A and call the subroutine again. The DemoIterativeEstimateNorm subroutine shows a simple example. Parameters: N - size of matrix A. V - vector. It is initialized by the subroutine on the first call. It is then passed into it on repeated calls. X - if KASE<>0, it contains the vector to be replaced by: A * X, if KASE=1 A^T * X, if KASE=2 Array whose index ranges within [1..N]. ISGN - vector. It is initialized by the subroutine on the first call. It is then passed into it on repeated calls. EST - if KASE=0, it contains the lower boundary of the matrix norm estimate. KASE - on the first call, it should be equal to 0. After the last return, it is equal to 0 (EST contains the matrix norm), on intermediate returns it can be equal to 1 or 2 depending on the operation to be performed on vector X. -- LAPACK auxiliary routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 *************************************************************************) procedure IterativeEstimate1Norm(N : AlglibInteger; var V : TReal1DArray; var X : TReal1DArray; var ISGN : TInteger1DArray; var EST : Double; var KASE : AlglibInteger); var ITMAX : AlglibInteger; I : AlglibInteger; T : Double; Flg : Boolean; PosITER : AlglibInteger; PosJ : AlglibInteger; PosJLAST : AlglibInteger; PosJUMP : AlglibInteger; PosALTSGN : AlglibInteger; PosESTOLD : AlglibInteger; PosTEMP : AlglibInteger; begin ITMAX := 5; PosALTSGN := N+1; PosESTOLD := N+2; PosTEMP := N+3; PosITER := N+1; PosJ := N+2; PosJLAST := N+3; PosJUMP := N+4; if KASE=0 then begin SetLength(V, N+3+1); SetLength(X, N+1); SetLength(ISGN, N+4+1); T := AP_Double(1)/N; I:=1; while I<=N do begin X[I] := T; Inc(I); end; KASE := 1; ISGN[PosJUMP] := 1; Exit; end; // // ................ ENTRY (JUMP = 1) // FIRST ITERATION. X HAS BEEN OVERWRITTEN BY A*X. // if ISGN[PosJUMP]=1 then begin if N=1 then begin V[1] := X[1]; EST := ABSReal(V[1]); KASE := 0; Exit; end; EST := 0; I:=1; while I<=N do begin EST := EST+AbsReal(X[I]); Inc(I); end; I:=1; while I<=N do begin if AP_FP_Greater_Eq(X[I],0) then begin X[I] := 1; end else begin X[I] := -1; end; ISGN[I] := Sign(X[I]); Inc(I); end; KASE := 2; ISGN[PosJUMP] := 2; Exit; end; // // ................ ENTRY (JUMP = 2) // FIRST ITERATION. X HAS BEEN OVERWRITTEN BY TRANDPOSE(A)*X. // if ISGN[PosJUMP]=2 then begin ISGN[PosJ] := 1; I:=2; while I<=N do begin if AP_FP_Greater(AbsReal(X[I]),AbsReal(X[ISGN[PosJ]])) then begin ISGN[PosJ] := I; end; Inc(I); end; ISGN[PosITER] := 2; // // MAIN LOOP - ITERATIONS 2,3,...,ITMAX. // I:=1; while I<=N do begin X[I] := 0; Inc(I); end; X[ISGN[PosJ]] := 1; KASE := 1; ISGN[PosJUMP] := 3; Exit; end; // // ................ ENTRY (JUMP = 3) // X HAS BEEN OVERWRITTEN BY A*X. // if ISGN[PosJUMP]=3 then begin APVMove(@V[0], 1, N, @X[0], 1, N); V[PosESTOLD] := EST; EST := 0; I:=1; while I<=N do begin EST := EST+AbsReal(V[I]); Inc(I); end; Flg := False; I:=1; while I<=N do begin if AP_FP_Greater_Eq(X[I],0) and (ISGN[I]<0) or AP_FP_Less(X[I],0) and (ISGN[I]>=0) then begin Flg := True; end; Inc(I); end; // // REPEATED SIGN VECTOR DETECTED, HENCE ALGORITHM HAS CONVERGED. // OR MAY BE CYCLING. // if not Flg or AP_FP_Less_Eq(EST,V[PosESTOLD]) then begin V[PosALTSGN] := 1; I:=1; while I<=N do begin X[I] := V[PosALTSGN]*(1+AP_Double((I-1))/(N-1)); V[PosALTSGN] := -V[PosALTSGN]; Inc(I); end; KASE := 1; ISGN[PosJUMP] := 5; Exit; end; I:=1; while I<=N do begin if AP_FP_Greater_Eq(X[I],0) then begin X[I] := 1; ISGN[I] := 1; end else begin X[I] := -1; ISGN[I] := -1; end; Inc(I); end; KASE := 2; ISGN[PosJUMP] := 4; Exit; end; // // ................ ENTRY (JUMP = 4) // X HAS BEEN OVERWRITTEN BY TRANDPOSE(A)*X. // if ISGN[PosJUMP]=4 then begin ISGN[PosJLAST] := ISGN[PosJ]; ISGN[PosJ] := 1; I:=2; while I<=N do begin if AP_FP_Greater(AbsReal(X[I]),AbsReal(X[ISGN[PosJ]])) then begin ISGN[PosJ] := I; end; Inc(I); end; if AP_FP_Neq(X[ISGN[PosJLAST]],ABSReal(X[ISGN[PosJ]])) and (ISGN[PosITER]<ITMAX) then begin ISGN[PosITER] := ISGN[PosITER]+1; I:=1; while I<=N do begin X[I] := 0; Inc(I); end; X[ISGN[PosJ]] := 1; KASE := 1; ISGN[PosJUMP] := 3; Exit; end; // // ITERATION COMPLETE. FINAL STAGE. // V[PosALTSGN] := 1; I:=1; while I<=N do begin X[I] := V[PosALTSGN]*(1+AP_Double((I-1))/(N-1)); V[PosALTSGN] := -V[PosALTSGN]; Inc(I); end; KASE := 1; ISGN[PosJUMP] := 5; Exit; end; // // ................ ENTRY (JUMP = 5) // X HAS BEEN OVERWRITTEN BY A*X. // if ISGN[PosJUMP]=5 then begin V[PosTEMP] := 0; I:=1; while I<=N do begin V[PosTEMP] := V[PosTEMP]+AbsReal(X[I]); Inc(I); end; V[PosTEMP] := 2*V[PosTEMP]/(3*N); if AP_FP_Greater(V[PosTEMP],EST) then begin APVMove(@V[0], 1, N, @X[0], 1, N); EST := V[PosTEMP]; end; KASE := 0; Exit; end; end; (************************************************************************* Example of usage of an IterativeEstimateNorm subroutine Input parameters: A - matrix. Array whose indexes range within [1..N, 1..N]. Return: Matrix norm estimated by the subroutine. -- ALGLIB -- Copyright 2005 by Bochkanov Sergey *************************************************************************) function DemoIterativeEstimate1Norm(const A : TReal2DArray; N : AlglibInteger):Double; var I : AlglibInteger; S : Double; X : TReal1DArray; T : TReal1DArray; V : TReal1DArray; IV : TInteger1DArray; KASE : AlglibInteger; i_ : AlglibInteger; begin KASE := 0; SetLength(T, N+1); IterativeEstimate1Norm(N, V, X, IV, Result, KASE); while KASE<>0 do begin if KASE=1 then begin I:=1; while I<=N do begin S := APVDotProduct(@A[I][0], 1, N, @X[0], 1, N); T[I] := S; Inc(I); end; end else begin I:=1; while I<=N do begin S := 0.0; for i_ := 1 to N do begin S := S + A[i_,I]*X[i_]; end; T[I] := S; Inc(I); end; end; APVMove(@X[0], 1, N, @T[0], 1, N); IterativeEstimate1Norm(N, V, X, IV, Result, KASE); end; end; end.
unit DemoForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, AsyncAwait; type TForm1 = class(TForm) btnDemo: TButton; btnFibonacci: TButton; lblResult: TLabel; procedure btnDemoClick(Sender: TObject); procedure btnFibonacciClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} //don't use recursive implementation function Fibonacci(aNumber: UInt64): Int64; var I, N_1, N_2, N: UInt64; begin case aNumber of 0: Result:= 0; 1: Result:= 1; else begin N_1:= 0; N_2:= 1; N := 1; for I:=2 to aNumber do begin N:= N_1 + N_2; N_1:= N_2; N_2:= N; end; Result:= N; end; end; end; procedure TForm1.btnFibonacciClick(Sender: TObject); var seed: UInt64; begin seed := Random(MaxInt); lblResult.Caption := Format('Calculating Fibonacci number for %d. Please wait...', [seed]); btnFibonacci.Enabled := false;// we will re-enable it when we are done TTask<UInt64>.Async( //timeconsuming call on a secondary thread function : UInt64 begin Result := Fibonacci(seed); //raise Exception.Create('Error Message'); end, //update the UI on the main thread procedure(task : ITask<UInt64>; Value : UInt64) begin if task.Status = TTaskStatus.RanToCompletion then lblResult.Caption := Format('Fibonacci number for %d is %d', [seed, Value]) else if task.Status = TTaskStatus.Faulted then lblResult.Caption := Format('Error calculating Fibonacci number: %s', [task.Exception.Message]); //re-enable the button - we are done btnFibonacci.Enabled := true; end, //tell to continue on the main thread - //don't need to specify this parameter as it defaults to true anyway true ); end; procedure TForm1.btnDemoClick(Sender: TObject); var t : ITask<integer>; syncContext : ISynchronizationContext; begin btnDemo.Enabled := false; //we will reenable it when we are done syncContext := TSynchronizationContext.Current; t := TTask<integer>.Async( //async function function() : integer var delay : integer; begin delay := Random(10000); sleep(delay); Result := delay; //run another task //start it explicitly since we need to configure the //synchornization context (main thread) first //before the continuation code has a chance to run TTask.Create( procedure() begin sleep(2000); end ). ContinueWith( procedure(task : ITask) begin ShowMessage('Done second task'); end, //use the sync context from the main thread since we are showing a window syncContext ). //now start the task after we configured it; Start; end, //continue with //it is guaranteed to run on the calling thread (this main thread) //since continueOnCapturedContext parameter defaults to true procedure(task : ITask<integer>; Value : integer ) begin if task.Status = TTaskStatus.RanToCompletion then ShowMessage(Format('All done after sleeping for %d seconds', [task.Value div 1000])) else if task.Status = TTaskStatus.Faulted then ShowMessage(Format('Task faulted. Exception type = %s: %s', [task.Exception.ClassName, task.Exception.Message])); //re-enable the buttton btnDemo.Enabled := true; end, //continue on the main thread - we don't need to specify this parameter //as it defaults to true anyway true ); if t.Wait(20000) //Wait is smart enough not to block on continuation call above executed on the same thread then ShowMessage(Format('Done after waiting for less than 20 seconds. Task returned %d', [t.Value])) else ShowMessage('Still not done after waiting for 2 seconds'); end; end.
unit Unit5; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ImgList, ComWriUtils, CoolCtrls, ExtCtrls; type TForm1 = class(TForm) Image1: TImage; AniCoolButton1: TAniCoolButton; AniCoolButton2: TAniCoolButton; AniButtonOutlook1: TAniButtonOutlook; ImageList1: TImageList; cbTransparent: TCheckBox; cbFlat: TCheckBox; btnConfig: TButton; procedure btnConfigClick(Sender: TObject); procedure cbTransparentClick(Sender: TObject); procedure cbFlatClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} uses BtnLookCfgDLG; procedure TForm1.btnConfigClick(Sender: TObject); var dlg : TdlgCfgBtnLook; begin dlg := TdlgCfgBtnLook.Create(Application); try dlg.Execute(AniButtonOutlook1); finally dlg.free; end; end; procedure TForm1.cbTransparentClick(Sender: TObject); begin AniCoolButton1.Transparent := cbTransparent.Checked; AniCoolButton2.Transparent := cbTransparent.Checked; end; procedure TForm1.cbFlatClick(Sender: TObject); begin AniButtonOutlook1.Flat := cbFlat.Checked; end; end.
unit Rectangles; interface uses Types, Rotations; procedure NormalizeRect( var R : TRect ); //procedure RotateRect( var R : TRect; Angle : TRot ); procedure ExtendRectangle( var Rectangle : TRect; const Additional : TRect ); implementation // ** arrange coords in normalised form * // ensures left<=right, top<=bottom // This is not a bounding rectangle procedure NormalizeRect( var R : TRect ); var Temp : integer; begin if R.Right < R.Left then begin Temp := R.Right; R.Right := R.Left; R.Left := Temp; end; if R.Bottom < R.Top then begin Temp := R.Bottom; R.Bottom := R.Top; R.Top := Temp; end; end; // ** Extend Rectangle so it encloses Additional Rectangle ** procedure ExtendRectangle( var Rectangle : TRect; const Additional : TRect ); begin if Additional.Left < Rectangle.Left then begin Rectangle.Left := Additional.Left; end; if Additional.Right > Rectangle.Right then begin Rectangle.Right := Additional.Right; end; if Additional.Top < Rectangle.Top then begin Rectangle.Top := Additional.Top; end; if Additional.Bottom > Rectangle.Bottom then begin Rectangle.Bottom := Additional.Bottom; end; end; end.
(******************************************************************************) (** Suite : AtWS **) (** Object : IAtWSvc **) (** Framework : **) (** Developed by : Nuno Picado **) (******************************************************************************) (** Interfaces : IAtWSvc **) (******************************************************************************) (** Dependencies : **) (******************************************************************************) (** Description : Sends a XML request to a webservice, and returns its **) (** response **) (******************************************************************************) (** Licence : MIT (https://opensource.org/licenses/MIT) **) (** Contributions : You can create pull request for all your desired **) (** contributions as long as they comply with the guidelines **) (** you can find in the readme.md file in the main directory **) (** of the Reusable Objects repository **) (** Disclaimer : The licence agreement applies to the code in this unit **) (** and not to any of its dependencies, which have their own **) (** licence agreement and to which you must comply in their **) (** terms **) (******************************************************************************) unit AtWSvcIntf; interface type IAtWSvc = interface ['{5119FAB4-F5BB-458E-99F0-96CF75F58981}'] function Send(const XMLData: WideString): WideString; end; implementation end.
{ ClickFORMS (C) Copyright 1998 - 2010, Bradford Technologies, Inc. All Rights Reserved. Purpose: A form for interfacing with the Pictometry imagery service. } unit UFormPictometry; interface uses ActnList, Classes, Controls, ExtCtrls, StdCtrls, UContainer, UForms, UGridMgr, uCell, // uGeoCoder, uUtil2, uForm, uStatus, uStrings; type AddrInfo = record //structure to hold lat/lon and address info Lat: String; Lon: String; StreetNum: String; StreetName: String; City: String; State: String; Zip: String; UnitNo: String; end; /// summary: A form for interfacing with the Pictometry imagery service. TPictometryForm = class(TVistaAdvancedForm) LabelStreet: TLabel; LabelCity: TLabel; LabelState: TLabel; LabelZip: TLabel; EditStreet: TEdit; EditCity: TEdit; EditState: TEdit; EditZip: TEdit; ButtonSearchByAddress: TButton; ActionList: TActionList; ActionSearchByAddress: TAction; ActionCancel: TAction; ButtonCancel: TButton; PanelImages: TPanel; ImageNorth: TImage; ImageEast: TImage; ImageSouth: TImage; ImageWest: TImage; ShapeImageNorth: TShape; ShapeImageEast: TShape; ShapeImageSouth: TShape; ShapeImageWest: TShape; ActionTransfer: TAction; PanelAddress: TPanel; ButtonTransfer: TButton; ShapeImageOrthogonal: TShape; ImageOrthogonal: TImage; LabelSouth: TLabel; LabelNorth: TLabel; LabelEast: TLabel; LabelWest: TLabel; RadioButtonFrontNorth: TRadioButton; RadioButtonFrontEast: TRadioButton; RadioButtonFrontSouth: TRadioButton; RadioButtonFrontWest: TRadioButton; LabelOverhead: TLabel; LabelSelectFrontImage: TLabel; procedure ActionCancelExecute(Sender: TObject); procedure ActionCancelUpdate(Sender: TObject); procedure ActionSearchByAddressUpdate(Sender: TObject); procedure ActionTransferUpdate(Sender: TObject); procedure EditAddressChange(Sender: TObject); private FAddressChanged: Boolean; FDocument: TContainer; // procedure GetGEOCode(var prop: AddrInfo); public FImagesLoaded: Boolean; procedure LoadFormData(const Document: TContainer); function LoadFormImages(const Orthogonal: TStream; const North: TStream; const South: TStream; const West: TStream; const East: TStream): Integer; // procedure GetSubjectLatLon(var Lat,Lon: Double); procedure TransferParcelViewToReport(ParcelImageView: WideString); end; implementation {$R *.dfm} uses Jpeg, SysUtils, UGlobals, UMain; // *** TPictometryForm ******************************************************* /// summary: Closes the form. procedure TPictometryForm.ActionCancelExecute(Sender: TObject); begin ModalResult := mrCancel; Close; end; /// summary: Updates the cancel action. procedure TPictometryForm.ActionCancelUpdate(Sender: TObject); var Action: TAction; begin if Assigned(Sender) and (Sender is TAction) then begin Action := Sender as TAction; Action.Enabled := True; end; end; /// summary: Updates the search by address action. procedure TPictometryForm.ActionSearchByAddressUpdate(Sender: TObject); var Action: TAction; Enabled: Boolean; begin if Assigned(Sender) and (Sender is TAction) then begin Action := Sender as TAction; Enabled := FAddressChanged; Enabled := Enabled and (EditStreet.Text <> ''); Enabled := Enabled and (EditCity.Text <> ''); Enabled := Enabled and (EditState.Text <> ''); Enabled := Enabled and (EditZip.Text <> ''); Enabled := Enabled and (TMethod(Action.OnExecute).Code <> nil); Action.Enabled := Enabled; end; end; /// summary: Updates the transfer action. procedure TPictometryForm.ActionTransferUpdate(Sender: TObject); var Action: TAction; Enabled: Boolean; begin if Assigned(Sender) and (Sender is TAction) then begin Action := Sender as TAction; Enabled := False; Enabled := Enabled or RadioButtonFrontNorth.Checked; Enabled := Enabled or RadioButtonFrontEast.Checked; Enabled := Enabled or RadioButtonFrontSouth.Checked; Enabled := Enabled or RadioButtonFrontWest.Checked; Enabled := Enabled and FImagesLoaded; Enabled := Enabled and (TMethod(Action.OnExecute).Code <> nil); Action.Enabled := Enabled; end; end; /// summary: Flags the address as changed when the address has been changed. procedure TPictometryForm.EditAddressChange(Sender: TObject); begin FAddressChanged := True; end; /// summary: Loads data into the form from the document. procedure TPictometryForm.LoadFormData(const Document: TContainer); const CellID_Address = CSubjectAddressCellID; CellID_City = 47; CellID_State = 48; CellID_Zip = 49; begin if Assigned(Document) then begin FDocument := Document; EditStreet.Text := Document.GetCellTextByID(CellID_Address); EditCity.Text := Document.GetCellTextByID(CellID_City); EditState.Text := Document.GetCellTextByID(CellID_State); EditZip.Text := Document.GetCellTextByID(CellID_Zip); FAddressChanged := True; end else begin EditStreet.Text := ''; EditCity.Text := ''; EditState.Text := ''; EditZip.Text := ''; FAddressChanged := False; end end; /// summary: Loads images into the form from the specified JPEG streams. function TPictometryForm.LoadFormImages(const Orthogonal: TStream; const North: TStream; const South: TStream; const West: TStream; const East: TStream): Integer; function LoadImage(const Stream: TStream; const Image: TImage): Boolean; var TempImage: TJpegImage; begin result := false; if Assigned(Stream) and (stream.Size > 0) and Assigned(Image) then begin TempImage := TJpegImage.Create; try TempImage.LoadFromStream(Stream); Image.Picture.Graphic := TempImage; // copy FImagesLoaded := True; finally FreeAndNIl(TempImage); end; result := true; end else Image.Picture.Graphic := nil; end; begin result := 0; FAddressChanged := False; FImagesLoaded := False; if LoadImage(Orthogonal, ImageOrthogonal) then inc(result); if LoadImage(North, ImageNorth) then inc(result); if LoadImage(South, ImageSouth) then inc(result); if LoadImage(West, ImageWest) then inc(result); if LoadImage(East, ImageEast) then inc(result);; end; function GetFullAddress(sNum,sName,sCity,sState,sZip: String):String; begin result := Format('%s %s %s, %s %s',[sNum, sName, sCity, sState, sZip]); end; (* procedure TPictometryForm.GetGEOCode(var prop: AddrInfo); var geoCoder: TGeoCoder; FullAddress, accuracy: String; begin GeoCoder := TGeoCoder.Create(nil); try FullAddress := GetFullAddress(prop.StreetNum,prop.StreetName,prop.City,prop.State,prop.Zip); GeoCoder.GetGeoCodeProperty(FullAddress, accuracy, prop.lat, prop.lon); finally GeoCoder.Free; end; end; *) { procedure TPictometryForm.GetSubjectLatLon(var Lat, Lon: Double); const gtSales = 1; var SubjCol: TCompColumn; DocCompTable: TCompMgr2; //Grid Mgr for the report tables GeoCodedCell: TGeocodedGridCell; prop: AddrInfo; NeedGeoCode: Boolean; Street, CityStZip: String; begin prop.StreetName := editStreet.Text; prop.City := EditCity.Text; prop.State := EditState.Text; prop.Zip := EditZip.Text; try (* User may change the address from original to new one, always use the one on the edit box. if assigned(FDocument) then begin DocCompTable := TCompMgr2.Create(True); DocCompTable.BuildGrid(FDocument, gtSales); if (DocCompTable = nil) then exit; if Assigned(DocCompTable) and (DocCompTable.Count > 0) then SubjCol := DocCompTable.Comp[0]; //subject column if assigned(SubjCol) and not SubjCol.IsEmpty then begin Street := SubjCol.GetCellTextByID(925); CityStZip := SubjCol.GetCellTextByID(926); if POS(prop.StreetName, trim(street)) > 0 then // Get report subject geocodes if (SubjCol.GetCellByID(CGeocodedGridCellID) is TGeocodedGridCell) then begin GeocodedCell := SubjCol.GetCellByID(CGeocodedGridCellID) as TGeocodedGridCell; lat := GeocodedCell.Latitude; lon := GeocodedCell.Longitude; end; end; end; *) Lat := 0; Lon := 0; //clear before fill in NeedGeoCode := (lat = 0) or (lon = 0); if NeedGeoCode then begin //only do geocode if we have street address GetGEOCode(prop); if (length(prop.lat) <> 0) and (length(prop.lon)<>0) then begin lat := StrToFloatDef(prop.lat,0); lon := StrToFloatDef(prop.lon, 0); end; end; except ; end; end; } procedure TPictometryForm.TransferParcelViewToReport(ParcelImageView: WideString); const frmAerialPlatView = 4121; var Cell: TGraphicCell; CreateForm: Boolean; Form: TDocForm; ParcelImage:TJPEGImage; begin if not assigned(FDocument) then FDocument := Main.ActiveContainer; if not assigned(FDocument) then exit; Form := FDocument.GetFormByOccurance(frmAerialPlatView, 0, False); if Assigned(Form) then begin CreateForm := (mrNo = WhichOption12('Replace', 'Add', msgPictometryConfirmReplace)); if CreateForm then Form := FDocument.GetFormByOccurance(frmAerialPlatView, -1, True); end else Form := FDocument.GetFormByOccurance(frmAerialPlatView, -1, True); if Assigned(Form) then begin ParcelImage := TJPEGImage.Create; try {Transfer images to JPGs} LoadJPEGFromByteArray(ParcelImageView,ParcelImage); //FOR DEBUG ONLY //ParcelImage.SaveToFile('c:\temp\parcel.jpg'); if not ParcelImage.Empty then Form.SetCellJPEG(1,13, ParcelImage); finally ParcelImage.Free; end; end; end; end.
Unit TSTOProjectWorkSpace.Xml; Interface Uses Windows, Classes, HsXmlDocEx, TSTOProjectWorkSpace.Types; Type IXmlTSTOWorkSpaceProjectSrcFolder = Interface(IXmlNodeCollectionEx) ['{C65944FF-18F9-4443-B163-828724879DFF}'] Function GetSrcPath() : AnsiString; Procedure SetSrcPath(Const ASrcPath : AnsiString); Function GetSrcFileCount() : Integer; Function GetSrcFiles(Index : Integer) : AnsiString; Function Add(Const FileName : AnsiString): IXmlNodeEx; Function Insert(Const Index : Integer; Const AFileName : AnsiString): IXmlNodeEx; Property SrcPath : AnsiString Read GetSrcPath Write SetSrcPath; Property SrcFileCount : Integer Read GetSrcFileCount; Property SrcFiles[Index : Integer] : AnsiString Read GetSrcFiles; Default; End; IXmlTSTOWorkSpaceProjectSrcFolders = Interface(IXmlNodeCollectionEx) ['{FD5DE83A-A14C-4A30-BB01-32FC28F712F0}'] Function Add() : IXmlTSTOWorkSpaceProjectSrcFolder; Function Insert(Const Index : Integer): IXmlTSTOWorkSpaceProjectSrcFolder; Function GetItem(Index : Integer): IXmlTSTOWorkSpaceProjectSrcFolder; Property Items[Index : Integer] : IXmlTSTOWorkSpaceProjectSrcFolder Read GetItem; Default; End; IXmlTSTOWorkSpaceProject = Interface(IXmlNodeEx) ['{6AB7F958-921E-4C0C-B584-C2CE4D89BBE9}'] Function GetProjectName() : AnsiString; Procedure SetProjectName(Const AProjectName : AnsiString); Function GetProjectKind() : TWorkSpaceProjectKind; Procedure SetProjectKind(Const AProjectKind : TWorkSpaceProjectKind); Function GetProjectType() : TWorkSpaceProjectType; Procedure SetProjectType(Const AProjectType : TWorkSpaceProjectType); Function GetZeroCrc32() : DWord; Procedure SetZeroCrc32(Const AZeroCrc32 : DWord); Function GetPackOutput() : Boolean; Procedure SetPackOutput(Const APackOutput : Boolean); Function GetOutputPath() : AnsiString; Procedure SetOutputPath(Const AOutputPath : AnsiString); Function GetCustomScriptPath() : AnsiString; Procedure SetCustomScriptPath(Const ACustomScriptPath : AnsiString); Function GetCustomModPath() : AnsiString; Procedure SetCustomModPath(Const ACustomModPath : AnsiString); Function GetSrcFolders() : IXmlTSTOWorkSpaceProjectSrcFolders; Procedure Assign(ASource : IInterface); Property ProjectName : AnsiString Read GetProjectName Write SetProjectName; Property ProjectKind : TWorkSpaceProjectKind Read GetProjectKind Write SetProjectKind; Property ProjectType : TWorkSpaceProjectType Read GetProjectType Write SetProjectType; Property ZeroCrc32 : DWord Read GetZeroCrc32 Write SetZeroCrc32; Property PackOutput : Boolean Read GetPackOutput Write SetPackOutput; Property OutputPath : AnsiString Read GetOutputPath Write SetOutputPath; Property CustomScriptPath : AnsiString Read GetCustomScriptPath Write SetCustomScriptPath; Property CustomModPath : AnsiString Read GetCustomModPath Write SetCustomModPath; Property SrcFolders : IXmlTSTOWorkSpaceProjectSrcFolders Read GetSrcFolders; End; IXmlTSTOWorkSpaceProjectList = Interface(IXmlNodeCollectionEx) ['{7CDEBA81-1CDC-461A-AA6B-297E76B85C4E}'] Function GetProjectGroupName() : AnsiString; Procedure SetProjectGroupName(Const AProjectGroupName : AnsiString); Function GetHackFileName() : AnsiString; Procedure SetHackFileName(Const AHackFileName : AnsiString); Function GetPackOutput() : Boolean; Procedure SetPackOutput(Const APackOutput : Boolean); Function GetOutputPath() : AnsiString; Procedure SetOutputPath(Const AOutputPath : AnsiString); Function Add() : IXmlTSTOWorkSpaceProject; Function Insert(Const Index : Integer) : IXmlTSTOWorkSpaceProject; Function GetItem(Index : Integer): IXmlTSTOWorkSpaceProject; Property ProjectGroupName : AnsiString Read GetProjectGroupName Write SetProjectGroupName; Property HackFileName : AnsiString Read GetHackFileName Write SetHackFileName; Property PackOutput : Boolean Read GetPackOutput Write SetPackOutput; Property OutputPath : AnsiString Read GetOutputPath Write SetOutputPath; Property Items[Index : Integer] : IXmlTSTOWorkSpaceProject Read GetItem; Default; End; IXmlTSTOWorkSpaceProjectGroup = Interface(IXmlNodeEx) ['{891622A2-67ED-4505-AC51-45ED2E51F0A9}'] Function GetProjectGroupName() : AnsiString; Procedure SetProjectGroupName(Const AProjectGroupName : AnsiString); Function GetHackFileName() : AnsiString; Procedure SetHackFileName(Const AHackFileName : AnsiString); Function GetPackOutput() : Boolean; Procedure SetPackOutput(Const APackOutput : Boolean); Function GetOutputPath() : AnsiString; Procedure SetOutputPath(Const AOutputPath : AnsiString); Function GetWorkSpaceProject() : IXmlTSTOWorkSpaceProjectList; Procedure Assign(ASource : IInterface); Property ProjectGroupName : AnsiString Read GetProjectGroupName Write SetProjectGroupName; Property HackFileName : AnsiString Read GetHackFileName Write SetHackFileName; Property PackOutput : Boolean Read GetPackOutput Write SetPackOutput; Property OutputPath : AnsiString Read GetOutputPath Write SetOutputPath; Property WorkSpaceProject : IXmlTSTOWorkSpaceProjectList Read GetWorkSpaceProject; End; TXmlTSTOWorkSpaceProjectGroup = Class(TObject) Public Class Function CreateWSProjectGroup() : IXmlTSTOWorkSpaceProjectGroup; OverLoad; Class Function CreateWSProjectGroup(Const AXmlString : AnsiString) : IXmlTSTOWorkSpaceProjectGroup; OverLoad; End; Implementation Uses SysUtils, RTLConsts, HsInterfaceEx, TSTOProjectWorkSpaceIntf, TSTOProjectWorkSpaceImpl; Type TXmlTSTOWorkSpaceProjectSrcFolder = Class(TXmlNodeCollectionEx, ITSTOWorkSpaceProjectSrcFolder, IXmlTSTOWorkSpaceProjectSrcFolder) Private Function GetImplementor() : ITSTOWorkSpaceProjectSrcFolder; Protected Property WSSrcFolder : ITSTOWorkSpaceProjectSrcFolder Read GetImplementor Implements ITSTOWorkSpaceProjectSrcFolder; Function GetSrcPath() : AnsiString; Procedure SetSrcPath(Const ASrcPath : AnsiString); Function GetSrcFileCount() : Integer; Function GetSrcFiles(Index : Integer) : AnsiString; Function Add(Const AFileName : AnsiString) : IXmlNodeEx; Function Insert(Const Index : Integer; Const AFileName : AnsiString) : IXmlNodeEx; Public Procedure AfterConstruction(); Override; End; TXmlTSTOWorkSpaceProjectSrcFolders = Class(TXmlNodeCollectionEx, IXmlTSTOWorkSpaceProjectSrcFolders) Protected Function Add() : IXmlTSTOWorkSpaceProjectSrcFolder; Function Insert(Const Index : Integer) : IXmlTSTOWorkSpaceProjectSrcFolder; Function GetItem(Index : Integer) : IXmlTSTOWorkSpaceProjectSrcFolder; End; TXmlTSTOWorkSpaceProject = Class(TXmlNodeEx, ITSTOWorkSpaceProject, IXmlTSTOWorkSpaceProject) Private FSrcFolder : IXmlTSTOWorkSpaceProjectSrcFolders; FOnChanged : TNotifyEvent; FWSProjectImpl : Pointer; Function GetImplementor() : ITSTOWorkSpaceProject; Procedure InternalAssign(ASource, ATarget : ITSTOWorkSpaceProject); Protected Property WSProjectImpl : ITSTOWorkSpaceProject Read GetImplementor; Protected Function GetProjectName() : AnsiString; Procedure SetProjectName(Const AProjectName : AnsiString); Function GetProjectKind() : TWorkSpaceProjectKind; Procedure SetProjectKind(Const AProjectKind : TWorkSpaceProjectKind); Function GetProjectType() : TWorkSpaceProjectType; Procedure SetProjectType(Const AProjectType : TWorkSpaceProjectType); Function GetZeroCrc32() : DWord; Procedure SetZeroCrc32(Const AZeroCrc32 : DWord); Function GetPackOutput() : Boolean; Procedure SetPackOutput(Const APackOutput : Boolean); Function GetOutputPath() : AnsiString; Procedure SetOutputPath(Const AOutputPath : AnsiString); Function GetCustomScriptPath() : AnsiString; Procedure SetCustomScriptPath(Const ACustomScriptPath : AnsiString); Function GetCustomModPath() : AnsiString; Procedure SetCustomModPath(Const ACustomModPath : AnsiString); Function GetSrcFolders() : IXmlTSTOWorkSpaceProjectSrcFolders; Function GetISrcFolders() : ITSTOWorkSpaceProjectSrcFolders; Function ITSTOWorkSpaceProject.GetSrcFolders = GetISrcFolders; Function GetOnChanged() : TNotifyEvent; Procedure SetOnChanged(AOnChanged : TNotifyEvent); Procedure Assign(ASource : IInterface); ReIntroduce; Public Procedure AfterConstruction(); Override; End; TXmlTSTOWorkSpaceProjectList = Class(TXmlNodeCollectionEx, IXmlTSTOWorkSpaceProjectList) Protected Function GetProjectGroupName() : AnsiString; Procedure SetProjectGroupName(Const AProjectGroupName : AnsiString); Function GetHackFileName() : AnsiString; Procedure SetHackFileName(Const AHackFileName : AnsiString); Function GetPackOutput() : Boolean; Procedure SetPackOutput(Const APackOutput : Boolean); Function GetOutputPath() : AnsiString; Procedure SetOutputPath(Const AOutputPath : AnsiString); Function Add() : IXmlTSTOWorkSpaceProject; Function Insert(Const Index: Integer): IXmlTSTOWorkSpaceProject; Function GetItem(Index: Integer): IXmlTSTOWorkSpaceProject; End; TXmlTSTOProjectGroupImpl = Class(TXmlNodeEx, ITSTOWorkSpaceProjectGroup, IXmlTSTOWorkSpaceProjectGroup) Private FWorkSpaceProject : IXmlTSTOWorkSpaceProjectList; Function GetImplementor() : ITSTOWorkSpaceProjectGroup; Function CreateITSTOWorkSpaceProjectGroup(ASource : IXmlTSTOWorkSpaceProjectGroup) : ITSTOWorkSpaceProjectGroup; Procedure InternalAssign(ASource, ATarget : ITSTOWorkSpaceProjectGroup); OverLoad; Procedure InternalAssign(ASource : ITSTOWorkSpaceProjectGroup; ATarget : IXmlTSTOWorkSpaceProjectGroup); OverLoad; Procedure InternalAssign(ASource : IXmlTSTOWorkSpaceProjectGroup; ATarget : ITSTOWorkSpaceProjectGroup); OverLoad; Protected Property WorkSpaceProjectGroupImpl : ITSTOWorkSpaceProjectGroup Read GetImplementor Implements ITSTOWorkSpaceProjectGroup; Function GetProjectGroupName() : AnsiString; Procedure SetProjectGroupName(Const AProjectGroupName : AnsiString); Function GetHackFileName() : AnsiString; Procedure SetHackFileName(Const AHackFileName : AnsiString); Function GetPackOutput() : Boolean; Procedure SetPackOutput(Const APackOutput : Boolean); Function GetOutputPath() : AnsiString; Procedure SetOutputPath(Const AOutputPath : AnsiString); Function GetWorkSpaceProject() : IXmlTSTOWorkSpaceProjectList; Procedure Assign(ASource : IInterface); Public Procedure AfterConstruction(); Override; End; Class Function TXmlTSTOWorkSpaceProjectGroup.CreateWSProjectGroup() : IXmlTSTOWorkSpaceProjectGroup; Begin Result := NewXMLDocument.GetDocBinding('ProjectGroup', TXmlTSTOProjectGroupImpl, '') As IXmlTSTOWorkSpaceProjectGroup; End; Class Function TXmlTSTOWorkSpaceProjectGroup.CreateWSProjectGroup(Const AXmlString : AnsiString) : IXmlTSTOWorkSpaceProjectGroup; Begin Result := LoadXmlData(AXmlString).GetDocBinding('ProjectGroup', TXmlTSTOProjectGroupImpl, '') As IXmlTSTOWorkSpaceProjectGroup; End; (******************************************************************************) Procedure TXmlTSTOWorkSpaceProject.AfterConstruction(); Begin RegisterChildNode('SrcFolder', TXmlTSTOWorkSpaceProjectSrcFolder); FSrcFolder := CreateCollection(TXmlTSTOWorkSpaceProjectSrcFolders, IXmlTSTOWorkSpaceProjectSrcFolder, 'SrcFolder') As IXmlTSTOWorkSpaceProjectSrcFolders; FWSProjectImpl := Pointer(ITSTOWorkSpaceProject(Self)); Inherited; End; Function TXmlTSTOWorkSpaceProject.GetOnChanged() : TNotifyEvent; Begin Result := FOnChanged; End; Procedure TXmlTSTOWorkSpaceProject.SetOnChanged(AOnChanged : TNotifyEvent); Begin FOnChanged := AOnChanged; End; Function TXmlTSTOWorkSpaceProject.GetImplementor() : ITSTOWorkSpaceProject; Begin Result := ITSTOWorkSpaceProject(FWSProjectImpl); End; Procedure TXmlTSTOWorkSpaceProject.InternalAssign(ASource, ATarget : ITSTOWorkSpaceProject); Var lXmlTrg : IXmlTSTOWorkSpaceProject; X, Y : Integer; Begin If ASource <> ATarget Then Begin ATarget.ProjectName := ASource.ProjectName; ATarget.ProjectKind := ASource.ProjectKind; ATarget.ProjectType := ASource.ProjectType; ATarget.ZeroCrc32 := ASource.ZeroCrc32; ATarget.PackOutput := ASource.PackOutput; ATarget.OutputPath := ASource.OutputPath; ATarget.CustomScriptPath := ASource.CustomScriptPath; ATarget.CustomModPath := ASource.CustomModPath; // ATarget.HackFileName := ASource.HackFileName; If Supports(ATarget, IXmlNodeEx) And Supports(ATarget, IXmlTSTOWorkSpaceProject, lXmlTrg) Then For X := 0 To ASource.SrcFolders.Count - 1 Do With lXmlTrg.SrcFolders.Add() Do Begin SrcPath := ASource.SrcFolders[X].SrcPath; For Y := 0 To ASource.SrcFolders[X].SrcFileCount - 1 Do Add(ASource.SrcFolders[X].SrcFiles[Y].FileName); End Else For X := 0 To ASource.SrcFolders.Count - 1 Do With ATarget.SrcFolders.Add() Do Begin SrcPath := ASource.SrcFolders[X].SrcPath; For Y := 0 To ASource.SrcFolders[X].SrcFileCount - 1 Do Add(ASource.SrcFolders[X].SrcFiles[Y].FileName); End; End; End; Procedure TXmlTSTOWorkSpaceProject.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOWorkSpaceProject; lSrc : ITSTOWorkSpaceProject; X, Y : Integer; Begin If Supports(ASource, ITSTOWorkSpaceProject, lSrc) Then Begin If FWSProjectImpl <> Pointer(lSrc) Then Begin InternalAssign(lSrc, Self); FWSProjectImpl := Pointer(lSrc); End; End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Function TXmlTSTOWorkSpaceProject.GetProjectName() : AnsiString; Begin Result := ChildNodes['ProjectName'].Text; End; Procedure TXmlTSTOWorkSpaceProject.SetProjectName(Const AProjectName : AnsiString); Begin ChildNodes['ProjectName'].NodeValue := AProjectName; If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.ProjectName := AProjectName; End; Function TXmlTSTOWorkSpaceProject.GetProjectKind() : TWorkSpaceProjectKind; Begin Result := TWorkSpaceProjectKind(ChildNodes['ProjectKind'].AsInteger); End; Procedure TXmlTSTOWorkSpaceProject.SetProjectKind(Const AProjectKind : TWorkSpaceProjectKind); Begin ChildNodes['ProjectKind'].NodeValue := Ord(AProjectKind); If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.ProjectKind := AProjectKind; End; Function TXmlTSTOWorkSpaceProject.GetProjectType() : TWorkSpaceProjectType; Begin Result := TWorkSpaceProjectType(ChildNodes['ProjectType'].AsInteger); End; Procedure TXmlTSTOWorkSpaceProject.SetProjectType(Const AProjectType : TWorkSpaceProjectType); Begin ChildNodes['ProjectType'].NodeValue := Ord(AProjectType); If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.ProjectType := AProjectType; End; Function TXmlTSTOWorkSpaceProject.GetZeroCrc32() : DWord; Begin Result := ChildNodes['ZeroCrc32'].AsInteger; End; Procedure TXmlTSTOWorkSpaceProject.SetZeroCrc32(Const AZeroCrc32 : DWord); Begin ChildNodes['ZeroCrc32'].NodeValue := AZeroCrc32; If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.ZeroCrc32 := AZeroCrc32; End; Function TXmlTSTOWorkSpaceProject.GetPackOutput() : Boolean; Begin Result := ChildNodes['PackOutput'].AsBoolean; End; Procedure TXmlTSTOWorkSpaceProject.SetPackOutput(Const APackOutput : Boolean); Begin ChildNodes['PackOutput'].AsBoolean := APackOutput; If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.PackOutput := APackOutput; End; Function TXmlTSTOWorkSpaceProject.GetOutputPath() : AnsiString; Begin Result := ChildNodes['OutputPath'].AsString; End; Procedure TXmlTSTOWorkSpaceProject.SetOutputPath(Const AOutputPath : AnsiString); Begin ChildNodes['OutputPath'].AsString := AOutputPath; If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.OutputPath := AOutputPath; End; Function TXmlTSTOWorkSpaceProject.GetCustomScriptPath() : AnsiString; Begin Result := ChildNodes['CustomScriptPath'].AsString; End; Procedure TXmlTSTOWorkSpaceProject.SetCustomScriptPath(Const ACustomScriptPath : AnsiString); Begin ChildNodes['CustomScriptPath'].AsString := ACustomScriptPath; If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.CustomScriptPath := ACustomScriptPath; End; Function TXmlTSTOWorkSpaceProject.GetCustomModPath() : AnsiString; Begin Result := ChildNodes['CustomModPath'].AsString; End; Procedure TXmlTSTOWorkSpaceProject.SetCustomModPath(Const ACustomModPath : AnsiString); Begin ChildNodes['CustomModPath'].AsString := ACustomModPath; If Not IsImplementorOf(WSProjectImpl) Then WSProjectImpl.CustomModPath := ACustomModPath; End; Function TXmlTSTOWorkSpaceProject.GetSrcFolders() : IXmlTSTOWorkSpaceProjectSrcFolders; Begin Result := FSrcFolder; End; Function TXmlTSTOWorkSpaceProject.GetISrcFolders() : ITSTOWorkSpaceProjectSrcFolders; Var X : Integer; Begin Result := TTSTOWorkSpaceProjectSrcFolders.Create(); For X := 0 To FSrcFolder.Count - 1 Do Result.Add().Assign(FSrcFolder.Items[X]); // Result := FSrcFolder As ITSTOWorkSpaceProjectSrcFolders; End; Procedure TXmlTSTOWorkSpaceProjectSrcFolder.AfterConstruction(); Begin ItemTag := 'File'; ItemInterface := IXmlNodeEx; Inherited; End; Function TXmlTSTOWorkSpaceProjectSrcFolder.GetImplementor() : ITSTOWorkSpaceProjectSrcFolder; Var X : Integer; Begin Result := TTSTOWorkSpaceProjectSrcFolder.Create(); Result.SrcPath := GetSrcPath; For X := 0 To List.Count - 1 Do Result.Add(List[X].NodeValue); End; Function TXmlTSTOWorkSpaceProjectSrcFolder.GetSrcPath() : AnsiString; Begin Result := AttributeNodes['Name'].Text; End; Procedure TXmlTSTOWorkSpaceProjectSrcFolder.SetSrcPath(Const ASrcPath : AnsiString); Begin SetAttribute('Name', ASrcPath); End; Function TXmlTSTOWorkSpaceProjectSrcFolder.GetSrcFileCount() : Integer; Begin Result := List.Count; End; Function TXmlTSTOWorkSpaceProjectSrcFolder.GetSrcFiles(Index: Integer): AnsiString; Begin Result := List[Index].Text; End; Function TXmlTSTOWorkSpaceProjectSrcFolder.Add(Const AFileName : AnsiString): IXmlNodeEx; Begin Result := AddItem(-1); Result.NodeValue := AFileName; End; Function TXmlTSTOWorkSpaceProjectSrcFolder.Insert(Const Index : Integer; Const AFileName : AnsiString): IXmlNodeEx; Begin Result := AddItem(Index); Result.NodeValue := AFileName; End; Function TXmlTSTOWorkSpaceProjectSrcFolders.Add() : IXmlTSTOWorkSpaceProjectSrcFolder; Begin Result := AddItem(-1) As IXmlTSTOWorkSpaceProjectSrcFolder; End; Function TXmlTSTOWorkSpaceProjectSrcFolders.Insert(Const Index: Integer): IXmlTSTOWorkSpaceProjectSrcFolder; Begin Result := AddItem(Index) As IXmlTSTOWorkSpaceProjectSrcFolder; End; Function TXmlTSTOWorkSpaceProjectSrcFolders.GetItem(Index: Integer): IXmlTSTOWorkSpaceProjectSrcFolder; Begin Result := List[Index] As IXmlTSTOWorkSpaceProjectSrcFolder; End; Function TXmlTSTOWorkSpaceProjectList.GetProjectGroupName() : AnsiString; Begin Result := OwnerDocument.DocumentElement.ChildNodes['ProjectGroupName'].Text; End; Procedure TXmlTSTOWorkSpaceProjectList.SetProjectGroupName(Const AProjectGroupName : AnsiString); Begin OwnerDocument.DocumentElement.ChildNodes['ProjectGroupName'].Text := AProjectGroupName; End; Function TXmlTSTOWorkSpaceProjectList.GetHackFileName() : AnsiString; Begin Result := OwnerDocument.DocumentElement.ChildNodes['HackFileName'].Text; End; Procedure TXmlTSTOWorkSpaceProjectList.SetHackFileName(Const AHackFileName : AnsiString); Begin OwnerDocument.DocumentElement.ChildNodes['HackFileName'].Text := AHackFileName; End; Function TXmlTSTOWorkSpaceProjectList.GetPackOutput() : Boolean; Begin Result := StrToBoolDef(OwnerDocument.DocumentElement.ChildNodes['PackOutput'].Text, False); End; Procedure TXmlTSTOWorkSpaceProjectList.SetPackOutput(Const APackOutput : Boolean); Begin If APackOutput Then OwnerDocument.DocumentElement.ChildNodes['HackFileName'].Text := 'true' Else OwnerDocument.DocumentElement.ChildNodes['HackFileName'].Text := 'false'; End; Function TXmlTSTOWorkSpaceProjectList.GetOutputPath() : AnsiString; Begin Result := OwnerDocument.DocumentElement.ChildNodes['OutputPath'].Text; End; Procedure TXmlTSTOWorkSpaceProjectList.SetOutputPath(Const AOutputPath : AnsiString); Begin OwnerDocument.DocumentElement.ChildNodes['HackFileName'].Text := AOutputPath; End; Function TXmlTSTOWorkSpaceProjectList.Add: IXmlTSTOWorkSpaceProject; Begin Result := AddItem(-1) As IXmlTSTOWorkSpaceProject; End; Function TXmlTSTOWorkSpaceProjectList.Insert(Const Index: Integer): IXmlTSTOWorkSpaceProject; Begin Result := AddItem(Index) As IXmlTSTOWorkSpaceProject; End; Function TXmlTSTOWorkSpaceProjectList.GetItem(Index: Integer): IXmlTSTOWorkSpaceProject; Begin Result := List[Index] As IXmlTSTOWorkSpaceProject; End; Procedure TXmlTSTOProjectGroupImpl.AfterConstruction(); Begin RegisterChildNode('WorkSpaceProject', TXmlTSTOWorkSpaceProject); FWorkSpaceProject := CreateCollection(TXmlTSTOWorkSpaceProjectList, IXmlTSTOWorkSpaceProject, 'WorkSpaceProject') As IXmlTSTOWorkSpaceProjectList; Inherited; End; Function TXmlTSTOProjectGroupImpl.CreateITSTOWorkSpaceProjectGroup(ASource : IXmlTSTOWorkSpaceProjectGroup) : ITSTOWorkSpaceProjectGroup; Var X : Integer; Begin Result := TTSTOWorkSpaceProjectGroup.Create(); Result.ProjectGroupName := ASource.ProjectGroupName; For X := 0 To ASource.WorkSpaceProject.Count - 1 Do Result.Add().Assign(ASource.WorkSpaceProject[X]); End; Procedure TXmlTSTOProjectGroupImpl.InternalAssign(ASource, ATarget : ITSTOWorkSpaceProjectGroup); Var X : Integer; Begin If ASource <> ATarget Then Begin ATarget.ProjectGroupName := ASource.ProjectGroupName; ATarget.HackFileName := ASource.HackFileName; ATarget.PackOutput := ASource.PackOutput; ATarget.OutputPath := ASource.OutputPath; For X := 0 To ASource.Count - 1 Do ATarget.Add().Assign(ASource[X]); End; End; Procedure TXmlTSTOProjectGroupImpl.InternalAssign(ASource : ITSTOWorkSpaceProjectGroup; ATarget : IXmlTSTOWorkSpaceProjectGroup); Begin InternalAssign(ASource, CreateITSTOWorkSpaceProjectGroup(ATarget)); End; Procedure TXmlTSTOProjectGroupImpl.InternalAssign(ASource : IXmlTSTOWorkSpaceProjectGroup; ATarget : ITSTOWorkSpaceProjectGroup); Begin InternalAssign(CreateITSTOWorkSpaceProjectGroup(ASource), ATarget); End; Procedure TXmlTSTOProjectGroupImpl.Assign(ASource : IInterface); Var lXmlSrc : IXmlTSTOWorkSpaceProjectGroup; lSrc : ITSTOWorkSpaceProjectGroup; X : Integer; Begin If Supports(ASource, IXmlNodeEx) And Supports(ASource, IXmlTSTOWorkSpaceProjectGroup, lXmlSrc) Then Begin FWorkSpaceProject.ProjectGroupName := lXmlSrc.ProjectGroupName; FWorkSpaceProject.HackFileName := lXmlSrc.HackFileName; FWorkSpaceProject.PackOutput := lXmlSrc.PackOutput; FWorkSpaceProject.OutputPath := lXmlSrc.OutputPath; For X := 0 To lXmlSrc.ChildNodes.Count Do FWorkSpaceProject.Add().Assign(lXmlSrc.ChildNodes[X]); End Else If Supports(ASource, ITSTOWorkSpaceProjectGroup, lSrc) Then Begin FWorkSpaceProject.ProjectGroupName := lSrc.ProjectGroupName; FWorkSpaceProject.HackFileName := lSrc.HackFileName; FWorkSpaceProject.PackOutput := lSrc.PackOutput; FWorkSpaceProject.OutputPath := lSrc.OutputPath; For X := 0 To lSrc.Count - 1 Do FWorkSpaceProject.Add().Assign(lSrc[X]); End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; Function TXmlTSTOProjectGroupImpl.GetImplementor() : ITSTOWorkSpaceProjectGroup; Begin Result := TTSTOWorkSpaceProjectGroup.Create(); InternalAssign(CreateITSTOWorkSpaceProjectGroup(Self), Result); End; Function TXmlTSTOProjectGroupImpl.GetProjectGroupName() : AnsiString; Begin Result := ChildNodes['ProjectGroupName'].Text; End; Procedure TXmlTSTOProjectGroupImpl.SetProjectGroupName(Const AProjectGroupName : AnsiString); Begin ChildNodes['ProjectGroupName'].NodeValue := AProjectGroupName; End; Function TXmlTSTOProjectGroupImpl.GetHackFileName() : AnsiString; Begin Result := ChildNodes['HackFileName'].Text; End; Procedure TXmlTSTOProjectGroupImpl.SetHackFileName(Const AHackFileName : AnsiString); Begin ChildNodes['HackFileName'].NodeValue := AHackFileName; End; Function TXmlTSTOProjectGroupImpl.GetPackOutput() : Boolean; Begin Result := ChildNodes['PackOutput'].AsBoolean; End; Procedure TXmlTSTOProjectGroupImpl.SetPackOutput(Const APackOutput : Boolean); Begin ChildNodes['PackOutput'].NodeValue := APackOutput; End; Function TXmlTSTOProjectGroupImpl.GetOutputPath() : AnsiString; Begin Result := ChildNodes['OutputPath'].Text; End; Procedure TXmlTSTOProjectGroupImpl.SetOutputPath(Const AOutputPath : AnsiString); Begin ChildNodes['OutputPath'].NodeValue := AOutputPath; End; Function TXmlTSTOProjectGroupImpl.GetWorkSpaceProject() : IXmlTSTOWorkSpaceProjectList; Begin Result := FWorkSpaceProject; End; End.
unit Resources; interface const // The current version number of the application. VERSIONNUMBER : String = 'v1.0'; EDITORNAME : String = 'Battle City Editor'; MAPEDITTEXT : String = 'Map Editing Mode Enabled'; OBJEDITTEXT : String = 'Object Editing Mode Enabled'; implementation end.
unit UFileVersion; interface function GetFileVersion: string; implementation uses System.SysUtils , Winapi.Windows , Vcl.Forms; procedure GetBuildInfo(var V1, V2, V3, V4: Word); var VerInfoSize: DWORD; VerInfo: pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; begin VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy); if VerInfoSize > 0 then begin GetMem(VerInfo, VerInfoSize); try if GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo) then begin if VerQueryValue(VerInfo, '\', pointer(VerValue), VerValueSize) then with VerValue^ do begin V1 := dwFileVersionMS shr 16; V2 := dwFileVersionMS and $FFFF; V3 := dwFileVersionLS shr 16; V4 := dwFileVersionLS and $FFFF; end; end; finally FreeMem(VerInfo, VerInfoSize); end; end; end; function GetFileVersion: string; var V1, V2, V3, V4: Word; const cBuild = '%d.%d.%d.%d'; begin GetBuildInfo(V1, V2, V3, V4); Result := Format(cBuild, [V1, V2, V3, V4]); end; end.
unit System.Parsero; interface uses System.SysUtils, System.Classes, DB, System.JSON, DataSetConverter4D.Impl; type TParseroHelper = class helper for TDataSet public procedure ToJSON(out AJSON: TJSONObject); overload; procedure ToJSON(out AJSON: TJSONArray); overload; procedure FromJSON(AJSON: TJSONObject); overload; procedure FromJSON(AJSON: TJSONArray); overload; procedure EditFromJson(AJSON: TJSONObject); end; implementation { TParseroHelper } procedure TParseroHelper.FromJSON(AJSON: TJSONObject); begin TConverter.New.JSON.Source(AJSON).ToDataSet(Self); end; procedure TParseroHelper.EditFromJson(AJSON: TJSONObject); begin TConverter.New.JSON.Source(AJSON).ToRecord(Self); end; procedure TParseroHelper.FromJSON(AJSON: TJSONArray); begin TConverter.New.JSON.Source(AJSON).ToDataSet(Self); end; procedure TParseroHelper.ToJSON(out AJSON: TJSONObject); begin if Self.IsEmpty then AJSON := TJSONObject.Create else AJSON := TConverter.New.DataSet(Self).AsJSONObject; end; procedure TParseroHelper.ToJSON(out AJSON: TJSONArray); begin if Self.IsEmpty then AJSON := TJSONArray.Create else AJSON := TConverter.New.DataSet(Self).AsJSONArray; end; end.
program ProzedurFeldmin (input, output) ; const MAX = 6; type tIndex = 1..MAX; tfeld = array[tIndex] of integer; var feldaussen : tfeld; i : tIndex; iVonA, inBisA : tIndex; outPos : tIndex; outMin : integer; procedure Feldmin (inFeld : tfeld; inVon, inBis : tIndex; var outPosition : tIndex; var outMinimum : integer) ; var j : tIndex; min : integer; begin min := inVon; for j := 1 to MAX do begin if inFeld[j] < inFeld[min] then begin outPosition := j; outMinimum := inFeld[j] end end; writeln end; begin write('Feldzahlen eingeben: '); for i := 1 to MAX do begin write('Feld', i); readln(feldaussen[i]) end; iVonA := 1; inBisA := MAX; (Feldmin(feldaussen, iVonA, inBisA, outPos, outMin)); writeln('Position ist: ', outPos); writeln('Minimum ist: ', outMin); end.
unit uSenha; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JvExControls, JvXPCore, JvXPButtons, StdCtrls, ExtCtrls; type TfrmSenha = class(TForm) Panel1: TPanel; Panel2: TPanel; edSenha: TLabeledEdit; btnOk: TJvXPButton; btnCancelar: TJvXPButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); private FComparar : String; public class function PedirSenha(var Senha : String; Texto : String = ''; Comparar: String = ''): Boolean; end; var frmSenha: TfrmSenha; implementation uses uDMPrincipal; {$R *.dfm} { TfrmSenha } procedure TfrmSenha.btnOkClick(Sender: TObject); begin edSenha.SetFocus; if edSenha.Text = '' then MessageBox(handle, 'A senha não pode ficar em branco', 'Atenção!', MB_ICONERROR) else if (FComparar <> '') and (edSenha.Text <> FComparar) then MessageBox(handle, 'Senha inválida!', 'Atenção!', MB_ICONERROR) else ModalResult := mrOk; end; procedure TfrmSenha.FormCreate(Sender: TObject); begin FComparar := ''; end; procedure TfrmSenha.FormShow(Sender: TObject); begin edSenha.Text := ''; end; class function TfrmSenha.PedirSenha(var Senha: String; Texto, Comparar: String): Boolean; begin Application.CreateForm( TfrmSenha, frmSenha); try if Texto <> '' then begin frmSenha.edSenha.EditLabel.Caption := Texto; if (frmSenha.edSenha.EditLabel.Left * 2 + frmSenha.edSenha.EditLabel.Width) > frmSenha.ClientWidth then frmSenha.ClientWidth := frmSenha.edSenha.EditLabel.Left * 2 + frmSenha.edSenha.EditLabel.Width; end; frmSenha.FComparar := Comparar; Result := frmSenha.ShowModal = mrOk; if Result then Senha := frmSenha.edSenha.text; finally FreeAndNil(frmSenha); end; end; end.
{ Copyright (C) 1998-2000, written by Shkolnik Mike FIDOnet: 2:463/106.14 E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com http://www.geocities.com/mshkolnik tel: 380-/44/-552-10-29 This component is a extended TLabel component and allows the next additional features: - you can define an angle for rotating text (in degrees) - see Angle property - you can define a text style - Style property: slNormal - usual normal 2D text slRaised - raised 3D text slLowered - lowered 3D text For slRaised and slLowered style you can define a shadow color in ShadowColor property } unit AngleLbl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TStyleLabel = (slNormal, slLowered, slRaised); TAngleLabel = class(TCustomLabel) private { Private declarations } FAngle: Integer; FStyle: TStyleLabel; FShadowColor: TColor; procedure SetAngle(Value: Integer); procedure SetStyle(Value: TStyleLabel); procedure SetShadowColor(Value: TColor); procedure DoDrawText(var Rect: TRect; Flags: Word); protected { Protected declarations } procedure Paint; override; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property Angle: Integer read FAngle write SetAngle; property Style: TStyleLabel read FStyle write SetStyle; property ShadowColor: TColor read FShadowColor write SetShadowColor; property Align; property Alignment; property Caption; property Color; property DragCursor; property DragMode; property Enabled; property FocusControl; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowAccelChar; property ShowHint; property Transparent; property Layout; property Visible; property WordWrap; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation {$R *.RES} procedure Register; begin RegisterComponents('SMComponents', [TAngleLabel]); end; constructor TAngleLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); AutoSize := False; FAngle := 0; FStyle := slRaised; FShadowColor := clHighlightText; Font.Name := 'Arial'; end; procedure TAngleLabel.SetAngle(Value: Integer); begin if (Value <> FAngle) then begin FAngle := Value; if (FAngle < 0) or (FAngle > 359) then FAngle := 0; Invalidate; end; end; procedure TAngleLabel.SetStyle(Value: TStyleLabel); begin if (Value <> FStyle) then begin FStyle := Value; Invalidate; end; end; procedure TAngleLabel.SetShadowColor(Value: TColor); begin if (Value <> FShadowColor) then begin FShadowColor := Value; Invalidate; end; end; procedure DrawWrapText(Canvas: TCanvas; Text: string; ARect: TRect; Flags: Word); begin Canvas.TextOut(ARect.Left, ARect.Top, Text) // DrawText(Canvas.Handle, PChar(Text), Length(Text), ARect, Flags) end; procedure TAngleLabel.DoDrawText(var Rect: TRect; Flags: Word); var Text: string; LogRec: TLogFont; OldFontHandle, NewFontHandle: hFont; fDegToRad, fCosAngle, fSinAngle: Double; H, W, X, Y: Integer; BRect: TRect; begin Text := GetLabelText; if (Flags and DT_CALCRECT <> 0) and ((Text = '') or ShowAccelChar and (Text[1] = '&') and (Text[2] = #0)) then Text := Text + ' '; if not ShowAccelChar then Flags := Flags or DT_NOPREFIX; fDegToRad := PI / 180; fCosAngle := cos(FAngle * fDegToRad); fSinAngle := sin(FAngle * fDegToRad); with Canvas do begin Font := Self.Font; Brush.Style := bsClear; {-create a rotated font based on the font object Font} GetObject(Font.Handle, SizeOf(LogRec), Addr(LogRec)); LogRec.lfEscapement := FAngle*10; LogRec.lfOrientation := FAngle*10; LogRec.lfOutPrecision := OUT_DEFAULT_PRECIS; LogRec.lfClipPrecision := OUT_DEFAULT_PRECIS; NewFontHandle := CreateFontIndirect(LogRec); W := TextWidth(Text); H := TextHeight(Text); case Alignment of taLeftJustify: begin X := 0; case FAngle of 91..180: X := X - Trunc(W*fCosAngle); 181..270: X := X - Trunc(W*fCosAngle) - Trunc(H*fSinAngle); 271..359: X := X - Trunc(H*fSinAngle); end; if X > Width then X := Width; end; taRightJustify: begin X := Width; case FAngle of 0..90: X := X - Trunc(W*fCosAngle) - Trunc(H*fSinAngle); 91..180: X := X - Trunc(H*fSinAngle); 271..359: X := X - Trunc(W*fCosAngle); end; if X < 0 then X := 0; end; else// taCenterJustify X := (Width div 2) - Trunc(W/2*fCosAngle) - Trunc(H/2*fSinAngle); end; case Layout of tlTop: begin Y := 0; case FAngle of 0..90: Y := Y + Trunc(W*fSinAngle); 91..180: Y := Y + Trunc(W*fSinAngle) - Trunc(H*fCosAngle); 181..270: Y := Y - Trunc(H*fCosAngle); end; if Y > Height then Y := Height; end; tlBottom: begin Y := Height; case FAngle of 0..90: Y := Y - Trunc(H*fCosAngle); 181..270: Y := Y + Trunc(W*fSinAngle); 271..359: Y := Y + Trunc(W*fSinAngle) - Trunc(H*fCosAngle); end; if Y < 0 then Y := 0; end; else// tlCenter Y := (Height div 2) + Trunc(W/2*fSinAngle) - Trunc(H/2*fCosAngle); end; if not Enabled then begin Font.Color := clBtnHighlight; OldFontHandle := SelectObject(Handle, NewFontHandle); with BRect do begin Left := X+1; Top := Y+1; Right := Rect.Right; Bottom := Rect.Bottom; end; // BRect := Rect; DrawWrapText(Canvas, Text, BRect, Flags); Font.Color := clBtnShadow; end else if (FStyle <> slNormal) then begin Font.Color := FShadowColor; OldFontHandle := SelectObject(Handle, NewFontHandle); if (FStyle = slRaised) then with BRect do begin Left := X-1; Top := Y-1; Right := Rect.Right; Bottom := Rect.Bottom; end else with BRect do begin Left := X+1; Top := Y+1; Right := Rect.Right; Bottom := Rect.Bottom; end; // BRect := Rect; DrawWrapText(Canvas, Text, BRect, Flags); Font.Color := Self.Font.Color; end; OldFontHandle := SelectObject(Handle, NewFontHandle); with BRect do begin Left := X; Top := Y; Right := Rect.Right; Bottom := Rect.Bottom; end; // BRect := Rect; DrawWrapText(Canvas, Text, BRect, Flags); NewFontHandle := SelectObject(Canvas.Handle, OldFontHandle); DeleteObject(NewFontHandle); end; end; procedure TAngleLabel.Paint; const Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER); WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK); var Rect, CalcRect: TRect; DrawStyle: Integer; begin with Canvas do begin if not Transparent then begin Brush.Color := Self.Color; Brush.Style := bsSolid; FillRect(ClientRect); end; Brush.Style := bsClear; Rect := ClientRect; DrawStyle := DT_EXPANDTABS or WordWraps[WordWrap] or Alignments[Alignment]; { Calculate vertical layout } if (Layout <> tlTop) then begin CalcRect := Rect; DoDrawText(CalcRect, DrawStyle or DT_CALCRECT); if (Layout = tlBottom) then OffsetRect(Rect, 0, Height - CalcRect.Bottom) else OffsetRect(Rect, 0, (Height - CalcRect.Bottom) div 2); end; DoDrawText(Rect, DrawStyle); end; end; end.
unit Tracer; interface {*************************************************** Tracer Class traces connections without a Netlist This class finds groups of interconnected strips. It does flag a simple error where a pin lies on a break - but otherwise it ignores pins and nets. **************************************************} uses Connective; type TcnScanType = ( stNetScan, stSimpleScan ); type TveTracer = class( TConnectivity ) protected FScanType : TcnScanType; procedure PropagateConnections; procedure CheckSimple; public property ScanType : TcnScanType read FScanType; procedure Check; end; implementation procedure TveTracer.PropagateConnections; // handle nets at both ends of a link // Return True = a strip has had a net change made on this pass. // Keep calling for all links until returns False because no futher nets // resolved. function PropagateLinkConnection( Link : TcnLink ) : boolean; var StartStripSet, EndStripSet : TcnStripSet; begin // assume nothing will change result := False; // if one end of link has no strip, get out - pointers are nil! if (Link.StartStrip = nil) or (Link.EndStrip = nil) then begin exit; end; // get local references to stripsets StartStripSet := Link.StartStrip.StripSet; EndStripSet := Link.EndStrip.StripSet; // if both ends of link are in same stripset, don't make a fuss, just // let it pass through - stripsets were already combined, or link // lies along a strip or between overlapping strips etc. if (StartStripSet = EndStripSet) then begin exit; end; // combine the stripsets into one AddToStripSet( StartStripSet , EndStripSet ); result := True; end; function PropagateWireConnection( WireSet : TcnWireSet ) : boolean; var i : integer; StripSet : TcnStripSet; MasterStripSet : TcnStripSet; begin // default is no new nets propagated result := False; // wires that do not sit on a strip were not added to WireSets, therefore // all Wire.Strip.StripSet is always valid. MasterStripSet := WireSet.Wires[0].Strip.StripSet; // combine all stripsets which connect via wires (thru this wireset) for i := 1 to WireSet.WireCount -1 do begin StripSet := WireSet.Wires[i].Strip.StripSet; if StripSet <> MasterStripset then begin AddToStripSet( MasterStripSet, StripSet ); // signal that at least one connection made result := True; end; end; end; var Changed : boolean; i : integer; begin repeat Changed := False; for i := 0 to FLinks.Count -1 do begin Changed := Changed or PropagateLinkConnection( TcnLink(FLinks[i]) ); end; for i := 0 to FWireSets.Count -1 do begin Changed := Changed or PropagateWireConnection( TcnWireSet(FWireSets[i]) ); end; until not Changed; end; procedure TveTracer.CheckSimple; begin Clear; {$IFDEF DEBUGFORM} if Assigned( FOnDebugStart ) then begin FOnDebugStart; end; {$ENDIF} // read all pin data into Cells[][] BuildPins; // mark as error where a break coincides with pin CheckBreaksOnPins; // copy over striprsets from Board StripGroups. Mark strips that include // a break as Broken. BuildStrips; // rescan Broken stripsets into new stripsets RescanBrokenStripSets; // build a SegmentSet for each TbrBoard.SegmentGroup BuildSegmentSets; // connect strips together using segments CombineStripsetsBySegments; // build an array of link objects, and record on each the start and end // strips (or stripsets) BuildLinks; // group connected wires to form wiresets BuildWireSets; // follow connections to leave stripsets for each connected strips PropagateConnections; end; procedure TveTracer.Check; begin Netlist := FProject.Netlist; // if we don't have a netlist, just follow traces, links and wires if Netlist.NodeCount <= 0 then begin FScanType := stSimpleScan; CheckSimple; end // we do have a netlist, so full check else begin FScanType := stNetScan; inherited Check; end; end; end.
unit TestCalculadora; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Vcl.Forms, Vcl.Graphics, Vcl.StdCtrls, Winapi.Windows, System.Variants, Vcl.Dialogs, Vcl.Controls, Calculadora, Winapi.Messages, System.Classes; type // Test methods for class TForm1 TestTForm1 = class(TTestCase) strict private FForm1: TForm1; public Valor1, Valor2: Double; procedure SetUp; override; procedure TearDown; override; published procedure TestbtnSomarClick; procedure TestbtnSubtrairClick; procedure TestbtnMultiplicarClick; procedure TestbtnDividirClick; procedure TestSomar; procedure TestSubtrair; procedure TestMultiplicar; procedure TestDividir; procedure TestValidarValoresZerados; procedure TestValidarResultadoNaGrid; procedure TestValidarQtdeResultadoNoClientDataSet; end; implementation uses System.SysUtils; procedure TestTForm1.SetUp; begin FForm1 := TForm1.Create(nil); Valor1 := 20; Valor2 := 5; end; procedure TestTForm1.TearDown; begin FForm1.Free; FForm1 := nil; end; procedure TestTForm1.TestbtnSomarClick; var Sender: TObject; begin // TODO: Setup method call parameters FForm1.btnSomarClick(Sender); // TODO: Validate method results CheckEquals((Valor1 + Valor2), StrToFloat(FForm1.edtResultado.Text)); end; procedure TestTForm1.TestbtnSubtrairClick; var Sender: TObject; begin // TODO: Setup method call parameters FForm1.btnSubtrairClick(Sender); // TODO: Validate method results CheckEquals((Valor1 - Valor2), StrToFloat(FForm1.edtResultado.Text)); end; procedure TestTForm1.TestbtnMultiplicarClick; var Sender: TObject; begin // TODO: Setup method call parameters FForm1.btnMultiplicarClick(Sender); // TODO: Validate method results CheckEquals((Valor1 * Valor2), StrToFloat(FForm1.edtResultado.Text)); end; procedure TestTForm1.TestbtnDividirClick; var Sender: TObject; begin // TODO: Setup method call parameters FForm1.btnDividirClick(Sender); // TODO: Validate method results CheckEquals((Valor1 / Valor2), StrToFloat(FForm1.edtResultado.Text)); end; procedure TestTForm1.TestSomar; var ReturnValue: Double; begin // TODO: Setup method call parameters ReturnValue := FForm1.Somar(Valor1, Valor2); // TODO: Validate method results CheckEquals((Valor1 + Valor2), ReturnValue); end; procedure TestTForm1.TestSubtrair; var ReturnValue: Double; begin // TODO: Setup method call parameters ReturnValue := FForm1.Subtrair(Valor1, Valor2); // TODO: Validate method results CheckEquals((Valor1 - Valor2), ReturnValue); end; procedure TestTForm1.TestValidarResultadoNaGrid; var Sender: TObject; begin FForm1.btnSomarClick(Sender); if FForm1.dbGridResultados.Columns[2].FieldName = 'Resultado' then CheckEquals((Valor1 + Valor2), FForm1.dbGridResultados.Columns[2].Field.AsFloat); end; procedure TestTForm1.TestValidarQtdeResultadoNoClientDataSet; var Sender: TObject; begin FForm1.btnSomarClick(Sender); FForm1.btnSubtrairClick(Sender); FForm1.btnMultiplicarClick(Sender); FForm1.btnDividirClick(Sender); CheckEquals(4, FForm1.cdsValores.RecordCount, 'Era esperado retornar 4 registros no ClientDataSet'); end; procedure TestTForm1.TestValidarValoresZerados; begin Valor1 := 0; Valor2 := 0; Check(FForm1.VerificaCampos(Valor1, Valor2), 'os parametros valor 1 e valor 2 devem estar zerados.'); end; procedure TestTForm1.TestMultiplicar; var ReturnValue: Double; begin // TODO: Setup method call parameters ReturnValue := FForm1.Multiplicar(Valor1, Valor2); // TODO: Validate method results CheckEquals((Valor1 * Valor2), ReturnValue); end; procedure TestTForm1.TestDividir; var ReturnValue: Double; begin // TODO: Setup method call parameters ReturnValue := FForm1.Dividir(Valor1, Valor2); // TODO: Validate method results CheckEquals((Valor1 / Valor2), ReturnValue); end; initialization // Register any test cases with the test runner RegisterTest(TestTForm1.Suite); end.
unit Frm_Selector; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, Data.DB, uniBasicGrid, uniDBGrid, uniToolBar, uniGUIBaseClasses, Funciones, Vcl.Forms; type TProcedimientoSeleccion=reference to procedure(Resultado:Integer;Dataset:TDataset); TFrmSelector = class(TUniForm) UniToolBar1: TUniToolBar; UBAceptar: TUniToolButton; UBCancelar: TUniToolButton; UniToolButton2: TUniToolButton; UBPrimero: TUniToolButton; UBAnterior: TUniToolButton; UBSiguiente: TUniToolButton; UBUltimo: TUniToolButton; UniDBGrid1: TUniDBGrid; DSSelector: TDataSource; UBEliminar: TUniToolButton; procedure UniFormCreate(Sender: TObject); procedure UBCancelarClick(Sender: TObject); procedure UBAceptarClick(Sender: TObject); procedure UniFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UniFormClose(Sender: TObject; var Action: TCloseAction); procedure UBPrimeroClick(Sender: TObject); procedure UBAnteriorClick(Sender: TObject); procedure UBSiguienteClick(Sender: TObject); procedure UBUltimoClick(Sender: TObject); procedure UniDBGrid1DblClick(Sender: TObject); procedure UniFormShow(Sender: TObject); procedure UBEliminarClick(Sender: TObject); procedure UniDBGrid1DrawColumnCell(Sender: TObject; ACol, ARow: Integer; Column: TUniDBGridColumn; Attribs: TUniCellAttribs); private { Private declarations } FResultado:Integer; FCampoADevolver:String; // FAncho:integer; FProcedimientoSeleccion:TProcedimientoSeleccion; public { Public declarations } constructor Crear(Caption:String;Dataset:TDataSet;Campos,Titulos:Array of String;ProcedimientoSeleccion:TProcedimientoSeleccion=nil;Ancho:integer=0;AnchosColumna: string='';PonerBotonDeBorrar:boolean=False;pintarCeldasDeRojo:boolean=False;MensajeMascara:String=''); end; implementation uses uniGUIApplication, MainModule, Math; {$R *.dfm} constructor TFrmSelector.Crear(Caption: String; Dataset: TDataSet; Campos, Titulos: array of String;ProcedimientoSeleccion:TProcedimientoSeleccion=nil;Ancho:integer=0;AnchosColumna: string='';PonerBotonDeBorrar:boolean=False;pintarCeldasDeRojo:boolean=False;MensajeMascara:String=''); var i:Integer; Anchos:TStringList; begin inherited create(uniGUIApplication.UniApplication); UBEliminar.Visible:=PonerBotonDeBorrar; Self.Caption:=Caption; DSSelector.DataSet:=Dataset; UniDBGrid1.Columns.Clear; IF ancho<>0 then Self.Width:=ancho; Anchos:=TStringList.Create; try if AnchosColumna<>'' then begin Anchos.Delimiter:=';'; Anchos.DelimitedText:=AnchosColumna; end; for i:=0 to Length(Campos)-1 do begin with UniDBGrid1.Columns.Add do begin FieldName:=Campos[i]; Title.Caption:=Titulos[i]; if anchos.Count>0 then Width:=StrToInt(Anchos[i]); end; end; finally FreeAndNil(Anchos); end; FProcedimientoSeleccion:=ProcedimientoSeleccion; if pintarCeldasDeRojo then UniDBGrid1.OnDrawColumnCell:=UniDBGrid1DrawColumnCell; UBAceptar.ScreenMask.Enabled:=MensajeMascara<>''; UBAceptar.ScreenMask.Message:=MensajeMascara; end; procedure TFrmSelector.UBAceptarClick(Sender: TObject); begin FResultado:=mrOk; Close; end; procedure TFrmSelector.UBAnteriorClick(Sender: TObject); begin DSSelector.DataSet.Prior; end; procedure TFrmSelector.UBCancelarClick(Sender: TObject); begin Close; end; procedure TFrmSelector.UBEliminarClick(Sender: TObject); begin DSSelector.DataSet.Delete end; procedure TFrmSelector.UBPrimeroClick(Sender: TObject); begin DSSelector.DataSet.First; end; procedure TFrmSelector.UBSiguienteClick(Sender: TObject); begin DSSelector.DataSet.Next; end; procedure TFrmSelector.UBUltimoClick(Sender: TObject); begin DSSelector.DataSet.Last; end; procedure TFrmSelector.UniDBGrid1DblClick(Sender: TObject); begin UBAceptarClick(UBAceptar); end; procedure TFrmSelector.UniDBGrid1DrawColumnCell(Sender: TObject; ACol, ARow: Integer; Column: TUniDBGridColumn; Attribs: TUniCellAttribs); begin Attribs.Font.Color:=clred; end; procedure TFrmSelector.UniFormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(FProcedimientoSeleccion) then FProcedimientoSeleccion(FResultado,DSSelector.DataSet); Action:=caFree; end; procedure TFrmSelector.UniFormCreate(Sender: TObject); var i:Integer; begin UniDBGrid1.ForceFit:=True; ClientEvents.ExtEvents.Values['window.maximize']:='function window.maximize(sender, eOpts){'+#13#10+ ' sender.setHeight(sender.getHeight()-'+IntToStr(UniMainModule.DimensionesMax.Top)+');'+#13#10+ ' sender.setWidth(sender.getWidth()-'+IntToStr(UniMainModule.DimensionesMax.Left)+');'+#13#10+ ' sender.setPosition('+IntToStr(UniMainModule.DimensionesMax.Left)+','+IntToStr(UniMainModule.DimensionesMax.Top)+');'+#13#10+ '}'; for i:=0 to UniDBGrid1.Columns.Count-1 do UniDBGrid1.Columns.Items[i].Menu.MenuEnabled:=False; MonitorizarTeclas(Self,[VK_ESCAPE,VK_RETURN],False); FResultado:=mrCancel; end; procedure TFrmSelector.UniFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN:UBAceptarClick(UBAceptar); VK_ESCAPE:UBCancelarClick(UBCancelar); end; end; procedure TFrmSelector.UniFormShow(Sender: TObject); begin Height:=Min(UniMainModule.DimensionesMax.Height+UniMainModule.DimensionesMax.Top, Height+60+28*DSSelector.DataSet.RecordCount-+UniDBGrid1.Height); end; end.
unit qCDKmodbusFuncs; interface uses qCDKclasses,qCDKmodbusTypes,qCDKmodbusClasses,uProgresses; // Modbus-ошибка из идентификатора в строку function mbGetErrorStr(me:integer):AnsiString; // Modbus-исключение в строку function mbExceptionToString(const me:byte):AnsiString; // Modbus-функция в строку function mbFunctionToString(const mf:byte):AnsiString; ////////// функции для работы по Modbus-протоколу // cb:TTransactionWaitCallBack - процедура обратного вызова при асинхронной операции и её завершении // pcc:TProgressCallBack - функция обратного вызова для информирования о прогрессе операции // аналогично mbReadBuffer_Sync function mbReadBuffer(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; // чтение синхронное в буфер Dst размером iDstSize function mbReadBuffer_Sync(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; // чтение асинхронное в буфер Dst размером iDstSize function mbReadBuffer_Async(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0; cb:TTransactionWaitCallBack=nil):integer; // аналогично mbWriteBuffer_Sync function mbWriteBuffer(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; // запись синхронная с чтением в буфер pDst размером iDstSize function mbWriteBuffer_Sync(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; // запись асинхронная с чтением в буфер pDst размером iDstSize function mbWriteBuffer_Async(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0; cb:TTransactionWaitCallBack=nil):integer; // чтение непрерывного блока данных, не обращая внимания на ограничение длины пакета данных в 255 байт function mbReadDataBlock(cd:TModbusDevice; wOrgAddr:word; pDst:pointer; iBytes:integer; {mf:TModbusFunction=mfReadHoldingRegisters;} pcc:TProgressCallBack=nil; PID:pointer=nil):integer; // запись непрерывного блока данных, не обращая внимания на ограничение длины пакета данных в 255 байт function mbWriteDataBlock(cd:TModbusDevice; wOrgAddr:word; pSrc:pointer; iBytes:integer; {mf:TModbusFunction=mfWriteMultipleRegisters;} pcc:TProgressCallBack=nil; PID:pointer=nil):integer; // чтение непрерывного блока данных из файла, не обращая внимания на ограничение длины пакета данных в 255 байт function mbReadFileDataBlock(cd:TModbusDevice; wFileNum,wOrgAddr:word; pDst:pointer; iBytes:integer; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; // запись непрерывного блока данных в файл, не обращая внимания на ограничение длины пакета данных в 255 байт function mbWriteFileDataBlock(cd:TModbusDevice; wFileNum,wOrgAddr:word; pSrc:pointer; iBytes:integer; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; ////////// функции для работы по Modbus-протоколу для устройств БЭМП // чтение конфигурационного файла устройства БЭМП function mbReadIniFile(cd:TModbusDevice; out sFileName,sFileText:AnsiString; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; // чтение LD-файла устройства БЭМП function mbReadLDFile(cd:TModbusDevice; out sFileName,sFileText:AnsiString; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; // запись LD-файла устройства БЭМП function mbWriteLDFile(cd:TModbusDevice; sFileName,sFileText:AnsiString; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; // чтение непрерывного блока данных осциллограммы function mbReadScopeDataBlock(cd:TModbusDevice; wOrgAddr:word; pDst:pointer; iRecs,iRecSize:integer; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; implementation uses Windows,Classes,SysUtils,uUtilsFunctions; {$BOOLEVAL OFF} {$RANGECHECKS OFF} {$OVERFLOWCHECKS OFF} const iMaxBufferSize=255; // размер буфера ////////// функции для работы по Modbus-протоколу // функция обратного вызова по умолчанию для асинхронных вызовов функций, кто-то забыл указать функцию обратного вызова или результат его не интересует procedure DefaultWaitCallback(id:integer; td:TTransactionData); stdcall; begin try td.Free; except end; end; // необходимо уничтожить созданные "данные транзакции" // Modbus-ошибка из идентификатора в строку function mbGetErrorStr(me:integer):AnsiString; begin if not IntToIdent(me,Result,ModbusErrorsInfos)then Result:=GetErrorStr(me); end; // Modbus-исключение в строку function mbExceptionToString(const me:byte):AnsiString; var s:AnsiString; begin if not IntToIdent(me,s,ModbusExceptionsInfos)then s:='незарегистрированное исключение'; Result:='0x'+IntToHex(me,2)+' - '+s; end; // Modbus-функция в строку function mbFunctionToString(const mf:byte):AnsiString; var s:AnsiString; begin if not IntToIdent(mf and$7F,s,ModbusFuncsInfos)then s:='неизвестная функция'; Result:='0x'+IntToHex(mf,2)+' - '+s; if(mf and$80)<>0then Result:=Result+' (исключение)'; end; // синхронное чтение function mbReadBuffer(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; begin Result:=comDoWait(cd,arrPacket,pDst,iDstSize); end; // синхронное чтение function mbReadBuffer_Sync(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; begin Result:=comDoWait(cd,arrPacket,pDst,iDstSize); end; // асинхронное чтение function mbReadBuffer_Async(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0; cb:TTransactionWaitCallBack=nil):integer; begin if@cb=nil then cb:=@DefaultWaitCallBack; Result:=comDoWait(cd,arrPacket,pDst,iDstSize,cb); end; // синхронная запись function mbWriteBuffer(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; begin Result:=comDoWait(cd,arrPacket,pDst,iDstSize); end; // синхронная запись function mbWriteBuffer_Sync(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0):integer; begin Result:=comDoWait(cd,arrPacket,pDst,iDstSize); end; // асинхронная запись function mbWriteBuffer_Async(cd:TModbusDevice; arrPacket:array of Int64; pDst:pointer=nil; iDstSize:integer=0; cb:TTransactionWaitCallBack=nil):integer; begin if@cb=nil then cb:=@DefaultWaitCallBack; Result:=comDoWait(cd,arrPacket,pDst,iDstSize,cb); end; // чтение непрерывного блока данных function mbReadDataBlock(cd:TModbusDevice; wOrgAddr:word; pDst:pointer; iBytes:integer; {mf:TModbusFunction=mfReadHoldingRegisters;} pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var iBytesLeft,iOffs,iBytesToRead:integer; pBuf:PAnsiChar; tc:longword; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,iBytes,lwTimeEllapsed,'',ps); end; begin Result:=ceUnknownError; if iBytes<=0then begin Result:=ceNoTransactionData; exit; end; try try iBytesLeft:=iBytes; tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; while iBytesLeft>0do begin iOffs:=iBytes-iBytesLeft; pBuf:=pAnsiChar(pDst)+iOffs; iBytesToRead:=(iMaxBufferSize-7)and$FE; if iBytesLeft<iBytesToRead then iBytesToRead:=iBytesLeft; Result:=mbReadBuffer(cd,[cd.Address,mfReadHoldingRegisters,wOrgAddr+iOffs shr 1,(iBytesToRead+1)shr 1],pBuf,iBytesToRead); dec(iBytesLeft,iBytesToRead); if Result<>meSuccess then break; if not DoProgress(iBytes-iBytesLeft,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; finally DoProgress(0,0,psClosed); end; except Result:=ceSysException; end; end; // запись непрерывного блока данных function mbWriteDataBlock(cd:TModbusDevice; wOrgAddr:word; pSrc:pointer; iBytes:integer; {mf:TModbusFunction=mfWriteMultipleRegisters;} pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var iBytesLeft,iOffs,iBytesToWrite,n:integer; pBuf:PAnsiChar; tc:longword; arr:array of Int64; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,iBytes,lwTimeEllapsed,'',ps); end; begin Result:=ceUnknownError; if iBytes<=0then begin Result:=ceNoTransactionData; exit; end; try try iBytesLeft:=iBytes; tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; while iBytesLeft>0do begin iOffs:=iBytes-iBytesLeft; pBuf:=pAnsiChar(pSrc)+iOffs; iBytesToWrite:=(iMaxBufferSize-11)and$FE; if iBytesLeft<iBytesToWrite then iBytesToWrite:=iBytesLeft; SetLength(arr,(iBytesToWrite+1)shr 1+5); arr[0]:=cd.Address; arr[1]:=mfWriteMultipleRegisters; arr[2]:=wOrgAddr+iOffs shr 1; arr[3]:=(iBytesToWrite+1)shr 1; arr[4]:=iBytesToWrite; for n:=0to(iBytesToWrite+1)shr 1-1do arr[5+n]:=psmallint(longword(pBuf)+longword(n)shl 1)^; Result:=mbWriteBuffer(cd,arr,nil,0); dec(iBytesLeft,iBytesToWrite); if Result<>meSuccess then break; if not DoProgress(iBytes-iBytesLeft,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; finally DoProgress(0,0,psClosed); end; except Result:=ceSysException; end; end; // чтение непрерывного блока данных из файла function mbReadFileDataBlock(cd:TModbusDevice; wFileNum,wOrgAddr:word; pDst:pointer; iBytes:integer; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var iBytesLeft,iOffs,iBytesToRead:integer; pBuf:PAnsiChar; tc:longword; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,iBytes,lwTimeEllapsed,'',ps); end; begin Result:=ceUnknownError; if iBytes<=0then begin Result:=ceNoTransactionData; exit; end; try try iBytesLeft:=iBytes; tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; while iBytesLeft>0do begin iOffs:=iBytes-iBytesLeft; pBuf:=pAnsiChar(pDst)+iOffs; iBytesToRead:=(iMaxBufferSize-7{9})and$FE; if iBytesLeft<iBytesToRead then iBytesToRead:=iBytesLeft; Result:=mbReadBuffer(cd,[cd.Address,mfReadFileRecord,7,6,wFileNum,wOrgAddr+iOffs shr 1,(iBytesToRead+1)shr 1],pBuf,iBytesToRead); dec(iBytesLeft,iBytesToRead); if Result<>meSuccess then break; if not DoProgress(iBytes-iBytesLeft,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; finally DoProgress(0,0,psClosed); end; except Result:=ceSysException; end; end; // запись непрерывного блока данных в файл function mbWriteFileDataBlock(cd:TModbusDevice; wFileNum,wOrgAddr:word; pSrc:pointer; iBytes:integer; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var iBytesLeft,iOffs,iBytesToWrite,n:integer; pBuf:PAnsiChar; tc:longword; arr:array of Int64; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,iBytes,lwTimeEllapsed,'',ps); end; begin Result:=ceUnknownError; if iBytes<=0then begin Result:=ceNoTransactionData; exit; end; try try iBytesLeft:=iBytes; tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; while iBytesLeft>0do begin iOffs:=iBytes-iBytesLeft; pBuf:=pAnsiChar(pSrc)+iOffs; iBytesToWrite:=(iMaxBufferSize-14)and$FE; if iBytesLeft<iBytesToWrite then iBytesToWrite:=iBytesLeft; SetLength(arr,(iBytesToWrite+1)shr 1+7); arr[0]:=cd.Address; arr[1]:=mfWriteFileRecord; arr[2]:=7+((iBytesToWrite+1)shr 1)shl 1; arr[3]:=6; arr[4]:=wFileNum; arr[5]:=wOrgAddr+iOffs shr 1; arr[6]:=(iBytesToWrite+1)shr 1; for n:=0to(iBytesToWrite+1)shr 1-1do arr[7+n]:=psmallint(longword(pBuf)+longword(n)shl 1)^; Result:=mbWriteBuffer(cd,arr,nil,0); dec(iBytesLeft,iBytesToWrite); if Result<>meSuccess then break; if not DoProgress(iBytes-iBytesLeft,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; finally DoProgress(0,0,psClosed); end; except Result:=ceSysException; end; end; ////////// функции для работы по Modbus-протоколу для устройств БЭМП type TIniHeader=packed record _wTotalSize,_wHeaderSize,_wHeaderVersion:word; _sFileName:array[0..35]of char; _wCheckSumType,_wCheckSum:word; _sCompressor:array[0..15]of char; _lwFileSize:longword; end; function mbReadIniFile(cd:TModbusDevice; out sFileName,sFileText:AnsiString; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var ih:TIniHeader; iRecsLeft,iRecsNum,iAddr,iRecsToRead,i:integer; tc:longword; wRetries:word; pBuf:PAnsiChar; ms:TMemoryStream; const sCompressedFileHeader='zlibcomr'; nRetries=3; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,(ih._wTotalSize+1)shl 1,lwTimeEllapsed,'',ps); end; begin pBuf:=nil; ms:=nil; try try tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; Result:=mbReadFileDataBlock(cd,0,0,@ih,SizeOf(ih),nil,nil); if Result<>meSuccess then exit; if not DoProgress(SizeOf(ih),GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; iRecsLeft:=ih._wTotalSize-ih._wHeaderSize-1; if iRecsLeft<=0then begin Result:=ceDataSize; exit; end; iRecsNum:=(iMaxBufferSize-7{9})shr 1; iAddr:=ih._wHeaderSize+2; sFileName:=ih._sFileName; pBuf:=GetMemory(iRecsNum shl 1); ms:=TMemoryStream.Create; i:=Length(sCompressedFileHeader); ms.Write(i,SizeOf(i)); ms.Write(sCompressedFileHeader[1],i); i:=$01; ms.Write(i,SizeOf(i)); i:=ih._lwFileSize; ms.Write(i,SizeOf(i)); i:=iRecsLeft shl 1; ms.Write(i,SizeOf(i)); while iRecsLeft>0do begin iRecsToRead:=iRecsNum; if iRecsLeft<iRecsToRead then iRecsToRead:=iRecsLeft; Result:=ceTimeout; wRetries:=nRetries; while(Result<>meSuccess)and(wRetries<>0)do begin dec(wRetries); Result:=mbReadFileDataBlock(cd,0,iAddr,pBuf,iRecsToRead shl 1,nil,nil); end; if Result<>meSuccess then break; // даже после нескольких попыток определённый блок не считался ms.Write(pBuf^,iRecsToRead shl 1); dec(iRecsLeft,iRecsToRead); inc(iAddr,iRecsToRead); if not DoProgress(iAddr shl 1,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; if not DoProgress(iAddr shl 1,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; if Result=meSuccess then begin Sleep(25); // дадим немного показать 100%-й прогресс if not Z_DecompressStream(ms)then begin Result:=ceDataFormat; exit; end; SetLength(sFileText,ms.Size); ms.Position:=0; ms.Size:=ih._lwFileSize; ms.Read(sFileText[1],ms.Size); //! проверку контролькой суммы ih._wCheckSumType можно сделать end; finally DoProgress(0,0,psClosed); FreeMemory(pBuf); ms.Free; end; except Result:=ceSysException; end; end; function mbReadLDFile(cd:TModbusDevice; out sFileName,sFileText:AnsiString; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var ih:TIniHeader; iRecsLeft,iRecsNum,iAddr,iRecsToRead:integer; tc:longword; wRetries:word; pBuf:PAnsiChar; ms:TMemoryStream; const nRetries=3; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,(ih._wTotalSize+1{2 было!})shl 1,lwTimeEllapsed,'',ps); end; begin pBuf:=nil; ms:=nil; try try tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; Result:=mbReadFileDataBlock(cd,1,0,@ih,SizeOf(ih),nil,nil); if Result<>meSuccess then exit; if not DoProgress(SizeOf(ih),GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; iRecsLeft:=ih._wTotalSize-ih._wHeaderSize-1; if iRecsLeft<=0then begin Result:=ceDataSize; exit; end; iRecsNum:=(iMaxBufferSize-9)shr 1; iAddr:=ih._wHeaderSize+2; sFileName:=ih._sFileName; pBuf:=GetMemory(iRecsNum shl 1); ms:=TMemoryStream.Create; while iRecsLeft>0do begin iRecsToRead:=iRecsNum; if iRecsLeft<iRecsToRead then iRecsToRead:=iRecsLeft; Result:=ceTimeout; wRetries:=nRetries; while(Result<>meSuccess)and(wRetries<>0)do begin dec(wRetries); Result:=mbReadFileDataBlock(cd,1,iAddr,pBuf,iRecsToRead shl 1,nil,nil); end; if Result<>meSuccess then break; // даже после нескольких попыток определённый блок не считался ms.Write(pBuf^,iRecsToRead shl 1); dec(iRecsLeft,iRecsToRead); inc(iAddr,iRecsToRead); if not DoProgress(iAddr shl 1,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; if not DoProgress(iAddr shl 1,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; if Result=meSuccess then begin Sleep(25); // дадим немного показать 100%-й прогресс SetLength(sFileText,ms.Size); ms.Position:=0; ms.Size:=ih._lwFileSize; ms.Read(sFileText[1],ms.Size); //! проверку контролькой суммы ih._wCheckSumType можно сделать end; finally DoProgress(0,0,psClosed); FreeMemory(pBuf); ms.Free; end; except Result:=ceSysException; end; end; function mbWriteLDFile(cd:TModbusDevice; sFileName,sFileText:AnsiString; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var ih:TIniHeader; iBytesLeft,iAddr,iBytesToWrite:integer; tc:longword; pBuf:PAnsiChar; ms:TMemoryStream; wRetries:word; const nRetries=3; // iRecsLeft,iRecsNum,iAddr,iRecsToRead:integer; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,(ih._wTotalSize+1)shl 1,lwTimeEllapsed,'',ps); end; begin pBuf:=nil; ms:=nil; try try tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; sFileName:=ChangeFileExt(sFileName,''); if Length(sFileName)>SizeOf(ih._sFileName)-3then SetLength(sFileName,SizeOf(ih._sFileName)-3); sFileName:=sFileName+'.ld'; ZeroMemory(@ih,SizeOf(ih)); FillMemory(@ih._sFileName,SizeOf(ih._sFileName),ord(#32)); FillMemory(@ih._sCompressor,SizeOf(ih._sCompressor),ord(#32)); CopyMemory(@ih._sFileName,@sFileName[1],Length(sFileName)); ih._wHeaderSize:=31; ih._wHeaderVersion:=1; ih._wCheckSumType:=3; ih._wCheckSum:=CheckSum_CalculateCRC16(sFileText); ih._lwFileSize:=Length(sFileText); ih._wTotalSize:=31+(Length(sFileText)+1)div 2+1; Result:=MBWriteFileDataBlock(cd,1,0,@ih,SizeOf(ih),nil,nil); if Result<>meSuccess then exit; if not DoProgress(SizeOf(ih),GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; iBytesLeft:=Length(sFileText); if iBytesLeft=0then begin Result:=ceDataSize; exit; end; iAddr:=ih._wHeaderSize+2; iBytesToWrite:=(iMaxBufferSize-14)and$FE; pBuf:=GetMemory(iBytesToWrite); ms:=TMemoryStream.Create; ms.Write(sFileText[1],Length(sFileText)); ms.Position:=0; while iBytesLeft<>0do begin iBytesToWrite:=(iMaxBufferSize-14)and$FE; if iBytesLeft<iBytesToWrite then iBytesToWrite:=iBytesLeft; Result:=ceTimeout; wRetries:=nRetries; ms.Read(pBuf^,iBytesToWrite); while(Result<>meSuccess)and(wRetries<>0)do begin dec(wRetries); Result:=mbWriteFileDataBlock(cd,1,iAddr,pBuf,iBytesToWrite,nil,nil); if(Result=ceTimeOut)and(iBytesLeft-iBytesToWrite<=0)then begin Result:=meSuccess; break; end; // после последней записи устройство может уйти в сброс end; if Result<>meSuccess then break; dec(iBytesLeft,iBytesToWrite); inc(iAddr,iBytesToWrite shr 1); if not DoProgress(iAddr shl 1,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; if not DoProgress(iAddr shl 1,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; finally DoProgress(0,0,psClosed); FreeMemory(pBuf); ms.Free; end; except Result:=ceSysException; end; end; // чтение непрерывного блока данных осциллограммы function mbReadScopeDataBlock(cd:TModbusDevice; wOrgAddr:word; pDst:pointer; iRecs,iRecSize:integer; pcc:TProgressCallBack=nil; PID:pointer=nil):integer; var iRecsLeft,iRecsNum,iRecsToRead:integer; tc:longword; wRetries:word; const nRetries=3; function DoProgress(const lwCurrentProgress,lwTimeEllapsed:LongWord; ps:TProgressState):boolean; begin Result:=(@pcc=nil)or pcc(PID,LongWord(PID),0,lwCurrentProgress,iRecs,lwTimeEllapsed,'',ps); end; begin Result:=ceUnknownError; if iRecs<=0then begin Result:=ceNoTransactionData; exit; end; if iRecSize<=0then begin Result:=ceNoTransactionData; exit; end; try try iRecsLeft:=iRecs; iRecsNum:=(iMaxBufferSize-7)div iRecSize; tc:=GetTickCount; if not DoProgress(0,0,psOpened)then begin Result:=ceAbortOperation; exit; end; while iRecsLeft>0do begin iRecsToRead:=iRecsNum; if iRecsLeft<iRecsToRead then iRecsToRead:=iRecsLeft; Result:=ceTimeout; wRetries:=nRetries; while(Result<>meSuccess)and(wRetries<>0)do begin dec(wRetries); Result:=mbReadBuffer(cd,[cd.Address,mfReadScopeRecords,wOrgAddr,iRecsToRead],pDst,iRecsToRead*iRecSize); end; dec(iRecsLeft,iRecsToRead); inc(wOrgAddr,iRecsToRead); if Result<>meSuccess then break; PAnsiChar(pDst):=PAnsiChar(pDst)+iRecsToRead*iRecSize; if not DoProgress(iRecs-iRecsLeft,GetTickCount-tc,psWorking)then begin Result:=ceAbortOperation; exit; end; end; finally DoProgress(0,0,psClosed); end; except Result:=ceSysException; end; end; end.
unit uRecipeDateMDY; interface uses Classes, RegularExpressions, uDemo, uRecipe; type TRecipeDateMDY = class(TRecipe) public class function Description: String; override; function Pattern: String; override; procedure GetInputs(const Inputs: TStrings); override; end; implementation { TRecipeDateMDY } class function TRecipeDateMDY.Description: String; begin Result := 'Recipes\Date MDY'; end; {$REGION} /// <B>Source</B>: http://www.regexlib.com/REDetails.aspx?regexp_id=113 /// <B>Author</B>: Michael Ash /// /// This expression validates dates in the US m/d/y format from 1/1/1600 - /// 12/31/9999. /// /// <B>Notes</B>: /// -Replaced "beginning of string (^)" and "end of string ($)" with /// "word boundaries (\b)" /// -Added named capturing groups to extract month, day and year function TRecipeDateMDY.Pattern: String; begin Result := // Alternative 1 '\b(?:(?:(?<month>0?[13578]|1[02])(?<sep1>\/|-|\.)31)\k<sep1>|' + '(?:(?<month>0?[13-9]|1[0-2])(?<sep2>\/|-|\.)' + '(?<day>29|30)\k<sep2>))' + '(?<year>(?:1[6-9]|[2-9]\d)?\d{2})\b|' + // Alternative 2 '\b(?:(?<month>0?2)(?<sep3>\/|-|\.)' + '(?<day>29)\k<sep3>' + '(?:(?<year>(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|' + '(?:(?:16|[2468][048]|[3579][26])00))))\b|' + // Alternative 3 '\b(?<month>(?:0?[1-9])|(?:1[0-2]))(?<sep4>\/|-|\.)' + '(?<day>0?[1-9]|1\d|2[0-8])\k<sep4>' + '(?<year>(?:1[6-9]|[2-9]\d)?\d{2})\b' end; procedure TRecipeDateMDY.GetInputs(const Inputs: TStrings); begin Inputs.Add('01.1.02'); Inputs.Add('11-30-2001'); Inputs.Add('2/29/2000'); Inputs.Add('02/29/01'); Inputs.Add('13/01/2002'); Inputs.Add('11/00/02'); Inputs.Add('Lorem ipsum 01.1.02 dolor sit amet, consectetur adipisicing'); Inputs.Add('elit, 11-30-2001 sed do eiusmod 2/29/2000 tempor incididunt ut'); Inputs.Add('labore 02/29/01 et dolore magna 13/01/2002 aliqua. Ut enim ad'); Inputs.Add('minim veniam, 11/00/02 quis nostrud exercitation ullamco'); Inputs.Add('laboris nisi ut aliquip ex ea commodo consequat.'); end; {$ENDREGION} initialization RegisterDemo(TRecipeDateMDY); end.
unit ServerModule; interface uses Classes, SysUtils, uniGUIServer, uniGUIMainModule, uniGUIApplication, uIdCustomHTTPServer, uniGUITypes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP; type TUniServerModule = class(TUniGUIServerModule) ftp: TIdFTP; private { Private declarations } function FtpPadrao(tipo: string): string; protected procedure FirstInit; override; public { Public declarations } function EnviarT1(arq: string; Armazem: integer; DoNumber: string; codOcorrencia: string; estadia: boolean = false; dtn: string = ''): boolean; end; function UniServerModule: TUniServerModule; implementation {$R *.dfm} uses UniGUIVars, uT1Tracking; function UniServerModule: TUniServerModule; begin Result := TUniServerModule(UniGUIServerInstance); end; function TUniServerModule.EnviarT1(arq: string; Armazem: integer; DoNumber: string; codOcorrencia: string; estadia: boolean = false; dtn: string = ''): boolean; begin GeraArquivo(FtpPadrao('') + arq, Armazem, DoNumber, codOcorrencia); end; procedure TUniServerModule.FirstInit; begin InitServerModule(Self); end; function TUniServerModule.FtpPadrao(tipo: string): string; var arquivo: string; begin arquivo := FilesFolderPath + 'ftp\'; if not DirectoryExists(ExtractFilePath(arquivo)) then CreateDir(ExtractFilePath(arquivo)); Result := arquivo; end; initialization RegisterServerModuleClass(TUniServerModule); end.
unit Project87.Scenes.IntroScene; interface uses QCore.Types, QCore.Input, QGame.Scene, QEngine.Camera, QEngine.Texture, Strope.Math; type TIntroSceneState = ( issNone = 0, issFirstWait = 1, issShowUp = 2, issWait = 3, issShowDown = 4, issChange = 5 ); TIntroScene = class sealed (TScene) strict private FCamera: IQuadCamera; FBalancer: TQuadTexture; FGearImages: array [0..2] of TQuadTexture; FQuadLogo: TQuadTexture; FIgdcLogo: TQuadTexture; FBalancerFrame: Integer; FBalancerTime: Single; FRotationAngle: Single; FRotationSpeed: Single; FState: TIntroSceneState; FLogo: Integer; FAlpha: Single; FTime: Single; FIsToMenu: Boolean; procedure LoadImages; procedure DrawQuadLogo; procedure DrawIgdcLogo; property Camera: IQuadCamera read FCamera; public constructor Create(const AName: string); procedure OnInitialize(AParameter: TObject = nil); override; procedure OnDraw(const ALayer: Integer); override; procedure OnUpdate(const ADelta: Double); override; procedure OnDestroy; override; function OnKeyDown(AKey: TKeyButton): Boolean; override; end; implementation uses SysUtils, QuadEngine, direct3d9, QEngine.Core, QGame.Game, Project87.Scenes.StarMapScene; {$REGION ' TIntroScene '} const BALANCER_FRAME_DELTA = 0.02; TIME_FIRST_WAIT = 1.2; TIME_SHOWUP = 1.3; TIME_WAIT = 3.5; TIME_SHOWDOWN = 1.3; TIME_CHANGE = 0.25; NEXT_SCENE = 'StarMap'; constructor TIntroScene.Create(const AName: string); begin inherited Create(AName); FAlpha := 1; end; procedure TIntroScene.DrawQuadLogo; var ALogoSize: TVectorF; ABalancerSize: TVectorF; ASize: Single; begin TheEngine.Camera := nil; TheRender.RectangleEx(0, 0, Camera.Resolution.X, Camera.Resolution.Y, $FF000080, $FF000080, $FF000000, $FF000000); TheEngine.Camera := Camera; ASize := Camera.DefaultResolution.Y * 0.853; ALogoSize.Create(ASize, ASize); ASize := Camera.DefaultResolution.Y * 0.213; ABalancerSize.Create(ASize, ASize); FGearImages[2].Draw(Vec2F(181, -83) * 1.28, Vec2F(256, 256) * 1.28 * 0.5, -FRotationAngle / 24 - 4, $FF404040); FGearImages[1].Draw(Vec2F(181, -167) * 1.28, Vec2F(128, 128) * 1.28 * 0.5, FRotationAngle / 14 + 8, $FF404040); FGearImages[2].Draw(Vec2F(221, -241) * 1.28, Vec2F(256, 256) * 1.28 * 0.5, -FRotationAngle / 24 - 4, $FF404040); FGearImages[0].Draw(Vec2F(106, -83) * 1.28, Vec2F(128, 128) * 1.28 * 0.5, FRotationAngle / 8 + 10, $FF404040); FGearImages[2].Draw(Vec2F(42, -44) * 1.28, Vec2F(256, 256) * 1.28 * 0.5, -FRotationAngle / 24, $FF404040); FGearImages[0].Draw(Vec2F(-314.88, 106.24), Vec2F(163.84, 163.84), FRotationAngle / 8 - 4, $FF888888); FGearImages[1].Draw(Vec2F(-245.76, 0), Vec2F(163.84, 163.84), -FRotationAngle / 14 + 15, $FF767676); FGearImages[1].Draw(Vec2F(-160, 201), Vec2F(163.84, 163.84) * 1.2, FRotationAngle / 24, $FF323232); FGearImages[2].Draw(Vec2F(6.4, -1), Vec2F(328, 328) * 1.2, -FRotationAngle / (288/7) + 2.8, $FF2A2A2A); FGearImages[2].Draw(Vec2F(-160, 201), Vec2F(328, 328), FRotationAngle / 24, $FF444444); TheRender.Rectangle(-164, -307, -156, -40, $FF222233); FBalancer.Draw(Vec2F(-160, -126), ABalancerSize, 0, $FF555555, FBalancerFrame); FQuadLogo.Draw(ZeroVectorF, ALogoSize, 0, $FFFFFFFF); end; procedure TIntroScene.DrawIgdcLogo; begin TheEngine.Camera := nil; TheRender.Rectangle(0, 0, Camera.Resolution.X, Camera.Resolution.Y, $FF000000); TheEngine.Camera := Camera; FIgdcLogo.Draw(ZeroVectorF, Vec2F(720, 720), 0, $FFFFFFFF); end; {$REGION ' Base Actions '} procedure TIntroScene.OnInitialize(AParameter: TObject = nil); begin FCamera := TheEngine.CreateCamera; FCamera.Position := ZeroVectorF; LoadImages; FBalancerFrame := 0; FBalancerTime := 0; FRotationAngle := 0; FRotationSpeed := 360; FAlpha := 1; FState := issFirstWait; FTime := 0; end; procedure TIntroScene.OnDraw(const ALayer: Integer); begin TheRender.SetBlendMode(qbmSrcAlpha); case FLogo of 0: DrawQuadLogo; 1: DrawIgdcLogo; end; TheEngine.Camera := nil; TheRender.Rectangle(0, 0, Camera.Resolution.X, Camera.Resolution.Y, D3DCOLOR_COLORVALUE(0, 0, 0, FAlpha)); end; procedure TIntroScene.OnUpdate(const ADelta: Double); var ASceneParameter: TStarMapSceneParameters; begin FBalancerTime := FBalancerTime + ADelta; if FBalancerTime > BALANCER_FRAME_DELTA then begin FBalancerTime := 0; FBalancerFrame := (FBalancerFrame + 1) mod FBalancer.FramesCount; end; FRotationAngle := FRotationAngle + FRotationSpeed * ADelta; FTime := FTime + ADelta; case FState of issFirstWait: if FTime > TIME_FIRST_WAIT then begin FState := issShowUp; FTime := 0; end; issShowUp: begin FAlpha := InterpolateValue(1, 0, FTime / TIME_SHOWUP, itHermit01); if FTime > TIME_SHOWUP then begin FState := issWait; FTime := 0; FAlpha := 0; end; end; issWait: if FTime > TIME_WAIT then begin FState := issShowDown; FTime := 0; end; issShowDown: begin FAlpha := InterpolateValue(0, 1, FTime / TIME_SHOWDOWN, itHermit01); if FTime > TIME_SHOWDOWN then begin FState := issChange; FTime := 0; FAlpha := 1; end; end; issChange: begin if FIsToMenu then begin TheGame.SceneManager.MakeCurrent(NEXT_SCENE); ASceneParameter := TStarMapSceneParameters.Create(False); TheSceneManager.OnInitialize(ASceneParameter); Exit; end; if FTime > TIME_CHANGE then begin FState := issShowUp; Inc(FLogo); if FLogo = 2 then begin TheGame.SceneManager.MakeCurrent(NEXT_SCENE); ASceneParameter := TStarMapSceneParameters.Create(False); TheSceneManager.OnInitialize(ASceneParameter); Exit; end; end; end; end; end; procedure TIntroScene.OnDestroy; begin FCamera := nil; FreeAndNil(FQuadLogo); FreeAndNil(FIgdcLogo); FreeAndNil(FBalancer); FreeAndNil(FGearImages[0]); FreeAndNil(FGearImages[1]); FreeAndNil(FGearImages[2]); end; {$ENDREGION} function TIntroScene.OnKeyDown(AKey: Word): Boolean; begin Result := True; if AKey in [KB_SPACE, KB_ENTER] then begin case FState of issFirstWait: begin FState := issChange; FTime := 0; end; issShowUp: begin FState := issShowDown; FTime := (1 - FTime / TIME_SHOWUP) * TIME_SHOWDOWN; end; issWait: begin FState := issShowDown; FTime := 0; end; issChange: FTime := 0; end; FIsToMenu := True; end; end; procedure TIntroScene.LoadImages; const AGfxDir = '..\data\gfx\logo_elements\'; begin FBalancer := TheEngine.CreateTexture; FBalancer.LoadFromFile(AGfxDir + 'balancer.png', 0, 128, 128); FGearImages[0] := TheEngine.CreateTexture; FGearImages[0].LoadFromFile(AGfxDir + 'gear.png', 0); FGearImages[1] := TheEngine.CreateTexture; FGearImages[1].LoadFromFile(AGfxDir + 'gear_med.png', 0); FGearImages[2] := TheEngine.CreateTexture; FGearImages[2].LoadFromFile(AGfxDir + 'gear_big.png', 0); FQuadLogo := TheEngine.CreateTexture; FQuadLogo.LoadFromFile(AGfxDir + 'quad_logo.png', 0); FIgdcLogo := TheEngine.CreateTexture; FIgdcLogo.LoadFromFile(AGfxDir + 'igdc.jpg', 0); end; {$ENDREGION} end.
unit TSTOCustomPatches.Xml; interface uses HsXmlDocEx; type ITSTOXmlDependencies = interface(IXMLNodeCollectionEx) ['{662B9657-6A94-4724-A295-FE516274F8DF}'] function GetDependency(Index: Integer): WideString; function Add(const Dependency: WideString): IXMLNodeEx; function Insert(const Index: Integer; const Dependency: WideString): IXMLNodeEx; property Dependency[Index: Integer]: WideString read GetDependency; default; end; ITSTOXmlPatchData = interface(IXMLNodeEx) ['{AF0FBAD8-C5AB-46AB-919E-7FBD772EA287}'] Function GetPatchType: Integer; Procedure SetPatchType(Const Value: Integer); Function GetPatchPath: WideString; Procedure SetPatchPath(Const Value: WideString); Function GetCode() : WideString; Procedure SetCode(Const Value : WideString); Function GetDependencies: ITSTOXmlDependencies; Procedure Assign(ASource : IInterface); Property PatchType : Integer Read GetPatchType Write SetPatchType; Property PatchPath : WideString Read GetPatchPath Write SetPatchPath; Property Code : WideString Read GetCode Write SetCode; Property Dependencies: ITSTOXmlDependencies read GetDependencies; end; ITSTOXmlPatchDataList = interface(IXMLNodeCollectionEx) ['{F5ACA895-35A1-41B4-851B-C2F97F5089A4}'] function Add: ITSTOXmlPatchData; function Insert(const Index: Integer): ITSTOXmlPatchData; function GetItem(Index: Integer): ITSTOXmlPatchData; property Items[Index: Integer]: ITSTOXmlPatchData read GetItem; default; end; ITSTOXMLCustomPatch = interface(IXMLNodeEx) ['{38E6678E-34D0-4B22-BB3F-984F9E92A505}'] Function GetPatchName: WideString; Procedure SetPatchName(Const Value: WideString); Function GetPatchActive: Boolean; Procedure SetPatchActive(Const Value: Boolean); Function GetPatchDesc: WideString; Procedure SetPatchDesc(Const Value: WideString); Function GetFileName: WideString; Procedure SetFileName(Const Value: WideString); Function GetPatchData: ITSTOXmlPatchDataList; Procedure Assign(ASource : IInterface); Property PatchName : WideString Read GetPatchName Write SetPatchName; Property PatchActive : Boolean Read GetPatchActive Write SetPatchActive; Property PatchDesc : WideString Read GetPatchDesc Write SetPatchDesc; Property FileName : WideString Read GetFileName Write SetFileName; Property PatchData : ITSTOXmlPatchDataList read GetPatchData; end; ITSTOXmlPatches = interface(IXMLNodeCollectionEx) ['{F902B5D9-E44C-477C-8420-A08667D54D72}'] Function GetPatch(Index: Integer): ITSTOXMLCustomPatch; Function Add: ITSTOXMLCustomPatch; Function Insert(const Index: Integer): ITSTOXMLCustomPatch; Property Patch[Index: Integer]: ITSTOXMLCustomPatch read GetPatch; default; end; ITSTOXmlCustomPatches = interface(IXMLNodeEx) ['{D8E9E295-73F0-4AD7-B102-6D2467A9E2FF}'] Function GetPatches: ITSTOXmlPatches; Function GetActivePatchCount() : Integer; Procedure Assign(ASource : IInterface); Property Patches : ITSTOXmlPatches read GetPatches; Property ActivePatchCount : Integer Read GetActivePatchCount; end; TTSTOXmlCustomPatches = Class(TObject) Public Class Function CreateCustomPatches(AXmlString : String) : ITSTOXmlCustomPatches; OverLoad; Class Function CreateCustomPatches() : ITSTOXmlCustomPatches; OverLoad; End; const TargetNamespace = ''; implementation Uses SysUtils, RtlConsts, HsInterfaceEx, XmlIntf, TSTOCustomPatchesIntf, TSTOCustomPatchesImpl; Type TTSTOXmlCustomPatchesImpl = class(TXMLNodeEx, ITSTOCustomPatches, ITSTOXmlCustomPatches) Private FInterfaceState : TInterfaceState; Protected Function GetInterfaceState() : TInterfaceState; Function GetPatches() : ITSTOXmlPatches; Function GetActivePatchCount() : Integer; Function MyGetPatches() : ITSTOCustomPatchList; Function ITSTOCustomPatches.GetPatches = MyGetPatches; Procedure Assign(ASource : IInterface); ReIntroduce; Public Procedure AfterConstruction(); OverRide; Procedure BeforeDestruction(); OverRide; end; TTSTOXmlPatches = class(TXMLNodeCollectionEx, ITSTOCustomPatchList, ITSTOXmlPatches) Private FPatches : Pointer; Function GetImplementor() : ITSTOCustomPatchList; Protected Property PatchesImpl : ITSTOCustomPatchList Read GetImplementor Implements ITSTOCustomPatchList; Function GetPatch(Index : Integer) : ITSTOXMLCustomPatch; Function Add() : ITSTOXMLCustomPatch; Function Insert(Const Index : Integer) : ITSTOXMLCustomPatch; Public Procedure AfterConstruction(); OverRide; end; TTSTOXmlPatch = class(TXMLNodeEx, ITSTOCustomPatch, ITSTOXMLCustomPatch) Private FPatchData: ITSTOXmlPatchDataList; FInterfaceState : TInterfaceState; Protected Function GetInterfaceState() : TInterfaceState; Function GetPatchName() : WideString; Procedure SetPatchName(Const Value: WideString); Function GetPatchActive() : Boolean; Procedure SetPatchActive(Const Value: Boolean); Function GetPatchDesc() : WideString; Procedure SetPatchDesc(Const Value: WideString); Function GetFileName() : WideString; Procedure SetFileName(Const Value: WideString); Function GetPatchData() : ITSTOXmlPatchDataList; Function MyGetPatchData() : ITSTOPatchDatas; Function ITSTOCustomPatch.GetPatchData = MyGetPatchData; Procedure Assign(ASource : IInterface); public Procedure AfterConstruction(); OverRide; Procedure BeforeDestruction(); OverRide; end; TTSTOXmlPatchData = class(TXMLNodeEx, ITSTOPatchData, ITSTOXmlPatchData) Private FInterfaceState : TInterfaceState; protected Function GetInterfaceState() : TInterfaceState; Function GetPatchType() : Integer; Procedure SetPatchType(Const Value: Integer); Function GetPatchPath() : WideString; Procedure SetPatchPath(Const Value: WideString); Function GetCode() : WideString; Procedure SetCode(Const Value : WideString); Function GetDependencies() : ITSTOXmlDependencies; Procedure Assign(ASource : IInterface); public Procedure AfterConstruction(); OverRide; Procedure BeforeDestruction(); OverRide; end; TTSTOXmlPatchDatas = class(TXMLNodeCollectionEx, ITSTOPatchDatas, ITSTOXmlPatchDataList) Private FPatcheDatas : Pointer; Function GetImplementor() : ITSTOPatchDatas; Protected Property PatchesImpl : ITSTOPatchDatas Read GetImplementor Implements ITSTOPatchDatas; Function Add() : ITSTOXmlPatchData; Function Insert(Const Index : Integer) : ITSTOXmlPatchData; Function GetItem(Index : Integer) : ITSTOXmlPatchData; end; TTSTOXmlDependenciesType = class(TXMLNodeCollectionEx, ITSTOXmlDependencies) protected function GetDependency(Index: Integer): WideString; function Add(const Dependency: WideString): IXMLNodeEx; function Insert(const Index: Integer; const Dependency: WideString): IXMLNodeEx; public procedure AfterConstruction; override; end; Class Function TTSTOXmlCustomPatches.CreateCustomPatches(AXmlString : String) : ITSTOXmlCustomPatches; Begin Result := LoadXMLData(AXmlString).GetDocBinding('CustomPatches', TTSTOXmlCustomPatchesImpl, TargetNamespace) as ITSTOXmlCustomPatches; End; Class Function TTSTOXmlCustomPatches.CreateCustomPatches() : ITSTOXmlCustomPatches; Begin Result := NewXMLDocument.GetDocBinding('CustomPatches', TTSTOXmlCustomPatchesImpl, TargetNamespace) as ITSTOXmlCustomPatches; End; (******************************************************************************) { TTSTOXmlCustomPatchesType } procedure TTSTOXmlCustomPatchesImpl.AfterConstruction(); begin RegisterChildNode('Patches', TTSTOXmlPatches); FInterfaceState := isCreating; InHerited AfterConstruction(); end; Procedure TTSTOXmlCustomPatchesImpl.BeforeDestruction(); Begin FInterfaceState := isDestroying; InHerited AfterConstruction(); End; Function TTSTOXmlCustomPatchesImpl.GetInterfaceState() : TInterfaceState; Begin Result := FInterfaceState; End; Procedure TTSTOXmlCustomPatchesImpl.Assign(ASource : IInterface); Var lXmlSrc : ITSTOXmlCustomPatches; lSrc : ITSTOCustomPatches; X : Integer; Begin If Supports(ASource, IXmlNodeEx) And Supports(ASource, ITSTOXmlCustomPatches, lXmlSrc) Then Begin For X := 0 To lXmlSrc.Patches.Count - 1 Do GetPatches().Add().Assign(lXmlSrc.Patches[X]); End Else If Supports(ASource, ITSTOCustomPatches, lSrc) Then Begin For X := 0 To lSrc.Patches.Count - 1 Do GetPatches().Add().Assign(lSrc.Patches[X]); // FFileImpl := Pointer(lSrc); End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; function TTSTOXmlCustomPatchesImpl.GetPatches() : ITSTOXmlPatches; begin Result := ChildNodes['Patches'] as ITSTOXmlPatches; end; Function TTSTOXmlCustomPatchesImpl.MyGetPatches() : ITSTOCustomPatchList; Begin Result := GetPatches() As ITSTOCustomPatchList; End; Function TTSTOXmlCustomPatchesImpl.GetActivePatchCount() : Integer; Var lNodeList : IXmlNodeListEx; Begin lNodeList := (OwnerDocument As IXmlDocumentEx).SelectNodes('//Patch[@Active="true"]'); If Assigned(lNodeList) Then Result := lNodeList.Count Else Result := 0; End; procedure TTSTOXmlPatches.AfterConstruction(); begin RegisterChildNode('Patch', TTSTOXmlPatch); ItemTag := 'Patch'; ItemInterface := ITSTOXMLCustomPatch; FPatches := Nil; InHerited AfterConstruction(); end; Function TTSTOXmlPatches.GetImplementor() : ITSTOCustomPatchList; Var X : Integer; Begin If Not Assigned(FPatches) Then Begin Result := TTSTOCustomPatchList.Create(); For X := 0 To List.Count - 1 Do Result.Add().Assign(List[X]); FPatches := Pointer(Result); End Else Result := ITSTOCustomPatchList(FPatches); End; function TTSTOXmlPatches.GetPatch(Index: Integer): ITSTOXMLCustomPatch; begin Result := List[Index] as ITSTOXMLCustomPatch; end; function TTSTOXmlPatches.Add: ITSTOXMLCustomPatch; begin Result := AddItem(-1) as ITSTOXMLCustomPatch; end; function TTSTOXmlPatches.Insert(const Index: Integer): ITSTOXMLCustomPatch; begin Result := AddItem(Index) as ITSTOXMLCustomPatch; end; procedure TTSTOXmlPatch.AfterConstruction(); begin RegisterChildNode('PatchData', TTSTOXmlPatchData); FPatchData := CreateCollection(TTSTOXmlPatchDatas, ITSTOXmlPatchData, 'PatchData') as ITSTOXmlPatchDataList; FInterfaceState := isCreating; InHerited AfterConstruction(); end; Procedure TTSTOXmlPatch.BeforeDestruction(); Begin FInterfaceState := isDestroying; InHerited BeforeDestruction(); End; Function TTSTOXmlPatch.GetInterfaceState() : TInterfaceState; Begin Result := FInterfaceState; End; Procedure TTSTOXmlPatch.Assign(ASource : IInterface); Var lXmlSrc : ITSTOXMLCustomPatch; lSrc : ITSTOCustomPatch; X : Integer; Begin If Supports(ASource, IXmlNodeEx) And Supports(ASource, ITSTOXMLCustomPatch, lXmlSrc) Then Begin SetAttribute('Name', lXmlSrc.PatchName); SetAttribute('Active', lXmlSrc.PatchActive); ChildNodes['PatchDesc'].NodeValue := lXmlSrc.PatchDesc; ChildNodes['FileName'].NodeValue := lXmlSrc.FileName; For X := 0 To lXmlSrc.PatchData.Count - 1 Do GetPatchData().Add().Assign(lXmlSrc.PatchData[X]); End Else If Supports(ASource, ITSTOCustomPatch, lSrc) Then Begin SetAttribute('Name', lSrc.PatchName); SetAttribute('Active', lSrc.PatchActive); ChildNodes['PatchDesc'].NodeValue := lSrc.PatchDesc; ChildNodes['FileName'].NodeValue := lSrc.FileName; For X := 0 To lSrc.PatchData.Count - 1 Do GetPatchData().Add().Assign(lSrc.PatchData[X]); // FHeaderImpl := Pointer(lSrc); End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; function TTSTOXmlPatch.GetPatchName: WideString; begin Result := AttributeNodes['Name'].Text; end; procedure TTSTOXmlPatch.SetPatchName(Const Value: WideString); begin SetAttribute('Name', Value); end; function TTSTOXmlPatch.GetPatchActive: Boolean; begin Result := AttributeNodes['Active'].AsBoolean; end; procedure TTSTOXmlPatch.SetPatchActive(Const Value: Boolean); begin SetAttribute('Active', Value); end; function TTSTOXmlPatch.GetPatchDesc: WideString; begin Result := ChildNodes['PatchDesc'].Text; end; procedure TTSTOXmlPatch.SetPatchDesc(Const Value: WideString); begin ChildNodes['PatchDesc'].NodeValue := Value; end; function TTSTOXmlPatch.GetFileName: WideString; begin Result := ChildNodes['FileName'].Text; end; procedure TTSTOXmlPatch.SetFileName(Const Value: WideString); begin ChildNodes['FileName'].NodeValue := Value; end; function TTSTOXmlPatch.GetPatchData: ITSTOXmlPatchDataList; begin Result := FPatchData; end; Function TTSTOXmlPatch.MyGetPatchData() : ITSTOPatchDatas; Begin Result := GetPatchData() As ITSTOPatchDatas; End; procedure TTSTOXmlPatchData.AfterConstruction(); begin RegisterChildNode('Dependencies', TTSTOXmlDependenciesType); FInterfaceState := isCreating; InHerited AfterConstruction(); end; Procedure TTSTOXmlPatchData.BeforeDestruction(); Begin FInterfaceState := isDestroying; InHerited BeforeDestruction(); End; Function TTSTOXmlPatchData.GetInterfaceState() : TInterfaceState; Begin Result := FInterfaceState; End; Procedure TTSTOXmlPatchData.Assign(ASource : IInterface); Var lXmlSrc : ITSTOXmlPatchData; lSrc : ITSTOPatchData; X : Integer; Begin If Supports(ASource, IXmlNodeEx) And Supports(ASource, ITSTOXmlPatchData, lXmlSrc) Then Begin ChildNodes['PatchType'].NodeValue := lXmlSrc.PatchType; ChildNodes['PatchPath'].NodeValue := lXmlSrc.PatchPath; SetCode(lXmlSrc.Code); End Else If Supports(ASource, ITSTOPatchData, lSrc) Then Begin ChildNodes['PatchType'].NodeValue := lSrc.PatchType; ChildNodes['PatchPath'].NodeValue := lSrc.PatchPath; SetCode(lSrc.Code); // FPatchDataImpl := Pointer(lSrc); End Else Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]); End; function TTSTOXmlPatchData.GetPatchType: Integer; begin Result := ChildNodes['PatchType'].AsInteger; end; procedure TTSTOXmlPatchData.SetPatchType(Const Value: Integer); begin ChildNodes['PatchType'].NodeValue := Value; end; function TTSTOXmlPatchData.GetPatchPath: WideString; begin Result := ChildNodes['PatchPath'].Text; end; procedure TTSTOXmlPatchData.SetPatchPath(Const Value : WideString); begin ChildNodes['PatchPath'].NodeValue := Value; end; function TTSTOXmlPatchData.GetCode() : WideString; begin Result := ChildNodes['Code'].ChildNodes['#cdata-section'].Text; end; Procedure TTSTOXmlPatchData.SetCode(Const Value : WideString); Var lNode : IXMLNode; begin lNode := OwnerDocument.CreateNode(Value, ntCDATA); ChildNodes['Code'].ChildNodes.Clear(); ChildNodes['Code'].ChildNodes.Add(lNode); End; function TTSTOXmlPatchData.GetDependencies: ITSTOXmlDependencies; begin Result := ChildNodes['Dependencies'] as ITSTOXmlDependencies; end; Function TTSTOXmlPatchDatas.GetImplementor() : ITSTOPatchDatas; Var X : Integer; Begin If Not Assigned(FPatcheDatas) Then Begin Result := TTSTOPatchDatas.Create(); For X := 0 To List.Count - 1 Do Result.Add().Assign(List[X]); FPatcheDatas := Pointer(Result); End Else Result := ITSTOPatchDatas(FPatcheDatas); End; function TTSTOXmlPatchDatas.Add: ITSTOXmlPatchData; begin Result := AddItem(-1) as ITSTOXmlPatchData; end; function TTSTOXmlPatchDatas.Insert(const Index: Integer): ITSTOXmlPatchData; begin Result := AddItem(Index) as ITSTOXmlPatchData; end; function TTSTOXmlPatchDatas.GetItem(Index: Integer): ITSTOXmlPatchData; begin Result := List[Index] as ITSTOXmlPatchData; end; procedure TTSTOXmlDependenciesType.AfterConstruction; begin ItemTag := 'Dependency'; ItemInterface := IXMLNodeEx; inherited; end; function TTSTOXmlDependenciesType.GetDependency(Index: Integer): WideString; begin Result := List[Index].Text; end; function TTSTOXmlDependenciesType.Add(const Dependency: WideString): IXMLNodeEx; begin Result := AddItem(-1); Result.NodeValue := Dependency; end; function TTSTOXmlDependenciesType.Insert(const Index: Integer; const Dependency: WideString): IXMLNodeEx; begin Result := AddItem(Index); Result.NodeValue := Dependency; end; end.
unit uGroupItemTreeNodeFactory; {$mode objfpc}{$H+} interface uses Classes, SysUtils, VirtualTrees, Forms, Windows, uPropertyEditor, uLibrary, uMap, uModbus, uSetting; type {$REGION Основные типы данных} // Базовый класс { TGroupItemData } TGroupItemData = class(TPropertyData) protected fReadOnly: Boolean; public procedure SetDescription(const {%H-}aStrings: TStrings); virtual; property ReadOnly: Boolean read fReadOnly; end; { TVarData } TVarData = class(TGroupItemData) protected fVarDefine: IVarDefine; fMap: IMap; fController: IController; fSlaveId: byte; protected function GetTable: TTypeTable; procedure WriteToDevice(const aFrame: IFrame); public constructor Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); virtual; reintroduce; public procedure SetDescription(const aStrings: TStrings); override; property VarDefine: IVarDefine read fVarDefine; end; { TStringData } TStringData = class(TVarData) protected function GetValue: String; override; procedure SetValue(const {%H-}aValue: String); override; public constructor Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); override; end; { TIntegerData } TIntegerData = class(TVarData) protected function GetValue: String; override; procedure SetValue(const aValue: String); override; public constructor Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); override; end; { TSingleData } TSingleData = class(TVarData) protected function GetValue: String; override; procedure SetValue(const aValue: String); override; public constructor Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); override; end; { TPicklistData } TPicklistData = class(TVarData) public constructor Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); override; procedure AfterConstruction; override; protected function GetValue: String; override; procedure SetValue(const aValue: String); override; public procedure SetDescription(const aStrings: TStrings); override; end; { TBitsData } TBitsData = class(TVarData) protected function GetValue: String; override; procedure SetValue(const {%H-}aValue: String); override; public constructor Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); override; end; { TBitData } TBitData = class(TGroupItemData) private fBitsData: TBitsData; fBit: IBitDefine; fOwner: PVirtualNode; protected function GetValue: String; override; procedure SetValue(const {%H-}aValue: String); override; public constructor Create(const aBit: IBitDefine; const aBitsData: TBitsData); reintroduce; public procedure SetDescription(const aStrings: TStrings); override; property Owner: PVirtualNode read fOwner write fOwner; end; {$ENDREGION Основные типы данных} {$REGION Фабрика узлов} { TGroupItemTreeNodeFactory } TGroupItemTreeNodeFactory = class private fTree: TBaseVirtualTree; public constructor Create(const aTree: TBaseVirtualTree); reintroduce; public function GetNode(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte): PVirtualNode; end; {$ENDREGION Фабрика узлов} implementation //uses // Logger; {$REGION Основные типы данных} { TGroupItemData } procedure TGroupItemData.SetDescription(const aStrings: TStrings); begin { TODO : Stub } end; { TVarData } function TVarData.GetTable: TTypeTable; begin case fVarDefine.TypeRegister of trHolding: Result := TTypeTable.ttHolding; trInput: Result := TTypeTable.ttInput; end; end; procedure TVarData.WriteToDevice(const aFrame: IFrame); const MAX_COUNTER = 10; var Counter: Integer; begin {$IFDEF DEBUG} Assert(aFrame <> nil); Assert(fController <> nil); {$ENDIF} fMap.WriteToTable(fVarDefine.Index, aFrame.RequestPdu); aFrame.Priority := TPriority.prHigh; Counter := 0; while not fController.InQueue(aFrame) do begin if Counter > MAX_COUNTER then begin MessageBox(0, PChar(Utf8ToAnsi('Ошибка записи в устройство')), PChar(Utf8ToAnsi('Ошибка')), MB_ICONERROR + MB_OK); Break; end; Application.ProcessMessages; sleep(10); Inc(Counter); end; end; constructor TVarData.Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); var S: string; begin if aVarDefine.Measure = '' then S := aVarDefine.ShortDescription else S := Format('%s, %s', [aVarDefine.ShortDescription, aVarDefine.Measure]); inherited Create(S, TTypeEditor.teEdit); fVarDefine := aVarDefine; fMap := aMap; fController := aController; fSlaveId := aSlaveId; fReadOnly := fVarDefine.TypeRegister = TTypeRegister.trInput; end; procedure TVarData.SetDescription(const aStrings: TStrings); var C: Char; Index: Integer; S: String; begin {$IFDEF DEBUG} Assert({%H-}aStrings <> nil); {$ENDIF} aStrings.BeginUpdate; try aStrings.Clear; if fVarDefine.TypeRegister = TTypeRegister.trHolding then C := 'h' else C := 'i'; Index := VarTypes.IndexOfData(fVarDefine.VarType); aStrings.Add(Format('[%s %d] %s (%s)', [C, fVarDefine.Index, fVarDefine.ShortDescription, VarTypes.Keys[Index]])); if fVarDefine.Measure <> '' then begin aStrings.Add(' '); aStrings.Add(Format('Формат хранения: %s x %d', [fVarDefine.Measure, fVarDefine.Multipler])); aStrings.Add(' '); end; for S in fVarDefine.Description do aStrings.Add(S); finally aStrings.EndUpdate; end; end; { TStringData } function TStringData.GetValue: String; begin case fVarDefine.VarType of vtUINTIP: Result := fMap.ReadIpAddress(GetTable, fVarDefine.Index); vtIO_DATA: Result := fMap.ReadIoData(GetTable, fVarDefine.Index, fVarDefine.Multipler); end; end; procedure TStringData.SetValue(const aValue: String); begin { TODO : Stub } end; constructor TStringData.Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); begin inherited Create(aVarDefine, aMap, aController, aSlaveId); end; { TIntegerData } function TIntegerData.GetValue: String; begin case fVarDefine.VarType of vtUINT8L: Result := Format('%d', [fMap.ReadUint8l(GetTable, fVarDefine.Index)]); vtUINT8H: Result := Format('%d', [fMap.ReadUint8h(GetTable, fVarDefine.Index)]); vtUINT16: Result := Format('%d', [fMap.ReadUint16(GetTable, fVarDefine.Index)]); vtSINT16: Result := Format('%d', [fMap.ReadSint16(GetTable, fVarDefine.Index)]); vtUINT32: Result := Format('%d', [fMap.ReadUint32(GetTable, fVarDefine.Index)]); vtSINT32: Result := Format('%d', [fMap.ReadSint32(GetTable, fVarDefine.Index)]); vtBOOL: Result := BoolToStr(fMap.ReadBool(GetTable, fVarDefine.Index)); vtBOOL_EXT: Result := Format('%d', [fMap.ReadUint32(GetTable, fVarDefine.Index)]); end; end; procedure TIntegerData.SetValue(const aValue: String); var I: Integer; W: DWord; Frame: IFrame; begin { TODO : StrToInt } I := StrToInt64Def(aValue, 0); case fVarDefine.VarType of vtUINT8L: begin W := (fMap.ReadUint16(GetTable, fVarDefine.Index) and $FF00) or I; Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, W, GetSetting.Timeout); end; vtUINT8H: begin W := fMap.ReadUint16(GetTable, fVarDefine.Index) and $FF or (I shl 8); Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, W, GetSetting.Timeout); end; vtUINT16: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, DWord(I), GetSetting.Timeout); vtSINT16: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, DWord(I), GetSetting.Timeout); vtUINT32: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); vtSINT32: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); vtFLOAT: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); end; //Log.LogStatus(Frame.ToString, Self.ClassName); if Frame <> nil then WriteToDevice(Frame); end; constructor TIntegerData.Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); begin inherited Create(aVarDefine, aMap, aController, aSlaveId); TypeEditor := TTypeEditor.teSpinEdit; end; { TSingleData } function TSingleData.GetValue: String; begin case fVarDefine.VarType of vtUINT8L: Result := FloatToStrF(fMap.ReadUint8l(GetTable, fVarDefine.Index, fVarDefine.Multipler), ffFixed, 15, NumberDecimals(fVarDefine.Multipler)); vtUINT8H: Result := FloatToStrF(fMap.ReadUint8h(GetTable, fVarDefine.Index, fVarDefine.Multipler), ffFixed, 15, NumberDecimals(fVarDefine.Multipler)); vtUINT16: Result := FloatToStrF(fMap.ReadUint16(GetTable, fVarDefine.Index, fVarDefine.Multipler), ffFixed, 15, NumberDecimals(fVarDefine.Multipler)); vtSINT16: Result := FloatToStrF(fMap.ReadSint16(GetTable, fVarDefine.Index, fVarDefine.Multipler),ffFixed, 15, NumberDecimals(fVarDefine.Multipler)); vtUINT32: Result := FloatToStrF(fMap.ReadUint32(GetTable, fVarDefine.Index, fVarDefine.Multipler), ffFixed, 15, NumberDecimals(fVarDefine.Multipler)); vtSINT32: Result := FloatToStrF(fMap.ReadSint32(GetTable, fVarDefine.Index, fVarDefine.Multipler), ffFixed, 15, NumberDecimals(fVarDefine.Multipler)); vtFLOAT: Result := FloatToStrF(fMap.ReadFloat(GetTable, fVarDefine.Index), ffGeneral, 15, 5); end; end; procedure TSingleData.SetValue(const aValue: String); var F: Single; I: Int64; W: DWord; Frame: IFrame; begin F := StrToFloatDef(aValue, 0); I := Round(F * fVarDefine.Multipler); case fVarDefine.VarType of vtUINT8L: begin W := (fMap.ReadUint16(GetTable, fVarDefine.Index) and $FF00) or I; Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, W, GetSetting.Timeout); end; vtUINT8H: begin W := fMap.ReadUint16(GetTable, fVarDefine.Index) and $FF or (I shl 8); Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, W, GetSetting.Timeout); end; vtUINT16: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, DWord(I), GetSetting.Timeout); vtSINT16: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, DWord(I), GetSetting.Timeout); vtUINT32: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); vtSINT32: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); end; if Frame <> nil then WriteToDevice(Frame); end; constructor TSingleData.Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); begin inherited Create(aVarDefine, aMap, aController, aSlaveId); TypeEditor := TTypeEditor.teFloatSpinEdit; end; { TPicklistData } constructor TPicklistData.Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); begin inherited Create(aVarDefine, aMap, aController, aSlaveId); TypeEditor := TTypeEditor.teComboBox; end; procedure TPicklistData.AfterConstruction; var P: Pointer; PickItem: IPickItem; V: Word; begin inherited AfterConstruction; {$IFDEF DEBUG} Assert(fVarDefine <> nil); Assert(Strings <> nil); {$ENDIF} for P in fVarDefine.Picklist do begin V := fVarDefine.Picklist.ExtractKey(P); PickItem := fVarDefine.Picklist.ExtractData(P); Strings.AddObject(Format('[%d] %s', [V, PickItem.ShortDescription]), TObject(Pointer(PickItem))); end; end; function TPicklistData.GetValue: String; var I, FoundIndex: Integer; begin I := 0; case fVarDefine.VarType of vtUINT8L: I := fMap.ReadUint8l(GetTable, fVarDefine.Index); vtUINT8H: I := fMap.ReadUint8h(GetTable, fVarDefine.Index); vtUINT16: I := fMap.ReadUint16(GetTable, fVarDefine.Index); vtSINT16: I := fMap.ReadSint16(GetTable, fVarDefine.Index); vtUINT32: I := fMap.ReadUint32(GetTable, fVarDefine.Index); vtSINT32: I := fMap.ReadSint32(GetTable, fVarDefine.Index); end; FoundIndex := fVarDefine.Picklist.IndexOf(I); if FoundIndex > -1 then Result := format('[%d] %s', [fVarDefine.Picklist.GetKey(FoundIndex), fVarDefine.Picklist.GetData(FoundIndex).ShortDescription]) else Result := format('[%d] %s', [fVarDefine.Picklist.GetKey(0), fVarDefine.Picklist.GetData(0).ShortDescription]); end; procedure TPicklistData.SetValue(const aValue: String); var FoundIndex: Integer; PickItem: IPickItem; I: Integer; W: DWord; Frame: IFrame; begin FoundIndex := Strings.IndexOf(aValue); if FoundIndex < 0 then Exit; PickItem := IPickItem(Pointer(Strings.Objects[FoundIndex])); if PickItem = nil then Exit; I := PickItem.Value; case fVarDefine.VarType of vtUINT8L: begin W := (fMap.ReadUint16(GetTable, fVarDefine.Index) and $FF00) or I; Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, W, GetSetting.Timeout); end; vtUINT8H: begin W := fMap.ReadUint16(GetTable, fVarDefine.Index) and $FF or (I shl 8); Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, W, GetSetting.Timeout); end; vtUINT16: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, DWord(I), GetSetting.Timeout); vtSINT16: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 1, DWord(I), GetSetting.Timeout); vtUINT32: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); vtSINT32: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); vtFLOAT: Frame := WriteMultiple(fSlaveId, fVarDefine.Index, 2, DWord(I), GetSetting.Timeout); end; if Frame <> nil then WriteToDevice(Frame); end; procedure TPicklistData.SetDescription(const aStrings: TStrings); var S: String; begin inherited SetDescription(aStrings); aStrings.BeginUpdate; try aStrings.Add('Список значений:'); for S in Strings do aStrings.Add(S); finally aStrings.EndUpdate; end; end; { TBitsData } function TBitsData.GetValue: String; begin case fVarDefine.VarType of vtBITMAP16: Result := Format('0x%.4x', [fMap.ReadBitmap16(GetTable, fVarDefine.Index)]); vtBITMAP32: Result := Format('0x%.8x', [fMap.ReadBitmap32(GetTable, fVarDefine.Index)]); end; end; procedure TBitsData.SetValue(const aValue: String); begin { TODO : Stub } end; constructor TBitsData.Create(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte); begin inherited Create(aVarDefine, aMap, aController, aSlaveId); fReadOnly := True; end; { TBitData } function TBitData.GetValue: String; var W: Dword; begin W := 0; case fBitsData.VarDefine.VarType of vtBITMAP16: W := fBitsData.fMap.ReadBitmap16(fBitsData.GetTable, fBitsData.VarDefine.Index); vtBITMAP32: W := fBitsData.fMap.ReadBitmap32(fBitsData.GetTable, fBitsData.VarDefine.Index); end; W := W and (1 shl fBit.Index); Result := Format('0x%.2x', [W]); if W > 0 then fOwner^.CheckState := TCheckState.csCheckedNormal else fOwner^.CheckState := TCheckState.csUncheckedNormal; end; procedure TBitData.SetValue(const aValue: String); var W: Dword; Frame: IFrame; begin case fBitsData.VarDefine.VarType of vtBITMAP16: begin W := fBitsData.fMap.ReadBitmap16(fBitsData.GetTable, fBitsData.VarDefine.Index); W := W {%H-}xor (1 shl fBit.Index); Frame := WriteMultiple(fBitsData.fSlaveId, fBitsData.fVarDefine.Index, 1, W, GetSetting.Timeout); end; vtBITMAP32: begin W := fBitsData.fMap.ReadBitmap32(fBitsData.GetTable, fBitsData.VarDefine.Index); W := W {%H-}xor (1 shl fBit.Index); Frame := WriteMultiple(fBitsData.fSlaveId, fBitsData.fVarDefine.Index, 2, W, GetSetting.Timeout); end; end; if Frame <> nil then fBitsData.WriteToDevice(Frame); end; constructor TBitData.Create(const aBit: IBitDefine; const aBitsData: TBitsData); begin inherited Create(aBit.ShortDescription); fBit := aBit; fBitsData := aBitsData; fReadOnly := aBitsData.VarDefine.TypeRegister = TTypeRegister.trInput; end; procedure TBitData.SetDescription(const aStrings: TStrings); var S: String; begin {$IFDEF DEBUG} Assert({%H-}aStrings <> nil); {$ENDIF} aStrings.BeginUpdate; try aStrings.Clear; aStrings.Add(Format('[%d] %s', [fBit.Index, fBit.ShortDescription])); for S in fBit.Description do aStrings.Add(S); finally aStrings.EndUpdate; end; end; {$ENDREGION Основные типы данных} {$REGION Фабрика узлов} constructor TGroupItemTreeNodeFactory.Create(const aTree: TBaseVirtualTree); begin inherited Create; fTree := aTree; end; function TGroupItemTreeNodeFactory.GetNode(const aVarDefine: IVarDefine; const aMap: IMap; const aController: IController; const aSlaveId: byte ): PVirtualNode; type TTypeData = (tdPickList, tdBits, tdString, tdSingle, tdInteger); var ConfigData: TGroupItemData; TypeData: TTypeData; P: Pointer; Node: PVirtualNode; Bit: IBitDefine; BitData: TBitData; begin {$IFDEF DEBUG} Assert(fTree <> nil); {$ENDIF} TypeData := TTypeData.tdInteger; if aVarDefine.Picklist.Count > 0 then TypeData := TTypeData.tdPickList else if (aVarDefine.VarType = TVarType.vtBITMAP16) or (aVarDefine.VarType = TVarType.vtBITMAP32) then TypeData := TTypeData.tdBits else if aVarDefine.VarType = TVarType.vtIO_DATA then TypeData := TTypeData.tdString else if (aVarDefine.Multipler > 1) or (aVarDefine.VarType = TVarType.vtFLOAT) then TypeData := TTypeData.tdSingle; case TypeData of tdPickList: begin ConfigData := TPickListData.Create(aVarDefine, aMap, aController, aSlaveId); Result := fTree.AddChild(nil, ConfigData); end; tdBits: begin ConfigData := TBitsData.Create(aVarDefine, aMap, aController, aSlaveId); Result := fTree.AddChild(nil, ConfigData); // Биты for P in aVarDefine.Bits do begin Bit := aVarDefine.Bits.ExtractData(P); BitData := TBitData.Create(Bit, ConfigData as TBitsData); Node := fTree.AddChild(Result, BitData); Node^.CheckType := ctCheckBox; BitData.Owner := Node; end; end; tdString: begin ConfigData := TStringData.Create(aVarDefine, aMap, aController, aSlaveId); Result := fTree.AddChild(nil, ConfigData); end; tdSingle: begin ConfigData := TSingleData.Create(aVarDefine, aMap, aController, aSlaveId); Result := fTree.AddChild(nil, ConfigData); end; tdInteger: begin ConfigData := TIntegerData.Create(aVarDefine, aMap, aController, aSlaveId); Result := fTree.AddChild(nil, ConfigData); end; end; end; {$ENDREGION Фабрика узлов} end.
{------------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is SynUnicode.pas by Maël Hörz, released 2004-05-30. All Rights Reserved. Contributors to the SynEdit and mwEdit projects are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. ------------------------------------------------------------------------------} unit SynUnicode; {$I SynEdit.inc} interface uses Windows, Messages, Controls, Forms, Graphics, Clipbrd, Types, Classes, SysUtils, TypInfo; const UTF8BOM: array[0..2] of Byte = ($EF, $BB, $BF); UTF16BOMLE: array[0..1] of Byte = ($FF, $FE); UTF16BOMBE: array[0..1] of Byte = ($FE, $FF); UTF32BOMLE: array[0..3] of Byte = ($FF, $FE, $00, $00); UTF32BOMBE: array[0..3] of Byte = ($00, $00, $FE, $FF); const WideNull = WideChar(#0); WideTabulator = WideChar(#9); WideSpace = WideChar(#32); // logical line breaks WideLF = WideChar(#10); WideLineFeed = WideChar(#10); WideVerticalTab = WideChar(#11); WideFormFeed = WideChar(#12); WideCR = WideChar(#13); WideCarriageReturn = WideChar(#13); WideCRLF = string(#13#10); WideLineSeparator = WideChar($2028); WideParagraphSeparator = WideChar($2029); { functions taken from JCLUnicode.pas } procedure StrSwapByteOrder(Str: PWideChar); { Unicode streaming-support } type TSynEncoding = (seUTF8, seUTF16LE, seUTF16BE, seAnsi); TSynEncodings = set of TSynEncoding; function IsAnsiOnly(const WS: string): Boolean; function IsUTF8(Stream: TStream; out WithBOM: Boolean; BytesToCheck: integer = $4000): Boolean; overload; function IsUTF8(const FileName: string; out WithBOM: Boolean; BytesToCheck: integer = $4000): Boolean; overload; function IsUTF8(const Bytes: TBytes; Start: Integer = 0; BytesToCheck: integer = $4000): Boolean; overload; function GetEncoding(const FileName: string; out WithBOM: Boolean): TEncoding; overload; function GetEncoding(Stream: TStream; out WithBOM: Boolean): TEncoding; overload; function ClipboardProvidesText: Boolean; function GetClipboardText: string; procedure SetClipboardText(const Text: string); { misc functions } function IsWideCharMappableToAnsi(const WC: WideChar): Boolean; var UserLocaleName: array [0..LOCALE_NAME_MAX_LENGTH - 1] of Char; implementation uses SynEditTextBuffer, Math, SysConst, RTLConsts; // exchanges in each character of the given string the low order and high order // byte to go from LSB to MSB and vice versa. // EAX contains address of string procedure StrSwapByteOrder(Str: PWideChar); var P: PWord; begin P := PWord(Str); while P^ <> 0 do begin P^ := MakeWord(HiByte(P^), LoByte(P^)); Inc(P); end; end; function IsAnsiOnly(const WS: string): Boolean; var UsedDefaultChar: BOOL; begin WideCharToMultiByte(DefaultSystemCodePage, 0, PWideChar(WS), Length(WS), nil, 0, nil, @UsedDefaultChar); Result := not UsedDefaultChar; end; function IsUTF8(const FileName: string; out WithBOM: Boolean; BytesToCheck: integer): Boolean; var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := IsUTF8(Stream, WithBOM, BytesToCheck); finally Stream.Free; end; end; // checks for a BOM in UTF-8 format or searches the first 4096 bytes for // typical UTF-8 octet sequences function IsUTF8(Stream: TStream; out WithBOM: Boolean; BytesToCheck: integer): Boolean; var Buffer: TBytes; BufferSize: Integer; BomLen: Integer; Encoding: TEncoding; begin // if Stream is nil, let Delphi raise the exception, by accessing Stream, // to signal an invalid result // start analysis at actual Stream.Position BufferSize := Min(BytesToCheck, Stream.Size - Stream.Position); // if no special characteristics are found it is not UTF-8 Result := False; WithBOM := False; if BufferSize > 0 then begin SetLength(Buffer, BufferSize); Stream.Read(Buffer, 0, BufferSize); Stream.Seek(-BufferSize, soCurrent); { first search for BOM } Encoding := nil; BomLen := TEncoding.GetBufferEncoding(Buffer, Encoding); WithBOM := BOMLen > 0; if Encoding = TEncoding.UTF8 then Exit(True) else if WithBom then Exit(False); { Now check the content for UTF8 sequences } Result := IsUtf8(Buffer, 0, BytesToCheck); end; end; function IsUTF8(const Bytes: TBytes; Start: Integer; BytesToCheck: integer): Boolean; overload; const MinimumCountOfUTF8Strings = 1; var Len, i, FoundUTF8Strings: Integer; // 3 trailing bytes are the maximum in valid UTF-8 streams, // so a count of 4 trailing bytes is enough to detect invalid UTF-8 streams function CountOfTrailingBytes: Integer; begin Result := 0; inc(i); while (i < Len) and (Result < 4) do begin if Bytes[i] in [$80..$BF] then inc(Result) else Break; inc(i); end; end; begin { NOTE: There is no 100% save way to detect UTF-8 streams. The bigger MinimumCountOfUTF8Strings, the lower is the probability of a false positive. On the other hand, a big MinimumCountOfUTF8Strings makes it unlikely to detect files with only little usage of non US-ASCII chars, like usual in European languages. } Result := False; Len := Min(Start + BytesToCheck, Length(Bytes)); FoundUTF8Strings := 0; i := Start; while i < Len do begin case Bytes[i] of $00..$7F: // skip US-ASCII characters as they could belong to various charsets ; $C2..$DF: if CountOfTrailingBytes = 1 then inc(FoundUTF8Strings) else Break; $E0: begin inc(i); if (i < Len) and (Bytes[i] in [$A0..$BF]) and (CountOfTrailingBytes = 1) then inc(FoundUTF8Strings) else Break; end; $E1..$EC, $EE..$EF: if CountOfTrailingBytes = 2 then inc(FoundUTF8Strings) else Break; $ED: begin inc(i); if (i < Len) and (Bytes[i] in [$80..$9F]) and (CountOfTrailingBytes = 1) then inc(FoundUTF8Strings) else Break; end; $F0: begin inc(i); if (i < Len) and (Bytes[i] in [$90..$BF]) and (CountOfTrailingBytes = 2) then inc(FoundUTF8Strings) else Break; end; $F1..$F3: if CountOfTrailingBytes = 3 then inc(FoundUTF8Strings) else Break; $F4: begin inc(i); if (i < Len) and (Bytes[i] in [$80..$8F]) and (CountOfTrailingBytes = 2) then inc(FoundUTF8Strings) else Break; end; $C0, $C1, $F5..$FF: // invalid UTF-8 bytes Break; $80..$BF: // trailing bytes are consumed when handling leading bytes, // any occurence of "orphaned" trailing bytes is invalid UTF-8 Break; end; if FoundUTF8Strings >= MinimumCountOfUTF8Strings then begin Result := True; Break; end; inc(i); end; end; function GetEncoding(const FileName: string; out WithBOM: Boolean): TEncoding; var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := GetEncoding(Stream, WithBOM); finally Stream.Free; end; end; function GetEncoding(Stream: TStream; out WithBOM: Boolean): TEncoding; function TBytesEqual(A, B: TBytes; Len: Integer): Boolean; Var I: Integer; begin Result := True; for I := 0 to Len - 1 do if A[i] <> B[i] then Exit(False) end; var Buffer: TBytes; Size: Integer; Preamble: TBytes; begin // if Stream is nil, let Delphi raise the exception, by accessing Stream, // to signal an invalid result // start analysis at actual Stream.Position Size := Stream.Size - Stream.Position; // if no special characteristics are found it is probably ANSI Result := TEncoding.ANSI; if IsUTF8(Stream, WithBOM) then Exit(TEncoding.UTF8); { try to detect UTF-16 by finding a BOM in UTF-16 format } // Check for Unicode Preamble := TEncoding.Unicode.GetPreamble; if Size >= Length(Preamble) then begin Setlength(Buffer, Length(Preamble)); Stream.Read(Buffer, 0, Length(Preamble)); Stream.Seek(-Length(Preamble), soCurrent); if TBytesEqual(Preamble, Buffer, Length(Preamble)) then begin WithBOM := True; Exit(TEncoding.Unicode); end; end; // Check for BigEndianUnicode Preamble := TEncoding.BigEndianUnicode.GetPreamble; if Size >= Length(Preamble) then begin Setlength(Buffer, Length(Preamble)); Stream.Read(Buffer, 0, Length(Preamble)); Stream.Seek(-Length(Preamble), soCurrent); if TBytesEqual(Preamble, Buffer, Length(Preamble)) then begin WithBOM := True; Exit(TEncoding.BigEndianUnicode); end; end; end; function ClipboardProvidesText: Boolean; begin Result := IsClipboardFormatAvailable(CF_UNICODETEXT); end; function GetClipboardText: string; begin Result := Clipboard.AsText; end; procedure SetClipboardText(const Text: string); begin Clipboard.AsText := Text; end; function IsWideCharMappableToAnsi(const WC: WideChar): Boolean; var UsedDefaultChar: BOOL; begin WideCharToMultiByte(DefaultSystemCodePage, 0, PWideChar(@WC), 1, nil, 0, nil, @UsedDefaultChar); Result := not UsedDefaultChar; end; initialization Assert(TOSVersion.Check(6), 'Unsupported Windows version. Windows Vista or higher required'); if LCIDToLocaleName(GetUserDefaultLCID, UserLocaleName, LOCALE_NAME_MAX_LENGTH, 0) = 0 then RaiseLastOSError; end.
(* ***************************************************************************** Copyright (C) 2010-2014 - Bambu Code SA de CV - Ing. Luis Carrasco Este archivo pertenece al proyecto de codigo abierto de Bambu Code: http://bambucode.com/codigoabierto La licencia de este codigo fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA ***************************************************************************** *) unit TestClaseOpenSSL; interface uses TestFramework, TestPrueba, ClaseOpenSSL; type TestTOpenSSL = class(TTestPrueba) strict private fOpenSSL: TOpenSSL; fArchivoLlavePrivada: String; fClaveLlavePrivada: String; private function EncriptarUsandoOpenSSL(aCadena: String; aTipoEncripcion: TTipoDigestionOpenSSL): string; public procedure SetUp; override; procedure TearDown; override; published procedure HacerDigestion_TipoMD5_FuncioneCorrectamente; procedure HacerDigestion_TipoSHA1_FuncioneCorrectamente; procedure HacerDigestion_ConClaveIncorrecta_CauseExcepcion; procedure ObtenerCertificado_CertificadoDePrueba_RegreseElCertificadoConPropiedades; procedure ObtenerModulusDeCertificado_DeCertificado_RegreseValorCorrecto; procedure ObtenerModulusDeLlavePrivada_DeLlave_RegreseValorCorrecto; end; implementation uses Windows, SysUtils, Classes, FacturaTipos, Forms, OpenSSLUtils, DateUtils, ConstantesFixtures, CodeSiteLogging; procedure TestTOpenSSL.SetUp; begin inherited; fArchivoLlavePrivada := fRutaFixtures + '\openssl\aaa010101aaa_csd_01.key'; fClaveLlavePrivada := '12345678a'; // Creamos el objeto OpenSSL fOpenSSL := TOpenSSL.Create(); end; procedure TestTOpenSSL.TearDown; begin FreeAndNil(fOpenSSL); end; function TestTOpenSSL.EncriptarUsandoOpenSSL(aCadena: String; aTipoEncripcion: TTipoDigestionOpenSSL): string; var sResultadoMD5OpenSSL: WideString; TipoEncripcion: String; const _ARCHIVO_CERTIFICADO = 'aaa010101aaa_CSD_01.cer'; _ARCHIVO_LLAVE_PEM = 'aaa010101aaa_CSD_01.pem'; _ARCHIVO_CADENA_TEMPORAL = 'cadena_hacerdigestion.txt'; _ARCHIVO_TEMPORAL_RESULTADO_OPENSSL = 'cadena_hacerdigestion.txt'; begin Assert(FileExists(fArchivoLlavePrivada), 'No existio el archivo de llave privada:' + fArchivoLlavePrivada); case aTipoEncripcion of tdMD5: TipoEncripcion:='md5'; tdSHA1: TipoEncripcion:='sha1'; end; // Borramos los archivos temporales que vamos a usar si acaso existen (de pruebas pasadas) BorrarArchivoTempSiExiste(_ARCHIVO_CADENA_TEMPORAL); BorrarArchivoTempSiExiste(_ARCHIVO_TEMPORAL_RESULTADO_OPENSSL); BorrarArchivoTempSiExiste(TipoEncripcion + '_cadena_de_prueba.bin'); Sleep(100); // Guardamos el contenido de la cadena de prueba a un archivo temporal guardarArchivoEnUTF8(UTF8Encode(aCadena), _ARCHIVO_CADENA_TEMPORAL); // Generamos el archivo PEM de la llave privada para usarla con OpenSSL EjecutarComandoOpenSSL('pkcs8 -inform DER -in ' + fArchivoLlavePrivada + ' -passin pass:' + fClaveLlavePrivada + ' -out ' + fDirTemporal + _ARCHIVO_LLAVE_PEM); // Primero hacemos la digestion usando openssl.exe y la linea de comandos EjecutarComandoOpenSSL('dgst -' + TipoEncripcion + ' -sign "' + fDirTemporal + _ARCHIVO_LLAVE_PEM + '" -out "' + fDirTemporal + '\' + TipoEncripcion + '_cadena_de_prueba.bin" "' + fDirTemporal + _ARCHIVO_CADENA_TEMPORAL + '"'); // Convertimos el resultado (archivo binario) a base64 EjecutarComandoOpenSSL(' enc -base64 -in "' + fDirTemporal + TipoEncripcion + '_cadena_de_prueba.bin" -out "' + fDirTemporal + _ARCHIVO_TEMPORAL_RESULTADO_OPENSSL + '"'); // Quitamos los retornos de carro ya que la codificacion Base64 de OpenSSL la regresa con ENTERs sResultadoMD5OpenSSL := QuitarRetornos(leerContenidoDeArchivo(fDirTemporal + _ARCHIVO_TEMPORAL_RESULTADO_OPENSSL)); //CodeSite.Send(TipoEncripcion + ' OpenSSL', sResultadoMD5OpenSSL); Result := sResultadoMD5OpenSSL; end; procedure TestTOpenSSL.HacerDigestion_TipoMD5_FuncioneCorrectamente; var sResultadoMD5DeClase, sResultadoMD5OpenSSL: WideString; const // Se puede probar la efectividad del metodo cambiando la siguiente cadena // la cual debe ser la misma entre el resultado de la clase y de comandos manuales de Openssl.exe _CADENA_DE_PRUEBA = '||2.0|AA|2|2010-11-03T13:36:23|35|2008|ingreso|UNA SOLA EXHIBICIÓN|13360.00|0.00|15497.60|FIFC000101AM1|CONTRIBUYENTE DE PRUEBA' + ' FICTICIO FICTICIO|1|99|CENTRO|SAN MIGUEL XOXTLA|SAN MIGUEL XOXTLA|PUEBLA|MÉXICO|72620|CPC400101CM9|CONTRIBUYENTE DE PRUEBA CUATRO' + ' SA DE CV|AV HIDALGO|77|GUERRERO|DISTRITO FEDERAL|México|06300|1.00|PZ|1|Mac Book Air|10000.00|10000.00|3.00|PZ|2|Magic Mouse|900.00' + '|2700.00|5.50|HRS|3|Servicio de soporte técnico|120.00|660.00|IVA|16.00|1600.00|IVA|16.00|432.00|IVA|16.00|105.60|2137.60||'; begin // Encriptamos la cadena de prueba usando OpenSSL para comparar los resultados sResultadoMD5OpenSSL:=EncriptarUsandoOpenSSL(_CADENA_DE_PRUEBA, tdMD5); {$IF Compilerversion < 20} // Si es Delphi 2009 o menor codificamos el String usando la funcion de UTF8Encode // en Delphi XE2 la cadena ya viene como tipo String que es igual que UnicodeString _CADENA_DE_PRUEBA := UTF8Encode(_CADENA_DE_PRUEBA); {$IFEND} // Ahora, hacemos la digestion con la libreria sResultadoMD5DeClase := fOpenSSL.HacerDigestion(fArchivoLlavePrivada, fClaveLlavePrivada, _CADENA_DE_PRUEBA, tdMD5); //CodeSite.Send('MD5 TFacturacion', sResultadoMD5DeClase); // Comparamos los resultados (sin retornos de carro), los cuales deben de ser los mismos CheckEquals(sResultadoMD5OpenSSL, sResultadoMD5DeClase, 'La digestion MD5 de la clase no fue la misma que la de OpenSSL'); end; procedure TestTOpenSSL.HacerDigestion_TipoSHA1_FuncioneCorrectamente; var sResultadoSHADeClase, sResultadoSHAOpenSSL: WideString; const _CADENA_DE_PRUEBA = '||2.0|AA|2|2010-11-03T13:36:23|35|2008|ingreso|UNA SOLA EXHIBICIÓN|13360.00|0.00|15497.60|FIFC000101AM1|CONTRIBUYENTE DE PRUEBA' + ' FICTICIO FICTICIO|1|99|CENTRO|SAN MIGUEL XOXTLA|SAN MIGUEL XOXTLA|PUEBLA|MÉXICO|72620|CPC400101CM9|CONTRIBUYENTE DE PRUEBA CUATRO' + ' SA DE CV|AV HIDALGO|77|GUERRERO|DISTRITO FEDERAL|México|06300|1.00|PZ|1|Mac Book Air|10000.00|10000.00|3.00|PZ|2|Magic Mouse|900.00' + '|2700.00|5.50|HRS|3|Servicio de soporte técnico|120.00|660.00|IVA|16.00|1600.00|IVA|16.00|432.00|IVA|16.00|105.60|2137.60||'; begin // Encriptamos la cadena de prueba usando OpenSSL para comparar los resultados sResultadoSHAOpenSSL:=EncriptarUsandoOpenSSL(_CADENA_DE_PRUEBA, tdSHA1); {$IF Compilerversion < 20} // Si es Delphi 2009 o menor codificamos el String usando la funcion de UTF8Encode // en Delphi XE2 la cadena ya viene como tipo String que es igual que UnicodeString _CADENA_DE_PRUEBA := UTF8Encode(_CADENA_DE_PRUEBA); {$IFEND} // Ahora, hacemos la digestion con la libreria sResultadoSHADeClase := fOpenSSL.HacerDigestion(fArchivoLlavePrivada, fClaveLlavePrivada, _CADENA_DE_PRUEBA, tdSHA1); // Comparamos los resultados (sin retornos de carro), los cuales deben de ser los mismos CheckEquals(sResultadoSHAOpenSSL, sResultadoSHADeClase, 'La digestion SHA1 de la clase no fue la misma que la de OpenSSL'); end; procedure TestTOpenSSL.HacerDigestion_ConClaveIncorrecta_CauseExcepcion; var fOpenSSL2: TOpenSSL; bExcepcionLanzada: Boolean; begin // Creamos un nuevo objeto OpenSSL con una clave incorrecta a proposito bExcepcionLanzada := False; fOpenSSL2 := TOpenSSL.Create(); try fOpenSSL2.HacerDigestion(fArchivoLlavePrivada, 'claveincorrectaintencional', 'Cadena', tdMD5); except On E: ELlavePrivadaClaveIncorrectaException do begin bExcepcionLanzada := True; end; end; CheckTrue(bExcepcionLanzada, 'No se lanzo excepcion cuando se especifico clave privada incorrecta.'); FreeAndNil(fOpenSSL2); end; procedure TestTOpenSSL.ObtenerCertificado_CertificadoDePrueba_RegreseElCertificadoConPropiedades; var Certificado: TX509Certificate; dtInicioVigencia, dtFinVigencia: TDateTime; sNumSerie: String; function NombreMesANumero(sMes: String) : Integer; begin sMes:=Uppercase(sMes); Result:=0; if sMes = 'JAN' then Result:=1; if sMes = 'FEB' then Result:=2; if sMes = 'MAR' then Result:=3; if sMes = 'APR' then Result:=4; if sMes = 'MAY' then Result:=5; if sMes = 'JUN' then Result:=6; if sMes = 'JUL' then Result:=7; if sMes = 'AUG' then Result:=8; if sMes = 'SEP' then Result:=9; if sMes = 'OCT' then Result:=10; if sMes = 'NOV' then Result:=11; if sMes = 'DEC' then Result:=12; end; function leerFechaDeArchivo(sRuta: String) : TDateTime; var sFecha, sTxt, sMes, sHora, sAno, sDia, hora, min, seg: String; begin // Leemos el archivo y convertimos el contenido a una fecha de Delphi sTxt:=leerContenidoDeArchivo(sRuta); // Quitamos la parte inicial (ej:notBefore=) sFecha:=Copy(sTxt,AnsiPos('=',sTxt)+1, Length(sTxt)); //Ej: Jul 30 16:58:40 2010 GMT sMes:=Copy(sFecha, 1, 3); sDia:=Copy(sFecha, 5, 2); sHora:=Copy(sFecha, 8, 8); sAno:=Copy(sFecha, 17, 4); hora := Copy(sHora, 1, 2); min := Copy(sHora, 4, 2); seg := Copy(sHora, 7, 2); // Procesamos la fecha que regresa OpenSSL para convertirla a formato Delphi Result:=EncodeDateTime(StrToInt(sAno), NombreMesANumero(sMes), StrToInt(sDia), StrToInt(hora), StrToInt(min), StrToInt(seg), 0); end; // Convertimos el num de serie que regresa OpenSSL en hexadecimal // a integer de Delphi. Gracias a usuario 'dado' por su ayuda // para obtener este dato: http://www.clubdelphi.com/foros/showthread.php?t=66807&page=14 function ValidarSerieDeOpenSSL(Serie: String) : String; var n: Integer; NumSerie: String; begin NumSerie := ''; n := 9; while n <= length(Serie) do begin NumSerie := NumSerie + Serie[n]; n := n + 2; end; Result:=NumSerie; end; const _LONGITUD_NUMERO_SERIE_CERTIFICADO = 20; begin BorrarArchivoTempSiExiste(fDirTemporal + 'VigenciaInicio.txt'); Assert(FileExists(fRutaFixtures + _RUTA_CERTIFICADO), 'Debe existir el certificado antes de poder ejecutar la prueba'); // Procesamos el certificado con el OpenSSL.exe para obtener los datos y // poder corroborarlos... EjecutarComandoOpenSSL(' x509 -inform DER -in "' + fRutaFixtures + _RUTA_CERTIFICADO + '" -noout -startdate > "' + fDirTemporal + 'VigenciaInicio.txt" '); dtInicioVigencia:=leerFechaDeArchivo(fDirTemporal + 'VigenciaInicio.txt'); // Fin de vigencia EjecutarComandoOpenSSL(' x509 -inform DER -in "' + fRutaFixtures + _RUTA_CERTIFICADO + '" -noout -enddate > "' + fDirTemporal + 'VigenciaFin.txt" '); dtFinVigencia:=leerFechaDeArchivo(fDirTemporal + 'VigenciaFin.txt'); // Numero de Serie EjecutarComandoOpenSSL(' x509 -inform DER -in "' + fRutaFixtures + _RUTA_CERTIFICADO + '" -noout -serial > "' + fDirTemporal + 'Serial.txt" '); // "Limpiamos" el Serie que nos da el OpenSSL ya que incluye caracteres de mas... sNumSerie:= ValidarSerieDeOpenSSL(leerContenidoDeArchivo(fDirTemporal + 'Serial.txt')); Certificado := fOpenSSL.ObtenerCertificado(fRutaFixtures + _RUTA_CERTIFICADO); try CodeSite.Send(Certificado.AsBase64); CheckTrue(Certificado <> nil, 'Se debio haber obtenido una instancia al certificado'); // Checamos las propiedades que nos interesan CheckEquals(dtInicioVigencia, Certificado.NotBefore, 'El inicio de vigencia del certificado no fue el mismo que regreso OpenSSL'); CheckEquals(dtFinVigencia, Certificado.NotAfter, 'El fin de vigencia del certificado no fue el mismo que regreso OpenSSL'); CheckEquals(sNumSerie, Certificado.SerialNumber, 'El numero de serie del certificado no fue el mismo que regreso OpenSSL'); // Checamos que la longitud del Numero de Serie sea de 20 (especificada en el RFC 3280 de la especificacion X509) CheckEquals(_LONGITUD_NUMERO_SERIE_CERTIFICADO, Length(Certificado.SerialNumber), 'La longitud del numero de serie no fue la correcta'); finally FreeAndNil(Certificado); end; end; procedure TestTOpenSSL.ObtenerModulusDeCertificado_DeCertificado_RegreseValorCorrecto; var openSSL: TOpenSSL; modulusCertificado, modulusCertificadoEsperado: string; begin // Obtenemos el modulus del Certificado usando OpenSSL.exe EjecutarComandoOpenSSL(' x509 -inform DER -in "' + fRutaFixtures + _RUTA_CERTIFICADO + '" -noout -modulus > "' + fDirTemporal + 'ModulusCertificado.txt" '); modulusCertificadoEsperado := leerContenidoDeArchivo(fDirTemporal + 'ModulusCertificado.txt'); // Quitamos la palabra "Modulus=" que regresa OpenSSL modulusCertificadoEsperado := StringReplace(modulusCertificadoEsperado, 'Modulus=', '', [rfReplaceAll]); try openSSL := TOpenSSL.Create; modulusCertificado := openSSL.ObtenerModulusDeCertificado(fRutaFixtures + _RUTA_CERTIFICADO); CheckTrue(modulusCertificado <> '', 'No se obtuvo el Modulus del Certificado'); CheckEquals(modulusCertificadoEsperado, modulusCertificado, 'El modulus del certificado obtenido no fue el mismo que regresó OpenSSL.exe'); finally openSSL.Free; end; end; procedure TestTOpenSSL.ObtenerModulusDeLlavePrivada_DeLlave_RegreseValorCorrecto; var openSSL: TOpenSSL; modulusDeLlave, modulusDeLlaveEsperado: string; begin // Desencriptamos la llave privada EjecutarComandoOpenSSL(' pkcs8 -inform DER -in "' + fArchivoLlavePrivada + '" -passin pass:'+ fClaveLlavePrivada + ' -out "' + fDirTemporal + 'llaveprivada.key" '); // Obtenemos el modulus de la Llave Privada usando OpenSSL.exe para corroborarlo EjecutarComandoOpenSSL(' rsa -in "' + fDirTemporal + 'llaveprivada.key"' + ' -noout -modulus > "' + fDirTemporal + 'ModulusLlave.txt" '); modulusDeLlaveEsperado := leerContenidoDeArchivo(fDirTemporal + 'ModulusLlave.txt'); // Quitamos la palabra "Modulus=" que regresa OpenSSL modulusDeLlaveEsperado := StringReplace(modulusDeLlaveEsperado, 'Modulus=', '', [rfReplaceAll]); try openSSL := TOpenSSL.Create; modulusDeLlave := openSSL.ObtenerModulusDeLlavePrivada(fArchivoLlavePrivada, fClaveLlavePrivada); CheckTrue(modulusDeLlave <> '', 'No se obtuvo el Modulus de la Llave Privada'); CheckEquals(modulusDeLlaveEsperado, modulusDeLlave, 'El modulus de la Llave Privada obtenido no fue el mismo que regresó OpenSSL.exe'); finally openSSL.Free; end; end; initialization // Registra la prueba de esta unidad en la suite de pruebas RegisterTest(TestTOpenSSL.Suite); end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2016 Vincent Parrett } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Assert.Ex; // This unit should contain DUnitX specific Assert commands and mechanisms // in order to keep DUnitX.Assert framework neutral and usable in other // test frameworks such as DUnit. interface {$I DUnitX.inc} uses DUnitX.Assert, DUnitX.ComparableFormat; type Assert = class(DUnitX.Assert.Assert) private class procedure FailStrCompare(const expected, actual: string; const compformat: TDUnitXComparableFormatClass = nil; const message : string = ''; const errorAddrs : pointer = nil); public class procedure AreEqual(const expected, actual : string; const compformat: TDUnitXComparableFormatClass; const ignoreCase : boolean; const message : string = ''); overload; class procedure AreEqual(const expected, actual : string; const compformat: TDUnitXComparableFormatClass; const message : string = ''); overload; //Reintroduced from Assert to throw ETestFailureStrCompare class procedure AreEqual(const expected : string; const actual : string; const ignoreCase : boolean; const message : string = ''); reintroduce; overload; //Reintroduced from Assert to throw ETestFailureStrCompare class procedure AreEqual(const expected : string; const actual : string; const message : string = ''); reintroduce; overload; end; implementation uses {$IFDEF USE_NS} System.SysUtils, {$ELSE} SysUtils, {$ENDIF} DUnitX.ResStrs, DUnitX.Exceptions; class procedure Assert.AreEqual(const expected, actual: string; const compformat: TDUnitXComparableFormatClass; const ignoreCase: boolean; const message: string); begin DoAssert; if ignoreCase then begin if not SameText(expected,actual) then FailStrCompare(expected, actual, compformat, message, ReturnAddress); end else if not SameStr(expected,actual) then FailStrCompare(expected, actual, compformat, message, ReturnAddress); end; class procedure Assert.AreEqual(const expected, actual: string; const compformat: TDUnitXComparableFormatClass; const message: string); begin AreEqual(expected, actual, compformat, IgnoreCaseDefault, message); end; class procedure Assert.AreEqual(const expected, actual : string; const ignoreCase : boolean; const message: string); begin AreEqual(expected, actual, nil, ignoreCase, message); end; class procedure Assert.AreEqual(const expected : string; const actual : string; const message : string); begin Assert.AreEqual(expected, actual, IgnoreCaseDefault, message); end; class procedure Assert.FailStrCompare(const expected, actual: string; const compformat : TDUnitXComparableFormatClass; const message: string; const errorAddrs: pointer); begin //If we have been given a return then use it. (makes the exception appear on level above in the stack) if errorAddrs <> nil then raise ETestFailureStrCompare.Create(expected, actual, message, compformat) at errorAddrs else //Otherwise use the return address we can currently get to for where to raise the exception raise ETestFailureStrCompare.Create(expected, actual, message, compformat) at ReturnAddress; end; end.
program programadores; procedure leerDatos(var legajo:integer; salario:real); begin writeln('Ingrese el nro de legajo y el salario'); readln(legajo); readln(salario); end; procedure actualizarMaximo(nuevoLegajo:integer; nuevoSalario: real; var maxLegajo:integer); var maxSalario:real; begin if(nuevoLegajo> maxLegajo)then begin maxLegajo:=nuevoLegajo; maxSalario:=nuevoSalario end; end; var legajo,maxLegajo,i:integer; salario,maxSalario:real; begin sumaSalarios:=0; for i:=1 to 130 do begin leerDatos(salario,legajo); actualizarMaximo(legajo,salario,maxLegajo); sumaSalarios:=sumaSalarios + salario; end; writeln('En todo el mes se gastan ',sumaSalarios, ' pesos'); writeln('El salario del empleado mas nuev es ',maxSalario); end. { Error linea 21, la variable sumaSalarios no esta declarada. Error linea 23, los argumentos pasados no corresponen con el tipo de dato que se espera en leerDatos() Error linea 2 en procedure leerDatos. La variable salario es pasada por valor, es decir el input leido no modifica la variable en el main. Error semantico. Error linea 12, maxLegajo no tiene valor por lo que hacer la comparacion con nuevoLegajo es imposible. Error linea 25, sumaSalarios no esta declarada, no es posible hacer la asignacion. Ademas salario tampoco tiene valor. Error linea 27, sumaSalarios no esta decalarada... Error linea 28, maxSalario no esta inicializado. }
unit blockinfobyteModel; interface type TblockinfobyteModel = class public bytechapter_content_decompress_lengt12: TArray<Byte>; bytechapter_file_size13: TArray<Byte>; bytechapter_index: TArray<Byte>; bytechapter_level: TArray<Byte>; bytechapter_name: TArray<Byte>; bytecompress_block_size: TArray<Byte>; bytecompress_type: TArray<Byte>; bytedatatype: TArray<Byte>; byteencoding: TArray<Byte>; bytefile_list_offset11: TArray<Byte>; bytelocale: TArray<Byte>; bytemin_tip: TArray<Byte>; bytemin_version: TArray<Byte>; constructor Create; end; implementation constructor TblockinfobyteModel.Create; begin SetLength(Self.bytemin_version, 4); SetLength(self.bytecompress_type, 4); SetLength(self.bytecompress_block_size, 4); SetLength(self.bytedatatype, 4); SetLength(self.bytelocale, 4); SetLength(self.byteencoding, 4); SetLength(self.bytechapter_index, 4); SetLength(self.bytechapter_level, 4); SetLength(self.bytefile_list_offset11, 4); SetLength(self.bytechapter_content_decompress_lengt12, 4); SetLength(self.bytechapter_file_size13, 4); end; end.
unit TSTOZeroImpl; interface Uses Windows, HsInterfaceEx, TSTOZeroIntf; Type TZeroFileHeaderClass = Class Of TZeroFileHeader; TZeroFileDatasClass = Class Of TZeroFileDatas; TArchivedFileDatasClass = Class Of TArchivedFileDatas; TArchivedFileData = Class(TInterfacedObjectEx, IArchivedFileData) Private FDataLength : Word; FFileName1 : AnsiString; FFileExtension : AnsiString; FFileName2 : AnsiString; FFileSize : DWord; FWord1 : Word; FArchiveFileId : Word; Protected Procedure Created(); OverRide; Function GetDataLength() : Word; Procedure SetDataLength(Const ADataLength : Word); Function GetFileName1() : AnsiString; Procedure SetFileName1(Const AFileName1 : AnsiString); Function GetFileExtension() : AnsiString; Procedure SetFileExtension(Const AFileExtension : AnsiString); Function GetFileName2() : AnsiString; Procedure SetFileName2(Const AFileName2 : AnsiString); Function GetFileSize() : DWord; Procedure SetFileSize(Const AFileSize : DWord); Function GetWord1() : Word; Procedure SetWord1(Const AWord1 : Word); Function GetArchiveFileId() : Word; Procedure SetArchiveFileId(Const AArchiveFileId : Word); Public Property DataLength : Word Read GetDataLength Write SetDataLength; Property FileName1 : AnsiString Read GetFileName1 Write SetFileName1; Property FileExtension : AnsiString Read GetFileExtension Write SetFileExtension; Property FileName2 : AnsiString Read GetFileName2 Write SetFileName2; Property FileSize : DWord Read GetFileSize Write SetFileSize; Property Word1 : Word Read GetWord1 Write SetWord1; Property ArchiveFileId : Word Read GetArchiveFileId Write SetArchiveFileId; Procedure Assign(ASource : TObject); ReIntroduce; Virtual; Procedure Clear(); End; TArchivedFileDatas = Class(TInterfaceListEx, IArchivedFileDatas) Private Function InternalSort(Item1, Item2 : IInterfaceEx) : Integer; Protected Function GetItemClass() : TInterfacedObjectExClass; OverRide; Function Get(Index : Integer) : IArchivedFileData; OverLoad; Procedure Put(Index : Integer; Const Item : IArchivedFileData); OverLoad; Function Add() : IArchivedFileData; ReIntroduce; OverLoad; Function Add(Const AItem : IArchivedFileData) : Integer; OverLoad; Procedure Sort(); End; TZeroFileData = Class(TInterfacedObjectEx, IZeroFileData) Private FDataLength : Word; FFileName : AnsiString; FByte1 : Byte; FCrc32 : DWord; FArchivedFiles : IArchivedFileDatas; Protected Procedure Created(); OverRide; Function GetArchivedFileDatasClass() : TArchivedFileDatasClass; Virtual; Function GetDataLength() : Word; Procedure SetDataLength(Const ADataLength : Word); Function GetFileName() : AnsiString; Procedure SetFileName(Const AFileName : AnsiString); Function GetByte1() : Byte; Procedure SetByte1(Const AByte1 : Byte); Function GetCrc32() : DWord; Procedure SetCrc32(Const ACrc32 : DWord); Function GetArchivedFiles() : IArchivedFileDatas; Public Property DataLength : Word Read GetDataLength Write SetDataLength; Property FileName : AnsiString Read GetFileName Write SetFileName; Property Byte1 : Byte Read GetByte1 Write SetByte1; Property Crc32 : DWord Read GetCrc32 Write SetCrc32; Property ArchivedFiles : IArchivedFileDatas Read GetArchivedFiles; Procedure Assign(ASource : TObject); ReIntroduce; Virtual; Procedure Clear(); End; TZeroFileDatas = Class(TInterfaceListEx, IZeroFileDatas) Protected Function GetItemClass() : TInterfacedObjectExClass; OverRide; Function Get(Index : Integer) : IZeroFileData; OverLoad; Procedure Put(Index : Integer; Const Item : IZeroFileData); OverLoad; Function Add() : IZeroFileData; ReIntroduce; OverLoad; Function Add(Const AItem : IZeroFileData) : Integer; OverLoad; End; TZeroFileHeader = Class(TInterfacedObjectEx, IZeroFileHeader) Private FStr1 : AnsiString; FWord1 : Word; FZeroFileSize : DWord; FByte1 : Byte; FWord2 : Word; Protected Procedure Created(); OverRide; Function GetStr1() : AnsiString; Procedure SetStr1(Const AStr1 : AnsiString); Function GetWord1() : Word; Procedure SetWord1(Const AWord1 : Word); Function GetZeroFileSize() : DWord; Procedure SetZeroFileSize(Const AZeroFileSize : DWord); Function GetByte1() : Byte; Procedure SetByte1(Const AByte1 : Byte); Function GetWord2() : Word; Procedure SetWord2(Const AWord2 : Word); Public Property Str1 : AnsiString Read GetStr1 Write SetStr1; Property Word1 : Word Read GetWord1 Write SetWord1; Property ZeroFileSize : DWord Read GetZeroFileSize Write SetZeroFileSize; Property Byte1 : Byte Read GetByte1 Write SetByte1; Property Word2 : Word Read GetWord2 Write SetWord2; Procedure Assign(ASource : TObject); ReIntroduce; Virtual; Procedure Clear(); End; TZeroFile = Class(TInterfacedObjectEx, IZeroFile) Private FFileHeader : IZeroFileHeader; FArchiveDirectory : AnsiString; FFileDatas : IZeroFileDatas; FCrc32 : DWord; Protected Procedure Created(); OverRide; Function GetFileHeaderClass() : TZeroFileHeaderClass; Virtual; Function GetZeroFileDatasClass() : TZeroFileDatasClass; Virtual; Function GetFileHeader() : IZeroFileHeader; Function GetArchiveDirectory() : AnsiString; Procedure SetArchiveDirectory(Const AArchiveDirectory : AnsiString); Function GetFileDatas() : IZeroFileDatas; Function GetCrc32() : DWord; Procedure SetCrc32(Const ACrc32 : DWord); Public Property FileHeader : IZeroFileHeader Read GetFileHeader; Property ArchiveDirectory : AnsiString Read GetArchiveDirectory Write SetArchiveDirectory; Property FileDatas : IZeroFileDatas Read GetFileDatas; Property Crc32 : DWord Read GetCrc32 Write SetCrc32; Procedure Assign(ASource : TObject); ReIntroduce; Virtual; Procedure Clear(); Destructor Destroy(); OverRide; End; implementation Uses SysUtils, RTLConsts; Procedure TZeroFileData.Created(); Begin Clear(); End; Function TZeroFileData.GetArchivedFileDatasClass() : TArchivedFileDatasClass; Begin Result := TArchivedFileDatas; End; Procedure TZeroFileData.Clear(); Begin FDataLength := 0; FFileName := ''; FByte1 := 1; FCrc32 := 0; FArchivedFiles := GetArchivedFileDatasClass().Create(); End; Procedure TZeroFileData.Assign(ASource : TObject); Var lSrc : IZeroFileData; Begin { If Supports(ASource, IArchiveFileData, lSrc) Then Begin FDataLength := lSrc.DataLength; FFileName := lSrc.FileName; FByte1 := lSrc.Byte1; FCrc32 := lSrc.Crc32; End Else Raise EConvertError.CreateResFmt(@SAssignError, [ASource.ClassName, ClassName]);} End; Function TZeroFileData.GetDataLength() : Word; Begin Result := FDataLength; End; Procedure TZeroFileData.SetDataLength(Const ADataLength : Word); Begin FDataLength := ADataLength; End; Function TZeroFileData.GetFileName() : AnsiString; Begin Result := FFileName; End; Procedure TZeroFileData.SetFileName(Const AFileName : AnsiString); Begin FFileName := AFileName; End; Function TZeroFileData.GetByte1() : Byte; Begin Result := FByte1; End; Procedure TZeroFileData.SetByte1(Const AByte1 : Byte); Begin FByte1 := AByte1; End; Function TZeroFileData.GetCrc32() : DWord; Begin Result := FCrc32; End; Procedure TZeroFileData.SetCrc32(Const ACrc32 : DWord); Begin FCrc32 := ACrc32; End; Function TZeroFileData.GetArchivedFiles() : IArchivedFileDatas; Begin Result := FArchivedFiles; End; Function TZeroFileDatas.GetItemClass() : TInterfacedObjectExClass; Begin Result := TZeroFileData; End; Function TZeroFileDatas.Get(Index : Integer) : IZeroFileData; Begin Result := InHerited Items[Index] As IZeroFileData; End; Procedure TZeroFileDatas.Put(Index : Integer; Const Item : IZeroFileData); Begin InHerited Items[Index] := Item; End; Function TZeroFileDatas.Add() : IZeroFileData; Begin Result := InHerited Add() As IZeroFileData; End; Function TZeroFileDatas.Add(Const AItem : IZeroFileData) : Integer; Begin Result := InHerited Add(AItem); End; Procedure TArchivedFileData.Created(); Begin Clear(); End; Procedure TArchivedFileData.Clear(); Begin FDataLength := 0; FFileName1 := ''; FFileExtension := ''; FFileName2 := ''; FFileSize := 0; FWord1 := 1; FArchiveFileId := 0; End; Procedure TArchivedFileData.Assign(ASource : TObject); Var lSrc : IArchivedFileData; Begin If Supports(ASource, IArchivedFileData, lSrc) Then Begin FDataLength := lSrc.DataLength; FFileName1 := lSrc.FileName1; FFileExtension := lSrc.FileExtension; FFileName2 := lSrc.FileName2; FFileSize := lSrc.FileSize; FWord1 := lSrc.Word1; FArchiveFileId := lSrc.ArchiveFileId; End Else Raise EConvertError.CreateResFmt(@SAssignError, [ASource.ClassName, ClassName]); End; Function TArchivedFileData.GetDataLength() : Word; Begin Result := FDataLength; End; Procedure TArchivedFileData.SetDataLength(Const ADataLength : Word); Begin FDataLength := ADataLength; End; Function TArchivedFileData.GetFileName1() : AnsiString; Begin Result := FFileName1; End; Procedure TArchivedFileData.SetFileName1(Const AFileName1 : AnsiString); Begin FFileName1 := AFileName1; End; Function TArchivedFileData.GetFileExtension() : AnsiString; Begin Result := FFileExtension; End; Procedure TArchivedFileData.SetFileExtension(Const AFileExtension : AnsiString); Begin FFileExtension := AFileExtension; End; Function TArchivedFileData.GetFileName2() : AnsiString; Begin Result := FFileName2; End; Procedure TArchivedFileData.SetFileName2(Const AFileName2 : AnsiString); Begin FFileName2 := AFileName2; End; Function TArchivedFileData.GetFileSize() : DWord; Begin Result := FFileSize; End; Procedure TArchivedFileData.SetFileSize(Const AFileSize : DWord); Begin FFileSize := AFileSize; End; Function TArchivedFileData.GetWord1() : Word; Begin Result := FWord1; End; Procedure TArchivedFileData.SetWord1(Const AWord1 : Word); Begin FWord1 := AWord1; End; Function TArchivedFileData.GetArchiveFileId() : Word; Begin Result := FArchiveFileId; End; Procedure TArchivedFileData.SetArchiveFileId(Const AArchiveFileId : Word); Begin FArchiveFileId := AArchiveFileId; End; Function TArchivedFileDatas.GetItemClass() : TInterfacedObjectExClass; Begin Result := TArchivedFileData; End; Function TArchivedFileDatas.Get(Index : Integer) : IArchivedFileData; Begin Result := InHerited Items[Index] As IArchivedFileData; End; Procedure TArchivedFileDatas.Put(Index : Integer; Const Item : IArchivedFileData); Begin InHerited Items[Index] := Item; End; Function TArchivedFileDatas.Add() : IArchivedFileData; Begin Result := InHerited Add() As IArchivedFileData; End; Function TArchivedFileDatas.Add(Const AItem : IArchivedFileData) : Integer; Begin Result := InHerited Add(AItem); End; Function TArchivedFileDatas.InternalSort(Item1, Item2 : IInterfaceEx) : Integer; Var lItem1, lItem2 : IArchivedFileData; Begin If Supports(Item1, IArchivedFileData, lItem1) And Supports(Item2, IArchivedFileData, lItem2) Then Begin If lItem1.ArchiveFileId > lItem2.ArchiveFileId Then Result := 1 Else If lItem1.ArchiveFileId < lItem2.ArchiveFileId Then Result := -1 Else Result := CompareText(lItem1.FileName1, lItem2.FileName1); End Else Raise Exception.Create('Invalid interface type'); End; Procedure TArchivedFileDatas.Sort(); Begin InHerited Sort(InternalSort); End; Procedure TZeroFileHeader.Created(); Begin Clear(); End; Procedure TZeroFileHeader.Clear(); Begin FStr1 := 'BGrm'; FWord1 := 770;//515; FZeroFileSize := 0; FByte1 := 0; FWord2 := 27904;//109; End; Procedure TZeroFileHeader.Assign(ASource : TObject); Var lSrc : IZeroFileHeader; Begin If Supports(ASource, IZeroFileHeader, lSrc) Then Begin FStr1 := lSrc.Str1; FWord1 := lSrc.Word1; FZeroFileSize := lSrc.ZeroFileSize; FByte1 := lSrc.Byte1; FWord2 := lSrc.Word2; End Else Raise EConvertError.CreateResFmt(@SAssignError, [ASource.ClassName, ClassName]); End; Function TZeroFileHeader.GetStr1() : AnsiString; Begin Result := FStr1; End; Procedure TZeroFileHeader.SetStr1(Const AStr1 : AnsiString); Begin FStr1 := AStr1; End; Function TZeroFileHeader.GetWord1() : Word; Begin Result := FWord1; End; Procedure TZeroFileHeader.SetWord1(Const AWord1 : Word); Begin FWord1 := AWord1; End; Function TZeroFileHeader.GetZeroFileSize() : DWord; Begin Result := FZeroFileSize; End; Procedure TZeroFileHeader.SetZeroFileSize(Const AZeroFileSize : DWord); Begin FZeroFileSize := AZeroFileSize; End; Function TZeroFileHeader.GetByte1() : Byte; Begin Result := FByte1; End; Procedure TZeroFileHeader.SetByte1(Const AByte1 : Byte); Begin FByte1 := AByte1; End; Function TZeroFileHeader.GetWord2() : Word; Begin Result := FWord2; End; Procedure TZeroFileHeader.SetWord2(Const AWord2 : Word); Begin FWord2 := AWord2; End; Procedure TZeroFile.Created(); Begin Clear(); End; Destructor TZeroFile.Destroy(); Begin FFileHeader := Nil; FFileDatas := Nil; InHerited Destroy(); End; Function TZeroFile.GetFileHeaderClass() : TZeroFileHeaderClass; Begin Result := TZeroFileHeader; End; Function TZeroFile.GetZeroFileDatasClass() : TZeroFileDatasClass; Begin Result := TZeroFileDatas; End; Procedure TZeroFile.Clear(); Begin FFileHeader := GetFileHeaderClass().Create(); FFileDatas := GetZeroFileDatasClass().Create(); FCrc32 := 0; End; Procedure TZeroFile.Assign(ASource : TObject); Var lSrc : TZeroFile; Begin { If ASource Is TZeroFile Then Begin lSrc := TZeroFile(ASource); FFileHeader := lSrc.FileHeader; FFileData := lSrc.FileData; FCrc32 := lSrc.Crc32; End Else Raise EConvertError.CreateResFmt(@SAssignError, [ASource.ClassName, ClassName]);} End; Function TZeroFile.GetFileHeader() : IZeroFileHeader; Begin Result := FFileHeader; End; Function TZeroFile.GetArchiveDirectory() : AnsiString; Begin Result := FArchiveDirectory; End; Procedure TZeroFile.SetArchiveDirectory(Const AArchiveDirectory : AnsiString); Begin FArchiveDirectory := AArchiveDirectory; End; Function TZeroFile.GetFileDatas() : IZeroFileDatas; Begin Result := FFileDatas; End; Function TZeroFile.GetCrc32() : DWord; Begin Result := FCrc32; End; Procedure TZeroFile.SetCrc32(Const ACrc32 : DWord); Begin FCrc32 := ACrc32; End; end.
unit mustapas; {$mode objfpc}{$H+} interface uses Classes,SysUtils,fpjson; type TCacheGetFunction = function (const Template: TStream; const Context: TJSONObject; Result: TStream): Boolean; TCachePutFunction = procedure (const Template: TStream; const Context: TJSONObject; const Result: TStream); ETokenize = class(Exception) end; ERender = class(Exception) end; var OnGetCache: TCacheGetFunction; OnPutCache: TCachePutFunction; function Escape(const S: String): String; inline; procedure Render(const Template: TStream; const Context: TJSONObject; Result: TStream); implementation uses StrUtils; function Escape(const S: String): String; begin Result := StringsReplace(S,[#13,#10],['\r','\n'],[rfReplaceAll]); end; { token } type TTokenKind = ( tkText,tkEscapedVariable,tkUnescapedVariable,tkOpenSection,tkCloseSection ); TToken = record Line,Col: LongWord; Kind: TTokenKind; Lexeme: String; ContextBasePath: String; end; TTokenList = array of TToken; procedure AddToken(const ALine,ACol: LongWord; const AKind: TTokenKind; const ALexeme,AContextBasePath: String; var Tokens: TTokenList); var n: SizeInt; t: TToken; begin // WriteLn('Token ',AKind,' of "',Escape(ALexeme),'" has been added'); with t do begin Line := ALine; Col := ACol; Kind := AKind; Lexeme := ALexeme; ContextBasePath := AContextBasePath; end; n := Length(Tokens); SetLength(Tokens,n + 1); Tokens[n] := t; end; { lexer } const EOFChar = #26; LFChar = #10; type TLexerState = ( lsText,lsPossiblyTagStart,lsTagStart,lsPossiblyTagEnd,lsTagEnd, lsEscapedVariable,lsUnescapedVariable,lsPossiblyUnescapedVariableEnd,lsUnescapedVariableAmp, lsOpenSection,lsCloseSection, lsEOF ); var LexerState: TLexerState; Line,Col: LongWord; // current lexer position function Tokenize(input: TStream): TTokenList; var StartLine,StartCol: LongWord; Kind: TTokenKind; Lexeme,ContextBasePath: String; Look: Char; TempState: TLexerState; procedure InitFields; begin StartLine := Line; StartCol := Col; Lexeme := EmptyStr; end; function ReadChar: Char; // read next character from the input stream begin if input.Position < input.Size then begin result:= chr(input.ReadByte); if Result = LFChar then begin Inc(Line); Col := 0; end else begin Inc(Col); end; end else result := EOFChar; end; procedure HandleText; begin case Look of '{': begin LexerState := lsPossiblyTagStart; end; else begin Lexeme := Lexeme + Look; end; end; Look := ReadChar; end; procedure HandlePossiblyTagStart; begin case Look of '{': begin if Lexeme <> EmptyStr then begin AddToken(StartLine,StartCol,Kind,Lexeme,ContextBasePath,Result); InitFields; end; LexerState := lsTagStart; end; else begin Lexeme := Lexeme + '{' + Look; LexerState := lsText; end; end; Look := ReadChar; end; procedure HandleTagStart; begin case Look of '{': begin LexerState := lsUnescapedVariable; Kind := tkUnescapedVariable; end; '&': begin LexerState := lsUnescapedVariableAmp; Kind := tkUnescapedVariable; end; '#': begin LexerState := lsOpenSection; Kind := tkOpenSection; end; '/': begin LexerState := lsCloseSection; Kind := tkCloseSection; end; 'a'..'z','A'..'Z','_',' ': begin LexerState := lsEscapedVariable; Kind := tkEscapedVariable; Lexeme := Look; end; else begin raise ETokenize.Create('Invalid tag char: ' + Look); end; end; Look := ReadChar; end; procedure HandlePossiblyTagEnd; var p: SizeInt; begin case Look of '}': begin Lexeme := Trim(Lexeme); case TempState of lsOpenSection: ContextBasePath := ContextBasePath + Lexeme + '.'; lsCloseSection: begin if ContextBasePath = EmptyStr then raise Exception.Create('Closing unopened section: ' + Lexeme) else begin p := RPos('.',ContextBasePath); Delete(ContextBasePath,p,Length(ContextBasePath) - p); end; end; end; AddToken(StartLine,StartCol,Kind,Lexeme,ContextBasePath,Result); InitFields; LexerState := lsTagEnd; end; else begin Lexeme := Lexeme + '}' + Look; LexerState := TempState; end; end; Look := ReadChar; end; procedure HandleTagEnd; begin LexerState := lsText; Kind := tkText; end; procedure HandleVariable; begin case Look of '}': begin TempState := LexerState; if LexerState = lsEscapedVariable then LexerState := lsPossiblyTagEnd else LexerState := lsPossiblyUnescapedVariableEnd; end; 'a'..'z','A'..'Z','0'..'9','_',' ','.': begin Lexeme := Lexeme + Look; end; else begin raise ETokenize.Create('Invalid tag char: ' + Look); end; end; Look := ReadChar; end; procedure HandlePossiblyUnescapedVariableEnd; begin case Look of '}': begin LexerState := lsPossiblyTagEnd; end; else begin raise ETokenize.Create('Invalid tag char: ' + Look); end; end; Look := ReadChar; end; procedure HandleUnescapedVariableAmp; begin case Look of '}': begin TempState := LexerState; LexerState := lsPossiblyTagEnd; end; 'a'..'z','A'..'Z','0'..'9','_',' ','.': begin Lexeme := Lexeme + Look; end; else begin raise ETokenize.Create('Invalid tag char: ' + Look); end; end; Look := ReadChar; end; procedure HandleSection; begin case Look of '}': begin TempState := LexerState; LexerState := lsPossiblyTagEnd; end; 'a'..'z','A'..'Z','0'..'9','_',' ','.': begin Lexeme := Lexeme + Look; end; else begin raise ETokenize.Create('Invalid tag char: ' + Look); end; end; Look := ReadChar; end; begin Initialize(Result); LexerState := lsText; input.Seek(0, fsFromBeginning); InitFields; ContextBasePath := EmptyStr; Look := ReadChar; Kind := tkText; while Look <> EOFChar do begin case LexerState of lsText : HandleText; lsPossiblyTagStart : HandlePossiblyTagStart; lsTagStart : HandleTagStart; lsPossiblyTagEnd : HandlePossiblyTagEnd; lsTagEnd : HandleTagEnd; lsEscapedVariable, lsUnescapedVariable : HandleVariable; lsPossiblyUnescapedVariableEnd: HandlePossiblyUnescapedVariableEnd; lsUnescapedVariableAmp : HandleUnescapedVariableAmp; lsOpenSection,lsCloseSection : HandleSection; end; end; if Lexeme <> EmptyStr then begin AddToken(StartLine,StartCol,Kind,Lexeme,ContextBasePath,Result); end; end; function HTMLEncode(const Data: string): string; var iPos, i: Integer; procedure Encode(const AStr: String); begin Move(AStr[1], result[iPos], Length(AStr) * SizeOf(Char)); Inc(iPos, Length(AStr)); end; begin SetLength(result, Length(Data) * 6); iPos := 1; for i := 1 to length(Data) do case Data[i] of '<': Encode('&lt;'); '>': Encode('&gt;'); '&': Encode('&amp;'); '"': Encode('&quot;'); else result[iPos] := Data[i]; Inc(iPos); end; SetLength(result, iPos - 1); end; procedure Interpret(const Tokens: TTokenList; const Context: TJSONObject; Result: TStream); var Token: TToken; Value,BasePath: String; Node: TJSONData; p: SizeInt; begin for Token in Tokens do case Token.Kind of tkText: begin // WriteLn('Rendering "' + Escape(Token.Lexeme) + '"'); Result.WriteBuffer(Token.Lexeme[1], length(Token.Lexeme)); end; tkEscapedVariable,tkUnescapedVariable: begin Value := ''; BasePath := Token.ContextBasePath; repeat Node := Context.FindPath(BasePath + Token.Lexeme); p := RPos('.',BasePath); if p > 0 then Delete(BasePath,p,Length(BasePath) - p); until Assigned(Node) or (BasePath = EmptyStr); if Assigned(Node) then case Node.JSONType of jtUnknown: raise Exception.Create('Don''t know how to interpret "' + Node.AsJSON + '"'); jtNumber: begin if Node is TJSONFloatNumber then Value := FloatToStr(Node.AsFloat) else Value := Node.AsString; end; jtString: if Token.Kind = tkEscapedVariable then Value := HTMLEncode(Node.AsString) else Value := Node.AsString; jtBoolean: Value := BoolToStr(Node.AsBoolean); jtNull: ; jtArray: raise Exception.Create('Can''t interpolate array directly'); jtObject: raise Exception.Create('Can''t interpolate object directly'); end; Result.WriteBuffer(Value[1], length(Value)); //Write(Output,Value); end; end; end; procedure Render(const Template: TStream; const Context: TJSONObject; Result: TStream); var Tokens: TTokenList; begin if not Assigned(OnGetCache) or not OnGetCache(Template,Context,Result) then begin // initialize lexer Line := 1; Col := 0; Tokens := Tokenize(template); Interpret(Tokens,Context,Result); if Assigned(OnPutCache) then OnPutCache(Template,Context,Result); end; end; end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} unit IdOpenSSLHeaders_buffer; interface // Headers for OpenSSL 1.1.1 // buffer.h {$i IdCompilerDefines.inc} uses IdCTypes, IdGlobal, IdOpenSSLConsts, IdOpenSSLHeaders_ossl_typ; const BUF_MEM_FLAG_SECURE = $01; type buf_mem_st = record length: TIdC_SIZET; data: PIdAnsiChar; max: TIdC_SIZET; flags: TIdC_ULONG; end; var function BUF_MEM_new: PBUF_MEM; function BUF_MEM_new_ex(flags: TIdC_ULONG): PBUF_MEM; procedure BUF_MEM_free(a: PBUF_MEM); function BUF_MEM_grow(str: PBUF_MEM; len: TIdC_SIZET): TIdC_SIZET; function BUF_MEM_grow_clean(str: PBUF_MEM; len: TIdC_SIZET): TIdC_SIZET; procedure BUF_reverse(out_: PByte; const in_: PByte; siz: TIdC_SIZET); implementation end.
unit oSpectrumFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, Types, Graphics, uESelector, ueled, TASources, TACustomSource, TACustomSeries, TAGraph, TASeries, TATransformations, TATools, oGlobal, oBaseFrame; type { TSpectrumFrame } TSpectrumFrame = class(TBaseFrame) CbLogarithmic: TCheckBox; CbYdB: TCheckBox; FrequencyAxisTransform: TChartAxisTransformations; FrequencyAxisTransformLog: TLogarithmAxisTransform; GbInfo: TGroupBox; LogLabelsSource: TListChartSource; Panel2: TPanel; RgChannels: TRadioGroup; Splitter1: TSplitter; TxtInfo: TLabel; RgSamples: TRadioGroup; procedure CbLogarithmicChange(Sender: TObject); procedure CbYdBChange(Sender: TObject); procedure DataPointCrosshairToolDraw(ASender: TDataPointDrawTool); procedure LeftChannelChartSourceGetChartDataItem( ASource: TUserDefinedChartSource; AIndex: Integer; var AItem: TChartDataItem); procedure RgChannelsClick(Sender: TObject); procedure RgSamplesClick(Sender: TObject); procedure RightChannelChartSourceGetChartDataItem( ASource: TUserDefinedChartSource; AIndex: Integer; var AItem: TChartDataItem); procedure TimerEventHandler(Sender: TObject); private FData: array of Single; FTimebaseLock: Integer; protected function GetNumChannels: Integer; inline; function GetNumSamples: Integer; inline; procedure PopulateLogLabels; procedure PopulateNumSamples; procedure SetSensitivity(AChannelIndex: TChannelIndex; AValue: Double); override; procedure SetupTimebase; override; procedure UpdateInfo; public constructor Create(AOwner: TComponent); override; procedure Activate; override; procedure Deactivate; override; procedure AutoSizeControls; override; end; implementation {$R *.lfm} uses Math, StrUtils, TAChartUtils, ouosDataCollector, omain, oUtils; constructor TSpectrumFrame.Create(AOwner: TComponent); begin inherited; inc(FTimebaseLock); PopulateNumSamples; dec(FTimebaseLock); LogLabelsSource.Clear; PopulateLogLabels; CbLogarithmic.Checked := LogFrequencyAxis; CbLogarithmicChange(nil); CbYdB.Checked := SpectrumDB; BoldRadiogroup(RgSamples); BoldRadioGroup(RgChannels); PopulateSensitivity(SwLeftSensitivity); PopulateSensitivity(SwRightSensitivity); end; procedure TSpectrumFrame.Activate; begin inherited; CbLogarithmic.Checked := LogFrequencyAxis; CbYdB.Checked := SpectrumDB; SetupTimebase; Timer.Enabled := Assigned(FDataCollector) and FDataCollector.Running; end; procedure TSpectrumFrame.AutoSizeControls; var wk: Integer; begin with SwLeftSensitivity do wk := DefKnobRadius + 2*LTicksSize + 2*GetTextWidth('50%', ValuesFont) + 2*ValuesMargin; ControlPanel.Constraints.MinWidth := 2*wk + CenterBevel.Width; end; procedure TSpectrumFrame.CbLogarithmicChange(Sender: TObject); begin LogFrequencyAxis := CbLogarithmic.Checked; if LogFrequencyAxis then begin FrequencyAxisTransformLog.Enabled := true; if Chart.IsZoomed then with Chart.BottomAxis do begin Intervals.Options := Intervals.Options + [aipGraphcoords]; Marks.Source := nil; Marks.Style := smsValue; end else with Chart.BottomAxis do begin Chart.BottomAxis.Marks.Source := LogLabelsSource; Chart.BottomAXis.Marks.Style := smsLabel; end; end else begin FrequencyAxisTransformLog.Enabled := false; with Chart.BottomAxis do begin Intervals.Options := Intervals.Options - [aipGraphcoords]; Marks.Source := nil; Marks.Style := smsValue; end; end; end; procedure TSpectrumFrame.CbYdBChange(Sender: TObject); begin SpectrumDB := CbYdB.Checked; ParamsToControls; end; procedure TSpectrumFrame.DataPointCrosshairToolDraw(ASender: TDataPointDrawTool); var series: TChartSeries; s: String; begin series := TChartSeries(ASender.Series); if series = LeftChannelSeries then s := 'L' else if series = RightChannelSeries then s := 'R' else exit; TxtInfo.Caption := Format( 'f = %.3f kHz' + LineEnding + '%s = %.3f' + LineEnding + 'Sampling period = %.0f ms', [ series.GetXValue(ASender.PointIndex), s, series.GetYValue(ASender.PointIndex), GetNumSamples / FSampleRate * 1000 ]); GbInfo.Show; end; procedure TSpectrumFrame.Deactivate; begin Timer.Enabled := false; inherited; end; function TSpectrumFrame.GetNumChannels: Integer; begin Result := succ(RgChannels.ItemIndex); end; function TSpectrumFrame.GetNumSamples: Integer; begin Result := NUM_SAMPLES[RgSamples.ItemIndex]; end; procedure TSpectrumFrame.LeftChannelChartSourceGetChartDataItem( ASource: TUserDefinedChartSource; AIndex: Integer; var AItem: TChartDataItem); { from bass.chm: "With a 2048 sample FFT, there will be 1024 floating-point values returned... Each value, or "bin", ranges from 0 to 1 (can actually go higher if the sample data is floating-point and not clipped). The 1st bin contains the DC component, the 2nd contains the amplitude at 1/2048 of the channel's sample rate, followed by the amplitude at 2/2048, 3/2048, etc. } begin Unused(ASource); // in case of an individual FFT of both channels the data array contains // interleaved left and right channel values. // For stereo, the even indexes are for the left channel // NOTE: For sampling of stereo data, the effective sample rate is halved! AIndex := AIndex * GetNumChannels; AItem.X := AIndex / GetNumSamples * FSampleRate * 0.001; if CbYdB.Checked then begin if FData[AIndex] = 0.0 then AItem.Y := NaN else AItem.Y := 10*Log10(FData[AIndex]) end else AItem.Y := FData[AIndex] * 100; end; procedure TSpectrumFrame.PopulateLogLabels; var mantisse, exponent: Integer; decade, value: Double; str: String; begin LogLabelsSource.Clear; for exponent := -4 to 4 do begin decade := IntPower(10.0, exponent); for mantisse := 1 to 9 do begin value := mantisse * decade; if mantisse in [5, 7, 9] then str := '' else str := Format('%.4g', [value]); LogLabelsSource.Add(value, value, str); end; end; end; procedure TSpectrumFrame.PopulateNumSamples; var i: Integer; begin RgSamples.Items.Clear; for i:=0 to High(NUM_SAMPLES) do RgSamples.Items.Add(IntToStr(NUM_SAMPLES[i])); RgSamples.ItemIndex := RgSamples.Items.IndexOf('2048'); end; procedure TSpectrumFrame.RgChannelsClick(Sender: TObject); begin SetupTimebase; end; procedure TSpectrumFrame.RgSamplesClick(Sender: TObject); begin SetupTimebase; end; procedure TSpectrumFrame.RightChannelChartSourceGetChartDataItem( ASource: TUserDefinedChartSource; AIndex: Integer; var AItem: TChartDataItem); begin Unused(ASource); if GetNumSamples = 2 then AIndex := AIndex * 2 + 1; AItem.X := AIndex / GetNumSamples * FSampleRate * 0.001; if CbYdB.Checked then begin if FData[AIndex] = 0.0 then AItem.Y := NaN else AItem.Y := 10*Log10(FData[AIndex]) end else AItem.Y := FData[AIndex] * 100; end; procedure TSpectrumFrame.SetSensitivity(AChannelIndex: TChannelIndex; AValue: Double); begin with GetAxis(AChannelIndex) do if CbYdB.Checked then begin Range.Max := 0; Range.Min := -80; Range.UseMax := true; Range.UseMin := true; Title.Caption := IfThen(AChannelIndex=ciLeft, 'Left', 'Right') + 'channel spectral power (dB)'; end else begin Range.Max := AValue; Range.Min := 0; Range.UseMax := true; Range.UseMin := true; Title.Caption := IfThen(AChannelIndex=ciLeft, 'Left', 'Right') + ' channel spectral power (% of full scale)'; end; end; procedure TSpectrumFrame.SetupTimebase; var bufsize, n: Integer; t: double; ch: Integer; begin if FTimebaseLock > 0 then exit; if FSampleRate = 0 then begin if Assigned(FDataCollector) and FDataCollector.Running then FSampleRate := FDataCollector.SampleRate else exit; end; ch := GetNumChannels; n := GetNumSamples; // sample rate = n / t, samples per second t := n / FSampleRate * 1000; // *1000 to convert sec to ms if Assigned(FDataCollector) then FDataCollector.SampleRate := FSampleRate; bufsize := n div 2 * ch * SizeOf(Single); SetLength(FData, bufsize); LeftChannelChartSource.PointsNumber := n div (2*ch); RightChannelChartSource.PointsNumber := n div (2*ch); Timer.Interval := ceil(t); end; procedure TSpectrumFrame.TimerEventHandler(Sender: TObject); var n: Integer; begin // Stop if no more data available if not FDataCollector.Running then begin Stop; exit; end; // Get data n := FDataCollector.GetFFTData(@FData[0], GetNumSamples, GetNumChannels); if MainForm.CbAudioEngine.text = 'uos' then FData := BData; // prepare series LeftChannelChartSource.Reset; RightChannelChartSource.Reset; // Repaint chart Chart.Invalidate; // Progress info display if not FCrosshairActive then begin UpdateInfo; if not GbInfo.Visible then GbInfo.Show; end; // Notify main form of received data if Assigned(OnDataReceived) then OnDataReceived(self); end; procedure TSpectrumFrame.UpdateInfo; begin TxtInfo.Caption := Format( 'Time: %s' + LineEnding + 'Bytes: %.0n' + LineEnding + 'Sampling period: %.0n ms', [ FormatDateTime('nn:ss.zzz', FDataCollector.GetRunningTime / (24*60*60)), FDataCollector.GetPlayedBytes*1.0, GetNumSamples / FSampleRate * 1000 ]); end; end.
unit uUpdateInfoForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, lclintf, ExtCtrls; type { TUpdateInfoForm } TUpdateInfoForm = class(TForm) DescMemo: TMemo; FileLinkStatText: TStaticText; StaticText1: TStaticText; StaticText2: TStaticText; VersionLabeledEdit: TLabeledEdit; procedure FileLinkStatTextClick(Sender: TObject); procedure FileLinkStatTextMouseEnter(Sender: TObject); procedure FileLinkStatTextMouseLeave(Sender: TObject); private procedure SetDescription(AValue: TStringList); procedure SetFileLink(AValue: string); procedure SetVersion(AValue: string); { private declarations } public property Version: string write SetVersion; property FileLink: string write SetFileLink; property DEscription: TStringList write SetDescription; end; implementation {$R *.lfm} { TUpdateInfoForm } procedure TUpdateInfoForm.FileLinkStatTextClick(Sender: TObject); begin OpenURL(FileLinkStatText.Caption); end; procedure TUpdateInfoForm.FileLinkStatTextMouseEnter(Sender: TObject); begin FileLinkStatText.Cursor := crHandPoint; {cursor changes into handshape when it is on StaticText} FileLinkStatText.Font.Color := clBlue; {StaticText changes color into blue when cursor is on StaticText} end; procedure TUpdateInfoForm.FileLinkStatTextMouseLeave(Sender: TObject); begin FileLinkStatText.Font.Color := clDefault; {when cursor is not on StaticText then color of text changes into default color} end; procedure TUpdateInfoForm.SetDescription(AValue: TStringList); begin DescMemo.Lines.Assign(AValue); end; procedure TUpdateInfoForm.SetFileLink(AValue: string); begin FileLinkStatText.Caption := AValue; end; procedure TUpdateInfoForm.SetVersion(AValue: string); begin VersionLabeledEdit.Text := AValue end; end.
unit uFrmModelo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, ToolWin, Buttons, ImgList, ActnList, StdCtrls, Mask, DBCtrls, Grids, DBGrids, DB; type TfrmCadModelo = class(TForm) tbPadrao: TToolBar; panPadrao: TPanel; btnNovo: TSpeedButton; btnGravar: TSpeedButton; btnEditar: TSpeedButton; btnUltimo: TSpeedButton; btnProximo: TSpeedButton; btnAnterior: TSpeedButton; btnPrimeiro: TSpeedButton; btnCancelar: TSpeedButton; btnExcluir: TSpeedButton; ToolButton1: TToolButton; ToolButton2: TToolButton; ActionList1: TActionList; ImageList1: TImageList; actNovo: TAction; actGravar: TAction; actEditar: TAction; actExcluir: TAction; actCancelar: TAction; actPrimeiro: TAction; actAnterior: TAction; actProximo: TAction; actUltimo: TAction; pgcPadrao: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Panel1: TPanel; dbGridPadrao: TDBGrid; dtsPadrao: TDataSource; btnListar: TSpeedButton; btnFechar: TSpeedButton; actListar: TAction; actFechar: TAction; procedure actNovoExecute(Sender: TObject); procedure actGravarExecute(Sender: TObject); procedure actEditarExecute(Sender: TObject); procedure actExcluirExecute(Sender: TObject); procedure actCancelarExecute(Sender: TObject); procedure actPrimeiroExecute(Sender: TObject); procedure actAnteriorExecute(Sender: TObject); procedure actProximoExecute(Sender: TObject); procedure actUltimoExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure actFecharExecute(Sender: TObject); procedure actListarExecute(Sender: TObject); procedure dbGridPadraoDblClick(Sender: TObject); private { Private declarations } procedure HabilitarControles; procedure HabilitarControlesVisuais(Status: Boolean); public { Public declarations } end; var frmCadModelo: TfrmCadModelo; implementation {$R *.dfm} procedure TfrmCadModelo.actNovoExecute(Sender: TObject); begin dtsPadrao.DataSet.Insert; pgcPadrao.ActivePage := TabSheet2; // edtNome.SetFocus; HabilitarControles; HabilitarControlesVisuais(true); end; procedure TfrmCadModelo.actGravarExecute(Sender: TObject); begin dtsPadrao.DataSet.Edit; dtsPadrao.DataSet.Post; HabilitarControles; HabilitarControlesVisuais(false); end; procedure TfrmCadModelo.actEditarExecute(Sender: TObject); begin dtsPadrao.DataSet.Edit; pgcPadrao.ActivePage := TabSheet2; HabilitarControles; HabilitarControlesVisuais(true); end; procedure TfrmCadModelo.actExcluirExecute(Sender: TObject); begin if MessageDlg('Deseja Excluir o Registro', mtconfirmation, [mbYes, mbNo], 0) = mrYes then begin dtsPadrao.dataset.delete; end; HabilitarControles; HabilitarControlesVisuais(false); end; procedure TfrmCadModelo.actCancelarExecute(Sender: TObject); begin dtsPadrao.DataSet.Cancel; dtsPadrao.dataset.filtered := false; HabilitarControles; HabilitarControlesVisuais(false); end; procedure TfrmCadModelo.actPrimeiroExecute(Sender: TObject); begin dtsPadrao.DataSet.First; end; procedure TfrmCadModelo.actAnteriorExecute(Sender: TObject); begin dtsPadrao.DataSet.Prior; end; procedure TfrmCadModelo.actProximoExecute(Sender: TObject); begin dtsPadrao.DataSet.Next; end; procedure TfrmCadModelo.actUltimoExecute(Sender: TObject); begin dtsPadrao.DataSet.Last; end; procedure TfrmCadModelo.FormShow(Sender: TObject); var page : integer; begin // Esconder as tabs do PageControl for page := 0 to pgcPadrao.PageCount - 1 do begin pgcPadrao.Pages[page].TabVisible := false; end; pgcPadrao.ActivePage := TabSheet1; HabilitarControles; HabilitarControlesVisuais(true); end; procedure TfrmCadModelo.actFecharExecute(Sender: TObject); begin Self.Close; end; procedure TfrmCadModelo.actListarExecute(Sender: TObject); begin pgcPadrao.ActivePage := TabSheet1; dtsPadrao.DataSet.Active := false; dtsPadrao.DataSet.Active := true; end; procedure TfrmCadModelo.dbGridPadraoDblClick(Sender: TObject); begin actEditar.Execute; end; procedure TfrmCadModelo.HabilitarControles; begin btnNovo.Enabled := not(dtsPadrao.DataSet.State in [dsInsert, dsEdit]); btnGravar.Enabled := (dtsPadrao.DataSet.State in [dsInsert, dsEdit]); btnEditar.Enabled := (dtsPadrao.DataSet.State in [dsBrowse]); btnExcluir.Enabled := (dtsPadrao.DataSet.State in [dsBrowse, dsEdit]); btnCancelar.Enabled := (dtsPadrao.DataSet.State in [dsInsert, dsEdit]); // btnPesquisar.Enabled := not (dtsPadrao.DataSet.State in [dsInsert, dsEdit]); end; procedure TfrmCadModelo.HabilitarControlesVisuais(Status: Boolean); var I: Integer; begin for I := 0 to ComponentCount - 1 do begin if Components[I] is TDBEdit then TDBEdit(Components[I]).Enabled := Status else if Components[I] is TEdit then TEdit(Components[I]).Enabled := Status else if Components[I] is TDBLookupComboBox then TDBLookupComboBox(Components[I]).Enabled := Status else if Components[I] is TDBComboBox then TDBComboBox(Components[I]).Enabled := Status else if Components[I] is TDBMemo then TDBMemo(Components[I]).Enabled := Status; end; end; end.
unit uBtnDialogo; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls; type TBtnDialogo = class(TStyledControl) private FBtnSim: String; FBtnNao: String; FBtnCancel: String; function GetBtn(const aNome,aDefault: String): String; procedure SetBtn(const aNome,aValor: String); function GetBtnCancel: String; function GetBtnNao: String; function GetBtnSim: String; procedure SetBtnCancel(const Value: String); procedure SetBtnNao(const Value: String); procedure SetBtnSim(const Value: String); { Private declarations } protected { Protected declarations } function GetStyleObject: TFmxObject; override; public { Public declarations } constructor Create(AOwner: TComponent); override; published { Published declarations } property Align default TAlignLayout.alBottom; property BtnSim: String read GetBtnSim write SetBtnSim; property BtnNao: String read GetBtnNao write SetBtnNao; property BtnCancel: String read GetBtnCancel write SetBtnCancel; end; procedure Register; implementation uses System.Types, FMX.Styles; {$IFDEF MACOS} {$R *.mac.res} {$ENDIF} {$IFDEF MSWINDOWS} {$R *.win.res} {$ENDIF} procedure Register; begin RegisterComponents('Samples', [TBtnDialogo]); end; { TBtnDialogo } const BtnSimNome = 'DoButton'; BtnNaoNome = 'DontButton'; BtnCancelNome = 'CancelButton'; constructor TBtnDialogo.Create(AOwner: TComponent); begin inherited; Height := 46; Width := 300; Align := TAlignLayout.alBottom; BtnSim := 'Sim'; BtnNao := 'Não'; BtnCancel := 'Cancelar'; end; function TBtnDialogo.GetBtn(const aNome,aDefault: String): String; var Base: TFmxObject; begin Base := FindStyleResource(aNome); if Base is TTextControl then Result := TTextControl(Base).Text else Result := aDefault; end; function TBtnDialogo.GetBtnCancel: String; begin Result := GetBtn(BtnCancelNome,FBtnCancel); end; function TBtnDialogo.GetBtnNao: String; begin Result := GetBtn(BtnNaoNome,FBtnNao); end; function TBtnDialogo.GetBtnSim: String; begin Result := GetBtn(BtnSimNome,FBtnSim); end; function TBtnDialogo.GetStyleObject: TFmxObject; const Style = 'BtnDialogoPanelStyle'; begin if (StyleLookup = '') then begin Result := TControl(TStyleManager.LoadFromResource(HInstance, Style, RT_RCDATA)); Exit; end; Result := inherited GetStyleObject; end; procedure TBtnDialogo.SetBtn(const aNome,aValor: String); var Base: TFmxObject; begin Base := FindStyleResource(aNome); if Base is TTextControl then TTextControl(Base).Text := AValor; end; procedure TBtnDialogo.SetBtnCancel(const Value: String); begin FBtnCancel := Value; SetBtn(BtnCancelNome,Value); end; procedure TBtnDialogo.SetBtnNao(const Value: String); begin FBtnNao := Value; SetBtn(BtnNaoNome,Value); end; procedure TBtnDialogo.SetBtnSim(const Value: String); begin FBtnSim := Value; SetBtn(BtnSimNome,Value); end; end.
unit Project87.Scenes.StarMapScene; interface uses QCore.Input, QGame.Scene, Strope.Math, Project87.Types.StarMap, Project87.Types.HeroInterface; type TStarMapSceneParameters = class sealed strict private FIsNewGame: Boolean; public constructor Create(AIsNewGame: Boolean); property IsNewGame: Boolean read FIsNewGame; end; TStarMapScene = class sealed (TScene) strict private FMap: TStarMap; FInterface: THeroInterface; public constructor Create(const AName: string); destructor Destroy; override; procedure OnInitialize(AParameter: TObject = nil); override; procedure OnDraw(const ALayer: Integer); override; procedure OnUpdate(const ADelta: Double); override; procedure OnDestroy; override; function OnMouseMove(const AMousePosition: TVectorF): Boolean; override; function OnMouseButtonUp(AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; override; function OnKeyUp(AKey: TKeyButton): Boolean; override; end; implementation uses QuadEngine, QEngine.Core, QApplication.Application, Project87.Hero; {$REGION ' TStarMapSceneParameters '} constructor TStarMapSceneParameters.Create(AIsNewGame: Boolean); begin FIsNewGame := AIsNewGame; end; {$ENDREGION} {$REGION ' TStarMapScene '} const STARMAP_FILE = '..\data\map\starmap.map'; constructor TStarMapScene.Create(const AName: string); begin inherited Create(AName); FInterface := THeroInterface.Create(THero.GetInstance); FMap := TStarMap.Create; end; destructor TStarMapScene.Destroy; begin FMap.Free; inherited; end; procedure TStarMapScene.OnInitialize(AParameter: TObject); begin if not Assigned(AParameter) then begin FMap.Clear; FMap.LoadFromFile(STARMAP_FILE); FMap.BackToMap; Exit; end; if AParameter is TStarMapSceneParameters then begin FMap.Clear; if (AParameter as TStarMapSceneParameters).IsNewGame then begin THero.GetInstance.NewPlayer; FMap.OnInitialize end else begin THero.GetInstance.LoadFromFile('..\data\map\player.user'); FMap.LoadFromFile(STARMAP_FILE); end; FMap.BackToMap; Exit; end; if AParameter is TStarSystemResult then FMap.BackToMap(AParameter as TStarSystemResult) else FMap.BackToMap; end; procedure TStarMapScene.OnDraw(const ALayer: Integer); begin TheEngine.Camera := nil; TheRender.Rectangle(0, 0, TheEngine.CurrentResolution.X, TheEngine.CurrentResolution.Y, $FF000000); FMap.OnDraw(0); FInterface.OnDraw; end; procedure TStarMapScene.OnUpdate(const ADelta: Double); begin FMap.OnUpdate(ADelta); THero.GetInstance.UpdateLife(ADelta); THero.GetInstance.UpdateTransPower(ADelta); end; procedure TStarMapScene.OnDestroy; begin FMap.SaveToFile(STARMAP_FILE); THero.GetInstance.SaveToFile('..\data\map\player.user'); end; function TStarMapScene.OnMouseMove(const AMousePosition: TVectorF): Boolean; begin Result := True; FMap.OnMouseMove(AMousePosition); end; function TStarMapScene.OnMouseButtonUp(AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; begin Result := True; FMap.OnMouseButtonUp(AButton, AMousePosition); end; function TStarMapScene.OnKeyUp(AKey: TKeyButton): Boolean; begin Result := True; if AKey = KB_ESC then begin TheApplication.Stop; Exit; end; FMap.OnKeyUp(AKey); end; {$ENDREGION} end.
{------------------------------------------------------------------------------} { SDLogUtils.pas for SDShell } {------------------------------------------------------------------------------} { 单元描述: 日志工具函数单元 } { 单元作者: 盛大网络 张洋 (zhangyang@snda.com) } { 参考文档: } { 创建日期: 2005-12-05 } {------------------------------------------------------------------------------} { 日志模块功能介绍: } { } { * 独立单元,避免循环引用,可在多个项目中直接引用 } { * 自动将子线程日志缩进显示 } { * 将日志分为普通日志和异常日志二类,方便定位错误 } { * 日志文件名分别为(假设为SDShell.exe): SDShell.log 和 SDShellErr.log } { * 提供异常信息日志函数 LogException } { * 日志文件超过指定大小之后自动在下次进程启动运行时删除 } { * 可通过 SDDebugViewer.exe 即时查看调试细节 } { } { Log日志函数: } { } { procedure Log(const AMsg: ansistring); // Log一般信息 } { procedure LogException(E: Exception; const AMsg: ansistring = '');// Log异常对象 } { procedure LogWarning(const AMsg: ansistring); // Log警告信息 } { procedure LogError(const AMsg: ansistring); // Log错误信息 } { procedure LogWithTag(const AMsg: ansistring; const ATag: ansistring); // Log加标记 } { procedure LogSeparator; // Log分隔符 } { procedure LogEnterProc(const AProcName: ansistring); // Log进入过程 } { procedure LogLeaveProc(const AProcName: ansistring); // Log退出过程 } { } {------------------------------------------------------------------------------} { 修改历史: } (* 2007.01.31 liaofeng } { 在写入日志时增加判断,如果写入的次数超出一定数量,则自动截断或重写日志 } { 增加条件编译选项:$DEFINE LOGTRUNCFILE,在日志超出限制时是否自动截断(重写 } { 日志并保留最后写入的一段日志,默认保留100K),未定义时重写文件 } * 2007.05.29 修改为不立即初始化日志文件,并且可以不仅仅透过编译开关彻底关闭日志文件,也可以 在程序软关闭日志文件。 {-----------------------------------------------------------------------------*) unit UtilsLog; {$WARN SYMBOL_PLATFORM OFF} {$DEFINE LOGTOFILE} // 是否LOG至文件 {.$DEFINE LOGTODEBUGGER} // 是否LOG至DebugView {$DEFINE LOGSOURCEFILENAME} // 是否在LOG文件中显示源代码名称 {$DEFINE REROUTEASSERT} // 是否替换Assert {$DEFINE ASSERTMSGLOG} // 将Assert信息Log至文件 {.$DEFINE ASSERTMSGSHOW} // 将Assert信息通过MessageBox显示出来 {$DEFINE ASSERTMSGRAISE} // 将Assert信息Raise出来 {.$DEFINE LOGERRORRAISE} // 将LogError或LogException的信息raise出来 {$DEFINE LOGTRUNCFILE} // 超出日志大小限制时截断文件而不是重写文件 interface uses Windows, SysUtils; type PLogFile = ^TLogFile; TLogFile = record Initialized : Boolean; { 是否已初始化参数 } AllowLogToFile: Boolean;// = True; LogFileNameMode: integer; LastLogTick : DWORD; LogLock : TRTLCriticalSection; { 日志写入锁 } FileHandle : THandle; ErrFileHandle : THandle; { 日志文件句柄 } LogWriteCount : Integer; { 日志已写入次数 } FileName : AnsiString; ErrorFileName : AnsiString; { 异常日志文件名全路径 } end; { Log系列输出函数} procedure Log(const ASourceFileName, AMsg: string; ALogFile: PLogFile = nil); // Log一般信息 procedure SDLog(const ASourceFileName, AMsg: string; ALogFile: PLogFile = nil); // Log一般信息 procedure LogException(const ASourceFileName: string; E: Exception; ALogFile: PLogFile = nil; const AMsg: string = ''; ARaise: Boolean = False); // Log异常对象 procedure LogWarning(const ASourceFileName, AMsg: string; ALogFile: PLogFile = nil); // Log警告信息 procedure LogError(const ASourceFileName, AMsg: string; ALogFile: PLogFile = nil; ErrorCode: Integer = 0); overload; // Log错误信息 procedure LogError(const ASourceFileName, AMsg: string; E: Exception; ALogFile: PLogFile = nil; ARaise: Boolean=False); overload; // Log错误信息 procedure LogWithTag(const ASourceFileName, AMsg, ATag: string; ALogFile: PLogFile = nil); // Log加标记 procedure LogSeparator(const ASourceFileName: string; ALogFile: PLogFile = nil); // Log分隔符 procedure LogEnterProc(const ASourceFileName, AProcName: string; ALogFile: PLogFile = nil); // Log进入过程 procedure LogLeaveProc(const ASourceFileName, AProcName: string; ALogFile: PLogFile = nil); // Log退出过程 procedure InitLogFileHandle(ALogFile: PLogFile = nil); procedure SurfaceLogError(const ASource, AMsg: string; E: Exception; ALogFile: PLogFile = nil); procedure InitLogFiles(ALogFile: PLogFile); procedure CloseLogFiles(ALogFile: PLogFile = nil); var G_LogFile : TLogFile; G_CurrentProcessId : Cardinal = 0; { 当前进程Id } // G_MainThreadId : Cardinal = 0; { 主线程Id } implementation procedure SDLog(const ASourceFileName, AMsg: string; ALogFile: PLogFile = nil); // Log一般信息 begin Log(ASourceFileName, AMsg, ALogFile); end; //uses // IniFiles; const { 最大日志文件大小,超过后下次运行时自动删除重新开始 } cMaxLogFileSize = 1024 * 1024 * 256; { 最大写入的次数,超过自动截断重写 } cMaxLogWriteCount = 6 * 1000 * 1000; { 自动截断时保留最后写入日志的大小 } cMaxLogSaveSize = 1024 * 100; procedure InitLogFileHandle(ALogFile: PLogFile); begin if ALogFile.Initialized then begin try DeleteCriticalSection(ALogFile.LogLock); except end; ALogFile.Initialized := False; end; if ALogFile.FileHandle <> INVALID_HANDLE_VALUE then begin CloseHandle(ALogFile.FileHandle); ALogFile.FileHandle := INVALID_HANDLE_VALUE; end; if ALogFile.ErrFileHandle <> INVALID_HANDLE_VALUE then begin CloseHandle(ALogFile.ErrFileHandle); ALogFile.ErrFileHandle := INVALID_HANDLE_VALUE; end; end; function GetFileSize(const AFileName: string): Int64; var HFileRes: THandle; begin Result := 0; HFileRes := CreateFile(PChar(@AFileName[1]), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if HFileRes <> INVALID_HANDLE_VALUE then begin Result := Windows.GetFileSize(HFileRes, nil); CloseHandle(HFileRes); end; end; procedure InitLogFiles(ALogFile: PLogFile); var s: ansistring; // ini: TIniFile; begin {$IFDEF LOGTOFILE} if not ALogFile.Initialized then begin if not ALogFile.AllowLogToFile then Exit; // ini := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); // try // logmode := strtointdef(ini.ReadString('Log', 'LogMode', '0'), 0); // finally // ini.Free; // end; if ALogFile.FileName = '' then begin case ALogFile.LogFileNameMode of 0: begin ALogFile.FileName := ansistring(ChangeFileExt(ParamStr(0), '.log')); ALogFile.ErrorFileName := ansistring(ChangeFileExt(ParamStr(0), '.Err.log')); end; 1: begin s := ansistring(trim(ParamStr(0))); s := copy(s, 1, length(s) - 4) + '_' + AnsiString(formatdatetime('mmdd_hhmmss', now())); ALogFile.FileName := s + '.log'; ALogFile.ErrorFileName := s + 'Err.log'; end; 2: begin ALogFile.Initialized := True; ALogFile.AllowLogToFile := False; exit; end; end; end; ALogFile.Initialized := true; try InitializeCriticalSection(ALogFile.LogLock); except end; // (ALogFile.FileHandle <> INVALID_HANDLE_VALUE) and // (ALogFile.FileHandle <> 0) and // (ALogFile.ErrFileHandle <> INVALID_HANDLE_VALUE) and // (ALogFile.ErrFileHandle <> 0); end; {$ENDIF} end; procedure CloseLogFiles(ALogFile: PLogFile); begin // 暂时不解锁 // Exit; if ALogFile <> nil then begin if ALogFile.Initialized then begin if (ALogFile.FileHandle <> INVALID_HANDLE_VALUE) then begin try if CloseHandle(ALogFile.FileHandle) then begin ALogFile.FileHandle := 0; end; except end; end; if (ALogFile.ErrFileHandle <> INVALID_HANDLE_VALUE) then begin try if CloseHandle(ALogFile.ErrFileHandle) then begin ALogFile.ErrFileHandle := 0; end; except end; end; ALogFile.Initialized := False; // 好像不能解锁 try DeleteCriticalSection(ALogFile.LogLock); except end; end; end; end; //------------------------------------------------------------------------------ // _Log - 写入信息至日志文件(可指定是否同时写入异常日志中) //------------------------------------------------------------------------------ // 函数参数: Msg = 日志信息 // IsError = 是否同时记录至异常日志中 // 返 回 值: 无 // 创建时间: 2005-12-5 22:29:51 //------------------------------------------------------------------------------ procedure _Log(const SourceFileName, AMsg: String; ALogFile: PLogFile; IsError: Boolean = False); var // hFile: THandle; BytesWrite: Cardinal; LocalTime: TSystemTime; // LogFileName: ansistring; LogFileHandle: THandle; CurrentThreadId: Cardinal; IsThreadMsg: Boolean; ErrMsg:string; T: Int64; L: Integer; {$IFDEF LOGTRUNCFILE} SaveBuffer: PChar; {$ENDIF} LogInfo: ansistring; tmpMsg: ansistring; FileSize: DWORD; begin {$IFDEF LOGTOFILE} if ALogFile = nil then begin ALogFile := @G_LogFile; end; InitLogFiles(ALogFile); if not ALogFile.Initialized then begin Exit; //InitLogFiles; end; if not ALogFile.AllowLogToFile then begin Exit; end; tmpMsg := ansistring(AMsg); L:= Length(tmpMsg); if L<65536 then //单行太大了。 begin {$IFDEF LOGTRUNCFILE} SaveBuffer:= @tmpMsg[1]; {$ENDIF} // if SaveBuffer[L] <> #0 then // Exit; end else begin Exit; end; CurrentThreadId := GetCurrentThreadId; IsThreadMsg := MainThreadId <> CurrentThreadId; if IsError then begin if (ALogFile.ErrFileHandle = 0) or (ALogFile.ErrFileHandle = INVALID_HANDLE_VALUE) then begin ALogFile.ErrFileHandle := CreateFileA(PAnsiChar(ALogFile.ErrorFileName), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if ALogFile.ErrFileHandle <> INVALID_HANDLE_VALUE then begin if Windows.GetFileSize(ALogFile.ErrFileHandle, @FileSize) > cMaxLogFileSize then SetEndOfFile(ALogFile.ErrFileHandle); SetFilePointer(ALogFile.ErrFileHandle, 0, nil, FILE_END); end; end; LogFileHandle := ALogFile.ErrFileHandle end else begin if (ALogFile.FileHandle = 0) or (ALogFile.FileHandle = INVALID_HANDLE_VALUE) then begin ALogFile.FileHandle := CreateFileA(PAnsiChar(ALogFile.FileName), GENERIC_WRITE {$IFDEF LOGTRUNCFILE}or GENERIC_READ{$ENDIF}, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if ALogFile.FileHandle <> INVALID_HANDLE_VALUE then begin if Windows.GetFileSize(ALogFile.FileHandle, @FileSize) > cMaxLogFileSize then begin {$IFDEF LOGTRUNCFILE} InterlockedExchange(ALogFile.LogWriteCount, cMaxLogWriteCount); // 设为最大日志写入次数,下次写就会自动截断了 {$ELSE} SetEndOfFile(G_LogFileHandle) {$ENDIF} end else begin InterlockedExchange(ALogFile.LogWriteCount, FileSize div 100); // 大致估算已写入日志次数 end; SetFilePointer(ALogFile.FileHandle, 0, nil, FILE_END); end; end; LogFileHandle := ALogFile.FileHandle; // 检查写入次数是否已超出限制,超出则自动截断或重写 if InterlockedIncrement(ALogFile.LogWriteCount) > cMaxLogWriteCount then begin if InterlockedExchange(ALogFile.LogWriteCount, 0) > cMaxLogWriteCount then begin {$IFDEF LOGTRUNCFILE} GetMem(SaveBuffer, cMaxLogSaveSize); try SetFilePointer(LogFileHandle, -cMaxLogSaveSize, nil, FILE_END); ReadFile(LogFileHandle, SaveBuffer^, cMaxLogSaveSize, BytesWrite, nil); {$ENDIF} SetFilePointer(LogFileHandle, 0, nil, FILE_BEGIN); SetEndOfFile(LogFileHandle); {$IFDEF LOGTRUNCFILE} WriteFile(LogFileHandle, SaveBuffer^, BytesWrite, BytesWrite, nil); except end; FreeMem(SaveBuffer); {$ENDIF} end; end; end; // LogFileName := G_LogErrorFileName else // LogFileName := G_LogFileName; // hFile := CreateFileA(PAnsiChar(LogFileName), GENERIC_WRITE, FILE_SHARE_READ, nil, // OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); // if hFile = INVALID_HANDLE_VALUE then Exit; try {$IFDEF LOGSOURCEFILENAME} LogInfo := '[' + ansistring(SourceFileName) + ']' + tmpMsg; {$ELSE} LogInfo := Msg; {$ENDIF LOGSOURCEFILENAME} if IsThreadMsg then begin LogInfo := AnsiString(Format(#9'[%.8x] %s', [CurrentThreadId, LogInfo])); end; // SetFilePointer(LogFileHandle, 0, nil, FILE_END); GetLocalTime(LocalTime); QueryPerformanceCounter(T); T:= T mod 1000000; LogInfo := ansistring(LogInfo + #13#10); //(*// try LogInfo := ansistring(Format('(%.8x) %.4d-%.2d-%.2d %.2d:%.2d:%.2d.%.3d.%.6d=%s'#13#10, [ G_CurrentProcessId, LocalTime.wYear, LocalTime.wMonth, LocalTime.wDay, LocalTime.wHour, LocalTime.wMinute, LocalTime.wSecond, LocalTime.wMilliseconds, T, LogInfo])); except LogInfo := ''; end; //*) // EnterCriticalSection(G_LogLock); try try SetFilePointer(LogFileHandle, 0, nil, FILE_END); WriteFile(LogFileHandle, LogInfo[1], Length(LogInfo), BytesWrite, nil); except on E: Exception do begin // 加一段日志情况的保护 ErrMsg := '日志错误:' + E.Message + #13#10; WriteFile(LogFileHandle, ErrMsg[1], Length(ErrMsg), BytesWrite, nil); end; end; // FlushFileBuffers(LogFileHandle); finally // LeaveCriticalSection(G_LogLock); end; finally // CloseHandle(hFile); end; if IsError then begin _Log(SourceFileName, string(tmpMsg), ALogFile, False); end; {$ENDIF} end; //------------------------------------------------------------------------------ // _LogE - 记录错误信息至日志文件(同时写入至二个日志文件中) //------------------------------------------------------------------------------ // 函数参数: Msg = 发生异常的过程名(或其他日志内容) // E = 异常对象 // 返 回 值: 无 // 创建时间: 2005-12-5 22:30:54 //------------------------------------------------------------------------------ procedure _LogE(const SourceFileName, Msg: ansistring; E: Exception; ALogFile: PLogFile); var LogInfo: ansistring; begin LogInfo := ansistring(Format('!!! Runtime Exception: %s (ClassName: %s; Msg: %s)', [Msg, E.ClassName, E.Message])); _Log(string(SourceFileName), string(LogInfo), ALogFile, True); end; //------------------------------------------------------------------------------ // DebugOut - 输出调试信息串 //------------------------------------------------------------------------------ // 函数参数: const S: ansistring // 返 回 值: 无 // 尚存问题: // 创建时间: 2006-5-9 12:05:15 //------------------------------------------------------------------------------ procedure DebugOut(const SourceFileName, S: ansistring); begin {$IFDEF LOGTODEBUGGER} OutputDebugStringA(PAnsiChar(Format('[%s] %s', [SourceFileName, S]))); {$ENDIF} end; // Log 系列输出函数 == Start == procedure Log(const ASourceFileName, AMsg: String; ALogFile: PLogFile); // Log一般信息 begin DebugOut(ansistring(ASourceFileName), ansistring(AMsg)); _Log(ASourceFileName, AMsg, ALogFile); end; procedure LogException(const ASourceFileName: String; E: Exception; ALogFile: PLogFile = nil; const AMsg: String=''; ARaise: Boolean = False); begin LogError(ASourceFileName, AMsg, E, ALogFile, ARaise); // DebugOut(ASourceFileName, Format('!! EXCEPTION [%s]: %s; %s', [E.ClassName, E.Message, AMsg])); // _LogE(ASourceFileName, AMsg, E); {$IFDEF LOGERRORRAISE} // 为方便查看错误 // raise E; {$ENDIF} end; procedure LogWithTag(const ASourceFileName, AMsg: String; const ATag: String; ALogFile: PLogFile); var S: String; begin S := Format('[tag=%s] %s', [ATag, AMsg]); DebugOut(ansistring(ASourceFileName), ansistring(S)); _Log(ASourceFileName, S, ALogFile); end; procedure LogWarning(const ASourceFileName, AMsg: string; ALogFile: PLogFile); var S: ansistring; begin S := '[WARNING] ' + AnsiString(AMsg); DebugOut(ansistring(ASourceFileName), S); _Log(ASourceFileName, string(S), ALogFile, True); end; procedure LogError(const ASourceFileName, AMsg: string; ALogFile: PLogFile = nil; ErrorCode: Integer = 0); var S: ansistring; begin if ErrorCode <> 0 then S := '[ERROR ErrorCode=' + ansistring(IntToStr(ErrorCode)) + '] ' + ansistring(AMsg) else S := '[ERROR] ' + ansistring(AMsg); DebugOut(ansistring(ASourceFileName), S); _Log(ASourceFileName, string(S), ALogFile, True); {$IFDEF LOGERRORRAISE} // 为方便查看错误 // 为了区分错误类型使用HelpContext标识 raise Exception.Create('[' + ASourceFileName + ']' + AMsg).HelpContext = ErrorCode; {$ENDIF} end; procedure LogError(const ASourceFileName, AMsg: string; E: Exception; ALogFile: PLogFile = nil; ARaise: Boolean = False); overload; // Log错误信息 var S: ansistring; begin S:= ansistring(Format('!!! EXCEPTION [%s][%d]: %s; %s', [E.ClassName, E.HelpContext, E.Message, AMsg])); DebugOut(ansistring(ASourceFileName), S); _Log(ASourceFileName, string(S), ALogFile, True); {$IFDEF LOGERRORRAISE} // 为方便查看错误 // 为了区分错误类型使用HelpContext标识 if ARaise then raise E; {$ENDIF} end; procedure LogSeparator(const ASourceFileName: string; ALogFile: PLogFile); begin DebugOut(ansistring(ASourceFileName), '-----------------------'); _Log(ASourceFileName, '-----------------------', ALogFile); end; procedure LogEnterProc(const ASourceFileName, AProcName: string; ALogFile: PLogFile); var S: ansistring; begin S := '[ENTERPROC] ' + ansistring(AProcName); DebugOut(ansistring(ASourceFileName), S); _Log(ASourceFileName, string(S), ALogFile); end; procedure LogLeaveProc(const ASourceFileName, AProcName: string; ALogFile: PLogFile); var S: ansistring; begin S := '[LEAVEPROC] ' + ansistring(AProcName); DebugOut(ansistring(ASourceFileName), S); _Log(ASourceFileName, string(S), ALogFile); end; procedure AssertErrorHandler(const Msg, Filename: string; LineNumber: Integer; ErrorAddr: Pointer); begin {$IFDEF ASSERTMSGSHOW} // 将Assert信息通过MessageBox显示出来 MessageBox(0, PAnsiChar(Format('%s (%s, line %d, address $%x)', [Msg, Filename, LineNumber, Pred(Integer(ErrorAddr))])) , '日志提示', MB_OK + MB_ICONSTOP); {$ENDIF} {$IFDEF ASSERTMSGLOG} // 将Assert信息Log至文件 Log(Format('%s, line %d, address $%x', [ExtractFileName(Filename), LineNumber, Pred(Integer(ErrorAddr))]) , Msg, @G_LogFile); {$ENDIF} {$IFDEF ASSERTMSGRAISE} raise Exception.Create(Format('%s (%s, line %d, address $%x)', [Msg, Filename, LineNumber, Pred(Integer(ErrorAddr))])); {$ENDIF} end; procedure RerouteAssertions; begin System.AssertErrorProc := AssertErrorHandler; end; procedure SurfaceLogError(const ASource, AMsg: String; E: Exception; ALogFile: PLogFile = nil); begin if E<>nil then LogError(ASource, AMsg, E, ALogFile, False) else LogError(ASource, AMsg, ALogFile); end; initialization // 替换原有的Assert // G_MainThreadId := GetCurrentThreadId; FillChar(G_LogFile, SizeOf(G_LogFile), 0); G_LogFile.AllowLogToFile := true; G_LogFile.FileHandle := INVALID_HANDLE_VALUE; G_LogFile.ErrFileHandle := INVALID_HANDLE_VALUE; {$IFDEF REROUTEASSERT} RerouteAssertions; {$ENDIF} //finalization // CloseLogFiles(@G_LogFile); end.
unit UQueen; interface uses USimulation; type TQueen = class(TRunningObject) public Col, Row : Byte; constructor Create(ACol : Byte); protected procedure Execute; override; end; TQueensSimulation = class(TRunningObject) protected procedure Execute; override; end; implementation const N = 5; var Queens : array [1 .. N] of TQueen; Rows : array [1 .. N] of Boolean; DiagsUp : array [-N + 1 .. N - 1] of Boolean; DiagsDown : array [2 .. 2 * N] of Boolean; function IsFree(Col, Row : Byte) : Boolean; begin Result := not Rows[Row] and not DiagsUp[Col - Row] and not DiagsDown[Col + Row]; end; procedure MakeOccupied(Col, Row : Byte); begin Rows[Row] := True; DiagsUp[Col - Row] := True; DiagsDown[Col + Row] := True; end; procedure MakeFree(Col, Row : Byte); begin Rows[Row] := False; DiagsUp[Col - Row] := False; DiagsDown[Col + Row] := False; end; procedure Remember; var i : Integer; begin for i := 1 to N do Write(Queens[i].Row, ' '); WriteLn; end; { TQueen } constructor TQueen.Create(ACol : Byte); begin Col := ACol; Row := 1; inherited Create; end; procedure TQueen.Execute; begin Detach; while True do begin if IsFree(Col, Row) then begin MakeOccupied(Col, Row); if Col < N then begin SwitchTo(Queens[Col + 1]); end else Remember; MakeFree(Col, Row); end; Inc(Row); if Row > N then begin Row := 1; if Col = 1 then Detach else SwitchTo(Queens[Col - 1]); end; end; end; { TQueensSimulation } procedure TQueensSimulation.Execute; var i : Integer; begin Detach; for i := 1 to N do Queens[i] := TQueen.Create(i); SwitchTo(Queens[1]); for i :=1 to N do Queens[i].Free; Detach; end; end.
{ Check for particular error conditions. } module hier_check; define hier_check_noparm; %include 'hier2.ins.pas'; { ******************************************************************************** * * Function HIER_CHECK_NOPARM (STAT) * * The function returns true iff STAT indicates that an attempt was made to * read a parameter or token, but it was not found. If so, STAT is cleard of * the error. } function hier_check_noparm ( {check for "no parameter" error} in out stat: sys_err_t) {status to check, cleared on "no parameter"} :boolean; {TRUE = STAT indicated "no parm" error} val_param; begin hier_check_noparm := sys_stat_match ( hier_subsys_k, hier_stat_noparm_k, stat); end;
{ @abstract(General functions for GMLib.) @author(Xavier Martinez (cadetill) <cadetill@gmail.com>) @created(August 21, 2022) @lastmod(August 21, 2022) The GMLib.Functions unit provides access to general functions used by GMLib. } unit GMLib.Functions.Vcl; {$I ..\gmlib.inc} interface uses GMLib.Functions; type // @include(..\Help\docs\GMLib.Functions.TGenFunc.txt) TGenFunc = class(GMLib.Functions.TGenFunc) public class procedure ProcessMessages; end; implementation uses {$IFDEF DELPHIXE2} Winapi.Windows; {$ELSE} Windows; {$ENDIF} { TGenFunc } class procedure TGenFunc.ProcessMessages; var Msg: TMsg; begin Sleep(1); while PeekMessage(msg, 0, 0, 0, PM_REMOVE) do DispatchMessage(msg); end; end.
(* Copyright (c) 2011, Stefan Glienke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of this library nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit DSharp.ComponentModel.Composition.Container deprecated; interface uses Classes, DSharp.ComponentModel.Composition, DSharp.ComponentModel.Composition.Primitives, DSharp.Core.Lazy, Generics.Collections, Rtti, SysUtils, TypInfo; type ILazyEvaluator = interface ['{12956345-B037-484D-88D1-FF7706184C20}'] function Evaluate: TObject; end; TCompositionContainer = class(TInterfacedObject, IServiceLocator) private type TEvaluator = class(TInterfacedObject, ILazyEvaluator) private FContainer: TCompositionContainer; FInstanceClass: TClass; FName: string; FOwned: Boolean; FPolicy: TCreationPolicy; public constructor Create(Container: TCompositionContainer; const Name: string; InstanceClass: TClass; Policy: TCreationPolicy; Owned: Boolean); function Evaluate: TObject; end; private FCatalog: TBaseCatalog; FContext: TRttiContext; FObjects: TObjectDictionary<string, TObject>; FOwnedObjects: TObjectList<TObject>; FPendingCreation: TStringList; function CheckAndCreate(const Name: string; InstanceClass: TClass; AddToContainer: Boolean; OwnsObject: Boolean): TObject; function CreateLazy(LazyType: TRttiType; LazyContentType: TRttiType; ALazyEvaluator: ILazyEvaluator; MetaData: TExportMetaData = nil): TValue; function GetRepositoryName(AType: TClass): string; overload; function Instantiate(AType: TClass; OwnsObject: Boolean): TObject; protected function Factory(const Name: string; InstanceClass: TClass; Policy: TCreationPolicy; Owned: Boolean; out Value: TObject): Boolean; public function GetExport(const Name: string; TypeInfo: PTypeInfo): TValue; overload; function GetExportName(const Name: string; TypeInfo: PTypeInfo): string; function GetExports(const Name: string; TypeInfo: PTypeInfo): TValue; overload; protected function GetLazyContentType(RttiType: TRttiType): TRttiType; function TryGetExport(const Name: string; TypeInfo: PTypeInfo; out Value: TValue): Boolean; function TryGetExports(const Name: string; TypeInfo: PTypeInfo; out OutValues: TValue): Boolean; public constructor Create(Catalog: TBaseCatalog); destructor Destroy; override; function GetExport<T>: T; overload; function GetExports<T>: T; overload; function GetExport(const Name: string): TObject; overload; function GetExport<T>(const Name: string): T; overload; function GetExports<T>(const Name: string): T; overload; function Resolve(TypeInfo: PTypeInfo; const Name: string): TValue; overload; function Resolve<T>(const Name: string = ''): T; overload; procedure SatisfyImportsOnce(Instance: TObject); end; ELazyException = class(Exception); implementation uses DSharp.Core.Reflection; type TLazy<T> = class(TInterfacedObject, ILazy<T>) private FInternalValue: T; FLazyEvaluator: ILazyEvaluator; FMetaData: TExportMetaData; FTypeInfo: PTypeInfo; function GetMetaData: TObject; function Invoke: T; public constructor Create(ALazyEvaluator: ILazyEvaluator; TypeInfo: PTypeInfo; MetaData: TExportMetaData = nil); function IsValueCreated: Boolean; property MetaData: TObject read GetMetaData; property Value: T read Invoke; end; { TCompositionContainer } function TCompositionContainer.CheckAndCreate(const Name: string; InstanceClass: TClass; AddToContainer: Boolean; OwnsObject: Boolean): TObject; var LFirstExport: Boolean; i: Integer; begin Result := nil; LFirstExport := not Assigned(FPendingCreation); if LFirstExport then begin FPendingCreation := TStringList.Create; end; try if FPendingCreation.IndexOf(Name) >= 0 then begin raise ECompositionException.Create('Could not instantiate object due to circular dependency.'); end; i := FPendingCreation.Add(Name); try Result := Instantiate(InstanceClass, OwnsObject); if not Assigned(Result) then begin raise ECompositionException.Create('Could not instantiate object.'); end; if AddToContainer then begin FObjects.Add(Name, Result); end; SatisfyImportsOnce(Result); finally FPendingCreation.Delete(i); end; finally if LFirstExport then begin FreeAndNil(FPendingCreation); end; end; end; constructor TCompositionContainer.Create(Catalog: TBaseCatalog); begin FCatalog := Catalog; FObjects := TObjectDictionary<string, TObject>.Create([]); FOwnedObjects := TObjectList<TObject>.Create; FContext := TRttiContext.Create; end; function TCompositionContainer.CreateLazy(LazyType: TRttiType; LazyContentType: TRttiType; ALazyEvaluator: ILazyEvaluator; MetaData: TExportMetaData): TValue; var LValue: TValue; LLazyInterface: IInterface; LLazyObject: IInterface; begin // a little bit of binary trickery if LazyContentType is TRttiInterfaceType then begin LLazyInterface := ILazy<IInterface>(TLazy<IInterface>.Create( ALazyEvaluator, LazyContentType.Handle, MetaData)); LValue := TValue.From<IInterface>(LLazyInterface); end; if LazyContentType is TRttiInstanceType then begin LLazyObject := ILazy<TObject>(TLazy<TObject>.Create( ALazyEvaluator, LazyContentType.Handle, MetaData)); LValue := TValue.From<IInterface>(LLazyObject); end; TValueData(LValue).FTypeInfo := LazyType.Handle; Result := LValue; end; destructor TCompositionContainer.Destroy; begin FOwnedObjects.Free; FObjects.Free; inherited; end; function TCompositionContainer.Factory(const Name: string; InstanceClass: TClass; Policy: TCreationPolicy; Owned: Boolean; out Value: TObject): Boolean; var LRepositoryName: string; begin Value := nil; Result := False; case Policy of cpShared: begin LRepositoryName := GetRepositoryName(InstanceClass); Result := FObjects.TryGetValue(LRepositoryName, Value); if not Result then begin Value := CheckAndCreate(LRepositoryName, InstanceClass, True, Owned); Result := True; end; end; cpNonShared: begin Value := CheckAndCreate(Name, InstanceClass, False, Owned); Result := True; end; end; end; function TCompositionContainer.GetExport(const Name: string; TypeInfo: PTypeInfo): TValue; var LValue: TValue; begin if TryGetExport(Name, TypeInfo, Result) then begin // Workaround for RTL bug. We want to assign the TValue in the correct type LValue := Result; Result.TryCast(TypeInfo, LValue); Result := LValue; end else begin raise ECompositionException.Create('No export is defined for ' + GetExportName(Name, TypeInfo)); end; end; function TCompositionContainer.TryGetExport(const Name: string; TypeInfo: PTypeInfo; out Value: TValue): Boolean; var LInfos: TExportInfoList; LOwned: Boolean; LFinalName: string; LTargetType, LLazyContentType: TRttiType; LObject: TObject; begin Value := nil; Result := False; LFinalName := Name; LTargetType := FContext.GetType(TypeInfo); LLazyContentType := GetLazyContentType(LTargetType); if Assigned(LLazyContentType) then begin if LFinalName = '' then begin LFinalName := LLazyContentType.QualifiedName; end; LOwned := LLazyContentType.TypeKind <> tkInterface; end else begin if LFinalName = '' then begin LFinalName := LTargetType.QualifiedName; end; LOwned := LTargetType.TypeKind <> tkInterface; end; if FCatalog.CanResolve(LFinalName) then begin LInfos := FCatalog.GetExports(LFinalName); if LInfos.Count <> 1 then begin raise ECompositionException.Create('There are multiple exports but a single import was requested.'); end; if Assigned(LInfos[0].RttiProperty) then LOwned := True; if Assigned(LLazyContentType) then begin Value := CreateLazy(LTargetType, LLazyContentType, TEvaluator.Create(Self, LFinalName, LInfos[0].InstanceClass, LInfos[0].Policy, LOwned), LInfos[0].MetaData); Result := True; end else begin Result := Factory(LFinalName, LInfos[0].InstanceClass, LInfos[0].Policy, LOwned, LObject); // handle exported property if LInfos[0].RttiProperty <> nil then begin Result := Result and LInfos[0].RttiProperty.IsReadable; if Result then begin Value := LInfos[0].RttiProperty.GetValue(LObject); end; end else begin if Result then begin Value := LObject; end else begin Value := nil; end; end; end; end; end; function TCompositionContainer.TryGetExports(const Name: string; TypeInfo: PTypeInfo; out OutValues: TValue): Boolean; var LInfos: TExportInfoList; LInfo: TExportInfo; LObject: TObject; i: Integer; LValues: array of TValue; LValue: TValue; LElementType: TRttiType; LOwned: Boolean; LLazyContentType: TRttiType; LFinalName: string; begin LValues := nil; Result := False; LElementType := (FContext.GetType(TypeInfo) as TRttiDynamicArrayType).ElementType; LLazyContentType := GetLazyContentType(LElementType); if Assigned(LLazyContentType) then begin if LFinalName = '' then begin LFinalName := LLazyContentType.QualifiedName; end; LOwned := LLazyContentType.TypeKind <> tkInterface; end else begin if LFinalName = '' then begin LFinalName := LElementType.QualifiedName; end; LOwned := LElementType.TypeKind <> tkInterface; end; if FCatalog.CanResolve(LFinalName) then begin LInfos := FCatalog.GetExports(LFinalName); if LInfos.Count = 0 then begin raise ECompositionException.Create('Resolving failed'); end; SetLength(LValues, LInfos.Count); if Assigned(LLazyContentType) then begin for i := 0 to LInfos.Count - 1 do begin LInfo := LInfos[i]; LValues[i] := CreateLazy(LElementType, LLazyContentType, TEvaluator.Create(Self, LFinalName, LInfo.InstanceClass, LInfo.Policy, LOwned), LInfo.MetaData); end; Result := True; end else begin Result := True; for i := 0 to LInfos.Count - 1 do begin LInfo := LInfos[i]; LObject := nil; Result := Result and Factory(LFinalName, LInfo.InstanceClass, LInfo.Policy, LOwned, LObject); // Workaround for RTL bug. We want to assign the TValue in the correct type LValues[i] := LObject; LValue := LValues[i]; LValues[i].TryCast(LElementType.Handle, LValue); LValues[i] := LValue; end; end; end; OutValues := TValue.FromArray(TypeInfo, LValues); end; function TCompositionContainer.GetExport<T>: T; begin Result := GetExport<T>(FContext.GetType(TypeInfo(T)).QualifiedName); end; function TCompositionContainer.GetExport(const Name: string): TObject; begin Result := GetExport<TObject>(Name); end; function TCompositionContainer.GetExport<T>(const Name: string): T; var LValue: TValue; begin LValue := GetExport(Name, TypeInfo(T)); Result := LValue.AsType<T>; end; function TCompositionContainer.GetExportName(const Name: string; TypeInfo: PTypeInfo): string; var LType, LLazyContentType: TRttiType; begin if Name <> '' then begin Result := Name; end else begin LType := FContext.GetType(TypeInfo); if LType is TRttiDynamicArrayType then begin LType := TRttiDynamicArrayType(LType).ElementType; end; LLazyContentType := GetLazyContentType(LType); if Assigned(LLazyContentType) then begin LType := LLazyContentType; end; Result := LType.QualifiedName; end; end; function TCompositionContainer.GetLazyContentType(RttiType: TRttiType): TRttiType; begin if RttiType.IsGenericTypeOf('ILazy') or RttiType.IsGenericTypeOf('TFunc') then begin Result := RttiType.GetGenericArguments()[0]; if not Assigned(Result) then begin raise ECompositionException.Create('Type parameter for ' + RttiType.Name + ' could not be found.'); end; end else begin Result := nil; end; end; function TCompositionContainer.GetExports(const Name: string; TypeInfo: PTypeInfo): TValue; begin if not TryGetExports(Name, TypeInfo, Result) then begin raise ECompositionException.Create('No export is defined for ' + GetExportName(Name, TypeInfo)); end; end; function TCompositionContainer.GetExports<T>: T; begin Result := GetExports<T>(FContext.GetType(TypeInfo(T)).QualifiedName); end; function TCompositionContainer.GetExports<T>(const Name: string): T; var LValue: TValue; begin if not (FContext.Create.GetType(TypeInfo(T)) is TRttiDynamicArrayType) then begin raise ECompositionException.Create('GetExports<T> must supply dynamic array type.'); end; LValue := GetExports(Name, TypeInfo(T)); Result := LValue.AsType<T>; end; constructor TCompositionContainer.TEvaluator.Create(Container: TCompositionContainer; const Name: string; InstanceClass: TClass; Policy: TCreationPolicy; Owned: Boolean); begin FContainer := Container; FName := Name; FInstanceClass := InstanceClass; FPolicy := Policy; FOwned := Owned; end; function TCompositionContainer.TEvaluator.Evaluate: TObject; begin if not FContainer.Factory(FName, FInstanceClass, FPolicy, FOwned, Result) then begin raise ELazyException.Create('Failed lazy evaluating...'); end; end; function TCompositionContainer.GetRepositoryName(AType: TClass): string; begin Result := FContext.Create.GetType(AType).QualifiedName; end; function TCompositionContainer.Instantiate(AType: TClass; OwnsObject: Boolean): TObject; function HasImportingConstructor(Method: TRttiMethod): Boolean; var LAttribute: TCustomAttribute; begin for LAttribute in Method.GetAttributes do begin if LAttribute is ImportingConstructorAttribute then begin Exit(True); end; end; Result := False; end; function IsValidConstructor(RttiType: TRttiType; Method: TRttiMethod): Boolean; var LAnotherMethod: TRttiMethod; begin if not Method.IsConstructor then begin Exit(False); end; if Method.Parent.AsInstance.MetaclassType <> TObject then begin Exit(True); end; // Method is TObject.Create, check if there are other constructors for LAnotherMethod in RttiType.GetMethods do begin if LAnotherMethod.IsConstructor and (LAnotherMethod.Visibility = mvPublic) then begin if LAnotherMethod.Parent.AsInstance.MetaclassType <> TObject then begin Exit(False); end; end; end; Result := True; end; var LMethod: TRttiMethod; LParams: TArray<TRttiParameter>; LType: TRttiType; LParamValues: array of TValue; i: Integer; begin LType := FContext.Create.GetType(AType); Result := nil; for LMethod in LType.GetMethods do begin if LMethod.IsConstructor and (LMethod.Visibility = mvPublic) then begin LParams := LMethod.GetParameters; if (Length(LParams) = 0) or HasImportingConstructor(LMethod) then begin if (Length(LParams) = 0) and IsValidConstructor(LType, LMethod) then begin Result := LMethod.Invoke(LType.AsInstance.MetaclassType, []).AsObject; Break; end; if Length(LParams) > 0 then begin SetLength(LParamValues, Length(LParams)); for i := 0 to Length(LParams) - 1 do begin LParamValues[i] := GetExport('', LParams[i].ParamType.Handle); end; Result := LMethod.Invoke(LType.AsInstance.MetaclassType, LParamValues).AsObject; Break; end; end; end; end; if (Result <> nil) and OwnsObject then begin FOwnedObjects.Add(Result); end; end; function TCompositionContainer.Resolve(TypeInfo: PTypeInfo; const Name: string): TValue; begin Result := GetExport(Name, TypeInfo); end; function TCompositionContainer.Resolve<T>(const Name: string): T; begin Result := Resolve(TypeInfo(T), Name).AsType<T>; end; procedure TCompositionContainer.SatisfyImportsOnce(Instance: TObject); var LType: TRttiType; LProperty: TRttiProperty; LAttribute: TCustomAttribute; LName: string; begin LType := FContext.GetType(Instance.ClassType); for LProperty in LType.GetProperties do begin for LAttribute in LProperty.GetAttributes do begin if LAttribute is ImportAttribute then begin if not LProperty.IsWritable then begin raise ECompositionException.Create('Property is not writable.'); end; LName := ImportAttribute(LAttribute).Name; LProperty.SetValue(Instance, GetExport(LName, LProperty.PropertyType.Handle)); end; if LAttribute is ImportManyAttribute then begin if not LProperty.IsWritable then begin raise ECompositionException.Create('Property is not writable.'); end; if not (LProperty.PropertyType is TRttiDynamicArrayType) then begin raise ECompositionException.Create('Only dynamic arrays can be written to.'); end; LProperty.SetValue(Instance, GetExports(ImportAttribute(LAttribute).Name, TRttiDynamicArrayType(LProperty.PropertyType).Handle)); end; end; end; end; { TLazy<T> } function TLazy<T>.IsValueCreated: Boolean; begin if SizeOf(FInternalValue) <> SizeOf(Pointer) then begin raise Exception.Create('Invalid internal value type'); end; Result := Cardinal(Pointer(@FInternalValue)^) <> 0; end; constructor TLazy<T>.Create(ALazyEvaluator: ILazyEvaluator; TypeInfo: PTypeInfo; MetaData: TExportMetaData); begin FLazyEvaluator := ALazyEvaluator; FTypeInfo := TypeInfo; FMetaData := MetaData; if SizeOf(FInternalValue) <> SizeOf(Pointer) then begin raise Exception.Create('Invalid internal value type'); end; end; function TLazy<T>.GetMetaData: TObject;//TExportMetaData; begin Result := FMetaData; end; function TLazy<T>.Invoke: T; var LValue: TObject; LInterfaceValue: IInterface; LType: TRttiType; begin if not IsValueCreated then begin if not Assigned(FLazyEvaluator) then begin raise ELazyException.Create('Could not lazy evaluate.'); end; LValue := FLazyEvaluator.Evaluate; LType := TRttiContext.Create.GetType(FTypeInfo); if LType is TRttiInterfaceType then begin if not Supports(LValue, TRttiInterfaceType(LType).GUID, LInterfaceValue) then begin raise ELazyException.Create('Could not lazy evaluate.' + GUIDToString(TRttiInterfaceType(LType).GUID)); end; LInterfaceValue._AddRef; Move(LInterfaceValue, FInternalValue, SizeOf(LInterfaceValue)); end else begin if LType is TRttiInstanceType then begin PPointer(@FInternalValue)^ := LValue; end else begin raise ELazyException.Create('Could not lazy evaluate.'); end; end; if not IsValueCreated then begin raise ELazyException.Create('Could not lazy evaluate.'); end; end; Result := FInternalValue; end; end.
unit UfbFichier; // |===========================================================================| // | UNIT UfbFichier | // | Copyright © 2009 F.BASSO | // |___________________________________________________________________________| // | Unité contenant les fonctions de manipulation de fichiers avec prise en | // | charge des nom de fichier > 255 caractères | // |___________________________________________________________________________| // | Ce programme est libre, vous pouvez le redistribuer et ou le modifier | // | selon les termes de la Licence Publique Générale GNU publiée par la | // | Free Software Foundation . | // | Ce programme est distribué car potentiellement utile, | // | mais SANS AUCUNE GARANTIE, ni explicite ni implicite, | // | y compris les garanties de commercialisation ou d'adaptation | // | dans un but spécifique. | // | Reportez-vous à la Licence Publique Générale GNU pour plus de détails. | // | | // | anbasso@wanadoo.fr | // |___________________________________________________________________________| // | Versions | // | 1.1.0.0 Ajout FBFileSetShortName, FBFileGetShortName | // | 1.0.0.0 Création de l'unité | // |===========================================================================| interface type TonBeforeDeleteFile = procedure (Max : integer)of object; TonprogressDeleteFile = procedure (position : integer)of object; const fmOpenRead = $0000; fmOpenWrite = $0001; fmOpenReadWrite = $0002; fmShareCompat = $0000 ; // DOS compatibility mode is not portable fmShareExclusive = $0010; fmShareDenyWrite = $0020; fmShareDenyRead = $0030 ; // write-only not supported on all platforms fmShareDenyNone = $0040; faReadOnly = $00000001 ; faHidden = $00000002 ; faSysFile = $00000004 ; faVolumeID = $00000008 deprecated; // not used in Win32 faDirectory = $00000010; faArchive = $00000020 ; faSymLink = $00000040 ; faAnyFile = $0000003F; var FBonprogressdelete : TonprogressDeleteFile ; FBonbeforedelete : TonBeforeDeleteFile ; procedure assignB( p : TonBeforeDeleteFile); function FBFileSetAttr ( const FileName: string; Attr: Integer ): Integer; function FBFileGetAttr ( const FileName: string ): Integer; function FBFileDelete ( const FileName : string ): boolean; overload; function FBFileDelete ( const FileName : string ; booBroyage : boolean ): boolean;overload; function FBFileOpen ( const FileName: string; Mode: LongWord ): Integer; function FBFileCreate ( const FileName: string ): Integer; procedure FBFileClose ( Handle: Integer ); function FBGetFileCreationTime ( const FileName: string ): TDateTime; function FBGetFileLastWriteTime ( const FileName: string ): TDateTime; function FBGetFileLastAccessTime ( const FileName: string ): TDateTime; function FBFileRename ( const OldName, NewName: string ): Boolean; function FBFileWrite ( Handle: Integer; const Buffer; Count: LongWord ): Integer; function FBFileRead ( Handle: Integer; var Buffer; Count: LongWord ): Integer; function FBFileSeek ( Handle, Offset, Origin: Integer ): Integer;overload; function FBFileSeek ( Handle: Integer; const Offset: Int64; Origin: Integer ): Int64;overload; function FBGetFileSize ( const FileName: string ): Int64; function FBFileExists ( const FileName: string ): boolean; function FBFileSetShortName ( Const FileName : string ; Const shortfilename : string ) : boolean; function FBFileGetShortName ( Const FileName : string ) : string; function FBFileGetLongName (const Filename : string) : string; function strCheminToUnicode ( Const Chemin:string ):pwidechar; function FBDirectoryExists ( const DirName: string ): boolean; function FBDirectoryRemove ( const FileName : string ): boolean;overload; function FBDirectoryRemove ( const FileName : string ;booBroyage : boolean ): boolean;overload; function FBDirectoryRemoveR ( const FileName : string ): integer; Function FBDirectoryCreate ( const DirName: string ) : boolean; function FBForceDirectories ( Dir: string ): Boolean; function FBChangeFileExt ( const FileName, Extension: string ): string; function FBExtractFilePath ( const FileName: string ): string; function FBExtractFileDir ( const FileName: string ): string; function FBExtractFileDrive ( const FileName: string ): string; function FBExtractFileName ( const FileName: string ): string; function FBExtractFileExt ( const FileName: string ): string; implementation uses windows,dialogs,sysutils; type PDayTable = ^TDayTable; TDayTable = array[1..12] of Word; Int64Rec = packed record case Integer of 0: (Lo, Hi: Cardinal); 1: (Cardinals: array [0..1] of Cardinal); 2: (Words: array [0..3] of Word); 3: (Bytes: array [0..7] of Byte); end; const MonthDays: array [Boolean] of TDayTable = ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)); function SetFileShortNameW(hFile: THandle;lpFileName: PWideChar): longbool ; stdcall; external 'Kernel32.dll' name 'SetFileShortNameW'; function EncodeTime(Hour, Min, Sec, MSec: Word): TDateTime; begin if (Hour < 24) and (Min < 60) and (Sec < 60) and (MSec < 1000) then result := (Hour * 3600000 + Min * 60000 + Sec * 60 + MSec) / 86400000 else result := -1; end; function IsLeapYear(Year: Word): Boolean; begin Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0)); end; function EncodeDate(Year, Month, Day: Word): TDateTime; var I: Integer; DayTable: PDayTable; begin DayTable := @MonthDays[IsLeapYear(Year)]; if (Year >= 1) and (Year <= 9999) and (Month >= 1) and (Month <= 12) and (Day >= 1) and (Day <= DayTable^[Month]) then begin for I := 1 to Month - 1 do Inc(Day, DayTable^[I]); I := Year - 1; result := I * 365 + I div 4 - I div 100 + I div 400 + Day - 693594; end else result := -1 end; function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime; begin with SystemTime do begin Result := EncodeDate(wYear, wMonth, wDay); if Result >= 0 then Result := Result + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds) else Result := Result - EncodeTime(wHour, wMinute, wSecond, wMilliSeconds); end; end; function ExcludeTrailingPathDelimiter(const S: string): string; begin Result := S; if Result[Length(Result)]='\' then SetLength(Result, Length(Result)-1); end; procedure assignb( p : TonBeforeDeleteFile ); begin FBonbeforedelete := p; end; function SetPrivilege(Privilege: PChar; EnablePrivilege: boolean; out PreviousState: boolean): DWORD; var Token: THandle; NewState: TTokenPrivileges; Luid: TLargeInteger; PrevState: TTokenPrivileges; Return: DWORD; begin PreviousState := True; if (GetVersion() > $80000000) then Result := ERROR_SUCCESS else begin if not OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, Token) then Result := GetLastError() else try if not LookupPrivilegeValue(nil, Privilege, Luid) then Result := GetLastError() else begin NewState.PrivilegeCount := 1; NewState.Privileges[0].Luid := Luid; if EnablePrivilege then NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED else NewState.Privileges[0].Attributes := 0; if not AdjustTokenPrivileges(Token, False, NewState, SizeOf(TTokenPrivileges), PrevState, Return) then Result := GetLastError() else begin Result := ERROR_SUCCESS; PreviousState := (PrevState.Privileges[0].Attributes and SE_PRIVILEGE_ENABLED <> 0); end; end; finally CloseHandle(Token); end; end; end; function FileTimetoDatetime (filetime: tfiletime):tdatetime; // ___________________________________________________________________________ // | function FileTimetoDatetime | // | _________________________________________________________________________ | // || Permet la convertion des dates fichier en dates tdatetime || // ||_________________________________________________________________________|| // || Entrées | filetime: tfiletime || // || | date à convertir || // ||_________|_______________________________________________________________|| // || Sorties | Result : tdatetime || // || | date convertie || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var SysTime : TSystemTime; begin fileTimeTosystemtime (filetime,SysTime); result := SystemTimeToDateTime(SysTime); end; function strCheminToUnicode(Const Chemin:string):pwidechar; // ___________________________________________________________________________ // | function strCheminToUnicode | // | _________________________________________________________________________ | // || Permet de transformer un chemin de fichier en chemin compatible avec || // || Les fonction unicode windows || // ||_________________________________________________________________________|| // || Entrées | Const Chemin:string || // || | Chemin à convertir || // ||_________|_______________________________________________________________|| // || Sorties | result : pwidechar || // || | Chemin converti || // || | "\\?\c:\rep" ou "\\?\UNC\serveur\partage" || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin // GetMem(result, sizeof(WideChar) * Succ(Length(Chemin)+8)); if pos('\\?\',chemin)= 1 then Result := PWideChar(WideString(chemin)) else if pos('\\',Chemin)=1 then result :=PWideChar(WideString('\\?\UNC\'+ copy(chemin,3,length(chemin)-2))) else result :=PWideChar(WideString('\\?\'+Chemin)); end; function FBFileSetAttr(const FileName: string; Attr: Integer): Integer; // ___________________________________________________________________________ // | function FBFileSetAttr | // | _________________________________________________________________________ | // || Permet de modifier les attributs d'un fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // || | Attr: Integer || // || | Attributs à affecter au fichier || // ||_________|_______________________________________________________________|| // || Sorties | Result : integer || // || | zéro si l'exécution de la fonction réussit || // || | Sinon, la valeur renvoyée est un code d'erreur || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin Result := 0; if not SetFileAttributesW(strCheminToUnicode(FileName), Attr) then Result := GetLastError; end; function FBFileGetAttr(const FileName: string): Integer; // ___________________________________________________________________________ // | function FBFileGetAttr | // | _________________________________________________________________________ | // || Permet de récupérer les attribut d'un fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | Result : integer || // || | valeur des attributs du fichier sous forme de masque || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin Result := GetFileAttributesW(strCheminToUnicode(FileName)); end; function FBFileDelete(const FileName : string): boolean; // ___________________________________________________________________________ // | function FBFileDelete | // | _________________________________________________________________________ | // || Permet de supprimer un fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName : string || // || | Nom du fichier à supprimer || // ||_________|_______________________________________________________________|| // || Sorties | Result : boolean || // || | Vrai en cas de réussite, faux le cas contraire voir || // || | GetLastError pour connaitre la raison || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin result := DeleteFileW(strCheminToUnicode(FileName)); end; function FBFileDelete(const FileName : string ; booBroyage : boolean): boolean; // ___________________________________________________________________________ // | function FBFileDelete | // | _________________________________________________________________________ | // || Permet de supprimer un fichier et de rendre ça restauration dificile || // || via une double écriture de 1010 et de 0101 || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName : string || // || | Nom du fichier à supprimer || // || | BooBroyage : boolean || // || | Vrai pour appliquer un écrasement se sécurité || // ||_________|_______________________________________________________________|| // || Sorties | Result : boolean || // || | Vrai en cas de réussite, faux le cas contraire voir || // || | GetLastError pour connaitre la raison || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| const tbuf =4096; var fh : integer; i, taille : int64; buf : array [0..tbuf-1] of byte; strNomfichier : string; boo : boolean; begin SetPrivilege('SeRestorePrivilege',true,boo); FBFileSetAttr(FileName,faArchive); strNomfichier := filename; if booBroyage then begin // **************************************************************************** // * Tentative de déplacer le fichier à la racine et de le renommer pour * // * brouiller les pistes * // **************************************************************************** if FBFileExists(FBExtractFileDrive(FileName )+'\fb000.0000') then begin FBFileSetAttr(FBExtractFileDrive(FileName )+'\fb000.0000',faArchive); FBFileDelete(FBExtractFileDrive(FileName )+'\fb000.0000'); end; if FBfileRename(FileName, FBExtractFileDrive(FileName )+'\fb000.0000') then strNomfichier := FBExtractFileDrive(FileName )+'\fb000.0000' else strnomfichier := FileName ; fh := FBFileOpen(strnomfichier,fmOpenReadWrite ); if fh <> -1 then begin taille:=FBGetFileSize (strnomfichier); taille :=( taille div tbuf) +1; if assigned( FBonbeforedelete) then FBonbeforedelete(taille *2); FillChar ( buf,tbuf,$AA); FBFileSeek(fh,0,0); i := 0 ; // **************************************************************************** // * Ecriture d'une suite de 10101010 * // **************************************************************************** repeat FBFileWrite(fh,buf[0],tbuf); i := i+1; if assigned(FBonprogressdelete ) then FBonprogressdelete(i); until i= taille; FlushFileBuffers(fh); FillChar ( buf,tbuf,$55); FBFileSeek(fh,0,0); i := 0 ; // **************************************************************************** // * Ecriture d'une suite de 01010101 * // **************************************************************************** repeat FBFileWrite(fh,buf[0],tbuf); i := i+1; if assigned(FBonprogressdelete ) then FBonprogressdelete(taille + i); until i= taille; FlushFileBuffers(fh); FBfileclose(fh); end; end; result := FBFileDelete(strNomFichier ); if not boo then SetPrivilege('SeRestorePrivilege',boo,boo); end; function FBFileOpen(const FileName: string; Mode: LongWord): Integer; // ___________________________________________________________________________ // | function FBFileOpen | // | _________________________________________________________________________ | // || Permet d'ouvrir un fichier et obtenir un handle de fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier à ouvrir || // || | string; Mode: LongWord || // || | mode d'accès au fichier || // ||_________|_______________________________________________________________|| // || Sorties | Result : integer || // || | >-1 handle de fichier , =-1 le fichier n'a pu être ouvert || || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| const AccessMode: array[0..2] of LongWord = ( GENERIC_READ, GENERIC_WRITE, GENERIC_READ or GENERIC_WRITE); ShareMode: array[0..4] of LongWord = ( 0, 0, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE); begin Result := -1; if ((Mode and 3) <= fmOpenReadWrite) and ((Mode and $F0) <= fmShareDenyNone) then Result := Integer(CreateFilew(strCheminToUnicode(FileName), AccessMode[Mode and 3], ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)); end; function FBFileCreate(const FileName: string): Integer; // ___________________________________________________________________________ // | function FBFileCreate | // | _________________________________________________________________________ | // || Permet de créer un nouveau fichier et d'obtenir un handle de fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier à créer || // ||_________|_______________________________________________________________|| // || Sorties | Result : integer || // || | >-1 handle de fichier , =-1 le fichier n'a pu être créé || || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin Result := Integer(CreateFileW(strCheminToUnicode(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)); end; function FBGetFileSize(const FileName: string): Int64; // ___________________________________________________________________________ // | function FBGetFileSize | // | _________________________________________________________________________ | // || Pemret de retourner la taille d'un fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | Retsult : int64 || // || | Taille du fichier en octet || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var FD: TWin32FindDataW; FH: THandle; begin FH := FindFirstFileW(strCheminToUnicode(FileName ), FD); if FH = INVALID_HANDLE_VALUE then Result := -1 else try Result := FD.nFileSizeHigh shl 32 + FD.nFileSizeLow; finally windows.findclose(FH); end; end; function FBGetFileCreationTime(const FileName: string): TDateTime; // ___________________________________________________________________________ // | function FBGetFileCreationTime | // | _________________________________________________________________________ | // || Permet de connaître la date de création du fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | Result : tdatetime || // || | Date de création du fichier || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var FD: TWin32FindDataW; FH: THandle; begin Result := -1; FH := FindFirstFileW(strCheminToUnicode(FileName ), FD); if FH = INVALID_HANDLE_VALUE then Result := -1 else try Result := FileTimetoDatetime (fd.ftCreationTime); finally windows.findclose(FH); end; end; function FBGetFileLastWriteTime(const FileName: string): TDateTime; // ___________________________________________________________________________ // | function FBGetFileLastWriteTime | // | _________________________________________________________________________ | // || Permet de connaître la date du dernier enregistrement du fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | Result : tdatetime || // || | Date du dernier enregistrement || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var FD: TWin32FindDataW; FH: THandle; begin Result := -1; FH := FindFirstFileW(strCheminToUnicode(FileName ), FD); if FH = INVALID_HANDLE_VALUE then Result := -1 else try Result := FileTimetoDatetime (fd.ftLastWriteTime); finally windows.findclose(FH); end; end; function FBGetFileLastAccessTime(const FileName: string): TDateTime; // ___________________________________________________________________________ // | function FBGetFileLastAccessTime | // | _________________________________________________________________________ | // || Permet de connaître la date du dernier accés au fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | Result : tdatetime || // || | Date du dernier accés || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var FD: TWin32FindDataW; FH: THandle; begin Result := -1; FH := FindFirstFileW(strCheminToUnicode(FileName ), FD); if FH = INVALID_HANDLE_VALUE then Result := -1 else try Result := FileTimetoDatetime (fd.ftLastAccessTime); finally windows.findclose(FH); end; end; // function FBFileExists(const FileName: string): boolean; // // // ___________________________________________________________________________ // // | function FBFileExists | // // | _________________________________________________________________________ | // // || Permet de savoir si un fichioer existe || // // || cette fonction gére les noms de fichier > 255 Caractères || // // ||_________________________________________________________________________|| // // || Entrées | const FileName: string || // // || | Nom du fichier || // // ||_________|_______________________________________________________________|| // // || Sorties | result : boolean || // // || | Vrai si le fichier existe si non Faux || // // ||_________|_______________________________________________________________|| // // |___________________________________________________________________________| // // var // Code: Integer; // begin // Code := GetFileAttributesW(strCheminToUnicode(FileName)); // Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code = 0); // // //result := FBGetFileLastWriteTime(FileName)> -1; // end; function FBFileExists(const FileName: string): boolean; // ___________________________________________________________________________ // | function FBFileExists | // | _________________________________________________________________________ | // || Permet de savoir si un fichioer existe || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | result : boolean || // || | Vrai si le fichier existe si non Faux || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var FD: TWin32FindDataW; FH: THandle; begin FH := FindFirstFileW(strCheminToUnicode(FileName ), FD); result := (FH <> INVALID_HANDLE_VALUE) and ( fd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY =0) ; windows.findclose(FH); end; function FBFileSetShortName ( Const FileName : string ; Const shortfilename : string ) : boolean; // ___________________________________________________________________________ // | function FBFileSetShortName | // | _________________________________________________________________________ | // || Permet de modifier le nom court d'un fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // || | const shortfilename: string || // || | Nom court du fichier || // ||_________|_______________________________________________________________|| // || Sorties | result : boolean || // || | Vrai si le modification OK || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var fh : THandle ; boo : boolean; begin SetPrivilege('SeRestorePrivilege',true,boo); fh := Integer(CreateFilew(strCheminToUnicode(FileName), GENERIC_ALL, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)); //FBFileOpen(filename,GENERIC_ALL or FILE_FLAG_BACKUP_SEMANTICS ); result := SetFileShortNamew(fh,PWideChar(WideString(shortfilename))); FBFileClose(fh); if not boo then SetPrivilege('SeRestorePrivilege',boo,boo); end; function FBFileGetShortName ( Const FileName : string ) : string; // ___________________________________________________________________________ // | function FBFileGetShortName | // | _________________________________________________________________________ | // || Permet de trouver le nom court d'un fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | result : string || // || | Nom court du fichier || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var FD: TWin32FindDataW; FH: THandle; begin result := ''; FH := FindFirstFileW(strCheminToUnicode(FileName ), FD); if (FH <> INVALID_HANDLE_VALUE)then result := fd.cAlternateFileName; windows.findclose(FH); end; function FBFileGetLongName (const Filename : string) : string; var FD: TWin32FindDataW; FH: THandle; begin result := ''; FH := FindFirstFileW(strCheminToUnicode(FileName ), FD); if (FH <> INVALID_HANDLE_VALUE)then result := fd.cFileName; windows.findclose(FH); end; function FBFileRename(const OldName, NewName: string): Boolean; // ___________________________________________________________________________ // | function FBFileRename | // | _________________________________________________________________________ | // || Permet de renommer un fichier || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const OldName: string || // || | Nom du fichier d'origine || // || | const NewName: string || // || | Nouveau nom du fichier || // ||_________|_______________________________________________________________|| // || Sorties | result : boolean || // || | Vrai si le renommage du fichier est fait si non Faux || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var s : widestring; begin s := strCheminToUnicode(OldName); Result := MoveFilew(PWideChar(s),strCheminToUnicode(NewName)); end; procedure FBFileClose(Handle: Integer); // ___________________________________________________________________________ // | procedure FBFileClose | // | _________________________________________________________________________ | // || Permet de fermer un fichier || // ||_________________________________________________________________________|| // || Entrées | Handle: Integer || // || | Handle du fichier à fermer || // ||_________|_______________________________________________________________|| // || Sorties | || // || | || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin CloseHandle(THandle(Handle)); End; function FBFileRead(Handle: Integer; var Buffer; Count: LongWord): Integer; // ___________________________________________________________________________ // | function FBFileRead | // | _________________________________________________________________________ | // || Permet de lire des données dans un fichier || // ||_________________________________________________________________________|| // || Entrées | Handle: Integer || // || | Handle du fichier dans le quel lire les données || // || | var Buffer : LongWord || // || | Tampon qui va recevoir les données lues || // || | Count: LongWord || // || | Nombre d'octets à lire || // ||_________|_______________________________________________________________|| // || Sorties | var Buffer : LongWord || // || | Tampon rempli avec les données || // || | result : integer || // || | Nombre d'octets effectivement lues || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin if not ReadFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then Result := -1; end; function FBFileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer; // ___________________________________________________________________________ // | function FBFileWrite | // | _________________________________________________________________________ | // || Permet d'écrire des données dans un fichier || // ||_________________________________________________________________________|| // || Entrées | Handle: Integer || // || | Handle du fichier dans le quel écrire les données || // || | var Buffer : LongWord || // || | Tampon qui contient les données à écrire || // || | Count: LongWord || // || | Nombre d'octets à écrire || // ||_________|_______________________________________________________________|| // || Sorties | result : integer || // || | Nombre d'octets écrit, -1 en cas d'erreur || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin if not WriteFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then Result := -1; end; function FBFileSeek(Handle, Offset, Origin: Integer): Integer; // ___________________________________________________________________________ // | function FBFileSeek | // | _________________________________________________________________________ | // || Pemret de déplacer le pointeur d'écriture/ lecture d'un fichier || // ||_________________________________________________________________________|| // || Entrées | Handle : Integer || // || | Handle du fichier dans le quel déplacer le pointeur || // || | Offset : Integer || // || | décalage par rapport à Origin du pointeur de fichier || // || | Origin : Integer || // || | code indiquant le début du fichier 0, la fin du fichier 2, || // || | ou encore la position en cours du pointeur 1 || // ||_________|_______________________________________________________________|| // || Sorties | Result : integer || // || | Nouvel valeur du pointeur ou -1 en cas d'erreur || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin Result := SetFilePointer(THandle(Handle), Offset, nil, Origin); end; function FBFileSeek(Handle: Integer; const Offset: Int64; Origin: Integer): Int64; // ___________________________________________________________________________ // | function FBFileSeek | // | _________________________________________________________________________ | // || Pemret de déplacer le pointeur d'écriture/ lecture d'un fichier || // ||_________________________________________________________________________|| // || Entrées | Handle : Integer || // || | Handle du fichier dans le quel déplacer le pointeur || // || | Offset : Int64 || // || | décalage par rapport à Origin du pointeur de fichier || // || | Origin : Integer || // || | code indiquant le début du fichier 0, la fin du fichier 2, || // || | ou encore la position en cours du pointeur 1 || // ||_________|_______________________________________________________________|| // || Sorties | Result : int64 || // || | Nouvel valeur du pointeur ou -1 en cas d'erreur || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin Result := Offset; Int64Rec(Result).Lo := SetFilePointer(THandle(Handle), Int64Rec(Result).Lo, @Int64Rec(Result).Hi, Origin); end; function FBDirectoryExists(const DirName: string): boolean; // ___________________________________________________________________________ // | function FBDirectoryExists | // | _________________________________________________________________________ | // || Permet de savoir si un répertoire existe || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const DirName: string || // || | Nom du répertoire || // ||_________|_______________________________________________________________|| // || Sorties | Result : boolean || // || | Vrai si le répertoire existe si non Faux || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var Code: Integer; begin Code := GetFileAttributesW(strCheminToUnicode(DirName)); Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0); end; Function FBDirectoryCreate(const DirName: string) : boolean; // ___________________________________________________________________________ // | Function FBDirectoryCreate | // | _________________________________________________________________________ | // || Permet de créer un repertoire || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const DirName: string || // || | Nom du répertoire à créer || // ||_________|_______________________________________________________________|| // || Sorties | result : boolean || // || | Vrai si le repertoire est bien créé si non faux || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin result := CreateDirectoryW(strCheminToUnicode(DirName),nil); end; function FBForceDirectories(Dir: string): Boolean; // ___________________________________________________________________________ // | function FBForceDirectories | // | _________________________________________________________________________ | // || Permet de créer un nouveau répertoire et si nécessaire les répertoires || // || parents || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const DirName: string || // || | Nom du répertoire à créer || // ||_________|_______________________________________________________________|| // || Sorties | result : boolean || // || | Vrai si le repertoire est bien créé si non faux || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| begin Result := True; if Dir = '' then exit; Dir := ExcludeTrailingPathDelimiter(Dir); if (Length(Dir) < 3) or FBDirectoryExists(Dir) or (FBExtractFilePath(Dir) = Dir) then Exit; Result := FBForceDirectories(FBExtractFilePath(Dir)) and FBDirectoryCreate(Dir); end; function FBDirectoryRemove(const FileName : string): boolean; // ___________________________________________________________________________ // | function FBDirectoryRemove | // | _________________________________________________________________________ | // || Permet de supprimer un répertoire, le répertoire doit être vide || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName : string || // || | Nom du répertoire à supprimer || // ||_________|_______________________________________________________________|| // || Sorties | Result : boolean || // || | Vrai en cas de réussite, faux le cas contraire voir || // || | GetLastError pour connaitre la raison || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var boo : boolean; begin SetPrivilege('SeRestorePrivilege',true,boo); result := RemoveDirectoryW(strCheminToUnicode(FileName)); if not boo then SetPrivilege('SeRestorePrivilege',boo,boo); end; function FBDirectoryRemove(const FileName : string;booBroyage : boolean ): boolean; // ___________________________________________________________________________ // | function FBDirectoryRemove | // | _________________________________________________________________________ | // || Permet de supprimer un répertoire, le répertoire doit être vide || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName : string || // || | Nom du répertoire à supprimer || // ||_________|_______________________________________________________________|| // || Sorties | Result : boolean || // || | Vrai en cas de réussite, faux le cas contraire voir || // || | GetLastError pour connaitre la raison || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var strtemp : string; begin strtemp := FileName ; if booBroyage then begin if FBDirectoryExists(FBExtractFileDrive(FileName )+'\fb0000000') then begin FBDirectoryRemove (FBExtractFileDrive(FileName )+'\fb0000000'); end; if FBFileRename(FileName ,FBExtractFileDrive(FileName )+'\fb0000000') then strtemp := FBExtractFileDrive(FileName )+'\fb0000000'; end; result := FBDirectoryRemove(strtemp); end; function FBDirectoryRemoveR(const FileName : string): integer; // ___________________________________________________________________________ // | function FBDirectoryRemoveR | // | _________________________________________________________________________ | // || Permet de supprimer un répertoire et tous ces sous répertoires si ils ne|| // || contiennent pas de fichiers || // || cette fonction gére les noms de fichier > 255 Caractères || // ||_________________________________________________________________________|| // || Entrées | const FileName : string || // || | Nom du répertoire à supprimer || // ||_________|_______________________________________________________________|| // || Sorties | Result : integer || // || | 1 en cas de réussite, -1 le cas contraire || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var FD: TWin32FindDataW; FH: THandle; boofind : boolean; strReporg : string; boook : integer; begin boofind := true; strReporg := FileName ; boook := 1; if strReporg[length(strReporg)] <> '\' then strReporg := strReporg + '\'; FH := FindFirstFilew ( strCheminToUnicode(strReporg + '*.*'), FD); if FH <> INVALID_HANDLE_VALUE then while boofind do begin if ((FD.dwFileAttributes and fadirectory )= faDirectory ) and (string(FD.cFileName) <> '.') and (string(FD.cFileName) <>'..') then begin boook := FBDirectoryRemoveR(strReporg + fd.cfilename+ '\' ); end; boofind := windows.FindNextFileW (FH,FD); end; windows.findclose(FH); if not RemoveDirectoryW(strCheminToUnicode(strReporg)) then boook := -1 ; result := boook; end; function FBChangeFileExt(const FileName, Extension: string): string; // ___________________________________________________________________________ // | function FBChangeFileExt | // | _________________________________________________________________________ | // || Permet de changer l'extension d'un fichier || // ||_________________________________________________________________________|| // || Entrées | const FileName : string || // || | Nom de fichier à modifier || // || | Extension : string || // || | Nouvelle extention du fichier || // ||_________|_______________________________________________________________|| // || Sorties | Result : string || // || | Nouveau nom de fichier || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var I: Integer; begin i := length(FileName ); while (i > 0)and (FileName[i]<>'.')and (FileName[i]<>'\')and (FileName[i]<>':') do dec(i); if (I = 0) or (FileName[I] <> '.') then I := MaxInt; Result := Copy(FileName, 1, I - 1) + Extension; end; function FBExtractFilePath(const FileName: string): string; // ___________________________________________________________________________ // | function FBExtractFilePath | // | _________________________________________________________________________ | // || Permet d'extraire le lecteur et le répertoire d'un nom de fichier || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom complet || // ||_________|_______________________________________________________________|| // || Sorties | Result : string || // || | Chemin du fichier incluant le '\' finale || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var I: Integer; begin i := length(FileName ); while (i > 0)and (FileName[i]<>'\')and (FileName[i]<>':')do dec(i); Result := Copy(FileName, 1, I); end; function FBExtractFileDir(const FileName: string): string; // ___________________________________________________________________________ // | function FBExtractFileDir | // | _________________________________________________________________________ | // || Permet d'extraire le lecteur et le répertoire d'un nom de fichier || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom complet || // ||_________|_______________________________________________________________|| // || Sorties | Result : string || // || | Chemin du fichier sans le '\' finale || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var I: Integer; begin i := length(FileName ); while (i > 0)and (FileName[i]<>'\')and (FileName[i]<>':')do dec(i); if (I > 1) and (FileName[I] = '\') and (FileName[I-1] <> ':')and(FileName[I-1] <> '\') then Dec(I); Result := Copy(FileName, 1, I); end; function FBExtractFileDrive(const FileName: string): string; // ___________________________________________________________________________ // | function FBExtractFileDrive | // | _________________________________________________________________________ | // || Permet d'extraire la partie lecteur d'un nom de fichier || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom complet || // ||_________|_______________________________________________________________|| // || Sorties | Result : string || // || | Partie lecteur 'c:' ou '\\Serveur\partage' || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var I, J: Integer; begin if (Length(FileName) >= 2) and (FileName[2] = ':') then Result := Copy(FileName, 1, 2) else if (Length(FileName) >= 2) and (FileName[1] = '\') and (FileName[2] = '\') then begin J := 0; I := 3; While (I < Length(FileName)) and (J < 2) do begin if FileName[I] = '\' then Inc(J); if J < 2 then Inc(I); end; if FileName[I] = '\' then Dec(I); Result := Copy(FileName, 1, I); end else Result := ''; end; function FBExtractFileName(const FileName: string): string; // ___________________________________________________________________________ // | function FBExtractFileName | // | _________________________________________________________________________ | // || Permet d'extraire la partie nom et extention d'un nom de fichier || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom complet || // ||_________|_______________________________________________________________|| // || Sorties | Result : string || // || | nom et extention du fichier || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var I: Integer; begin i := length(FileName ); while (i > 0)and (FileName[i]<>'\')and (FileName[i]<>':')do dec(i); Result := Copy(FileName, I + 1, MaxInt); end; function FBExtractFileExt(const FileName: string): string; // ___________________________________________________________________________ // | function FBExtractFileExt | // | _________________________________________________________________________ | // || Permet d'extraire la partie extentino d'un nom de fichier || // ||_________________________________________________________________________|| // || Entrées | const FileName: string || // || | Nom complet || // ||_________|_______________________________________________________________|| // || Sorties | Result : string || // || | extention du fichier || // ||_________|_______________________________________________________________|| // |___________________________________________________________________________| var I: Integer; begin i := length(FileName ); while (i > 0)and (FileName[i]<>'.')and (FileName[i]<>'\')and (FileName[i]<>':')do dec(i); if (I > 0) and (FileName[I] = '.') then Result := Copy(FileName, I, MaxInt) else Result := ''; end; end.
unit SignalGenerator3DVideoFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Winapi.ActiveX, Winapi.DirectShow9, DeckLinkAPI, DeckLinkAPI.Modes, DeckLinkAPI.Types, DeckLinkAPI.Discovery; type TSignalGenerator3DVideoFrame = class(TInterfacedObject, IDeckLinkVideoFrame, IDeckLinkVideoFrame3DExtensions) protected m_frameLeft : IDeckLinkMutableVideoFrame; m_frameRight : IDeckLinkMutableVideoFrame; m_refCount : integer; private { Private declarations } public constructor Create(left: IDeckLinkMutableVideoFrame; right : IDeckLinkMutableVideoFrame = nil); destructor Destroy; override; // IUnknown methods function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; // IDeckLinkVideoFrame methods function GetWidth: Integer; stdcall; function GetHeight: Integer; stdcall; function GetRowBytes: Integer; stdcall; function GetPixelFormat: _BMDPixelFormat; stdcall; function GetFlags: _BMDFrameFlags; stdcall; function GetBytes(out buffer: Pointer): HResult; stdcall; function GetTimecode(format: _BMDTimecodeFormat; out timecode: IDeckLinkTimecode): HResult; stdcall; function GetAncillaryData(out ancillary: IDeckLinkVideoFrameAncillary): HResult; stdcall; // IDeckLinkVideoFrame3DExtensions methods function Get3DPackingFormat: _BMDVideo3DPackingFormat; stdcall; function GetFrameForRightEye(out rightEyeFrame: IDeckLinkVideoFrame): HResult; stdcall; end; implementation function TSignalGenerator3DVideoFrame._AddRef: Integer; begin Result := InterlockedIncrement(m_RefCount); end; function TSignalGenerator3DVideoFrame._Release: Integer; var newRefValue : integer; begin newRefValue:=InterlockedDecrement(m_RefCount); if newRefValue=0 then begin //Destroy; free; Result := 0; end; result:=newRefValue; end; function TSignalGenerator3DVideoFrame.QueryInterface(const IID: TGUID; out Obj): HRESULT; const IID_IUnknown : TGUID = '{00000000-0000-0000-C000-000000000046}'; begin Result := E_NOINTERFACE; Pointer(Obj):=nil; if IsEqualGUID(IID, IID_IUnknown)then begin Pointer(Obj) := Self; _addRef; Result := S_OK; end else if IsEqualGUID(IID, IDeckLinkInputCallback)then begin //GetInterface(IDeckLinkInputCallback, obj); Pointer(Obj) := Pointer(IDeckLinkVideoFrame(self)); _addRef; Result := S_OK; end; end; constructor TSignalGenerator3DVideoFrame.Create(left: IDeckLinkMutableVideoFrame; right : IDeckLinkMutableVideoFrame = nil); begin m_frameLeft:=left; m_frameRight:=right; m_refCount:=1; if not assigned(m_frameLeft) then raise Exception.Create('at minimum a left frame must be defined'); m_frameLeft._AddRef(); if assigned(m_frameRight) then m_frameRight._AddRef(); end; destructor TSignalGenerator3DVideoFrame.Destroy; begin if assigned(m_frameLeft) then m_frameLeft._Release; m_frameLeft := nil; if assigned(m_frameRight) then m_frameRight._Release; m_frameRight := nil; inherited; end; function TSignalGenerator3DVideoFrame.GetWidth(): integer; begin result := m_frameLeft.GetWidth(); end; function TSignalGenerator3DVideoFrame.GetHeight(): integer; begin result := m_frameLeft.GetHeight(); end; function TSignalGenerator3DVideoFrame.GetRowBytes(): integer; begin result := m_frameLeft.GetRowBytes(); end; function TSignalGenerator3DVideoFrame.GetPixelFormat(): _BMDPixelFormat; begin result := m_frameLeft.GetPixelFormat(); end; function TSignalGenerator3DVideoFrame.GetFlags(): _BMDFrameFlags; begin result := m_frameLeft.GetFlags(); end; function TSignalGenerator3DVideoFrame.GetBytes(out buffer: Pointer): HResult; begin result := m_frameLeft.GetBytes(buffer); end; function TSignalGenerator3DVideoFrame.GetTimecode(format: _BMDTimecodeFormat; out timecode: IDeckLinkTimecode): HResult; begin result := m_frameLeft.GetTimecode(format, timecode); end; function TSignalGenerator3DVideoFrame.GetAncillaryData(out ancillary: IDeckLinkVideoFrameAncillary): HResult; begin result := m_frameLeft.GetAncillaryData(ancillary); end; function TSignalGenerator3DVideoFrame.Get3DPackingFormat: _BMDVideo3DPackingFormat; begin result := bmdVideo3DPackingLeftOnly; end; function TSignalGenerator3DVideoFrame.GetFrameForRightEye(out rightEyeFrame: IDeckLinkVideoFrame): HResult; begin if assigned(m_frameRight) then result := m_frameRight.QueryInterface(IID_IDeckLinkVideoFrame, rightEyeFrame) else result := S_FALSE; end; end.
Unit WSRestClient_ConsumeADP; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} {$M+} { Class TWSRestClient_ConsumeADP 30/07/2018 SCotillard Usage : try // ******************** // Creation via : // ******************** // myConsumeADP := TWSRestClient_ConsumeADP.Create(); // ******************** // ou alors via : // ******************** // myConsumeADP := TWSRestClient_ConsumeADP.Create(); // ******************** myConsumeADP.raiseOnError = true; myConsumeADP.raiseOnTechError = true; validationTicket := myConsumeADP.Rechercher(); if not validationTicket then writeln(myConsumeADP.ResponseHTTPCode); writeln(myConsumeADP.ErrorCode); writeln(myConsumeADP.ErrorMessage); writeln(myConsumeADP.ResponseMessage); writeln(myConsumeADP.ResponseCode); writeln(myConsumeADP.ResponseRawMessage); writeln(myConsumeADP.ResponseRawCode); else writeln(myConsumeADP.ResponseMessage); end; on E: EWSValidatationErrorExeception do begin // ************************** writeln(‘La demande à echoué ‘+ E.Message ); // erreur dans le traitement de la reponse serveur ; erreur JSON end; on E: EWSTechErrorExeception do begin // ************************** writeln(‘Une erreur technique a fait echoué la demande ‘+ E.Message ); // timeout ; serveur 500 ; end; end; } interface uses Classes, StrUtils, SysUtils, Variants, WSRESTClient, Windows, WSObject, GNSWSTypes; // in 'TWSRESTClient.pas'; // contient les URLs pour les webservices // ********************** // Reglages // ********************** // '%s://%s:%s/kWSName-kWSVersion/kWSEntryPoint/kWSMethodName?' const kWSName_ConsumeADP ='adp-api'; Const kWSProcessName_ConsumeADP = 'Threads ...; ConsumeADP'; Const kWSMethodName_ConsumeADP = 'graphql'; const kWSEnvRequired_ConsumeADP = wsPreProd; const kWSEntryPoint_ConsumeADP = ''; const kWSEntryPointVersion_ConsumeADP = ''; const kWSEndPoint_ConsumeADP = 'adp-api/'; // ************************************* // **** Le Block Suivant permet de creer les Proprerty ++ HTTPURIParams / HTTPBodyParams // ************************************* type kWSInfo_AccessibleObjectProperties_ConsumeADP = record const Names : array [0..1] of string = ( 'query', 'apikey' ); // le kIdx[Valeur] doit avoir la meme position dans kWSAccessibleProperties et kWSAccessiblePropertiesIndex type kWSInfo_AccessibleObjectProperties_Indexes_ConsumeADP = ( kWSInfo_AccessibleObjectProperties_ConsumeADP_kIdxquery, kWSInfo_AccessibleObjectProperties_ConsumeADP_kIdxapikey ); const APIKEYS : array [0..0] of string = ( 'dc5747d8-bc39-442c-9a32-f37e806bfce8' ); const APIKEY_Defaultidx : integer = 0; end; // ************************************* // **** Le Block Suivant permet de creer les Methodes Accessible et VALIDE ;; Conjointement avec le Block kWSInfoMethodAvail _[classname];; par ce WebService // ************************************* type kWSInfo_MethodNameAvail_ConsumeADP = record const graphQLBase = 'graphql'; end; // ************************************* // **** Le Block Suivant permet de Generer ; tout les reglages et Validation de Champs;; redirige les Params dans HTTPURIParams / HTTPBodyParams // ************************************* var kWSInfoMethodAvail_ConsumeADP : array[0..0] of TWSInfoHTTPMethodTypeInfo = ( ( WSInfoHTTPMethodName: kWSInfo_MethodNameAvail_ConsumeADP.graphQLBase; WSInfoHTTPMethodNameVersion : kWSEntryPointVersion_ConsumeADP; WSInfoHTTPMethodSendType : TWSHTTPMethodType.kWSHTTPMethodType_GET; WSInfoHTTPMethodURIEntryPoint : kWSEntryPoint_ConsumeADP; WSInfoHTTPMethodURIEndPoint : kWSEndPoint_ConsumeADP; WSInfoHTTPMethodURIParamsFormat : ''; WSInfoHTTPMethodProcessName : kWSProcessName_ConsumeADP; WSInfoHTTPMethodURIFieldWithUserInfo : false; WSInfoHTTPMethodBODYFieldWithUserInfo : false; // WSInfoHTTPMethodURIValidateFieldDefinition : @aDefinition; WSInfoHTTPMethodURIUSEFieldIdx : [ // :: integer(kWSInfo_AccessibleObjectProperties_ConsumeADP_kIdxapikey) // :: , integer(kWSInfo_AccessibleObjectProperties_ConsumeADP_kIdxquery) ] ; ) ); // *************************************************** // *************************************************** // ************* TWSRestClient_[Classname] ************** // *************************************************** // *************************************************** type TWSRestClient_ConsumeADP = class(TWSRESTClient) private // ************************************** // ************************************** // ******* Variable inherent au modele TWSRestClient_[Classname] // ******** Nom de la Methode Reclamee lors du Create() // ************************************** var __RequestedConsumeMethod : string; // ************************************** // ************************************** public // ********************** // ********************** constructor Create(); overload; constructor Create(aMethodRequested : string); overload; // constructor Create(aMethodRequested : kWSInfo_MethodNameAvail_[ClassName] ); overload; function WSGetURL():String; overload; //function WSValidate() : boolean; overload; //function WSReplyPassed() : Boolean;overload; // ********************** // ********************** published // ************************************** // ************************************** // ******** Methode unifiee pour l envoi de la requete // ************************************** function Declencher( bCreateDemand : boolean = true) : boolean; // ************************************** // ************************************** // ******* // ************************************** // ************************************** function RechercherADP(sMethodNameAdp:string; sStringRequeteAdp:string; iPageNumberAdp: integer; sScopeValuesADP: TStringList; var aResponseValues: TWSArrayObject) : boolean; function ExtractADP(sQueryIndex : String; aArrayFiltres: TStringList; var aResponseValues: TWSArrayArrayStrings) : boolean; function RechercherFromCodeStreet(sStringRequeteAdp:string; var aResponseValues: TWSArrayArrayStrings) : boolean; function RechercherFromCodeVille(sStringRequeteAdp:string; var aResponseValues: TWSArrayArrayStrings) : boolean; // ************************************** // ************************************** property query : variant Index kWSInfo_AccessibleObjectProperties_ConsumeADP_kIdxquery read WSPropsReadingByIdx write WSPropsWritingByIdx; property apikey : variant Index kWSInfo_AccessibleObjectProperties_ConsumeADP_kIdxapikey read WSPropsReadingByIdx write WSPropsWritingByIdx; // ************************************** // ************************************** end; implementation // ************************************** // ************************************** constructor TWSRestClient_ConsumeADP.Create(); begin Create(kWSMethodName_ConsumeADP); end; // ************************************** // ************************************** constructor TWSRestClient_ConsumeADP.Create(aMethodRequested : string); var iValue : integer; var aMethodNameValid : string; begin inherited Create(); {$IFDEF DEBUG_VERBOSE} WSInternalLogActivityToFileScreen := true; {$ENDIF} {$IFDEF DEBUG_VERBOSE_FILE } WSInternalLogActivityToFileLog := true; {$ENDIF} {$IFDEF DEBUG_RAISE_EALL } {$DEFINE DEBUG_RAISE_ERROR} {$DEFINE DEBUG_RAISE_ERROR_TECH} {$ENDIF} {$IFDEF DEBUG_RAISE_ERROR } WSInternalRaiseOnError := true; {$ENDIF} {$IFDEF DEBUG_RAISE_ERROR_TECH } WSInternalRaiseOnTechError := true; {$ENDIF} // descripteur des champs a envoyer au WEbService, via Body Ou Uri RegisterWSMethodInfoForName(kWSInfoMethodAvail_ConsumeADP, aMethodRequested); // creation des points d'entrees ... //WSQueryParams := CreateWSRegisterObjectProperties(kWSInfo_AccessibleObjectProperties_ConsumeADP.Names); CreateWSRegisterConsumerProperties(kWSInfoMethodAvail_ConsumeADP,kWSInfo_AccessibleObjectProperties_ConsumeADP.Names); WSHTTPServerEnvType := kWSEnvRequired_ConsumeADP; WSInternalProcessName := WSFindMethodInfo(kWSInfoMethodAvail_ConsumeADP, aMethodRequested, TWSInfoHTTPMethodTypeInfo_ReturnInfo.kWSInfoHTTPMethodProcessName ) ; // *********** l utilisation de WSFindMethodInfo permet de valider transmis ************** // modification de l'url WSHTTPQuerySendMethod := WSFindMethodInfo(kWSInfoMethodAvail_ConsumeADP, aMethodRequested, TWSInfoHTTPMethodTypeInfo_ReturnInfo.kWSInfoHTTPMethodSendType ) ; WSConsumeMethodName := WSFindMethodInfo(kWSInfoMethodAvail_ConsumeADP, aMethodRequested, TWSInfoHTTPMethodTypeInfo_ReturnInfo.kWSInfoHTTPMethodName ) ; if( length(WSConsumeMethodName) <= 2 ) then begin Raise TEWSValidationErrorException.create('La methode demandee n existe pas ... ('+WSConsumeMethodName+')'); exit; end; WSConsumeEntryPoint := WSFindMethodInfo(kWSInfoMethodAvail_ConsumeADP, aMethodRequested, TWSInfoHTTPMethodTypeInfo_ReturnInfo.kWSInfoHTTPMethodURIEntryPoint ) ; WSConsumeVersion := WSFindMethodInfo(kWSInfoMethodAvail_ConsumeADP, aMethodRequested, TWSInfoHTTPMethodTypeInfo_ReturnInfo.kWSInfoHTTPMethodNameVersion ) ; WSConsumeEndPoint := WSFindMethodInfo(kWSInfoMethodAvail_ConsumeADP, aMethodRequested, TWSInfoHTTPMethodTypeInfo_ReturnInfo.kWSInfoHTTPMethodURIEndPoint ) ; // par defaut :: /services/ :: // ********************** // ecrtire des entets HTTP WSHTTPQueryHeaders[kWSInfo_AccessibleObjectProperties_ConsumeADP.Names[integer(kWSInfo_AccessibleObjectProperties_ConsumeADP_kIdxapikey)]] := kWSInfo_AccessibleObjectProperties_ConsumeADP.APIKEYS[ integer(kWSInfo_AccessibleObjectProperties_ConsumeADP.APIKEY_Defaultidx)]; // apikey := kKey__APIM_valeur; WSHTTPQueryHeaders[TWSHTTPContentType.kWSHTTPContentType_key_AcceptContentType] := TWSHTTPContentType.kWSHTTPContentType_APPJSON; WSHTTPQueryContentEncoding := TWSHTTPContentType.kWSHTTPContentType_ENCODING_ISO8859_15; WSHTTPQueryContentType := TWSHTTPContentType.kWSHTTPContentType_TEXTJSON; // ********************** // Reglage du SSL // ********************** WSHTTPQueryUseSSLType := kWSHTTPSSLMethod_SSLv2; // ********************** // :: WSHTTPQueryURIParams['query'] := ''; inherited Clear(); // :: WSInternalLogActivityToFileLog := true; // :: WSInternalLogActivityToFileScreen := true; // ********************** end; // ***************************************** // WSGetURL est appele a l'ouverture de la requete HTTP // en interne les portions seront assemblees // ***************************************** function TWSRestClient_ConsumeADP.WSGetURL(): String; begin try // :: WSHTTPQueryProtocolType := TWSHTTPProtocolType.ProtocolType_HTTP; case WSHTTPServerEnvType of wsDev : begin WSHTTPQueryHost := 'apim.kong.dev.xxxxxx.fr'; WSHTTPQueryPort := '8443'; end; wsTest : begin WSHTTPQueryHost := 'apim.kong.dev.xxxxxx.fr'; WSHTTPQueryPort := '8443'; end; wsPreProd : begin WSHTTPQueryHost := 'apim.kong.xxxxxx.fr'; WSHTTPQueryPort := '8443'; end; wsProduction : begin WSHTTPQueryHost := 'apim.kong.xxxxxx.fr'; WSHTTPQueryPort := '8443'; end; end; // *************************** // le parent se charge du reste de l'assemblage Result := inherited WSGetURL(); // *************************** except on ErrGetUrl: Exception do begin WSRaiseLogStack(' Exception::Inherited WSGetURL ('+ErrGetUrl.Message+')'); exit; end; end; end; // ********************************************** // ********************************************** function TWSRestClient_ConsumeADP.Declencher( bCreateDemand : boolean = true) : boolean; var ResVariant : variant; begin if ( ( Length(WSHTTPQueryURIParams[kWSInfo_AccessibleObjectProperties_ConsumeADP.Names[0]]) >10) ) then begin // Tout est géré en interne pour la communication / décodage JSON try // le json sera validee en interne Result := Open(WSGetURL()); ResVariant := WSResponseRawText; Result := (length(ResVariant)>0) and (WSErrorCode = '200'); except on Err: Exception do begin // ************************** // **** MessageDlg('La demande à echoué :: Exception :: '+chr(13)+' Message :'+ Err.Message ,mtError,[mbOk],0); // ************************** WSErrorMessage := Err.Message ; if(WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin WSRaiseLogStack(''); end; end; end; end else begin WSErrorMessage :='Certains Parametres Obligatoire ne sont pas renseignes ... '; raise TEWSValidationErrorException.Create(WSErrorMessage); end; end; // ********************************************** // Envoi de requete // Recuperation des valeurs via accesseur WSResponseJSONObject[] ;; UtilisationType Object TListString<String, TWSObject> // ********************************************** function TWSRestClient_ConsumeADP.RechercherADP(sMethodNameAdp:string; sStringRequeteAdp:string; iPageNumberAdp: integer; sScopeValuesADP: TStringList; var aResponseValues: TWSArrayObject) : boolean; var sScopeList : string; var iScopeIndex : integer; var ResVariant : variant; begin result := false; for iScopeIndex := 0 to sScopeValuesADP.count do begin sScopeList := sScopeList + ' ' + sScopeValuesADP.Strings[iScopeIndex]; end; // :: == WSHTTPQueryURIParams['query'] query := '{'+sMethodNameAdp+'( '+sStringRequeteAdp+', pageSize: '+inttostr(iPageNumberAdp)+', pageNumber: pageSize: '+inttostr(iPageNumberAdp)+' ) { scope { '+sScopeList+' } }} '; if (Length(sStringRequeteAdp) >2) then begin try begin if( Declencher() ) then begin aResponseValues := WSResponseJSONObject; // :: premier index == ['data']; end else begin ;; end; end; except on Err: Exception do begin WSWriteEventLog('TWSRestClient_ConsumeADP::RechercherFromCodeStreet :: Exception :: '+Err.Message, kWSEventLogType_EWSTechInternalRuntimeErrorException); WSErrorMessage := Err.Message ; if(WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin WSRaiseLogStack(''); end; end; end; end else begin WSErrorMessage :='Certains Parametres Obligatoire ne sont pas renseignes ... '; if (WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin raise TEWSValidationErrorException.Create(WSErrorMessage); end; end; end; function TWSRestClient_ConsumeADP.extractADP(sQueryIndex : String; aArrayFiltres: TStringList; var aResponseValues: TWSArrayArrayStrings) : boolean; var lWSResultat : TWSObject; var aSubObject : TWSObject; var iNbResultat : Integer; var iIndexResultat : Integer; var iIndexResultat_sub : integer; var iFilterIndex : integer; var iNbFilter : integer; var sObjectValue : string; var sCurrentFilterName: string; var iFilterStart : integer; var iFilterEnd : integer; var sFilterParams : string; // const aArrayFiltres : array[0..4] of string = ('rivoli','afnorLabel','hexacleStreet','postCode','cityAfnorLabel'); begin try Result := false; // Le JSON Parse est Maintenant Accessible dans un TStringList<string, TObject> // meme sans resultat de ADP, l utilisation suivante est VALIDE lWSResultat := ((WSResponseJSONObject['data'])[sQueryIndex]); iNbResultat := (lWSResultat).count; // :: WSWriteEventLog('Result Count ;; '+inttostr(lWSResultat.count)+''); Result := false; if (iNbResultat = 0) then begin Result := True; setlength(aResponseValues,0,0); exit; end else begin setlength(aResponseValues, iNbResultat, (aArrayFiltres.count)); iNbFilter := (aArrayFiltres.count)-1; for iIndexResultat := 0 to iNbResultat-1 do begin aSubObject := TWSArrayObject(lWSResultat.Elements[iIndexResultat])['scope']; iFilterStart := 0; iFilterEnd := 0; for iFilterIndex := 0 to iNbFilter do begin sCurrentFilterName := aArrayFiltres[iFilterIndex]; if(AnsiPos(':', sCurrentFilterName) >0 ) then begin sFilterParams := RightStr(sCurrentFilterName, length(sCurrentFilterName) - AnsiPos(':', sCurrentFilterName) ); sCurrentFilterName := LeftStr(sCurrentFilterName, AnsiPos(':', sCurrentFilterName)-1 ); if (length(sFilterParams) > 0) and (AnsiPos(':', sFilterParams) > 0 ) then begin iFilterStart := strtoint( LeftStr(sFilterParams, AnsiPos(':', sFilterParams) ) ); iFilterEnd := strtoint( RightStr(sFilterParams, length(sFilterParams) - AnsiPos(':', sFilterParams) ) ); end else if (length(sFilterParams) > 0) then begin iFilterEnd := strtoint( sFilterParams ); end; end; if(iFilterStart > 0) then begin sObjectValue := RightStr(sObjectValue, length(sObjectValue) - iFilterStart); end; if(iFilterEnd > 0) then begin sObjectValue := LeftStr(sObjectValue, iFilterEnd); end; sObjectValue := TWSObject(aSubObject[sCurrentFilterName]).toString(); aResponseValues[iIndexResultat,iFilterIndex] := string(sObjectValue); end; end; Result := true; end; except on Err: Exception do begin WSWriteEventLog('TWSRestClient_ConsumeADP::extractADPStreet :: Exception :: '+Err.Message, kWSEventLogType_EWSTechInternalRuntimeErrorException); WSErrorMessage := Err.Message ; if(WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin WSRaiseLogStack(''); end; end; end; // :: Return array ;; etat traitement end; // ********************************************** // ********************************************** function TWSRestClient_ConsumeADP.RechercherFromCodeStreet(sStringRequeteAdp:string; var aResponseValues: TWSArrayArrayStrings) : boolean; var aArrayFiltre : TStringList; begin // :: WSHTTPQueryURIParams['query'] query :='{findStreetByCitycode(citycode: "'+sStringRequeteAdp+'", pageSize: 1000, pageNumber: 0){ scope{ afnorLabel cityAfnorLabel rivoli postCode hexacleStreet }}}'; Result := false; if (Length(sStringRequeteAdp) >2) then begin try begin // le json sera validee en interne if( Declencher() ) then begin aArrayFiltre := TStringList.create(); aArrayFiltre.add('rivoli'); aArrayFiltre.add('afnorLabel'); aArrayFiltre.add('hexacleStreet'); aArrayFiltre.add('postCode'); aArrayFiltre.add('cityAfnorLabel'); Result := extractADP('findStreetByCitycode', aArrayFiltre, aResponseValues); end else begin ;; end; end; except on Err: Exception do begin WSWriteEventLog('TWSRestClient_ConsumeADP::RechercherFromCodeStreet :: Exception :: '+Err.Message, kWSEventLogType_EWSTechInternalRuntimeErrorException); WSErrorMessage := Err.Message ; if(WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin WSRaiseLogStack(''); end; end; end; end else begin WSErrorMessage :='Certains Parametres Obligatoire ne sont pas renseignes ... '; if (WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin raise TEWSValidationErrorException.Create(WSErrorMessage); end; end; end; // ********************************************** // ********************************************** function TWSRestClient_ConsumeADP.RechercherFromCodeVille(sStringRequeteAdp:string; var aResponseValues: TWSArrayArrayStrings) : boolean; var aArrayFiltre : TStringList; begin // :: WSHTTPQueryURIParams['query'] query :='{findCityByPostcode(postcode: "'+sStringRequeteAdp+'", pageSize: 1000, pageNumber: 0){ scope{ cityId cityCode postCode addressIdentifier locationId afnorLabel aliasAfnorLabel }}}'; // query := '{ findCityByPostcode(postcode: "75003", pageSize: 1000, pageNumber: 0) { scope { cityCode afnorLabel aliasAfnorLabel } }}'; // apikey := 'dc5747d8-bc39-442c-9a32-f37e806bfce8'; Result := false; if (Length(sStringRequeteAdp) >2) then begin try begin // le json sera validee en interne if( Declencher() ) then begin aArrayFiltre := TStringList.create(); aArrayFiltre.add( 'cityCode'); aArrayFiltre.add('postCode:2'); aArrayFiltre.add('postCode'); aArrayFiltre.add('afnorLabel'); aArrayFiltre.add('aliasAfnorLabel'); Result := extractADP('findCityByPostcode', aArrayFiltre, aResponseValues); end else begin ;; end; end; except on Err: Exception do begin WSWriteEventLog('TWSRestClient_ConsumeADP::RechercherFromCodeVille :: Exception :: '+Err.Message, kWSEventLogType_EWSTechInternalRuntimeErrorException); WSErrorMessage := Err.Message ; if(WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin WSRaiseLogStack(''); end; end; end; end else begin WSErrorMessage :='Certains Parametres Obligatoire ne sont pas renseignes ... '; if (WSInternalRaiseOnError or WSInternalRaiseOnTechError ) then begin raise TEWSValidationErrorException.Create(WSErrorMessage); end; end; end; end.
unit Unit_SD_TD04_EX_UNIT_VERSION4; interface type TData = record val : Integer; end; PItem = ^TItem; TItem = record data : TData; pPrec : PItem; pSuiv : PItem; end; TFile = record pSommet : PItem; pCour : PItem; pFin : PItem; nb : Integer; end; procedure init(var p : TFile); function estVide(p : TFile) : Boolean; procedure afficheOrdre(p : TFile); procedure afficheOrdreInverse(p : TFile); procedure emfile(var p : TFile; e : TData); procedure sommet(p : TFile; var e : TData; var b : Boolean); procedure dernier(p : TFile; var e : TData; var b : Boolean); procedure defile(var p : TFile; var e : TData; var b : Boolean); implementation procedure init(var p : TFile); begin p.nb := 0; p.pSommet := NIL; p.pCour := NIL; p.pFin := NIL; end; function estVide(p : TFile) : Boolean; begin estVide := (p.pSommet = NIL); end; procedure affData(e : TData); begin writeln(e.val); end; procedure afficheOrdre(p : TFile); begin p.pCour := p.pSommet; while (p.pCour <> NIL) do begin affData((p.pCour^).data); p.pCour := (p.pCour^).pSuiv; end; end; procedure afficheOrdreInverse(p : TFile); begin p.pCour := p.pFin; while (p.pCour <> NIL) do begin affData((p.pCour^).data); p.pCour := (p.pCour^).pPrec; end; end; procedure emfile(var p : TFile; e : TData); var pTemp : PItem; begin new(pTemp); pTemp^.data := e; pTemp^.pPrec := p.pFin; pTemp^.pSuiv := NIL; p.nb := p.nb + 1; p.pCour := pTemp; if estVide(p) then begin pTemp^.pPrec := NIL; p.pSommet := pTemp; end else begin p.pFin^.pSuiv := pTemp; end; p.pFin := pTemp; end; procedure sommet(p : TFile; var e : TData; var b : Boolean); begin if (estVide(p)) then begin b := False; end else begin b := True; e := (p.pSommet^).data; end; end; procedure dernier(p : TFile; var e : TData; var b : Boolean); begin if (estVide(p)) then begin b := False; end else begin b := True; e := (p.pFin^).data; end; end; procedure defile(var p : TFile; var e : TData; var b : Boolean); var pTemp : PItem; begin if (estVide(p)) then begin b := False; end else begin b := True; e := (p.pSommet^).data; pTemp := p.pSommet; p.nb := p.nb - 1; p.pSommet := (pTemp^).pSuiv; p.pSommet^.pPrec := NIL; dispose(pTemp); end; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (c) 2002 Cunningham & Cunningham, Inc. // Released under the terms of the GNU General Public License version 2 or later. // Ported to Delphi by Salim Nair. unit ColumnFixtureTests; interface uses ColumnFixture, TestFrameWork; type {$METHODINFO ON} TColumnTestFixture = class(TColumnFixture) public FField : integer; FstringField : string; constructor Create; override; published function method : Integer; property field : Integer read FField write FField; function stringMethod : string; property stringField : string read FstringField write FstringField; end; {$METHODINFO OFF} TColumnFixtureTests = class(TTestCase) private fixture : TColumnTestFixture; protected procedure SetUp; override; procedure TearDown; override; published procedure testBindColumnToMethod; procedure testBindColumnToField; procedure testBindColumnToFieldSymbol; procedure testBindColumnToMethodSymbol; procedure testGracefulColumnNames; procedure testDoTable; end; implementation uses Field, Method, TypeAdapter, parse, sysUtils, fixture, classes, Variants, Binding; { TestFixture } constructor TColumnTestFixture.Create; begin inherited; FField := 0; end; function TColumnTestFixture.method : Integer; begin Result := 86; end; function TColumnTestFixture.stringMethod : string; begin result := ''; end; { ColumnFixtureTests } procedure TColumnFixtureTests.SetUp; begin inherited; fixture := TColumnTestFixture.Create; end; procedure TColumnFixtureTests.TearDown; begin inherited; fixture.Free; end; procedure TColumnFixtureTests.testBindColumnToMethod; var i : integer; table, tableHead : TParse; method : TMethod; const methodSpecifiers : array[0..5] of string = ('method()', 'method?', 'method!', 'string method()', 'string method?', 'string method!'); resultingMethodName : array[0..5] of string = ('method', 'method', 'method', 'stringMethod', 'stringMethod', 'stringMethod'); begin for i := 0 to length(methodSpecifiers) - 1 do begin table := TParse.Create('<table><tr><td>' + methodSpecifiers[i] + '</td></tr></table>'); tableHead := table.parts.parts; fixture.bind(tableHead); CheckNotNull(fixture.columnBindings[0], methodSpecifiers[i] + ' no binding found.'); method := fixture.columnBindings[0].adapter.method; CheckNotNull(method, methodSpecifiers[i] + 'no method found.'); CheckEquals(resultingMethodName[i], method.Name); end; end; procedure TColumnFixtureTests.testBindColumnToField(); var table, tableHead : TParse; field : TField; begin table := TParse.Create('<table><tr><td>field</td></tr></table>'); tableHead := table.parts.parts; fixture.bind(tableHead); CheckNotNull(fixture.columnBindings[0]); field := fixture.columnBindings[0].adapter.field; CheckNotNull(field); CheckEquals('field', field.FieldName); end; procedure TColumnFixtureTests.testGracefulColumnNames(); var table : TParse; tableHead : TParse; field : TField; begin table := TParse.Create('<table><tr><td>string field</td></tr></table>'); tableHead := table.parts.parts; fixture.bind(tableHead); CheckNotNull(fixture.columnBindings[0]); field := fixture.columnBindings[0].adapter.field; CheckNotNull(field); CheckEquals('stringField', field.FieldName); end; procedure TColumnFixtureTests.testBindColumnToFieldSymbol(); var table : TParse; rows : TParse; binding : TBinding; field : TField; begin Fixture.setSymbol('Symbol', '42'); table := TParse.Create('<table><tr><td>field=</td></tr><tr><td>Symbol</td></tr></table>'); rows := table.parts; fixture.doRows(rows); binding := fixture.columnBindings[0]; CheckNotNull(binding); CheckEquals(TRecallBinding, binding.ClassType); field := binding.adapter.field; CheckNotNull(field); CheckEquals('field', field.FieldName); CheckEquals(42, fixture.field); end; procedure TColumnFixtureTests.testBindColumnToMethodSymbol(); var table : TParse; rows : TParse; binding : TBinding; method : TMethod; begin table := TParse.Create('<table><tr><td>=method?</td></tr><tr><td>MethodSymbol</td></tr></table>'); rows := table.parts; fixture.doRows(rows); binding := fixture.columnBindings[0]; CheckNotNull(binding); CheckEquals(TSaveBinding, binding.ClassType); method := binding.adapter.method; CheckEquals('method', method.Name); CheckEquals('86', Fixture.getSymbol('MethodSymbol')); end; procedure TColumnFixtureTests.testDoTable; var parse : TParse; fixture : TFixture; begin parse := TParse.create('<table><tr><td>TColumnTestFixture</td></tr>' + '<tr><td>field</td><td>method()</td></tr>' + '<tr><td>1</td><td>2</td></tr>' + '<tr><td>2</td><td>86</td></tr></table>'); fixture := TFixture.Create; try fixture.doTables(parse); checkEquals(1, fixture.Counts.right, 'wrong tally for rights'); checkEquals(1, fixture.Counts.wrong, 'wrong tally for wrongs'); finally fixture.Free; end; end; initialization TestFramework.RegisterTest('uColumnFixtureTests Suite', TColumnFixtureTests.Suite); classes.RegisterClass(TColumnTestFixture); end.
unit AT.FMX.Graphics.Shapes; interface uses System.Types, System.SysUtils, System.Classes, System.Math, FMX.Types, FMX.Controls, FMX.Objects, FMX.Graphics; const pidATPlatforms = pidWin32 OR pidWin64 OR pidOSX32 OR pidiOSSimulator32 OR pidiOSSimulator64 OR pidiOSDevice32 OR pidiOSDevice64 OR pidAndroid32Arm OR pidAndroid64Arm OR pidLinux64; type [ComponentPlatformsAttribute(pidATPlatforms)] TATRoundRect = class(TRoundRect) strict private FCornerRadius: Integer; procedure SetCornerRadius(const Value: Integer); strict protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property CornerRadius: Integer read FCornerRadius write SetCornerRadius; end; [ComponentPlatformsAttribute(pidATPlatforms)] TATPolygon = class(TShape) strict private FNumberOfSides: Integer; FPath: TPathData; procedure SetNumberOfSides(const Value: Integer); strict protected procedure CreatePath; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function PointInObject(X, Y: Single): Boolean; override; published property Align; property Anchors; property ClipChildren; property ClipParent; property Cursor; property DragMode; property Enabled; property EnableDragHighlight; property Fill; property Height; property HitTest; property Locked; property Margins; property NumberOfSides: Integer read FNumberOfSides write SetNumberOfSides; property Opacity; property Padding; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property Stroke; property Visible; property Width; end; implementation { TATRoundRect } constructor TATRoundRect.Create(AOwner: TComponent); begin inherited; FCornerRadius := 8; end; procedure TATRoundRect.Paint; var Radius: Single; begin Radius := FCornerRadius; Canvas.FillRect(GetShapeRect, Radius, Radius, Corners, AbsoluteOpacity, Fill); Canvas.DrawRect(GetShapeRect, Radius, Radius, Corners, AbsoluteOpacity, Stroke); end; procedure TATRoundRect.SetCornerRadius(const Value: Integer); begin if FCornerRadius <> Value then begin FCornerRadius := Value; Repaint; end; end; { TATPolygon } constructor TATPolygon.Create(AOwner: TComponent); begin inherited; FNumberOfSides := 3; FPath := TPathData.Create; end; destructor TATPolygon.Destroy; begin FreeAndNil(FPath); inherited; end; procedure TATPolygon.CreatePath; procedure GoToAVertex(n: Integer; Angle, Radius: Double; IsLineTo: Boolean = True); var NewLocation: TPointF; begin NewLocation.X := Width / 2 + Cos(n * Angle) * Radius; NewLocation.Y := Height / 2 - Sin(n * Angle) * Radius; if (IsLineTo) then FPath.LineTo(NewLocation) else FPath.MoveTo(NewLocation); end; var i: Integer; Angle: Double; Radius: Double; begin Angle := 2 * Pi / FNumberOfSides; Radius := Min(ShapeRect.Width / 2, ShapeRect.Height / 2); FPath.Clear; GoToAVertex(0, Angle, Radius, False); for i := 1 to FNumberOfSides do begin GoToAVertex(i, Angle, Radius); end; FPath.ClosePath; end; procedure TATPolygon.Paint; begin CreatePath; Canvas.FillPath(FPath, AbsoluteOpacity, Fill); Canvas.DrawPath(FPath, AbsoluteOpacity, Stroke); end; function TATPolygon.PointInObject(X, Y: Single): Boolean; begin CreatePath; Result := Canvas.PtInPath(AbsoluteToLocal(PointF(X, Y)), FPath); end; procedure TATPolygon.SetNumberOfSides(const Value: Integer); begin if ( (FNumberOfSides <> Value) AND (Value >= 3) ) then begin FNumberOfSides := Value; Repaint; end; end; end.
{ ******************************************************* } { } { Delphi FireMonkey Platform } { } { Copyright(c) 1995-2013 Embarcadero Technologies, Inc. } { } { ******************************************************* } unit FMX.ActnList; {$T-,H+,X+} interface uses System.Classes, System.SysUtils, System.Actions; type /// <summary> The usual list of actions (without published properties) in Fire Monkey </summary> TCustomActionList = class(TContainedActionList) public function DialogKey(const Key: Word; const Shift: TShiftState): boolean; virtual; end; /// <summary> The usual list of actions (with published properties) in Fire Monkey </summary> TActionList = class(TCustomActionList) published property Name; property State; property OnChange; property OnExecute; property OnStateChange; property OnUpdate; end; /// <summary> This class is designed to communicate with some of the object in Fire Monkey </summary> TActionLink = class(TContainedActionLink) protected end; TActionLinkClass = class of TActionLink; /// <summary> List of additional combinations of hot keys in Fire Monkey </summary> TShortCutList = class(TCustomShortCutList) public function Add(const S: String): Integer; override; end; /// <summary> The usual action (without published properties) in Fire Monkey </summary> TCustomAction = class(TContainedAction) private FShortCutPressed: boolean; FTarget: TComponent; FUnsupportedArchitectures: TArchitectures; FUnsupportedPlatforms: TPlatforms; FOldVisible: boolean; FOldEnabled: boolean; FSupported: boolean; FCustomText: string; FSupportedChecked: boolean; FHideIfUnsupportedInterface: boolean; function GetText: string; inline; procedure SetText(const Value: string); inline; function GetCustomActionList: TCustomActionList; procedure SetCustomActionList(const Value: TCustomActionList); procedure ReaderCaptionProc(Reader: TReader); procedure WriterCaptionProc(Writer: TWriter); procedure ReaderImageIndexProc(Reader: TReader); procedure WriterImageIndexProc(Writer: TWriter); procedure SetUnsupportedArchitectures(const Value: TArchitectures); procedure SetUnsupportedPlatforms(const Value: TPlatforms); procedure SetCustomText(const Value: string); procedure SetHideIfUnsupportedInterface(const Value: boolean); protected procedure SetShortCutPressed(const Value: boolean); inline; procedure UpdateSupported; function IsSupportedInterface: boolean; virtual; function CreateShortCutList: TCustomShortCutList; override; procedure DefineProperties(Filer: TFiler); override; function IsDialogKey(const Key: Word; const Shift: TShiftState): boolean; procedure SetTarget(const Value: TComponent); virtual; procedure SetEnabled(Value: Boolean); override; procedure SetVisible(Value: Boolean); override; procedure Loaded; override; procedure CustomTextChanged; virtual; property CustomText: string read FCustomText write SetCustomText; public constructor Create(AOwner: TComponent); override; function Execute: Boolean; override; function Update: Boolean; override; property Text: string read GetText write SetText; property Caption stored false; property ActionList: TCustomActionList read GetCustomActionList write SetCustomActionList; property HideIfUnsupportedInterface: boolean read FHideIfUnsupportedInterface write SetHideIfUnsupportedInterface; property ShortCutPressed: boolean read FShortCutPressed; property Target: TComponent read FTarget; property UnsupportedArchitectures: TArchitectures read FUnsupportedArchitectures write SetUnsupportedArchitectures default []; property UnsupportedPlatforms: TPlatforms read FUnsupportedPlatforms write SetUnsupportedPlatforms default []; property Supported: boolean read FSupported; end; /// <summary> The usual action (with published properties) in Fire Monkey </summary> TAction = class(TCustomAction) public constructor Create(AOwner: TComponent); override; published property AutoCheck; property Text; property Checked; property Enabled; property GroupIndex; property HelpContext; property HelpKeyword; property HelpType; property Hint; property ShortCut default 0; property SecondaryShortCuts; property Visible; property UnsupportedArchitectures; property UnsupportedPlatforms; property OnExecute; property OnUpdate; end; function TextToShortCut(Text: string): integer; implementation uses System.RTLConsts, FMX.Consts, FMX.Platform, FMX.Forms, FMX.Menus; function TextToShortCut(Text: string): Integer; var MenuService: IFMXMenuService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXMenuService, IInterface(MenuService)) then Result:= MenuService.TextToShortCut(Text) else Result := -1; end; { TCustomActionList } function TCustomActionList.DialogKey(const Key: Word; const Shift: TShiftState): boolean; var I: Integer; LAction: TCustomAction; begin Result := False; if (State <> asNormal) then Exit; for I := 0 to ActionCount - 1 do if (Actions[I] is TCustomAction) and (TCustomAction(Actions[I]).Supported) and (TCustomAction(Actions[I]).IsDialogKey(Key, Shift)) then begin LAction := TCustomAction(Actions[I]); LAction.SetShortCutPressed(True); try Result := LAction.HandleShortCut; if (not Result) and (LAction.Enabled) and (LAction.HandlesTarget(nil)) then begin LAction.UpdateTarget(nil); if LAction.Enabled then begin LAction.ExecuteTarget(nil); Result := True; end; end; finally LAction.SetShortCutPressed(False); end; if Result then Exit; end; end; { TCustomShortCutList } function TShortCutList.Add(const S: String): Integer; var ShortCut: NativeInt; begin ShortCut := TextToShortCut(S); if ShortCut <> 0 then begin Result := inherited Add(S); Objects[Result] := TObject(ShortCut); end else raise EActionError.CreateFMT(SErrorShortCut, [S]); end; { TCustomAction } constructor TCustomAction.Create(AOwner: TComponent); begin inherited; FSupported := True; FOldEnabled := Enabled; FOldVisible := Visible; end; function TCustomAction.CreateShortCutList: TCustomShortCutList; begin Result := TShortCutList.Create; end; procedure TCustomAction.ReaderCaptionProc(Reader: TReader); var S: string; begin try S := Reader.ReadString; except S := ''; end; if S <> '' then Text := S; end; procedure TCustomAction.WriterCaptionProc(Writer: TWriter); begin Writer.WriteString(Caption); end; procedure TCustomAction.ReaderImageIndexProc(Reader: TReader); begin ImageIndex := Reader.ReadInteger; end; procedure TCustomAction.WriterImageIndexProc(Writer: TWriter); begin Writer.WriteInteger(ImageIndex); end; procedure TCustomAction.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Caption', ReaderCaptionProc, WriterCaptionProc, False); Filer.DefineProperty('ImageIndex', ReaderImageIndexProc, WriterImageIndexProc, ImageIndex <> -1); end; function TCustomAction.IsDialogKey(const Key: Word; const Shift: TShiftState): boolean; var I: integer; MenuService: IFMXMenuService; procedure UpdateResult; var k: word; SState: TShiftState; begin SState := []; k := 0; if Assigned(MenuService) then MenuService.ShortCutToKey(ShortCut, k, SState) else begin k := ShortCut and not (scCommand + scShift + scCtrl + scAlt); if ShortCut and scShift <> 0 then Include(SState, ssShift); if ShortCut and scCtrl <> 0 then Include(SState, ssCtrl); if ShortCut and scAlt <> 0 then Include(SState, ssAlt); if ShortCut and scCommand <> 0 then Include(SState, ssCommand); end; Result := (k = Key) and (Shift = SState); end; begin Result := False; MenuService := nil; if Supported and (ShortCut <> 0) then begin TPlatformServices.Current.SupportsPlatformService(IFMXMenuService, IInterface(MenuService)); UpdateResult; if (not Result) and (SecondaryShortCutsCreated) then begin I := 0; while (not Result) and (I < SecondaryShortCuts.Count) do begin UpdateResult; inc(I); end; end; end; end; procedure TCustomAction.Loaded; begin inherited; if Supported and (([csLoading, csDestroying] * ComponentState) = []) then CustomTextChanged; end; function TCustomAction.Execute: Boolean; begin Result := False; if (not Supported) or Assigned(ActionList) and (ActionList.State <> asNormal) then exit; Update; if Enabled and AutoCheck then if (not Checked) or (Checked and (GroupIndex = 0)) then Checked := not Checked; Result := Enabled and inherited Execute; end; function TCustomAction.Update: Boolean; begin if FHideIfUnsupportedInterface then begin if not FSupportedChecked then begin UpdateSupported; FSupportedChecked := True; end; end; if Supported then Result := ((ActionList <> nil) and ActionList.UpdateAction(Self)) or (Application.UpdateAction(Self)) or inherited Update else Result := False; end; function TCustomAction.GetCustomActionList: TCustomActionList; begin Result := TCustomActionList(inherited ActionList); end; procedure TCustomAction.SetCustomActionList(const Value: TCustomActionList); begin inherited ActionList := Value; end; procedure TCustomAction.CustomTextChanged; begin end; procedure TCustomAction.SetCustomText(const Value: string); begin if FCustomText <> Value then begin FCustomText := Value; if (Supported or vDesignAction) and (([csLoading, csDestroying] * ComponentState) = []) then CustomTextChanged; end; end; procedure TCustomAction.SetEnabled(Value: Boolean); var V: Boolean; begin V := Value and Supported; if Supported or (csLoading in ComponentState) then FOldEnabled := Value; if V <> Enabled then inherited SetEnabled(V); end; procedure TCustomAction.SetHideIfUnsupportedInterface(const Value: boolean); begin if FHideIfUnsupportedInterface <> Value then begin FHideIfUnsupportedInterface := Value; if FHideIfUnsupportedInterface then FSupportedChecked := False; end; end; procedure TCustomAction.SetVisible(Value: Boolean); var V: Boolean; begin V := Value and Supported; if Supported or (csLoading in ComponentState) then FOldVisible := Value; if V <> Visible then inherited SetVisible(V); end; procedure TCustomAction.SetShortCutPressed(const Value: boolean); begin FShortCutPressed := Value; end; function TCustomAction.GetText: string; begin Result := inherited Caption; end; procedure TCustomAction.SetTarget(const Value: TComponent); begin FTarget := Value; end; procedure TCustomAction.SetText(const Value: string); begin Caption := Value; end; function TCustomAction.IsSupportedInterface: boolean; begin Result := True; end; procedure TCustomAction.UpdateSupported; var LSupp: boolean; begin if (([csDesigning] * ComponentState) <> []) or (vDesignAction) then LSupp := True else begin LSupp := not ((TOSVersion.Architecture in FUnsupportedArchitectures) or (TOSVersion.Platform in FUnsupportedPlatforms)); if LSupp and FHideIfUnsupportedInterface then LSupp := IsSupportedInterface; end; if LSupp <> FSupported then begin FSupported := LSupp; if FSupported then begin SetEnabled(FOldEnabled); SetVisible(FOldVisible); end else begin SetVisible(False); SetEnabled(False); end; Change; end; end; procedure TCustomAction.SetUnsupportedArchitectures(const Value: TArchitectures); begin if FUnsupportedArchitectures <> Value then begin FUnsupportedArchitectures := Value; UpdateSupported; end; end; procedure TCustomAction.SetUnsupportedPlatforms(const Value: TPlatforms); begin if FUnsupportedPlatforms <> Value then begin FUnsupportedPlatforms := Value; UpdateSupported; end; end; { TAction } constructor TAction.Create(AOwner: TComponent); begin inherited; DisableIfNoHandler := True; end; initialization finalization end.
unit chairName2; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, StdCtrls, ExtCtrls, Grids, AdvObj, BaseGrid, AdvGrid, AdvUtil; type TChairName2_f = class(TForm) Panel1: TPanel; plbottom: TPanel; plgrid: TPanel; Grdmain: TAdvStringGrid; Label2: TLabel; btnAdd: TButton; btnPost: TButton; btnDelete: TButton; btnClose: TButton; procedure btnPostClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); private procedure SelectData; procedure PostData; procedure DeleteData; { Private declarations } public { Public declarations } end; var ChairName2_f: TChairName2_f; const // Grid Columns Index GR_EMPNO = 0; GR_LNAME = 1; GR_FNAME = 2; // Query SQL_SELECT_DATA = 'SELECT * FROM ma_basic_chair '; SQL_INSERT_DATA = 'INSERT INTO ma_basic_chair ' + #13#10 + ' (ChairNo, ChairName, ChairRemark ) ' + #13#10 + ' VALUES ' + #13#10 + ' (:ChairNo, :ChairName, :ChairRemark ) '; SQL_UPDATE_DATA = 'UPDATE ma_basic_chair SET ' + #13#10 + ' ChairName = :ChairName, ChairRemark=:ChairRemark ' + #13#10 + ' WHERE ChairNo = :ChairNo '; SQL_DELETE_DATA = 'DELETE FROM ma_basic_chair ' + #13#10 + ' WHERE ChairNo = :ChairNo '; SQL_SELECT_MAXCODE = 'select max(ChairNo) as MaxCode from ma_basic_chair '; implementation uses uDm, uMain; {$R *.DFM} procedure TChairName2_f.SelectData; var nRowcount, i:integer; begin i:=1; grdMain.beginupdate; with Dm_f.sqlTemp do begin SQL.Text := SQL_SELECT_MAXCODE; Open; label2.caption:= FieldByName('Maxcode').AsString; end; with Dm_f.sqlTemp, grdMain do begin //Clear; // RealGrid.Clear; SQL.Text := SQL_SELECT_DATA; Open; nRowCount:=recordcount; rowCount:=nRowcount+1; if not Dm_f.sqlTemp.IsEmpty then while not EOF do begin Cells[1, i] := FieldByName('ChairNo').AsString; Cells[2, i] := FieldByName('ChairRemark').AsString; inc(i); Next; end; autonumbercol(0); end; grdMain.Endupdate; end; procedure TChairName2_f.PostData; //일괄저장 방법 var nRow: Integer; begin with Dm_f.sqlTemp, grdMain do try Close; Sql.Clear; Sql.Add('delete from ma_basic_chair'); execsql; for nRow := 1 to RowCount - 1 do begin Close; Sql.Clear; Sql.Add('INSERT INTO ma_basic_chair'); Sql.Add('(ChairNo, ChairName, ChairRemark )VALUES '); Sql.Add('(:ChairNo, :ChairName, :ChairRemark )'); ParamByName('ChairNo').AsString := grdmain.Cells[1, nRow]; ParamByName('ChairName').AsString := grdmain.Cells[1, nRow]; ParamByName('ChairRemark').AsString := grdmain.Cells[2, nRow]; ExecSQL; autonumbercol(0); end; except on E: Exception do begin //dbMain.Rollback; //result := false; ShowMessage(E.Message + ' [저장오류]'); end; end; showmessage('저장되었습니다.'); SelectData; end; procedure TChairName2_f.DeleteData; begin with Dm_f.sqlTemp do try Close; Sql.text:= SQL_DELETE_DATA ; parambyname('chairNo').asString:= grdmain.Cells[1, grdmain.Row]; execsql; except end; end; // Event procedure TChairName2_f.btnPostClick(Sender: TObject); begin PostData; end; procedure TChairName2_f.btnDeleteClick(Sender: TObject); begin DeleteData; SelectData; end; procedure TChairName2_f.FormShow(Sender: TObject); begin //main_f.panelSet(plbottom,albottom); //main_f.panelSet(plgrid,alclient); //main_f.GridSet(grdmain,false,plgrid,alclient,0,0,0,0); Caption := '체어명 설정'; label2.caption:=''; SelectData; end; procedure TChairName2_f.btnCloseClick(Sender: TObject); begin close; end; procedure TChairName2_f.btnAddClick(Sender: TObject); var nRow: integer; begin grdmain.InsertRows(grdmain.RowCount,1); nRow := grdmain.RowCount - 1; if (nRow > 0) and (GrdMain.Cells[2, nRow] = '') and (GrdMain.Cells[1, nRow] = '') then begin label2.caption:=inttostr(nRow-1); GrdMain.Cells[1, nRow] := formatfloat('0', StrToInt(label2.caption) + 1); end else if (nRow = 0) then begin GrdMain.Cells[1, nRow] := '1'; GrdMain.Cells[2, nRow] := ''; end; label2.caption:= GrdMain.Cells[1, nRow]; end; procedure TChairName2_f.FormClose(Sender: TObject; var Action: TCloseAction); begin action:=caFree; end; procedure TChairName2_f.FormDestroy(Sender: TObject); begin ChairName2_f:=nil; end; end.
unit System.CSV; interface uses System.Generics.Collections, System.Classes, System.Rtti, System.SysUtils; type TBufferedReader = class; TLineInfo = record Size: Int64; Line: Int64; Data: string; Buffer: TBufferedReader; function ToString: string; Function ReadText: string; end; TBufferedReader = class private FFile: TextFile; BufferSize: Integer; LinesIndex: array of TLineInfo; procedure LoadAllLines; procedure WriteLine(AData: string; ALine: Int64); function EnsureLineIndex(ALine: Int64): Boolean; public function PageSize: Integer; function PageCount: Int64; function ReadLine(ALine: Int64): TLineInfo; constructor Create(AFileName: string; ABufferSize: Integer = -1); destructor Destroy; override; end; TCSVField = record var raw: string; function GetBoolean: Boolean; function GetDateTime: TDateTime; function GetFloat: Double; function GetInt64: Int64; function GetInteger: Integer; function GetString: string; procedure SetBoolean(const Value: Boolean); procedure SetDateTime(const Value: TDateTime); procedure SetFloat(const Value: Double); procedure SetInt64(const Value: Int64); procedure SetInteger(const Value: Integer); procedure SetString(const Value: string); property AsString: string read GetString write SetString; property AsFloat: Double read GetFloat write SetFloat; property AsInteger: Integer read GetInteger write SetInteger; property AsInt64: Int64 read GetInt64 write SetInt64; property AsBoolean: Boolean read GetBoolean write SetBoolean; property AsDateTime: TDateTime read GetDateTime write SetDateTime; end; TCSVFile = class private FBuffer: TBufferedReader; FIndex: Int64; FDelimiter: Char; FFieldIndex: TDictionary<string, Integer>; FCurrentLine: string; FCurrentLineInfo: TLineInfo; constructor Create(AFileName: string; ADelimiter: Char; ABufferSize: Integer); procedure ReadLine(ALine: Int64); function GetValue(Index: String): TCSVField; function GetFields: TArray<String>; function GetLine(Index: Int64): TCSVFile; public property Value[Index: String]: TCSVField read GetValue; default; property Line[Index: Int64]: TCSVFile read GetLine; property CurrentIndex: Int64 read FIndex; property CurrentLine: string read FCurrentLine; property CurrentLineInfo: TLineInfo read FCurrentLineInfo; function Size: Int64; function HasField(AField: string): Boolean; property Fields: TArray<String> read GetFields; procedure Initialize; public destructor Destroy; override; end; function ReadCSV(AFileName: string): TCSVFile; overload; function ReadCSV(AFileName: string; ADelimiter: Char): TCSVFile; overload; function ReadCSV(AFileName: string; ADelimiter: Char; ABufferSize: Integer): TCSVFile; overload; implementation uses System.IOUtils, System.Math; function MakeField(AValue: string): TCSVField; begin Result.raw := AValue; end; function MakeLineInfo(AData: string; ALine: Int64; AReader: TBufferedReader): TLineInfo; begin Result.Line := ALine; Result.Data := AData; Result.Buffer := AReader; Result.Size := Length(AData); end; { TCSVFile } constructor TCSVFile.Create(AFileName: string; ADelimiter: Char; ABufferSize: Integer); begin Assert(ABufferSize >= 1024, 'Buffer need >= 1024 B'); FBuffer := TBufferedReader.Create(AFileName, ABufferSize); FDelimiter := ADelimiter; FCurrentLine := ''; FIndex := 1; FFieldIndex := TDictionary<string, Integer>.Create; Initialize; end; destructor TCSVFile.Destroy; begin FFieldIndex.Free; FBuffer.Free; inherited; end; function TCSVFile.GetFields: TArray<String>; begin Result := FFieldIndex.Keys.ToArray; end; function TCSVFile.GetLine(Index: Int64): TCSVFile; begin ReadLine(Index + 1); Result := Self; end; function TCSVFile.GetValue(Index: String): TCSVField; begin if not HasField(Index) then raise Exception.Create('Field ' + Index + ' not found'); if not FCurrentLine.IsEmpty then Result := MakeField(FCurrentLine.Split(FDelimiter)[FFieldIndex[Index]]); end; function TCSVFile.HasField(AField: string): Boolean; begin Result := FFieldIndex.ContainsKey(AField); end; procedure TCSVFile.Initialize; var LFields: TArray<string>; LIndex: Integer; begin LFields := FBuffer.ReadLine(1).ReadText.Split(FDelimiter); for LIndex := 0 to Length(LFields) - 1 do FFieldIndex.Add(LFields[LIndex], LIndex); end; procedure TCSVFile.ReadLine(ALine: Int64); begin if FIndex = ALine then Exit; FIndex := ALine; FCurrentLineInfo := FBuffer.ReadLine(FIndex); FCurrentLine := FCurrentLineInfo.ReadText; end; function TCSVFile.Size: Int64; begin Result := FBuffer.PageCount; end; function ReadCSV(AFileName: string; ADelimiter: Char; ABufferSize: Integer): TCSVFile; overload; begin Result := TCSVFile.Create(AFileName, ADelimiter, ABufferSize); end; function ReadCSV(AFileName: string; ADelimiter: Char): TCSVFile; begin Result := ReadCSV(AFileName, ADelimiter, 1024); end; function ReadCSV(AFileName: string): TCSVFile; begin Result := ReadCSV(AFileName, ';'); end; { TBufferedReader } constructor TBufferedReader.Create(AFileName: string; ABufferSize: Integer); begin if not FileExists(AFileName) then raise Exception.Create('File not exists'); AssignFile(FFile, AFileName); {$I-} Append(FFile); {$I+} end; destructor TBufferedReader.Destroy; begin inherited; end; function TBufferedReader.EnsureLineIndex(ALine: Int64): Boolean; var LData: string; LLineNo: Int64; begin Result := True; if Length(LinesIndex) >= ALine then Exit; while (Length(LinesIndex) < ALine) and not Eof(Self.FFile) do begin Readln(FFile, LData); LLineNo := Length(LinesIndex) + 1; SetLength(LinesIndex, Length(LinesIndex) + 1); LinesIndex[High(LinesIndex)] := MakeLineInfo(LData, LLineNo, Self); Result := True; end; end; procedure TBufferedReader.LoadAllLines; begin EnsureLineIndex(Int64.MaxValue); end; function TBufferedReader.PageCount: Int64; begin LoadAllLines; Result := Length(LinesIndex) - 1; end; function TBufferedReader.PageSize: Integer; begin Result := BufferSize; end; function TBufferedReader.ReadLine(ALine: Int64): TLineInfo; begin EnsureLineIndex(ALine); Result := LinesIndex[ALine]; end; procedure TBufferedReader.WriteLine(AData: string; ALine: Int64); begin Writeln(FFile, AData, ALine); end; { TLineInfo } function TLineInfo.ReadText: string; begin Result := Self.Data; end; function TLineInfo.ToString: string; begin Result := '{' + sLineBreak + ' "Size": ' + Self.Size.ToString + ',' + sLineBreak + ' "Line": ' + Self.Line.ToString + ',' + sLineBreak + ' "Data": ' + Self.Data + sLineBreak + '}'; end; end.
unit uFormRelLucroPeriodo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFormBase, Vcl.StdCtrls, Data.DB, Vcl.Mask, JvExMask, JvToolEdit, Vcl.Grids, Vcl.DBGrids, JvExDBGrids, JvDBGrid, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Menus; type TfrmRelLucroPeriodo = class(TfrmBase) btnConsultar: TButton; btnSair: TButton; btnImprimir: TButton; DBGrid: TJvDBGrid; dtInicial: TJvDateEdit; dtFinal: TJvDateEdit; Label1: TLabel; Label2: TLabel; ds: TDataSource; qr: TFDQuery; PopupMenu1: TPopupMenu; CloseDataSet1: TMenuItem; procedure btnSairClick(Sender: TObject); procedure btnConsultarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure qrAfterOpen(DataSet: TDataSet); procedure qrBeforeOpen(DataSet: TDataSet); procedure CloseDataSet1Click(Sender: TObject); procedure btnImprimirClick(Sender: TObject); private { Private declarations } procedure BotaoConsultar; procedure BotaoImprimir; public { Public declarations } end; var frmRelLucroPeriodo: TfrmRelLucroPeriodo; implementation uses uDataModule, uFormRelatorios; {$R *.dfm} procedure TfrmRelLucroPeriodo.BotaoConsultar; var DataInicial, DataFinal: string; begin DataInicial:= FormatDateTime('YYYY-mm-dd', dtInicial.Date) + ' 00:00:00'; DataFinal:= FormatDateTime('YYYY-mm-dd', dtFinal.Date) + ' 23:59:59'; qr.Close; if (dtInicial.Date > dtFinal.Date) or (dtFinal.Date < dtInicial.Date)then begin Erro('Período inválido!'); dtInicial.SetFocus; Abort; end; qr.ParamByName('DataInicial').AsString:= DataInicial; qr.ParamByName('DataFinal').AsString:= DataFinal; qr.Open; if qr.IsEmpty then begin Informacao('Nenhum dado retornado neste período!'); end; end; procedure TfrmRelLucroPeriodo.BotaoImprimir; begin if not(qr.Active)then begin Exit; end; if (qr.Active) and (qr.RecordCount <= 0) then begin Informacao('Nenhum dado para imprimir!'); Exit; end; Application.CreateForm(TfrmRelatorios, frmRelatorios); try frmRelatorios.RLReport2.DataSource := Self.ds; frmRelatorios.lbPeriodo2.Caption := frmRelatorios.lbPeriodo2.Caption + ': '+ DateToStr(dtInicial.Date) + ' à ' + DateToStr(dtFinal.Date); frmRelatorios.RLReport2.Preview; finally FreeAndNil(frmRelatorios); end; end; procedure TfrmRelLucroPeriodo.btnConsultarClick(Sender: TObject); begin inherited; BotaoConsultar; end; procedure TfrmRelLucroPeriodo.btnImprimirClick(Sender: TObject); begin inherited; BotaoImprimir; end; procedure TfrmRelLucroPeriodo.btnSairClick(Sender: TObject); begin inherited; Close; end; procedure TfrmRelLucroPeriodo.CloseDataSet1Click(Sender: TObject); begin inherited; qr.Close; end; procedure TfrmRelLucroPeriodo.FormCreate(Sender: TObject); begin inherited; dtInicial.Date := Date; dtFinal.Date := Date; end; procedure TfrmRelLucroPeriodo.qrAfterOpen(DataSet: TDataSet); begin inherited; DBGridTitleColor(DBGrid); DBGrid.Columns[0].Width:= 30; DBGrid.Columns[1].Width:= 320; DBGrid.Columns[2].Width:= 60; DBGrid.Columns[3].Width:= 60; DBGrid.Columns[4].Width:= 60; end; procedure TfrmRelLucroPeriodo.qrBeforeOpen(DataSet: TDataSet); begin inherited; SetFloatFields(qr); end; end.
unit UVoiceForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MPlayer, ExtCtrls, UzLogConst, UzLogSound, UzLogOperatorInfo; type TVoiceForm = class(TForm) Timer2: TTimer; procedure FormCreate(Sender: TObject); procedure Timer2Timer(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private 宣言 } FWaveSound: array[1..maxmessage + 2] of TWaveSound; FCurrentOperator: TOperatorInfo; FCurrentVoice: Integer; FOnNotifyStarted: TNotifyEvent; FOnNotifyFinished: TPlayMessageFinishedProc; public { Public 宣言 } procedure Init(); procedure SendVoice(i: integer); procedure StopVoice(); procedure SetOperator(op: TOperatorInfo); function IsPlaying(): Boolean; property OnNotifyStarted: TNotifyEvent read FOnNotifyStarted write FOnNotifyStarted; property OnNotifyFinished: TPlayMessageFinishedProc read FOnNotifyFinished write FOnNotifyFinished; end; implementation {$R *.dfm} uses UzLogKeyer, UzLogGlobal; procedure TVoiceForm.FormCreate(Sender: TObject); var i: Integer; begin FOnNotifyStarted := nil; FOnNotifyFinished := nil; FCurrentVoice := 0; FCurrentOperator := nil; for i := 1 to High(FWaveSound) do begin FWaveSound[i] := TWaveSound.Create(); end; end; procedure TVoiceForm.FormDestroy(Sender: TObject); var i: Integer; begin for i := 1 to High(FWaveSound) do begin FWaveSound[i].Free(); end; end; procedure TVoiceForm.Init(); var i: Integer; begin for i := 1 to High(FWaveSound) do begin FWaveSound[i].Close(); end; FCurrentVoice := 0; end; procedure TVoiceForm.SendVoice(i: integer); var filename: string; begin if FCurrentOperator = nil then begin case i of 1..12: begin filename := dmZLogGlobal.Settings.FSoundFiles[i]; end; 101: begin filename := dmZLogGlobal.Settings.FSoundFiles[1]; i := 1; end; 102: begin filename := dmZLogGlobal.Settings.FAdditionalSoundFiles[2]; i := 13; end; 103: begin filename := dmZLogGlobal.Settings.FAdditionalSoundFiles[3]; i := 14; end; end; end else begin case i of 1..12: begin filename := FCurrentOperator.VoiceFile[i]; end; 101: begin filename := FCurrentOperator.VoiceFile[1]; i := 1; end; 102: begin filename := FCurrentOperator.AdditionalVoiceFile[2]; i := 13; end; 103: begin filename := FCurrentOperator.AdditionalVoiceFile[3]; i := 14; end; end; end; // ファイル名が空か、ファイルがなければ何もしない if (filename = '') or (FileExists(filename) = False) then begin // if Assigned(FOnNotifyStarted) then begin // FOnNotifyStarted(nil); // end; if Assigned(FOnNotifyFinished) then begin FOnNotifyFinished(nil, mSSB, False); end; Exit; end; // 前回Soundと変わったか if FWaveSound[i].FileName <> filename then begin FWaveSound[i].Close(); end; if FWaveSound[i].IsLoaded = False then begin FWaveSound[i].Open(filename, dmZLogGlobal.Settings.FSoundDevice); end; FWaveSound[i].Stop(); if Assigned(FOnNotifyStarted) then begin FOnNotifyStarted(FWaveSound[i]); end; FCurrentVoice := i; FWaveSound[i].Play(); Timer2.Enabled := True; end; procedure TVoiceForm.StopVoice(); begin Timer2.Enabled := False; if FCurrentVoice <> 0 then begin FWaveSound[FCurrentVoice].Stop(); end; if Assigned(FOnNotifyFinished) then begin // Stop時のFinishイベントは不要 //FOnNotifyFinished(nil, mSSB, True); end; end; procedure TVoiceForm.SetOperator(op: TOperatorInfo); begin FCurrentOperator := op; Init(); end; function TVoiceForm.IsPlaying(): Boolean; begin Result := FWaveSound[FCurrentVoice].Playing; end; // Voice再生終了まで待つタイマー procedure TVoiceForm.Timer2Timer(Sender: TObject); begin if IsPlaying() = True then begin Exit; end; Timer2.Enabled := False; if Assigned(FOnNotifyFinished) then begin FOnNotifyFinished(FWaveSound[FCurrentVoice], mSSB, False); end; {$IFDEF DEBUG} OutputDebugString(PChar('---Voice Play finished!! ---')); {$ENDIF} end; end.
unit CapsuleEndpoint; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Capsule; type ICapsuleEndpoint = interface(IInterface) ['{3034C771-6CC0-47E0-826D-9C4608A2D84D}'] function All: ICapsuleList; function One(const Id: string): ICapsule; end; function NewCapsuleEndpoint: ICapsuleEndpoint; implementation uses Endpoint_Helper, fpjson; const Endpoint = 'capsules/'; type { TCapsulesEndpoint } TCapsuleEndpoint = class(TInterfacedObject, ICapsuleEndpoint) function All: ICapsuleList; function One(const Id: string): ICapsule; end; function NewCapsuleEndpoint: ICapsuleEndpoint; begin Result := TCapsuleEndpoint.Create; end; { TCapsulesEndpoint } function TCapsuleEndpoint.All: ICapsuleList; begin Result := NewCapsuleList; EndpointToModel(Endpoint, Result); end; function TCapsuleEndpoint.One(const Id: string): ICapsule; begin Result := NewCapsule; EndpointToModel(SysUtils.ConcatPaths([Endpoint, Id]), Result); end; end.
unit TreeItemsx; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, ExtCtrls, ComCtrls,ComWriUtils,Commctrl; type TTreeItemType = longword; TTreeItem = class; TTreeFolder = class; TTreeItemclass = class of TTreeItem; TTreeItem = class private FParent : TTreeFolder; procedure SetCaption(const Value: string); virtual; procedure SetModified(const Value: boolean); virtual; protected FModified : boolean; FCaption : string; FItemType : TTreeItemType; public constructor Create(AParent : TTreeFolder); virtual; property Caption : string Read FCaption Write SetCaption; property ItemType: TTreeItemType Read FItemType; property Parent : TTreeFolder read FParent; function IsFolder: boolean; virtual; property Modified : boolean Read FModified Write SetModified; procedure Delete; published end; TTreeFolder = class(TTreeItem) private FOpened : boolean; FChilrenModified: boolean; procedure SetOpened(const Value: boolean); function GetCount: integer; function GetItems(index: integer): TTreeItem; protected FItems : TObjectList; procedure ItemChanged(Item : TTreeItem); virtual; public constructor Create(AFolder : TTreeFolder); override; destructor destroy; override; function IsFolder: boolean; override; // set ChilrenModified when a child item changed, or // add / delete a item. property ChilrenModified : boolean Read FChilrenModified Write FChilrenModified; property Opened: boolean Read FOpened Write SetOpened; procedure Open; virtual; abstract; procedure Save; virtual; abstract; procedure Close; virtual; // manage all items property Count : integer read GetCount; property Items[index : integer] : TTreeItem Read GetItems; function NewItem(AItemType : TTreeItemType): TTreeItem; virtual; function DeleteItem(Item : TTreeItem):boolean ; class function ItemClass(AItemType : TTreeItemType) : TTreeItemClass; virtual; abstract; published end; TFolderMan = class; TFolderView = class; TFolderMan = class private FFolderView: TFolderView; FRoot: TTreeFolder; procedure SetFolderView(const Value: TFolderView); public constructor Create(ARoot : TTreeFolder; AFolderView : TFolderView); destructor Destroy; override; property Root : TTreeFolder read FRoot; property FolderView : TFolderView read FFolderView write SetFolderView; function CanEdit(Item : TTreeItem): Boolean; virtual; end; TInitImageIndexEvent = procedure (Sender: TFolderView; Node: TTreeNode; TreeItem : TTreeItem) of object; TFolderView = class(TTreeView) private FFolderMan: TFolderMan; FOnInitItemImage: TInitImageIndexEvent; procedure SetFolderMan(const Value: TFolderMan); function GetSelectedTreeItem: TTreeItem; protected function CanEdit(Node: TTreeNode): Boolean; override; procedure Edit(const Item: TTVItem); override; function CanExpand(Node: TTreeNode): Boolean; override; function GetNodeFromItem(const Item: TTVItem): TTreeNode; public property FolderMan : TFolderMan read FFolderMan write SetFolderMan; property SelectedTreeItem : TTreeItem Read GetSelectedTreeItem; function OpenNode(Node : TTreeNode):boolean; function AddTreeItem(ParentNode : TTreeNode; TreeItem : TTreeItem): TTreeNode; published property OnInitItemImage: TInitImageIndexEvent Read FOnInitItemImage Write FOnInitItemImage; end; implementation { TTreeItem } constructor TTreeItem.Create(AParent: TTreeFolder); begin inherited Create; FParent := AParent; end; procedure TTreeItem.Delete; begin if parent<>nil then parent.deleteItem(self); end; function TTreeItem.IsFolder: boolean; begin result := false; end; procedure TTreeItem.SetCaption(const Value: string); begin if FCaption <> Value then begin FCaption := Value; Modified := true; end; end; procedure TTreeItem.SetModified(const Value: boolean); begin FModified := Value; if FModified and (Parent<>nil) then Parent.ItemChanged(self); end; { TTreeFolder } constructor TTreeFolder.Create(AFolder: TTreeFolder); begin inherited Create(AFolder); FItems := TObjectList.Create(true); FOpened := false; FModified := false; FChilrenModified := false; end; destructor TTreeFolder.destroy; begin Close; FItems.free; inherited destroy; end; function TTreeFolder.GetCount: integer; begin result := FItems.count; end; procedure TTreeFolder.Close; begin //if opened and modified then Save; FItems.clear; FOpened := false; FModified := false; FChilrenModified := false; end; function TTreeFolder.NewItem(AItemType : TTreeItemType): TTreeItem; var AClass : TTreeItemClass; begin AClass := ItemClass(AItemType); if AClass<>nil then begin result := AClass.Create(self); FItems.Add(result); FChilrenModified := true; end else result:=nil; end; procedure TTreeFolder.SetOpened(const Value: boolean); begin if FOpened <> Value then begin if value then open else close; end; end; function TTreeFolder.GetItems(index: integer): TTreeItem; begin result := TTreeItem(FItems[index]); end; function TTreeFolder.DeleteItem(Item: TTreeItem): boolean; begin result := FItems.Remove(Item)>=0; FChilrenModified := true; end; function TTreeFolder.IsFolder: boolean; begin result := true; end; procedure TTreeFolder.ItemChanged(Item: TTreeItem); begin FChilrenModified := true; end; { TFolderMan } function TFolderMan.CanEdit(Item: TTreeItem): Boolean; begin result := true; end; constructor TFolderMan.Create(ARoot: TTreeFolder; AFolderView: TFolderView); begin inherited Create; FRoot :=ARoot; FFolderView:=AFolderView; AFolderView.FFolderMan := self; end; destructor TFolderMan.Destroy; begin FFolderView.FolderMan := nil; FRoot.free; inherited Destroy; end; procedure TFolderMan.SetFolderView(const Value: TFolderView); begin if FFolderView <> Value then begin if FFolderView<>nil then FFolderView.FFolderMan := nil; FFolderView := Value; if FFolderView<>nil then FFolderView.FolderMan := self; end; end; { TFolderView } function TFolderView.CanEdit(Node: TTreeNode): Boolean; begin result := inherited CanEdit(Node); if result and (FolderMan<>nil) then result := FolderMan.CanEdit(TTreeItem(Node.data)); end; function TFolderView.CanExpand(Node: TTreeNode): Boolean; begin result := inherited CanExpand(Node) and TTreeItem(Node.data).IsFolder; if result then result := OpenNode(Node); end; procedure TFolderView.Edit(const Item: TTVItem); var Node: TTreeNode; begin inherited Edit(Item); Node := GetNodeFromItem(Item); if Node<>nil then TTreeItem(Node.data).caption := Node.text; end; function TFolderView.GetSelectedTreeItem: TTreeItem; begin if selected=nil then result := nil else result := TTreeItem(selected.data); end; function TFolderView.AddTreeItem(ParentNode: TTreeNode; TreeItem: TTreeItem): TTreeNode; begin result := Items.AddChildObject(ParentNode, TreeItem.caption, TreeItem); result.HasChildren := TreeItem.IsFolder; if Assigned(FOnInitItemImage) then FOnInitItemImage(self,result,TreeItem); end; function TFolderView.OpenNode(Node: TTreeNode): boolean; var i : integer; begin assert(Node<>nil); with TTreeFolder(Node.data) do begin if not opened then begin Node.DeleteChildren; Opened := true; end; if opened and (Node.Count=0) then for i:=0 to count-1 do begin AddTreeItem(node,items[i]); end; result := opened; end; end; procedure TFolderView.SetFolderMan(const Value: TFolderMan); begin if FFolderMan <> Value then begin if FFolderMan<>nil then FFolderMan.FFolderView := nil; FFolderMan := Value; if FFolderMan<>nil then FFolderMan.FFolderView := self; items.Clear; if (FFolderMan<>nil) and (FFolderMan.root<>nil) then AddTreeItem(nil,FFolderMan.root); end; end; function TFolderView.GetNodeFromItem(const Item: TTVItem): TTreeNode; begin with Item do if (state and TVIF_PARAM) <> 0 then Result := Pointer(lParam) else Result := Items.GetNode(hItem); end; end.
{ Mystix Copyright (C) 2005 Piotr Jura This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You can contact with me by e-mail: pjura@o2.pl } unit uReplace; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFind, StdCtrls, ExtCtrls; type TReplaceDialog = class(TFindDialog) btnReplaceAll: TButton; lblReplace: TLabel; chkPrompt: TCheckBox; cmbReplace: TMemo; procedure btnFindNextClick(Sender: TObject); procedure btnReplaceAllClick(Sender: TObject); procedure cmbFindChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure chkInAllClick(Sender: TObject); private { Private declarations } procedure Replace(ReplaceAll: Boolean); protected procedure SetOptions; override; public Find,ReplaceWith:String; end; var ReplaceDialog: TReplaceDialog; implementation uses uDocuments, uMain, uUtils, uMyIniFiles; {$R *.dfm} procedure TReplaceDialog.btnFindNextClick(Sender: TObject); begin Replace(False); end; procedure TReplaceDialog.Replace(ReplaceAll: Boolean); var i: Integer; procedure NotFound; begin MainForm.StatusMsg( PChar( Format(msgNotFound, [cmbFind.Text]) ), ErrorMsgColor, clWhite, 4000, False ); end; begin SetOptions; if chkPrompt.Checked then Hide; if chkInAll.Checked then for i := 0 to DocumentFactory.Count - 1 do begin if DocumentFactory.IsSearchedForTheFirstTime(frFindText) then DocumentFactory.Documents[i].ReplaceText(frFindText, frReplaceText, frWholeWords, frMatchCase, frRegExp, frSelOnly, frFromCursor, frPrompt, frDirUp, ReplaceAll) else DocumentFactory.Documents[i].ReplaceNext; end else begin if DocumentFactory.IsSearchedForTheFirstTime(cmbFind.Text) then begin if not Document.ReplaceText(frFindText, frReplaceText, frWholeWords, frMatchCase, frRegExp, frSelOnly, frFromCursor, frPrompt, frDirUp, ReplaceAll) then NotFound; end else begin if not Document.ReplaceNext then NotFound; end; end; if chkPrompt.Checked then Show; end; procedure TReplaceDialog.btnReplaceAllClick(Sender: TObject); begin Replace(True); end; procedure TReplaceDialog.cmbFindChange(Sender: TObject); begin inherited; btnReplaceAll.Enabled := cmbFind.Text <> ''; end; procedure TReplaceDialog.FormCreate(Sender: TObject); begin inherited; cmbFindChange(nil); if Document.Editor.SelText <> '' then cmbFind.Text := Document.Editor.SelText; end; procedure TReplaceDialog.SetOptions; begin inherited; frReplaceText := cmbReplace.Text; frPrompt := chkPrompt.Checked; end; procedure TReplaceDialog.chkInAllClick(Sender: TObject); begin chkPrompt.Enabled := not chkInAll.Checked; if chkInAll.Checked then chkPrompt.Checked := False; end; end.
unit UTransparentListBox; {composant écrit par Walter Irion et publié sur : http://www.swissdelphicenter.ch/torry/showcode.php?id=1982 Utilisation par jean_jean pour delphifr * TTransparentListBox is far from being a universal solution: * it does not prevent Windows' scrolling mechanism from * shifting the background along with scrolled listbox lines. * Moreover, the scroll bar remains hidden until the keyboard * is used to change the selection, and the scroll buttons * become visible only when clicked. * * To break it short: TTransparentListBox is only suitable * for non-scrolling lists. * * In fact it must be possible to write a listbox component * that handles scrolling correctly. But my essays to intercept * EM_LINESCROLL messages were fruitles, even though I tried * subclassing via WndProc. * * A solution for transparent TEdit and TMemo controls is * introduced in issue 9/1996 of the c't magazine, again * by Arne Sch?pers. But these are outright monsters with * wrapper windows to receive notification messages as well * as so-called pane windows that cover the actual control's * client area and display its content. * * They expect a crossed cheque amounting to DM 14,00 * to be included with your order, but I don't know about * international orders. -------------------------------------------------------------------------------} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TTransparentListBox = class(TListBox) private { Private declarations } protected { Protected declarations } procedure CreateParams(var Params: TCreateParams); override; procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND; procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published { Published declarations } property Style default lbOwnerDrawFixed; property Ctl3D default False; property BorderStyle default bsNone; end; //procedure Register; implementation //procedure Register; //begin // RegisterComponents('Samples', [TTransparentListBox]); //end; constructor TTransparentListBox.Create(AOwner: TComponent); begin inherited Create(AOwner); Ctl3D := False; BorderStyle := bsNone; Style := lbOwnerDrawFixed; // changing it to lbStandard results // in loss of transparency end; procedure TTransparentListBox.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT; end; procedure TTransparentListBox.WMEraseBkgnd(var Msg: TWMEraseBkgnd); begin Msg.Result := 1; // Prevent background from getting erased end; procedure TTransparentListBox.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var tlbVisible: Boolean; begin tlbVisible := (Parent <> nil) and IsWindowVisible(Handle); // Check for visibility if tlbVisible then ShowWindow(Handle, SW_HIDE); // Hide-Move-Show strategy... inherited SetBounds(ALeft, ATop, AWidth, AHeight); // ... to prevent background... if tlbVisible then ShowWindow(Handle, SW_SHOW); // ... from getting copied end; procedure TTransparentListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); var FoundStyle: TBrushStyle; R: TRect; begin FoundStyle := Canvas.Brush.Style; // Remember the brush style R := Rect; // Adapt coordinates of drawing rect... MapWindowPoints(Handle, Parent.Handle, R, 2); // ... to parent's coordinate system InvalidateRect(Parent.Handle, @R, True); // Tell parent to redraw the item Position Parent.Update; // Trigger instant redraw (required) if not (odSelected in State) then begin // If an unselected line is being handled Canvas.Brush.Style := bsClear; // use a transparent background end else begin // otherwise, if the line needs to be highlighted, Canvas.Brush.Style := bsSolid; // some colour to the brush is essential end; inherited DrawItem(Index, Rect, State); // Do the regular drawing and give component users... // ... a chance to provide an OnDrawItem handler Canvas.Brush.Style := FoundStyle; // Boy-scout rule No. 1: leave site as you found it end; end.
(*--------------------------------------------------------*) (* Exercise 7 (Stringmanipulationen) *) (* Developer: Neuhold Michael *) (* Date: 23.11.2018 *) (* Verson: 1.0 *) (*--------------------------------------------------------*) PROGRAM Zeiochenkettenverarbeitung; (* multiple usage *) PROCEDURE Seperator; BEGIN WriteLn('-------------------------------------------------'); END; (* returns reversed version from input string *) FUNCTION Reversed(str: STRING): STRING; VAR len: INTEGER; strNew: STRING; BEGIN len := length(str); REPEAT strNew := strNew + str[len]; len := len - 1; UNTIL len <= 0; Reversed := strNew; END; (* remove blanks from string *) PROCEDURE StripBlanks(VAR str: STRING); VAR len,i: INTEGER; BEGIN len := length(str); REPEAT IF str[len] = ' ' THEN BEGIN FOR i := len TO length(str) DO BEGIN str[i] := str[i+1]; END; END; len := len - 1; UNTIL len <= 0; END; (* replaces one word in a string with another *) PROCEDURE ReplaceAll(old: STRING; new: STRING; VAR s: STRING); VAR p : INTEGER; (* position *) n : STRING; (* new string *) BEGIN WHILE Pos(old,s) > 0 DO BEGIN p := Pos(old,s); n := Copy(s,1,p-1); n := n + new; n := n + Copy(s,p+Length(old),(Length(s) + 1 - Length(old) - p)); s := n; END; END; VAR str1, str2: STRING; BEGIN (* test strings *) str1 := 'DieserTextbesitztkeineBlanks!!!!'; str2 := 'Hier soll ein Wort getauscht werden!'; Seperator; WriteLn('Rückwerts ausgeben:'); WriteLn(Reversed(str1)); Seperator; WriteLn('OhneBlanks ausgeben:'); StripBlanks(str1); WriteLn(str1); Seperator; WriteLn('Bestimmtes Wort durch anders ersetzen:'); ReplaceAll('ein Wort','ein Teilstring',str2); WriteLn(str2); Seperator; END.
(*============================================================================ -----BEGIN PGP SIGNED MESSAGE----- This code (c) 1994, 1997 Graham THE Ollis GENERAL NOTES ============= This is 16bit DOS TURBO PASCAL source code. It has been tested using TURBO PASCAL 7.0. You will need AT LEAST version 5.0 to compile this source code. You may need 7.0. This is a generic pascal header for all my old pascal programs. Most of these programs were written before I really got excited enough about 32bit operating systems. In general this code dates back to 1994. Some of it is important enough that I still work on it. For the most part though, it's not the best code and it's probably the worst example of documentation in all of computer science. oh well, you've been warned. PGP NOTES ========= This PGP signed message is provided in the hopes that it will prove useful and informative. My name is Graham THE Ollis <ollisg@ns.arizona.edu> and my public PGP key can be found by fingering my university account: finger ollisg@u.arizona.edu LEGAL NOTES =========== You are free to use, modify and distribute this source code provided these headers remain in tact. If you do make modifications to these programs, i'd appreciate it if you documented your changes and leave some contact information so that others can blame you and me, rather than just me. If you maintain a anonymous ftp site or bbs feel free to archive this stuff away. If your pressing CDs for commercial purposes again have fun. It would be nice if you let me know about it though. HOWEVER- there is no written or implied warranty. If you don't trust this code then delete it NOW. I will in no way be held responsible for any losses incurred by your using this software. CONTACT INFORMATION =================== You may contact me for just about anything relating to this code through e-mail. Please put something in the subject line about the program you are working with. The source file would be best in this case (e.g. frag.pas, hexed.pas ... etc) ollisg@ns.arizona.edu ollisg@idea-bank.com ollisg@lanl.gov The first address is the most likely to work. all right. that all said... HAVE FUN! -----BEGIN PGP SIGNATURE----- Version: 2.6.2 iQCVAwUBMv1UFoazF2irQff1AQFYNgQAhjiY/Dh3gSpk921FQznz4FOwqJtAIG6N QTBdR/yQWrkwHGfPTw9v8LQHbjzl0jjYUDKR9t5KB7vzFjy9q3Y5lVHJaaUAU4Jh e1abPhL70D/vfQU3Z0R+02zqhjfsfKkeowJvKNdlqEe1/kSCxme9mhJyaJ0CDdIA 40nefR18NrA= =IQEZ -----END PGP SIGNATURE----- ============================================================================== | bined.pas | * allow the user to modify the current byte of the bit level | | History: | Date Author Comment | ---- ------ ------- | -- --- 94 G. Ollis created and developed program ============================================================================*) {$I-} Unit BinEd; INTERFACE Uses Header; {++PROCEDURES++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure BinaryEditor(Var B:Byte; Var D:DataType); {++FUNCTIONS+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} IMPLEMENTATION Uses CRT,VConvert,FUTIL,Cursor; Var LastB:Byte; {------------------------------------------------------------------------} Procedure Display(B:Byte; CE:Integer; Y:Integer); Var I,X:Integer; Begin GotoXY(1,Y); For I:=8 DownTo 1 Do Begin If (I=CE) Then TextAttr:=ICFG.Highlight; If Boolean(B And Bit[I]) Then Write('1') Else Write('0'); If (I=CE) Then TextAttr:=ICFG.Numbers; End; Write(' '); ClrEol; Write(Byte2Str(B),B:4,' '); If B<>Byte(^G) Then Write(Chr(B)) Else Write(' '); End; {------------------------------------------------------------------------} Procedure WriteCmdline(S:String; X,Y:Byte); Var Index:Integer; Begin GotoXY(X,Y); TextAttr:=ICFG.Lolight; For Index:=1 To Length(S) Do Begin If ((S[Index]>='A') And (S[Index]<='Z')) Or (S[Index]='<') Or (S[Index]='>') Then TextAttr:=ICFG.Highlight; Write(S[Index]); If ((S[Index]>='A') And (S[Index]<='Z')) Or (S[Index]='<') Or (S[Index]='>') Then TextAttr:=ICFG.LoLight; End; End; {------------------------------------------------------------------------} Procedure BinaryEditor(Var B:Byte; Var D:DataType); Var CE:Integer; Temp:Byte; C:Char; Begin HideCursor; Temp:=B; CE:=8; GotoXY(1,8); TextAttr:=ICFG.Lolight; ClrEOL; Window(1,6,80,7); ClrScr; WriteCMDLine(' <ENTER> save byte <ESC> exit ''<'' shift left ''>'' shift right',19,1); WriteCMDLine(' <SPACE> toggle Not And Or Xor Increment Decrement Swap',19,2); Window(1,6,19,7); Repeat Display(B,CE,1); Display(LastB,CE,2); C:=UpCase(Readkey); If (C='S') Then Begin B:=B XOr LastB; LastB:=B XOr LastB; B:=B XOr LastB; End; If (C='I') Then Inc(B); If (C='D') Then Dec(B); If (C='N') Then B:=NOT B; If (C='A') Then B:=B And LastB; If (C='O') Then B:=B Or LastB; If (C='X') Then B:=B XOr LastB; If (C=' ') Then If Boolean(B And Bit[CE]) Then B:=B And Not Bit[CE] Else B:=B XOR Bit[CE]; If (C='<') Or (C=',') Then B:=B Shl 1; If (C='>') Or (C='.') Then B:=B Shr 1; If C=#0 Then Begin C:=Readkey; If (C=#75) Then CE:=CE+1; If (C=#77) Then CE:=CE-1; IF CE>8 Then CE:=8; If CE<1 Then CE:=1; End; Until (C=#13) Or (C=#27); If (C=#13) Then Begin LastB:=B; ToggleChanges(D); End Else B:=Temp; Window(1,6,80,7); ClrScr; TextAttr:=ICFG.LoLight; ClrScr; Window(1,1,80,25); ShowCursor; End; {======================================================================} Begin LastB:=0; End.
unit PertoCheque; interface uses SysUtils, Dialogs, Forms, Windows; type TInfoCheque = record Data : string; Favorecido : string; Cidade : string; Valor : string; Verso : string; BomPara : string; Chancelado : boolean; Cruzado : boolean; end; //****************************************************************************// // MÉTODOS DE COMUNICAÇÃO PELA PORTA PARALELA // //****************************************************************************// function habilita_paralela(si : PChar) : boolean; far; stdcall external 'PertoChekPar.dll'; function desabilita_paralela : boolean; far; stdcall external 'PertoChekPar.dll'; function transmite(si : PChar) : integer; far; stdcall external 'PertoChekPar.dll'; function recebe(t : integer; bufrx : PChar) : integer; far; stdcall external 'PertoChekPar.dll'; //****************************************************************************// // MÉTODOS DE COMUNICAÇÃO PELA PORTA SERIAL // //****************************************************************************// function IniComm(si : PChar) : boolean; far; stdcall external 'pertochekser.dll'; function EndComm : boolean; far; stdcall external 'pertochekser.dll'; function EnvComm(si : PChar) : integer; far; stdcall external 'pertochekser.dll'; function RecComm(t : integer; bufrx : PChar) : integer; far; stdcall external 'pertochekser.dll'; //****************************************************************************// // MÉTODOS GERADOS COM INTUITO DE NÃO HAVER RESTRIÇÕES QUANTO AO TIPO DE // // COMUNICAÇÃO // //****************************************************************************// function HabilitaPorta(Porta : string) : boolean; function DesabilitaPorta(Porta : string) : boolean; function EnviaDados(Porta,Texto : string) : integer; function RecebeDados(Porta : string; TimeOut : integer; var Resposta : array of char) : integer; function EnviaComando(Porta, Texto : string; TimeOut : integer; var Resposta : array of char) : boolean; //****************************************************************************// // MÉTODOS PARA ENVIO DE DADOS PARA IMPRESSORA PERTO CHECK // //****************************************************************************// function LeituraCMC7(Porta : string; TimeOut : integer; var Resposta : array of char) : boolean; function PreencheCheque(Porta : string; TimeOut : integer; var Resposta : array of char; Cheque : TInfoCheque) : boolean; function RetornaErro : string; var LastError : integer; implementation function HabilitaPorta(Porta : string) : boolean; var Envio : array [0..255] of char; begin Result := True; if Pos('LPT',UpperCase(Porta)) > 0 then begin StrPCopy(Envio,Porta); if not habilita_paralela(Envio) then Result := False; end else if Pos('COM',UpperCase(Porta)) > 0 then begin StrPCopy(Envio,UpperCase(Porta) + ':4800,N,8,1'); if not IniComm(Envio) then Result := False; end; end; function DesabilitaPorta(Porta : string) : boolean; begin if Pos('LPT',UpperCase(Porta)) > 0 then Result := desabilita_paralela() else if Pos('COM',UpperCase(Porta)) > 0 then Result := EndComm(); end; function EnviaDados(Porta,Texto : string) : integer; begin Result := 0; if Pos('LPT',UpperCase(Porta)) > 0 then Result := transmite(PChar(Texto)) else if Pos('COM',UpperCase(Porta)) > 0 then Result := EnvComm(PChar(Texto)); LastError := Result; end; function RecebeDados(Porta : string; TimeOut : integer; var Resposta : array of char) : integer; begin Result := 0; if Pos('LPT',UpperCase(Porta)) > 0 then Result := recebe(TimeOut,Resposta) else if Pos('COM',UpperCase(Porta)) > 0 then Result := RecComm(TimeOut,Resposta); LastError := Result; if LastError in [20..27] then begin Application.MessageBox('Detectamos que o cheque está trancado na impressora, o sistema tentará destrancá-lo automaticamente! #13 Caso o cheque não seja ejetado você terá que removê-lo manualmente.','Informa', MB_OK + MB_SYSTEMMODAL + MB_SETFOREGROUND + MB_ICONINFORMATION); EnviaComando(Porta,'>',TimeOut,Resposta); end; end; function EnviaComando(Porta,Texto : string; TimeOut : integer; var Resposta : array of char) : boolean; begin Result := True; if HabilitaPorta(Porta) then begin if (EnviaDados(Porta,Texto) > 0) then begin if RecebeDados(Porta,TimeOut,Resposta) = 0 then Result := False; end else Result := False; end else Result := False; if not DesabilitaPorta(Porta) then Result := False; end; function LeituraCMC7(Porta : string; TimeOut : integer; var Resposta : array of char) : boolean; begin Result := EnviaComando(Porta,'P',TimeOut,Resposta); Result := EnviaComando(Porta,'>',TimeOut,Resposta); end; function PreencheCheque(Porta : string; TimeOut : integer; var Resposta : array of char; Cheque : TInfoCheque) : boolean; function Remove(Valor : string) : string; begin Result := Valor; while Pos('.',Result) > 0 do Delete(Result,Pos('.',Result),1); while Pos(',',Result) > 0 do Delete(Result,Pos(',',Result),1); while Length(Result) < 12 do Result := '0' + Result; Result := Result + '000'; end; begin Result := True; if Cheque.Data <> '' then Result := EnviaComando(Porta,'!' + Cheque.Data,TimeOut,Resposta); if Cheque.Favorecido <> '' then Result := EnviaComando(Porta,'%' + Cheque.Favorecido,TimeOut,Resposta); if Cheque.Cidade <> '' then Result := EnviaComando(Porta,'#' + Cheque.Cidade,TimeOut,Resposta); if Cheque.Verso <> '' then Result := EnviaComando(Porta,'"' + Cheque.Verso + 'ÿ',TimeOut,Resposta); if Cheque.BomPara <> '' then Result := EnviaComando(Porta,'+BOM PARA: ' + Cheque.BomPara,TimeOut,Resposta); if ((not Cheque.Chancelado) and (not Cheque.Cruzado)) then Result := EnviaComando(Porta,'$4' + Remove(Cheque.Valor),TimeOut,Resposta) else if ((not Cheque.Chancelado) and (Cheque.Cruzado)) then Result := EnviaComando(Porta,'$8' + Remove(Cheque.Valor),TimeOut,Resposta) else Result := EnviaComando(Porta,'$1' + Remove(Cheque.Valor),TimeOut,Resposta); end; function RetornaErro : string; begin case LastError of 0 : Result := 'Sucesso na execução do comando.'; 1 : Result := 'Mensagem com dados inválidos.'; 2 : Result := 'Tamanho de mensagem inválido.'; 5 : Result := 'Leitura dos caracteres magnéticos inválida.'; 6 : Result := 'Problemas no acionamento do motor 1.'; 8 : Result := 'Problemas no acionamento do motor 2.'; 9 : Result := 'Banco diferente do solicitado.'; 11 : Result := 'Sensor 1 obstruído.'; 12 : Result := 'Sensor 2 obstruído.'; 13 : Result := 'Sensor 4 obstruído.'; 14 : Result := 'Erro o posicionamento da cabeça de impressão (relativo a S4).'; 15 : Result := 'Erro o posicionamento na pós-marcação.'; 16 : Result := 'Dígito verificador do cheque não confere.'; 17 : Result := 'Ausência de caracteres magnéticos ou cheque na posição errada.'; 18 : Result := 'Tempo esgotado.'; 19 : Result := 'Documento mal inserido.'; 20 : Result := 'Cheque preso durante o alinhamento (S1 e S2 desobstruídos).'; 21 : Result := 'Cheque preso durante o alinhamento (S1 obstruído e S2 desobstruído).'; 22 : Result := 'Cheque preso durante o alinhamento (S1 desobstruído e S2 obstruído).'; 23 : Result := 'Cheque preso durante o alinhamento (S1 e S2 obstruídos).'; 24 : Result := 'Cheque preso durante o preenchimento (S1 e S2 desobstruídos).'; 25 : Result := 'Cheque preso durante o preenchimento (S1 obstruído e S2 desobstruído).'; 26 : Result := 'Cheque preso durante o preenchimento (S1 desobstruído e S2 obstruído).'; 27 : Result := 'Cheque preso durante o preenchimento (S1 e S2 obstruídos).'; 28 : Result := 'Caracter inexistente.'; 30 : Result := 'Não há cheques na memória.'; 31 : Result := 'Lista negra interna cheia.'; 42 : Result := 'Cheque ausente.'; 43 : Result := 'Pin pad ou teclado ausente.'; 50 : Result := 'Erro de transmissão.'; 51 : Result := 'Erro de transmissão: Impressora off line, desconectada ou ocupada.'; 52 : Result := 'Erro no pin pad.'; 60 : Result := 'Cheque na lista negra.'; 73 : Result := 'Cheque não encontrado na lista negra.'; 74 : Result := 'Comando cancelado.'; 84 : Result := 'Arquivo de lay out´s cheio.'; 85 : Result := 'Lay out inexistente na memória.'; 91 : Result := 'Leitura de cartão inválida.'; 97 : Result := 'Cheque na posição errada.'; 111 : Result := 'Pin pad não retornou EOT.'; 150 : Result := 'Pin pad não retornou NAK.'; 155 : Result := 'Pin pad não responde.'; 171 : Result := 'Tempo esgotado na resposta do pin pad.'; 255 : Result := 'Comando inexistente.'; end; end; end.
unit TOblRizeni; { Tato unita se stara o rizeni Oblasti rizeni (OR, tedy stanic). OR slouzi jako prostrednik mezi technologickymi bloky (technologii) a panely (zobrazenim). Blok vola metodu primo do prislusne oblasti rizeni, kde jsou data v pripade, ze patri konkretni OR, rovnou odeslane do soketu neni tedy vyuzivano ORTCPServer } interface uses Types, IniFiles, SysUtils, Classes, Graphics, Menus, stanicniHlaseni, IdContext, TechnologieRCS, StrUtils, ComCtrls, Forms, Generics.Collections, Zasobnik, Messages, Windows; const _MAX_CON_PNL = 16; // maximalni poce tpripojenych panelu k jedne oblasti rizeni _MAX_ORREF = 16; // zvuky - musi korespondovat se zvuky klienta _SND_TRAT_ZADOST = 4; _SND_PRIVOLAVACKA = 5; _SND_TIMEOUT = 6; _SND_PRETIZENI = 7; _SND_POTVR_SEKV = 8; _SND_ZPRAVA = 9; _SND_CHYBA = 10; _SND_STAVENI_VYZVA = 11; _SND_NENI_JC = 12; type TORControlRights = (null = 0, read = 1, write = 2, superuser = 3); TPanelButton = (F1, F2, ENTER, ESCAPE); // podminky potvrzovaci sekvence TPSPodminka = record blok:TObject; podminka:string; end; TPSPodminky = TList<TPSPodminka>; //1 osvetleni TOsv = record board:Byte; // MTB deska osvetleni port:Byte; // MTB port osvetleni name:string; // popis osvetleni, max 5 znaku default_state:boolean; // vychozi stav osvetleni - toto je ukladano do souboru a nacitano ze souboru end; //primarni vlastnosti kazde OR TORProp = record Name:string; // plne jemno oblati rizeni (napr. "Klobouky u Brna") ShortName:string; // zkratka oblasti rizeni (napr. "Klb"), nemusi byt unikatni id:string; // unikatni ID oblasti rizeni (napr. "Klb") Osvetleni:TList<TOsv>; // seznam osvetleni OR end; TPSCallback = procedure (Relief:TObject; Panel:TObject; // callback potvrzovaci sekvence success:boolean) of object; TBlkCallback = procedure (SenderPnl:TIDContext; SenderOR:TObject; // callback kliku na dopravni kacelar Button:TPanelButton) of object; // jedno mereni casu TMereniCasu = record Start:TDateTime; // cas startu mereni Length:TDateTime; // delka mereni callback:TNotifyEvent; // callback pri uplynuti mereni casu id:Integer; // id mereni casu (vyuzivano pro komunikaci s pamely) end; //databaze pripojenych panelu //kazda OR si pamatuje, jake panely jsou k ni pripojeny a s temito panely komunikuje // toto je 1 prvek databaze pripojenych panelu TORPanel = record Panel:TIdContext; // spojeni na klienta Rights:TORControlRights; // pristupova prava k OR user:string; // id uzivatele, ktery se k OR logoval end; // stav OR TORStav = record NUZtimer:boolean; // probiha ruseni useku NUZ? NUZblkCnt:Integer; // kolik bloku ma zaplych NUZ (ruseni jeste neprobiha) NUZmerCasuID:Integer; // ID mereni casu NUZ ZkratBlkCnt:Integer; // kolik bloku je ve zkratu (vyuzivano pro prehravani zvuku) ZadostBlkCnt:Integer; // pocet uvazek, na ktere je zadost o tratovy souhlas (kvuli prehravani zvuku) PrivolavackaBlkCnt:Integer; // pocet aktivnich privolavacich navesti timerCnt:Integer; // pocet bezicich timeru dk_click_callback:TBlkCallback; // callback kliku na dopravni kancelar reg_please:TIdCOntext; // zde je ulozen regulator, ktery danou oblast rizeni zada o prideleni lokomotivy end; // jedno MTB oblasti rizeni TORMTB = record present:boolean; // jestli je MTB v OR pritomno failed:boolean; // jestli MTB v OR selhalo (nekomunikuje) end; // seznam MTB v OR TORMTBs = record MTBs: array [0..TRCS._MAX_RCS] of TORMTB; // seznam MTB v OR, staticky mapovano kde index je adresa MTB failture:boolean; // jestli doslo k selhani jakohokoliv MTB v OR last_failture_time:TDateTime; // cas posledniho selhani (pouziva se pro vytvareni souhrnnych zprav o selhani MTB pro dispecera) end; ///////////////////////////////////////////////////////////////////////////// TOR = class private const //chybove hlasky komunikace _COM_ACCESS_DENIED = 'Přístup odepřen'; //levely opravneni _R_no = 0; // zadne opravneni _R_read = 1; // opravneni ke cteni stavu bloku _R_write = 2; // opravneni k nastavovani bloku _R_superuser = 3; // opravneni superuser, neboli "root" private findex:Integer; // index OR v tabulce oblasti rizeni ORProp:TORProp; // vlastnosti OR ORStav:TORStav; // stav OR MereniCasu:TList<TMereniCasu>; // seznam mereni casu bezicich v OR OR_MTB:TORMTBs; // seznam MTB pritomnych v OR, seznam vsech MTB asociovanych s bloky pritomnych v teto OR // prace s databazi pripojenych panelu: function PnlDAdd(Panel:TIdContext; rights:TORControlRights; user:string):Byte; function PnlDRemove(Panel:TIdContext):Byte; function PnlDGetRights(Panel:TIdContext):TORControlRights; function PnlDGetIndex(Panel:TIdContext):Integer; procedure NUZTimeOut(Sender:TObject); // callback ubehnuti mereni casu pro ruseni nouzovych zaveru bloku procedure NUZ_PS(Sender:TIdContext; success:boolean); // callback potvrzovaci sekvence NUZ procedure ORAuthoriseResponse(Panel:TIdContext; Rights:TORControlRights; msg:string; username:string); procedure SetNUZBlkCnt(new:Integer); procedure SetZkratBlkCnt(new:Integer); procedure SetZadostBlkCnt(new:Integer); procedure SetPrivolavackaBlkCnt(new:Integer); procedure SetTimerCnt(new:Integer); procedure MTBClear(); // nastavi vsem MTB, ze nejsou v OR procedure MTBUpdate(); // posila souhrnne zpravy panelu o vypadku MTB modulu (moduly, ktere vypadly hned za sebou - do 500 ms, jsou nahlaseny v jedne chybe) procedure SendStatus(panel:TIdContext); // odeslani stavu IR do daneho panelu, napr. kam se ma posilat klik na DK, jaky je stav zasobniku atp.; je ovlano pri pripojeni panelu, aby se nastavila OR do spravneho stavu function PanelGetOsv(index:Integer):boolean; // vrati stav osvetleni // tyto funkce jsou volany pri zmene opravenni mezi cteni a zapisem // primarni cil = v techto funkcich resit zapinani a vypinani zvuku v panelu procedure AuthReadToWrite(panel:TIdContext); procedure AuthWriteToRead(panel:TIdContext); procedure OnHlaseniAvailable(Sender:TObject; available:boolean); public stack:TORStack; // zasobnik povelu changed:boolean; // jestli doslo ke zmene OR - true znamena aktualizaci tabulky vb:TList<TObject>; // seznam variantnich bodu, ktere jsou aktualne "naklikle"; zde je ulozen seznam bloku Connected:TList<TORPanel>; // seznam pripojenych panelu hlaseni:TStanicniHlaseni; // technologie stanicnich hlaseni constructor Create(index:Integer); destructor Destroy(); override; procedure LoadData(str:string); procedure LoadStat(ini:TMemIniFile; section:string); procedure SaveStat(ini:TMemIniFile; section:string); procedure RemoveClient(Panel:TIdContext); // smaze klienta \Panel z databze pripojenych panelu, typicky volano pri odpojeni klienta procedure Update(); // pravidelna aktualizace stavu OR - napr. mereni casu procedure DisconnectPanels(); // vyhodi vsechny autorizovane panely z teto OR function AddMereniCasu(callback:TNotifyEvent; len:TDateTime):Byte; // prida mereni casu; vrati ID mereni procedure StopMereniCasu(id:Integer); // zastavi mereni casu s danym ID procedure MTBAdd(addr:integer); // prida MTB do OR procedure MTBFail(addr:integer); // informuje OR o vypadku MTB procedure UpdateLine(LI:TListItem); // aktualizuje zaznam v tabulce oblasti rizeni ve F_Main procedure BroadcastData(data:string; min_rights:TORControlRights = read); // posle zpravu \data vsem pripojenym panelum s minimalnim opravnenim \min_rights s prefixem oblaati rizeni procedure BroadcastGlobalData(data:string; min_rights:TORControlRights = read); // posle zpravu \data vsem pripojenym panelum s minimalnim opravnenim \min_rights s prefixem "-" procedure ClearVb(); // smaze aktualni varientni body //--- komunikace s technologickymi bloky --- procedure BlkChange(Sender:TObject; specificClient:TIDContext = nil); // doslo ke zmene bloku v OR, je potreba propagovat zmenu do panelu procedure BlkPlaySound(Sender:TObject; min_rights:TORCOntrolRights; // prehraje zvuk sound:Integer; loop:boolean = false); procedure BlkRemoveSound(Sender:TObject; sound:Integer); // zrusi prehravani zvuku procedure BlkWriteError(Sender:TObject; error:string; system:string); // posle chybovou hlasku do vsech stanic, ktere maji autorizovany zapis procedure BlkNewSpr(Sender:TObject; Panel:TIdContext; sprUsekIndex:Integer); // posle do panelu pozadavek na otevreni dialogu pro novou soupravu procedure BlkEditSpr(Sender:TObject; Panel:TIdContext; Souprava:TObject);// posle do panelu pozadavek na otevreni dialogu editace soupravy function ORSendMsg(Sender:TOR; msg:string):Byte; // odesle zpravu OR (od jine OR) procedure ORDKClickServer(callback:TBlkCallback); // klik na DK probehne na server procedure ORDKClickClient(); // klik na DK probehne na klieta // volany pri zadosti o poskytnuti loko pro regulator: function LokoPlease(Sender:TIDContext; user:TObject; comment:string):Integer; procedure LokoCancel(Sender:TIdContext); procedure InitOsv(); //--- komunikace s panely zacatek: --- procedure PanelAuthorise(Sender:TIdContext; rights:TORControlRights; username:string; password:string); procedure PanelFirstGet(Sender:TIdContext); procedure PanelClick(Sender:TIdContext; blokid:Integer; Button:TPanelButton; params:string = ''); procedure PanelEscape(Sender:TIdContext); procedure PanelNUZ(Sender:TIdContext); procedure PanelNUZCancel(Sender:TIdContext); procedure PanelMessage(Sender:TIdContext; recepient:string; msg:string); procedure PanelHVList(Sender:TIdContext); procedure PanelSprChange(Sender:TIdContext; spr:TStrings); procedure PanelMoveLok(Sender:TIdContext; lok_addr:word; new_or:string); procedure PanelZAS(Sender:TIdContext; str:TStrings); procedure PanelDKClick(SenderPnl:TIdContext; Button:TPanelButton); procedure PanelLokoReq(Sender:TIdContext; str:TStrings); procedure PanelHlaseni(Sender:TIDContext; str:TStrings); procedure PanelHVAdd(Sender:TIDContext; str:string); procedure PanelHVRemove(Sender:TIDContext; addr:Integer); procedure PanelHVEdit(Sender:TIDContext; str:string); procedure PanelSendOsv(Sender:TIdContext); procedure PanelSetOsv(Sender:TIdCOntext; id:string; state:boolean); function PanelGetSprs(Sender:TIdCOntext):string; procedure PanelRemoveSpr(Sender:TIDContext; spr_index:Integer); function GetORPanel(conn:TIdContext; var ORPanel:TORPanel):Integer; class function GetRightsString(rights:TORControlRights):string; procedure UserUpdateRights(user:TObject); procedure UserDelete(userid:string); class function ORRightsToString(rights:TORControlRights):string; class function GetPSPodminka(blok:TObject; podminka:string):TPSPodminka; class function GetPSPodminky(podm:TPSPodminka):TPSPodminky; property NUZtimer:Boolean read ORStav.NUZtimer write ORStav.NUZtimer; property NUZblkCnt:Integer read ORStav.NUZblkCnt write SetNUZBlkCnt; property ZKratBlkCnt:Integer read ORStav.ZKratBlkCnt write SetZkratBlkCnt; property ZadostBlkCnt:Integer read ORStav.ZadostBlkCnt write SetZadostBlkCnt; property PrivolavackaBlkCnt:Integer read ORStav.PrivolavackaBlkCnt write SetPrivolavackaBlkCnt; property TimerCnt:Integer read ORStav.TimerCnt write SetTimerCnt; property reg_please:TIdContext read ORStav.reg_please; //--- komunikace s panely konec --- property Name:string read ORProp.Name; property ShortName:string read ORProp.ShortName; property id:string read ORProp.id; end;//TOR implementation //////////////////////////////////////////////////////////////////////////////// uses TBloky, GetSystems, TBlokVyhybka, TBlokUsek, TBlokSCOm, fMain, Booster, TechnologieJC, TBlokPrejezd, TJCDatabase, Prevody, TCPServerOR, TBlokUvazka, TBlokTrat, TOblsRizeni, TBlok, THVDatabase, SprDb, Logging, UserDb, THnaciVozidlo, Trakce, TBlokZamek, User, fRegulator, TBlokRozp, RegulatorTCP, ownStrUtils, TBlokTratUsek, Souprava, TBlokSouctovaHlaska, predvidanyOdjezd; constructor TOR.Create(index:Integer); begin inherited Create(); Self.findex := index; Self.ORProp.Osvetleni := TList<TOsv>.Create(); Self.Connected := TList<TORPanel>.Create(); Self.MTBClear(); Self.ORStav.dk_click_callback := nil; Self.ORStav.reg_please := nil; Self.stack := TORStack.Create(index+1, Self); Self.vb := TList<TObject>.Create(); Self.changed := false; Self.MereniCasu := TList<TMereniCasu>.Create(); Self.hlaseni := nil; end;//ctor destructor TOR.Destroy(); begin if (Assigned(Self.hlaseni)) then Self.hlaseni.Free(); Self.stack.Free(); Self.ORProp.Osvetleni.Free(); Self.vb.Free(); Self.MereniCasu.Free(); Self.Connected.Free(); inherited Destroy(); end;//dtor //////////////////////////////////////////////////////////////////////////////// //nacitani dat OR //na kazdem radku je ulozena jedna oblast rizeni ve formatu: // nazev;nazev_zkratka;id;(osv_mtb|osv_port|osv_name)(osv_mtb|...)...;; procedure TOR.LoadData(str:string); var data_main,data_osv,data_osv2:TStrings; j:Integer; Osv:TOsv; begin data_main := TStringList.Create(); data_osv := TStringList.Create(); data_osv2 := TStringList.Create(); try ExtractStrings([';'],[],PChar(str), data_main); if (data_main.Count < 3) then raise Exception.Create('Mene nez 3 parametry v popisu oblasti rizeni'); Self.ORProp.Name := data_main[0]; Self.ORProp.ShortName := data_main[1]; Self.ORProp.id := data_main[2]; Self.ORProp.Osvetleni.Clear(); data_osv.Clear(); if (data_main.Count > 3) then begin ExtractStrings(['(', ')'], [], PChar(data_main[3]), data_osv); for j := 0 to data_osv.Count-1 do begin data_osv2.Clear(); ExtractStrings(['|'], [], PChar(data_osv[j]), data_osv2); try Osv.default_state := false; Osv.board := StrToInt(data_osv2[0]); Osv.port := StrToInt(data_osv2[1]); Osv.name := data_osv2[2]; Self.ORProp.Osvetleni.Add(Osv); except end; end;//for j end; Self.hlaseni := TStanicniHlaseni.Create(Self.id); Self.hlaseni.OnAvailable := Self.OnHlaseniAvailable; finally FreeAndNil(data_main); FreeAndNil(data_osv); FreeAndNil(data_osv2); end; end;//procedure //////////////////////////////////////////////////////////////////////////////// // nacitani or_stat.ini souboru // musi byt volano po LoadData procedure TOR.LoadStat(ini:TMemIniFile; section:string); var osv:TOsv; i:Integer; begin // nacteme stav osvetleni for i := 0 to Self.ORProp.Osvetleni.Count-1 do begin osv := Self.ORProp.Osvetleni[i]; osv.default_state := ini.ReadBool(section, osv.name, false); Self.ORProp.Osvetleni[i] := osv; end; end; // ukladani or_stat.ini souboru procedure TOR.SaveStat(ini:TMemIniFile; section:string); var i:Integer; begin // zapiseme stav osvetleni for i := 0 to Self.ORProp.Osvetleni.Count-1 do ini.WriteBool(section, Self.ORProp.Osvetleni[i].name, Self.ORProp.Osvetleni[i].default_state); end; //////////////////////////////////////////////////////////////////////////////// // or;CHANGE;typ_blk;tech_blk_id;barva_popredi;barva_pozadi;blikani; dalsi argumenty u konkretnich typu bloku: // typ_blk = cislo podle typu bloku na serveru // usek : konec_jc;[souprava;barva_soupravy;sipkaLsipkaS;barva_pozadi] - posledni 3 argumenty jsou nepovinne // vyhybka : poloha (cislo odpovidajici poloze na serveru - [disabled = -5, none = -1, plus = 0, minus = 1, both = 2]) // navestidlo: ab (false = 0, true = 1) // pjejezd: stav (otevreno = 0, vystraha = 1, uzavreno = 2, anulace = 3) // uvazka: smer (0 = zakladni, 1 = opacny); soupravy - cisla souprav oddelena carkou //komunikace mezi technologickymi bloky a oblastmi rizeni //tato funkce je vyvolana pri zmene stavu jakehokoliv bloku procedure TOR.BlkChange(Sender:TObject; specificClient:TIDContext = nil); var blk_glob:TBlkSettings; i:Integer; msg:string; fg, bg, nebarVetve, sfg, sbg:TColor; Blk:TBlk; begin if (Self.Connected.Count = 0) then Exit(); blk_glob := (Sender as TBlk).GetGlobalSettings; fg := clFuchsia; bg := clBlack; if (blk_glob.typ = _BLK_TU) then blk_glob.typ := _BLK_USEK; msg := Self.id+';CHANGE;'+IntToStr(blk_glob.typ)+';'+IntToStr(blk_glob.id)+';'; case (blk_glob.typ) of _BLK_VYH:begin //vytvoreni dat if (not (Sender as TBlkVyhybka).vyhZaver) then begin case ((Sender as TBlkVyhybka).Obsazeno) of TUsekStav.disabled: fg := clFuchsia; TUsekStav.none : fg := $A0A0A0; TUsekStav.uvolneno: fg := $A0A0A0; TUsekStav.obsazeno: fg := clRed; end;//case if ((Sender as TBlkVyhybka).Obsazeno = TUsekStav.uvolneno) then begin case ((Sender as TBlkVyhybka).Zaver) of vlak : fg := clLime; posun : fg := clWhite; nouz : fg := clAqua; ab : fg := $707070; end;//case // je soucasti vybarveneho neprofiloveho useku Blky.GetBlkByID(TBlkVyhybka(Sender).UsekID, Blk); if ((Blk <> nil) and ((Blk.typ = _BLK_USEK) or (Blk.typ = _BLK_TU)) and (fg = $A0A0A0) and (TBlkUsek(Blk).IsNeprofilJC)) then fg := clYellow; end; // do profilu vyhybky zasahuje obsazeny usek if (((fg = $A0A0A0) or (fg = clRed)) and (TBlkVyhybka(Sender).npBlokPlus <> nil) and (TBlkVyhybka(Sender).Poloha = TVyhPoloha.plus) and (TBlkUsek(TBlkVyhybka(Sender).npBlokPlus).Obsazeno <> TUsekStav.uvolneno)) then fg := clYellow; // do profilu vyhybky zasahuje obsazeny usek if (((fg = $A0A0A0) or (fg = clRed)) and (TBlkVyhybka(Sender).npBlokMinus <> nil) and (TBlkVyhybka(Sender).Poloha = TVyhPoloha.minus) and (TBlkUsek(TBlkVyhybka(Sender).npBlokMinus).Obsazeno <> TUsekStav.uvolneno)) then fg := clYellow; end else begin // nouzovy zaver vyhybky ma prioritu i nad obsazenim useku fg := clAqua; end; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; bg := clBlack; if ((Sender as TBlkVyhybka).Stitek <> '') then bg := clTeal; if ((Sender as TBlkVyhybka).Vyluka <> '') then bg := clOlive; msg := msg + PrevodySoustav.ColorToStr(bg) + ';'; if ((Sender as TBlkVyhybka).NUZ) then msg := msg + '1;' else msg := msg + '0;'; msg := msg + IntToStr(Integer((Sender as TBlkVyhybka).Poloha))+';'; end;//_BLK_VYH ///////////////////////////////////////////////// _BLK_USEK:begin //vytvoreni dat nebarVetve := $A0A0A0; if ((Sender as TBlkUsek).Obsazeno = TUsekStav.disabled) then begin msg := msg + PrevodySoustav.ColorToStr(clFuchsia) + ';' + PrevodySoustav.ColorToStr(clBlack) + ';0;0;' + PrevodySoustav.ColorToStr(clBlack); end else begin case ((Sender as TBlkUsek).Obsazeno) of TUsekStav.disabled : fg := clFuchsia; TUsekStav.none : fg := $A0A0A0; TUsekStav.uvolneno : fg := $A0A0A0; TUsekStav.obsazeno : fg := clRed; end;//case // zobrazeni zakazu odjezdu do trati if ((fg = $A0A0A0) and ((Sender as TBlk).typ = _BLK_TU) and ((Sender as TBlkTU).InTrat > -1)) then begin Blky.GetBlkByID((Sender as TBlkTU).InTrat, Blk); if ((Blk <> nil) and (Blk.typ = _BLK_TRAT)) then if ((Blk as TBlkTrat).ZAK) then fg := clBlue; end; // neprofilove deleni v useku if ((fg = $A0A0A0) and (TBlkUsek(Sender).IsNeprofilJC())) then fg := clYellow; // zobrazeni zaveru if ((((Sender as TBlkUsek).Obsazeno) = TUsekStav.uvolneno) and ((Sender as TBlk).typ = _BLK_USEK) and ((Sender as TBlkUsek).GetSettings().RCSAddrs.Count > 0)) then begin case ((Sender as TBlkUsek).Zaver) of vlak : fg := clLime; posun : fg := clWhite; nouz : fg := clAqua; ab : fg := $707070; end;//case end; // zobrazeni poruchy BP v trati if (((Sender as TBlk).typ = _BLK_TU) and (TBlkTU(Sender).poruchaBP)) then fg := clAqua; // neprofilove deleni v useku if (fg = clYellow) then nebarVetve := clYellow; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; if ((Sender as TBlkUsek).Stitek <> '') then bg := clTeal; if ((Sender as TBlkUsek).Vyluka <> '') then bg := clOlive; if (not TBlkUsek(Sender).DCC) then bg := clMaroon; if ((Sender as TBlkUsek).ZesZkrat = TBoosterSignal.error) then bg := clFuchsia; if (((Sender as TBlkUsek).ZesNapajeni <> TBoosterSignal.ok) or ((Sender as TBlkUsek).ZesZkrat = TBoosterSignal.undef)) then bg := clBlue; msg := msg + PrevodySoustav.ColorToStr(bg) + ';'; if ((Sender as TBlkUsek).NUZ) then msg := msg + '1;' else msg := msg + '0;'; msg := msg + IntToStr(Integer((Sender as TBlkUsek).KonecJC)) + ';'; msg := msg + PrevodySoustav.ColorToStr(nebarVetve) + ';'; // odeslani seznamu souprav msg := msg + '{'; for i := 0 to (Sender as TBlkUsek).Soupravs.Count-1 do begin sfg := fg; sbg := bg; if ((Sender as TBlkUsek).Obsazeno = uvolneno) then sfg := clAqua; msg := msg + '(' + Soupravy[(Sender as TBlkUsek).Soupravs[i]].nazev + ';'; if (Soupravy[(Sender as TBlkUsek).Soupravs[i]].sdata.smer_L) then msg := msg + '1' else msg := msg + '0'; if (Soupravy[(Sender as TBlkUsek).Soupravs[i]].sdata.smer_S) then msg := msg + '1;' else msg := msg + '0;'; if ((Soupravy[(Sender as TBlkUsek).Soupravs[i]].cilovaOR = Self) and (sbg = clBlack)) then sbg := clSilver; // predvidany odjezd if (Soupravy[(Sender as TBlkUsek).Soupravs[i]].IsPOdj(Sender as TBlk)) then if (Soupravy[(Sender as TBlkUsek).Soupravs[i]].IsPOdj(Sender as TBlkUsek)) then predvidanyOdjezd.GetPOdjColors(Soupravy[(Sender as TBlkUsek).Soupravs[i]].GetPOdj(Sender as TBlkUsek), sfg, sbg); msg := msg + PrevodySoustav.ColorToStr(sfg) + ';'; msg := msg + PrevodySoustav.ColorToStr(sbg) + ';'; if ((Sender as TBlkUsek).vlakPresun = i) then msg := msg + PrevodySoustav.ColorToStr(clYellow) + ';'; msg := msg + ')'; end; // predpovidana souprava if ((Sender as TBlkUsek).SprPredict > -1) then begin // predvidany odjezd sfg := fg; sbg := bg; if (Soupravy[(Sender as TBlkUsek).SprPredict].IsPOdj(Sender as TBlkUsek)) then predvidanyOdjezd.GetPOdjColors(Soupravy[(Sender as TBlkUsek).SprPredict].GetPOdj(Sender as TBlkUsek), sfg, sbg); msg := msg + '(' + Soupravy.GetSprNameByIndex((Sender as TBlkUsek).SprPredict) + ';' + '00;' + PrevodySoustav.ColorToStr(sfg) + ';' + PrevodySoustav.ColorToStr(sbg) + ';)'; end; msg := msg + '}'; end; end;//_BLK_USEK ///////////////////////////////////////////////// _BLK_SCOM:begin //vytvoreni dat if ((Sender as TBlkSCom).Navest = -1) then begin fg := clBlack; bg := clFuchsia; end else begin // privolavaci navest if ((Sender as TBlkSCom).Navest = 8) then begin fg := clWhite; end else begin if (((Sender as TBlkSCom).DNjc <> nil) and ((Sender as TBlkSCom).Navest > 0)) then begin case ((Sender as TBlkSCom).DNjc.data.TypCesty) of TJCType.vlak : fg := clLime; TJCType.posun : fg := clWhite; else fg := clAqua; end; end else begin if (((Sender as TBlkSCom).Navest <> 8) and ((Sender as TBlkSCom).canRNZ)) then fg := clTeal else fg := $A0A0A0; end; end;// else privolavacka if ((Sender as TBlkSCom).ZAM) then begin case ((Sender as TBlkSCom).SymbolType) of 0 : fg := clRed; 1 : fg := clBlue; end; end; case ((Sender as TBlkSCom).ZacatekVolba) of TBlkSComVolba.none : bg := clBlack; TBlkSComVolba.VC : bg := clGreen; TBlkSComVolba.PC : bg := clWhite; TBlkSComVolba.NC, TBlkSComVolba.PP : bg := clTeal; end;//case end;//else Navest = -1 msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; msg := msg + PrevodySoustav.ColorToStr(bg) + ';'; // blikani privolavacky if ((Sender as TBlkSCom).Navest = 8) then msg := msg + '1;' else msg := msg + '0;'; msg := msg + IntToStr(PrevodySoustav.BoolToInt((Sender as TBlkSCom).AB)) + ';'; end;//_BLK_SCOM ///////////////////////////////////////////////// _BLK_PREJEZD:begin //vytvoreni dat if ((Sender as TBlkPrejezd).Stitek <> '') then bg := clTeal; if ((Sender as TBlkPrejezd).NOtevreni) then fg := clRed else if ((Sender as TBlkPrejezd).UZ) then fg := clWhite else fg := $A0A0A0; case ((Sender as TBlkPrejezd).Stav.basicStav) of TBlkPrjBasicStav.disabled : begin fg := clBlack; bg := clFuchsia; end; TBlkPrjBasicStav.none : begin fg := clBlack; bg := clRed; end; end; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; msg := msg + PrevodySoustav.ColorToStr(bg) + ';0;'; msg := msg + IntToStr(Integer((Sender as TBlkPrejezd).Stav.basicStav)) + ';'; end;//_BLK_SCOM ///////////////////////////////////////////////// _BLK_UVAZKA:begin //vytvoreni dat if (((Sender as TBlkUvazka).parent as TBlkTrat).Smer = TTratSmer.disabled) then begin fg := clBlack; bg := clFuchsia; end else begin if ((Sender as TBlkUvazka).Stitek <> '') then bg := clTeal else bg := clBlack; if (((Sender as TBlkUvazka).parent as TBlkTrat).RBPCan) then fg := clRed else if (((Sender as TBlkUvazka).parent as TBlkTrat).Zaver) then fg := clBlue else if (((Sender as TBlkUvazka).parent as TBlkTrat).nouzZaver) then fg := clAqua else if (((Sender as TBlkUvazka).parent as TBlkTrat).Obsazeno) then fg := clBlue else fg := $A0A0A0; end; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; msg := msg + PrevodySoustav.ColorToStr(bg) + ';'; if (((Sender as TBlkUvazka).parent as TBlkTrat).Zadost) then msg := msg + '1;' else msg := msg + '0;'; // smer trati case (((Sender as TBlkUvazka).parent as TBlkTrat).Smer) of TTratSmer.disabled, TTratSmer.zadny : msg := msg + '0;'; TTratSmer.AtoB : msg := msg + '1;'; TTratSmer.BtoA : msg := msg + '2;'; end;//case // soupravy msg := msg + ((Sender as TBlkUvazka).parent as TBlkTrat).GetSprList(',') + ';'; end;//_BLK_UVAZKA ///////////////////////////////////////////////// _BLK_ZAMEK:begin //vytvoreni dat if ((Sender as TBlkZamek).stitek <> '') then bg := clTeal else bg := clBlack; if ((Sender as TBlkZamek).porucha) then begin fg := bg; bg := clBlue; end else if ((Sender as TBlkZamek).klicUvolnen) then fg := clBlue else if ((Sender as TBlkZamek).nouzZaver) then fg := clAqua else fg := $A0A0A0; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; msg := msg + PrevodySoustav.ColorToStr(bg) + ';0;'; end;//_BLK_ZAMEK ///////////////////////////////////////////////// _BLK_ROZP:begin //vytvoreni dat bg := clBlack; case ((Sender as TBlkRozp).status) of TRozpStatus.disabled : fg := clFuchsia; TRozpStatus.not_selected : fg := $A0A0A0; TRozpStatus.mounting : fg := clYellow; TRozpStatus.active : fg := clLime; end;//case msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; msg := msg + PrevodySoustav.ColorToStr(bg) + ';0;'; end;//_BLK_ROZP ///////////////////////////////////////////////// _BLK_SH:begin //vytvoreni dat // n.o. rail fg := clTeal; if (TBlkSH(Sender).anulace) then fg := clWhite; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; msg := msg + PrevodySoustav.ColorToStr(clBlack) + ';0;'; // left rectangle fg := clGreen; if ((TBlkSH(Sender).porucha) or (TBlkSH(Sender).nouzoveOT)) then fg := clRed; if (not TBlkSH(Sender).komunikace) then fg := clFuchsia; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; // right rectangle fg := clBlack; if (TBlkSH(Sender).uzavreno) then fg := $A0A0A0; if (TBlkSH(Sender).UZ) then fg := clWhite; msg := msg + PrevodySoustav.ColorToStr(fg) + ';'; end;//_BLK_SH else Exit; end; //odeslani do OR for i := 0 to Self.Connected.Count-1 do begin if (Self.Connected[i].Rights < TORControlRights.read) then continue; if ((specificClient <> nil) and (Self.Connected[i].Panel <> specificClient)) then continue; ORTCPServer.SendLn(Self.Connected[i].Panel, msg); // aktualizace menu if ((Self.Connected[i].Panel.Data as TTCPORsRef).menu = Sender) then ORTCPServer.Menu(Self.Connected[i].Panel, (Sender as TBlk), Self, (Sender as TBlk).ShowPanelMenu(Self.Connected[i].Panel, Self, Self.Connected[i].Rights)); end;//for i end;//procedure procedure TOR.BlkWriteError(Sender:TObject; error:string; system:string); var i:Integer; begin for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights >= TORControlRights.write) then ORTCPServer.BottomError(Self.Connected[i].Panel, error, Self.ShortName, system); end;//procedure procedure TOR.BlkPlaySound(Sender:TObject; min_rights:TORCOntrolRights; sound:Integer; loop:boolean = false); var i:Integer; begin for i := 0 to Self.Connected.COunt-1 do if (Self.Connected[i].Rights >= min_rights) then ORTCPServer.PlaySound(Self.Connected[i].Panel, sound, loop); end;//procedure procedure TOR.BlkRemoveSound(Sender:TObject; sound:Integer); var i:Integer; begin for i := 0 to Self.Connected.Count-1 do ORTCPServer.DeleteSound(Self.Connected[i].Panel, sound); end;//procedure procedure TOR.BlkNewSpr(Sender:TObject; Panel:TIdContext; sprUsekIndex:Integer); begin TTCPORsRef(Panel.Data).spr_new_usek_index := sprUsekIndex; TTCPORsRef(Panel.Data).spr_usek := Sender; ORTCPServer.SendLn(Panel, Self.id+';SPR-NEW;'); end;//procedure procedure TOR.BlkEditSpr(Sender:TObject; Panel:TIdContext; Souprava:TObject); begin TTCPORsRef(Panel.Data).spr_new_usek_index := -1; TTCPORsRef(Panel.Data).spr_edit := TSouprava(Souprava); TTCPORsRef(Panel.Data).spr_usek := Sender; ORTCPServer.SendLn(Panel, Self.id+';'+'SPR-EDIT;'+TSouprava(Souprava).GetPanelString()); end;//procedure //////////////////////////////////////////////////////////////////////////////// //funkce pro praci s databazi pripojenych panelu //pridani 1 prvku do databaze //v pripade existence jen zvysime prava function TOR.PnlDAdd(Panel:TIdContext; rights:TORControlRights; user:string):Byte; var i:Integer; pnl:TORPanel; begin Result := 0; for i := 0 to Self.Connected.Count-1 do begin if (Self.Connected[i].Panel = Panel) then begin // pokud uz je zaznam v databazi, pouze upravime tento zaznam pnl := Self.Connected[i]; pnl.Rights := rights; pnl.user := user; Self.Connected[i] := pnl; Exit; end; end;//for i if (Self.Connected.Count >= _MAX_CON_PNL) then Exit(1); if ((Panel.Data as TTCPORsRef).ORsCnt >= _MAX_ORREF) then Exit(2); //pridani 1 panelu pnl.Panel := Panel; pnl.Rights := rights; pnl.user := user; Self.Connected.Add(pnl); // pridame referenci na sami sebe do TIDContext (Panel.Data as TTCPORsRef).ORsCnt := (Panel.Data as TTCPORsRef).ORsCnt + 1; (Panel.Data as TTCPORsRef).ORs[(Panel.Data as TTCPORsRef).ORsCnt-1] := Self; // odesleme incializacni udaje if (rights > TORCOntrolRights.null) then begin Self.SendStatus(Panel); Self.stack.NewConnection(Panel); end; end;//function //mazani 1 panelu z databaze function TOR.PnlDRemove(Panel:TIdContext):Byte; var i, found:Integer; begin for i := 0 to Self.Connected.Count-1 do begin if (Self.Connected[i].Panel = Panel) then begin Self.Connected.Delete(i); Break; end; end;//for i // a samozrejme se musime smazat z oblasti rizeni found := -1; for i := 0 to (Panel.Data as TTCPORsRef).ORsCnt-1 do if ((Panel.Data as TTCPORsRef).ORs[i] = Self) then begin found := i; break; end; if (found <> -1) then begin for i := found to (Panel.Data as TTCPORsRef).ORsCnt-2 do (Panel.Data as TTCPORsRef).ORs[i] := (Panel.Data as TTCPORsRef).ORs[i+1]; (Panel.Data as TTCPORsRef).ORsCnt := (Panel.Data as TTCPORsRef).ORsCnt - 1; end; Result := 0; end;//function //ziskani prav daneho panelu z databaze //v pripade nenalezeni panelu v datbazi vracime prava 'no' = zadna function TOR.PnlDGetRights(Panel:TIdContext):TORControlRights; var index:Integer; begin index := Self.PnlDGetIndex(Panel); if (index < 0) then begin Result := TORCOntrolRights.null; Exit; end; Result := Self.Connected[index].Rights; end;//function function TOR.PnlDGetIndex(Panel:TIdContext):Integer; var i:Integer; begin for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Panel = Panel) then Exit(i); Result := -1; end;//function //////////////////////////////////////////////////////////////////////////////// //komunikace s panely: //touto funkci panel zada o opravneni procedure TOR.PanelAuthorise(Sender:TIdContext; rights:TORControlRights; username:string; password:string); var i:Integer; UserRights:TORControlRights; msg:string; panel:TORPanel; user:TUser; last_rights:TORControlRights; begin // panel se chce odpojit -> vyradit z databaze if (rights = TORControlRights.null) then begin Self.ORAuthoriseResponse(Sender, TORControlRights.null, 'Úspěšně autorizováno - odpojen', ''); ORTCPServer.GUIQueueLineToRefresh((Sender.Data as TTCPORsRef).index); if (Self.PnlDGetRights(Sender) >= write) then Self.AuthWriteToRead(Sender); if (Self.PnlDGetIndex(Sender) > -1) then Self.PnlDRemove(Sender); Exit(); end; // tady mame zaruceno, ze panel chce zadat o neco vic, nez null // -> zjistime uzivatele user := UsrDb.GetUser(username); // kontrola existence uzivatele if (not Assigned(user)) then begin UserRights := TORControlRights.null; msg := 'Uživatel '+username+' neexistuje !'; end else // kontrola BANu uzivatele if (user.ban) then begin UserRights := TORControlRights.null; msg := 'Uživatel '+user.id+' má BAN !'; end else // kontrola opravneni uzivatele pro tento panel if (not TUser.ComparePasswd(password, user.password, user.salt)) then begin UserRights := TORControlRights.null; msg := 'Neplatné heslo !'; end else begin UserRights := user.GetRights(Self.id); if (UserRights < rights) then msg := 'K této OŘ nemáte oprávnění'; end; // do last_rights si ulozime posledni opravneni panelu last_rights := Self.PnlDGetRights(Sender); if (UserRights < rights) then begin if (UserRights > TORControlRights.null) then begin Self.PnlDAdd(Sender, UserRights, username); Self.ORAuthoriseResponse(Sender, UserRights, msg, user.fullName) end else begin Self.PnlDRemove(Sender); Self.ORAuthoriseResponse(Sender, UserRights, msg, '') end; ORTCPServer.GUIQueueLineToRefresh((Sender.Data as TTCPORsRef).index); Exit; end; // kontrola vyplych systemu if ((not GetFunctions.GetSystemStart) and (rights > read) and (rights < superuser)) then begin // superuser muze autorizovat zapis i pri vyplych systemech Self.PnlDAdd(Sender, TORControlRights.read, username); Self.ORAuthoriseResponse(Sender, TORControlRights.read, 'Nelze autorizovat zápis při vyplých systémech !', user.fullName); ORTCPServer.GUIQueueLineToRefresh((Sender.Data as TTCPORsRef).index); Exit; end; msg := 'Úspěšně autorizováno !'; // kontrola pripojeni dalsich panelu // pokud chce panel zapisovat, musime zkontrolovat, jestli uz nahodou neni nejaky panel s pravy zapisovat, pripojeny if (UserRights < TORCOntrolRights.superuser) then begin // pokud jsme superuser, pripojenost dalsich panelu nekontrolujeme for i := 0 to Self.Connected.Count-1 do begin if ((Self.Connected[i].Rights > read) and (Self.Connected[i].Panel <> Sender) and (Self.Connected[i].Rights < superuser)) then begin // pokud se pripojuje stejny uzivatel, prevezme rizeni z jiz pripojene OR // jiny uzivatel rizeni prevzit nemuze // -> technologie pripojovani zarucuje, ze pripojeny dispecer muze byt jen jeden if (Self.Connected[i].user = username) then begin panel := Self.Connected[i]; panel.Rights := TORCOntrolRights.read; Self.Connected[i] := panel; Self.ORAuthoriseResponse(panel.Panel, panel.Rights, 'Převzetí řízení', user.fullName); ORTCPServer.GUIQueueLineToRefresh(i); end else begin rights := TORControlRights.read; msg := 'Panel již připojen !'; break; end; end; end;//for i end; if (Self.PnlDAdd(Sender, rights, username) <> 0) then begin ORTCPServer.GUIQueueLineToRefresh((Sender.Data as TTCPORsRef).index); Self.ORAuthoriseResponse(Sender, TORControlRights.null, 'Připojeno maximum OŘ, nelze autorizovat další !', ''); Exit; end; UsrDb.LoginUser(username); Self.ORAuthoriseResponse(Sender, rights, msg, user.fullName); ORTCPServer.GUIQueueLineToRefresh((Sender.Data as TTCPORsRef).index); if ((rights > read) and (last_rights <= read)) then Self.AuthReadToWrite(Sender); if ((rights < write) and (last_rights >= write)) then Self.AuthWriteToRead(Sender); end;//procedure //ziskani stavu vsech bloku v panelu procedure TOR.PanelFirstGet(Sender:TIdContext); var addr:Integer; rights:TORControlRights; begin rights := Self.PnlDGetRights(Sender); if (rights < read) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; Blky.GetORBlk(Self.id, Sender); // zjistime RUC u vsech hnacich vozidel for addr := 0 to _MAX_ADDR-1 do if ((HVDb.HVozidla[addr] <> nil) and (HVDb.HVozidla[addr].Stav.stanice = Self)) then HVDb.HVozidla[addr].UpdateRuc(false); end;//procedure //////////////////////////////////////////////////////////////////////////////// //v panelu je kliknuto na urcity blok procedure TOR.PanelClick(Sender:TIdContext; blokid:Integer; Button:TPanelButton; params:string = ''); var Blk:TBlk; i:Integer; rights:TORCOntrolRights; begin //kontrola opravneni rights := Self.PnlDGetRights(Sender); if (rights < TORCOntrolRights.write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; if (Blky.GetBlkByID(blokid, Blk) <> 0) then Exit; // musime provest kontrolu, jestli OR ma povoleno menit blok // tj. jestli ma technologicky blok toto OR for i := 0 to Blk.OblsRizeni.Cnt-1 do if (Blk.OblsRizeni.ORs[i] = Self) then begin Blk.PanelClick(Sender, Self, Button, rights, params); Exit; end; ORTCPServer.SendInfoMsg(Sender, 'Nemáte oprávnění měnit tento blok'); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelEscape(Sender:TIdContext); var Blk:TBlk; begin //kontrola opravneni klienta if (Integer(Self.PnlDGetRights(Sender)) < _R_write) then begin // ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); // tady se schvalne neposila informace o chybe - aby klienta nespamovala chyba v momente, kdy provadi escape a nema autorizovana vsechna OR na panelu Exit; end; Self.ORDKClickClient(); if (Self.vb.Count > 0) then begin (Self.vb[Self.vb.Count-1] as TBlkUsek).KonecJC := TZaver.no; Self.vb.Delete(Self.vb.Count-1); end else begin Blk := Blky.GetBlkSComZacatekVolba(Self.id); if (Blk <> nil) then (Blk as TBlkSCom).ZacatekVolba := TBlkScomVolba.none; end; Blk := Blky.GetBlkUsekVlakPresun(Self.id); if (Blk <> nil) then (Blk as TBlkUsek).VlakPresun := -1; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelNUZ(Sender:TIdContext); var i,j:Integer; Blk:TBlk; podminky:TList<TPSPodminka>; begin //kontrola opravneni klienta if (Integer(Self.PnlDGetRights(Sender)) < _R_write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; podminky := TList<TPSPodminka>.Create(); // zjisteni jmen bloku: for i := 0 to Blky.Cnt-1 do begin Blky.GetBlkByIndex(i, Blk); if (Blk.typ <> _BLK_USEK) then continue; if (not (Blk as TBlkUsek).NUZ) then continue; for j := 0 to (Blk as TBlkUsek).OblsRizeni.Cnt-1 do if ((Blk as TBlkUsek).OblsRizeni.ORs[j] = Self) then podminky.Add(GetPSPodminka(Blk, 'Nouzové vybavování')); end;//for i ORTCPServer.Potvr(Sender, Self.NUZ_PS, Self, 'Nouzové uvolnění závěrů úseků', TBlky.GetBlksList(Self), podminky); end;//procedure procedure TOR.PanelNUZCancel(Sender:TIdContext); begin //kontrola opravneni klienta if (Integer(Self.PnlDGetRights(Sender)) < _R_write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; Blky.NUZ(Self.id, false); Self.StopMereniCasu(Self.ORStav.NUZmerCasuID); Self.ORStav.NUZtimer := false; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelMessage(Sender:TIdContext; recepient:string; msg:string); var orindex, return:Integer; tmp:TOR; begin //kontrola opravneni klienta if (Integer(Self.PnlDGetRights(Sender)) < _R_write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; orindex := ORs.GetORIndex(recepient); if (orindex < 0) then begin ORTCPServer.SendLn(Sender, Self.id + ';MSG-ERR;' + recepient + ';Tato OŘ neexistuje'); Exit(); end; ORs.GetORByIndex(orindex, tmp); return := tmp.ORSendMsg(Self, msg); if (return = 1) then ORTCPServer.SendLn(Sender, Self.id + ';MSG-ERR;' + recepient + ';K této OŘ aktuálně není připojen žádný panel'); end;//procedure //////////////////////////////////////////////////////////////////////////////// // pozadavek na ziskani sezmu hnacich vozidel procedure TOR.PanelHVList(Sender:TIdContext); var addr:Integer; str:string; begin //kontrola opravneni klienta if (Integer(Self.PnlDGetRights(Sender)) < _R_read) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; str := Self.id + ';HV-LIST;{'; for addr := 0 to _MAX_ADDR-1 do if ((Assigned(HVDb.HVozidla[addr])) and (HVDb.HVozidla[addr].Stav.stanice = Self)) then str := str + '[{' + HVDb.HVozidla[addr].GetPanelLokString(full) + '}]'; str := str + '}'; ORTCPServer.SendLn(Sender, str); end;//procedure //////////////////////////////////////////////////////////////////////////////// // format dat soupravy: nazev;pocet_vozu;poznamka;smer_Lsmer_S;hnaci vozidla procedure TOR.PanelSprChange(Sender:TIdContext; spr:TStrings); begin if ((TTCPORsRef(Sender.Data).spr_new_usek_index = -1) and (TTCPORsRef(Sender.Data).spr_edit = nil)) then Exit(); //kontrola opravneni klienta if (Integer(Self.PnlDGetRights(Sender)) < _R_write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; try if (TTCPORsRef(Sender.Data).spr_new_usek_index > -1) then Soupravy.AddSprFromPanel(spr, TTCPORsRef(Sender.Data).spr_usek, Self, (TTCPORsRef(Sender.Data).spr_new_usek_index)) else begin // kontrola jestli je souprava porad na useku if ((TTCPORsRef(Sender.Data).spr_usek as TBlkUsek).IsSouprava(TTCPORsRef(Sender.Data).spr_edit.index)) then TTCPORsRef(Sender.Data).spr_edit.UpdateSprFromPanel(spr, TTCPORsRef(Sender.Data).spr_usek, Self) else begin ORTCPServer.SendLn(Sender, Self.id+';SPR-EDIT-ERR;Souprava již není na úseku'); Exit(); end; end; except on E: Exception do begin ORTCPServer.SendLn(Sender, Self.id+';SPR-EDIT-ERR;'+E.Message); Exit(); end; end; TTCPORsRef(Sender.Data).spr_new_usek_index := -1; TTCPORsRef(Sender.Data).spr_edit := nil; TTCPORsRef(Sender.Data).spr_usek := nil; ORTCPServer.SendLn(Sender, Self.id+';SPR-EDIT-ACK;'); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelMoveLok(Sender:TIdContext; lok_addr:word; new_or:string); var n_or:Integer; new:TOR; begin //kontrola opravneni klienta if (Integer(Self.PnlDGetRights(Sender)) < _R_write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; n_or := ORs.GetORIndex(new_or); if (n_or < 0) then begin ORTCPServer.SendInfoMsg(Sender, 'Tato OR neexistuje!'); Exit; end; if (not Assigned(HVDb.HVozidla[lok_addr])) then begin ORTCPServer.SendInfoMsg(Sender, 'HV '+IntToStr(lok_addr)+' neexistuje!'); Exit; end; if (HVDb.HVozidla[lok_addr].Stav.souprava > -1) then begin ORTCPServer.SendInfoMsg(Sender, 'HV '+IntToStr(lok_addr)+' přiřazeno soupravě '+Soupravy.GetSprNameByIndex(HVDb.HVozidla[lok_addr].Stav.souprava)+'!'); Exit; end; if (HVDb.HVozidla[lok_addr].Stav.stanice <> Self) then begin ORTCPServer.SendInfoMsg(Sender, 'HV '+IntToStr(lok_addr)+' nepatří této stanici!'); Exit; end; ORs.GetORByIndex(n_or, new); HVDb.HVozidla[lok_addr].PredejStanici(new); ORTCPServer.SendInfoMsg(Sender, 'HV '+IntToStr(lok_addr)+' předáno stanici '+new.Name); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.Update(); var i:Integer; begin Self.MTBUpdate(); Self.stack.Update(); //aktualizace mereni casu: for i := 0 to Self.MereniCasu.Count-1 do begin if (Now >= (Self.MereniCasu[i].Start + Self.MereniCasu[i].Length)) then begin if (Assigned(Self.MereniCasu[i].callback)) then Self.MereniCasu[i].callback(Self); Self.MereniCasu.Delete(i); break; end; end;//for i end;//procedure // vraci id pridaneho mereni function TOR.AddMereniCasu(callback:TNotifyEvent; len:TDateTime):Byte; var id:Integer; mc:TMereniCasu; begin if (Self.MereniCasu.Count > 0) then id := Self.MereniCasu[Self.MereniCasu.Count-1].id+1 else id := 0; // pridat mereni casu do vsech OR: Self.BroadcastData('CAS;START;'+IntToStr(id)+';'+FormatDateTime('s', len)+';'); mc.Start := Now; mc.Length := len; mc.callback := callback; mc.id := id; Self.MereniCasu.Add(mc); Result := id; end;//function procedure TOR.StopMereniCasu(id:Integer); var i:Integer; begin // pridat mereni casu do vsech OR: for i := 0 to Self.MereniCasu.Count-1 do if (Self.MereniCasu[i].id = id) then Self.MereniCasu.Delete(i); Self.BroadcastData('CAS;STOP;'+IntToStr(id)+';'); end;//function //////////////////////////////////////////////////////////////////////////////// // zavola se, az probehne meerni casu: procedure TOR.NUZTimeOut(Sender:TObject); begin Blky.NUZ(Self.id); Self.ORStav.NUZtimer := false; Self.NUZblkCnt := 0; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.NUZ_PS(Sender:TIdContext; success:boolean); var i, j:Integer; JC:TJC; Blk, Nav:TBlk; begin if (not success) then Exit; Self.ORStav.NUZtimer := true; // ruseni pripadnych jiznich cest: for i := 0 to Blky.Cnt-1 do begin Blky.GetBlkByIndex(i, Blk); if (Blk.typ <> _BLK_USEK) then continue; if (not TBlkUsek(Blk).NUZ) then continue; for j := 0 to (Blk as TBlkUsek).OblsRizeni.Cnt-1 do begin if ((Blk as TBlkUsek).OblsRizeni.ORs[j] = Self) then begin JC := JcDb.GetJCByIndex(JCDb.FindPostavenaJCWithUsek(Blk.id)); if (JC <> nil) then begin Blky.GetBlkByID(JC.data.NavestidloBlok, Nav); if (((Nav as TBlkSCom).Navest > 0) and ((Nav as TBlkSCom).DNjc = JC)) then ORTCPServer.BottomError(JC.stav.SenderPnl, 'Chyba povolovací návěsti '+Blky.GetBlkName(JC.data.NavestidloBlok), Self.ShortName, 'TECHNOLOGIE'); JC.RusJCWithoutBlk(); if ((Nav as TBlkSCom).DNjc = JC) then (Nav as TBlkSCom).DNjc := nil; end; end; end;//for j end;//for i Self.BroadcastData('NUZ;2;'); Self.ORStav.NUZmerCasuID := Self.AddMereniCasu(Self.NUZTimeOut, EncodeTime(0, 0, 20, 0)); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.ORAuthoriseResponse(Panel:TIdContext; Rights:TORControlRights; msg:string; username:string); begin ORTCPServer.SendLn(Panel, Self.id+';AUTH;'+IntToStr(Integer(Rights))+';'+msg+';'+username); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.RemoveClient(Panel:TIdContext); begin Self.PnlDRemove(Panel); Self.stack.OnDisconnect(Panel); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.SetNUZBlkCnt(new:Integer); begin if ((Self.ORStav.NUZblkCnt = 0) and (new > 0)) then begin // zacina NUZ, informovat oblasti rizeni Self.BroadcastData('NUZ;1;'); end; if ((Self.ORStav.NUZblkCnt > 0) and (new = 0)) then begin // nekdo si rekl, ze bloky nechce nuzovat Self.BroadcastData('NUZ;0;'); end; Self.ORStav.NUZblkCnt := new; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.SetZkratBlkCnt(new:Integer); var i:Integer; begin if (new < 0) then Exit(); if ((new > 2) and (Self.ORStav.ZkratBlkCnt = 2)) then begin // V OR nastal zkrat -> prehrat zvuk for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights > TORCOntrolRights.read) then ORTCPServer.PlaySound(Self.Connected[i].Panel, _SND_PRETIZENI, true); end; if ((new <= 2) and (Self.ORStav.ZkratBlkCnt = 2)) then begin // zkrat skoncil -> vypnout zvuk for i := 0 to Self.Connected.Count-1 do ORTCPServer.DeleteSound(Self.Connected[i].Panel, _SND_PRETIZENI); end; Self.ORStav.ZkratBlkCnt := new; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.SetZadostBlkCnt(new:Integer); var i:Integer; begin if (new < 0) then Exit(); if ((new > 0) and (Self.ZadostBlkCnt = 0)) then begin // nastala zadost -> prehrat zvuk for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights > TORCOntrolRights.read) then ORTCPServer.PlaySound(Self.Connected[i].Panel, _SND_TRAT_ZADOST, true); end; if ((new = 0) and (Self.ZadostBlkCnt > 0)) then begin // skocnila zadost -> vypnout zvuk for i := 0 to Self.Connected.Count-1 do ORTCPServer.DeleteSound(Self.Connected[i].Panel, _SND_TRAT_ZADOST); end; Self.ORStav.ZadostBlkCnt := new; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.SetPrivolavackaBlkCnt(new:Integer); var i:Integer; begin if (new < 0) then Exit(); if ((new > 0) and (Self.PrivolavackaBlkCnt = 0)) then begin // aktivace prvni privolavaci navesti -> prehrat zvuk for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights > TORCOntrolRights.read) then ORTCPServer.PlaySound(Self.Connected[i].Panel, _SND_PRIVOLAVACKA, true); end; if ((new = 0) and (Self.PrivolavackaBlkCnt > 0)) then begin // skocnila posledni privolavaci navest -> vypnout zvuk for i := 0 to Self.Connected.Count-1 do ORTCPServer.DeleteSound(Self.Connected[i].Panel, _SND_PRIVOLAVACKA); end; Self.ORStav.PrivolavackaBlkCnt := new; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.SetTimerCnt(new:Integer); var i:Integer; begin if (new < 0) then Exit(); if ((new > 0) and (Self.TimerCnt = 0)) then begin // aktivace prvniho timeru -> prehrat zvuk for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights > TORCOntrolRights.read) then ORTCPServer.PlaySound(Self.Connected[i].Panel, _SND_TIMEOUT, true); end; if ((new = 0) and (Self.TimerCnt > 0)) then begin // skocnil posledni timer -> vypnout zvuk for i := 0 to Self.Connected.Count-1 do ORTCPServer.DeleteSound(Self.Connected[i].Panel, _SND_TIMEOUT); end; Self.ORStav.timerCnt := new; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.DisconnectPanels(); var i:Integer; index:Integer; begin for i := Self.Connected.Count-1 downto 0 do begin Self.ORAuthoriseResponse(Self.Connected[i].Panel, TORControlRights.null, 'Odpojení systémů', ''); index := (Self.Connected[i].Panel.Data as TTCPORsRef).index; Self.PnlDRemove(Self.Connected[i].Panel); ORTCPServer.GUIQueueLineToRefresh(index); end; Self.stack.ClearStack(); end;//procedure //////////////////////////////////////////////////////////////////////////////// function TOR.ORSendMsg(Sender:TOR; msg:string):Byte; var i:Integer; begin Result := 1; // defaultne vracime chybu nedorucitelnosti for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights >= TORControlRights.write) then begin ORTCPServer.SendLn(Self.Connected[i].Panel, Self.id + ';MSG;' + Sender.id + ';{'+msg+'}'); Result := 0; end; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.MTBClear(); var i:Integer; begin for i := 0 to TRCS._MAX_RCS do Self.OR_MTB.MTBs[i].present := false; end;//procedure procedure TOR.MTBAdd(addr:integer); begin try Self.OR_MTB.MTBs[addr].present := true; except end; end;//procedure procedure TOR.MTBFail(addr:integer); begin try if (not Self.OR_MTB.MTBs[addr].present) then Exit(); Self.OR_MTB.MTBs[addr].failed := true; Self.OR_MTB.failture := true; Self.OR_MTB.last_failture_time := Now; except end; end;//procedure procedure TOR.MTBUpdate(); var i:Integer; str:string; begin if (not Self.OR_MTB.failture) then Exit(); if ((Self.OR_MTB.last_failture_time + EncodeTime(0, 0, 0, 500)) < Now) then begin str := 'Výpadek MTB modulu '; for i := 0 to TRCS._MAX_RCS do if (Self.OR_MTB.MTBs[i].failed) then begin str := str + IntToStr(i) + ', '; Self.OR_MTB.MTBs[i].failed := false; end; str := LeftStr(str, Length(str)-2); Self.OR_MTB.failture := false; for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights >= read) then ORTCPServer.BottomError(Self.Connected[i].Panel, str, Self.ShortName, 'TECHNOLOGIE'); end; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.UpdateLine(LI:TListItem); var str:string; i: Integer; begin LI.SubItems.Strings[0] := Self.Name; LI.SubItems.Strings[1] := Self.ShortName; LI.SubItems.Strings[2] := Self.id; str := Self.stack.GetList(); LI.SubItems.Strings[3] := RightStr(str, Length(str)-2); case (Self.stack.volba) of TORStackVolba.PV : LI.SubItems.Strings[4] := 'PV'; TORStackVolba.VZ : LI.SubItems.Strings[4] := 'VZ'; end; str := ''; for i := 0 to Self.ORProp.Osvetleni.Count-1 do str := str + '(' + Self.ORProp.Osvetleni[i].name + ' - ' + IntToStr(Self.ORProp.Osvetleni[i].board) + ':' + IntToStr(Self.ORProp.Osvetleni[i].port) + ')'; LI.SubItems.Strings[5] := str; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelZAS(Sender:TIdContext; str:TStrings); begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; Self.stack.ParseCommand(Sender, str); end;//procedure //////////////////////////////////////////////////////////////////////////////// // vrati stav jednoho osvetleni function TOR.PanelGetOsv(index:Integer):boolean; begin if ((index < 0) or (index >= Self.ORProp.Osvetleni.Count)) then Exit(false); try if (RCSi.GetOutput(Self.ORProp.Osvetleni[index].board, Self.ORProp.Osvetleni[index].port) = 1) then Result := true else Result := false; except Result := false; end; end; // or;OSV;(code;stav)(code;srav) ... - informace o stavu osvetleni (stav = [0,1]) procedure TOR.PanelSendOsv(Sender:TIdContext); var i:Integer; str:string; begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < read) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; str := Self.id + ';OSV;'; for i := 0 to Self.ORProp.Osvetleni.Count-1 do str := str + '[' + Self.ORProp.Osvetleni[i].name + '|' + IntToStr(PrevodySoustav.BoolToInt(Self.PanelGetOsv(i))) + ']'; ORTCPServer.SendLn(Sender, str); end;//procedure procedure TOR.PanelSetOsv(Sender:TIdCOntext; id:string; state:boolean); var i:Integer; osv:TOsv; begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; for i := 0 to Self.ORProp.Osvetleni.Count-1 do if (Self.ORProp.Osvetleni[i].name = id) then begin try RCSi.SetOutput(Self.ORProp.Osvetleni[i].board, Self.ORProp.Osvetleni[i].port, PrevodySoustav.BoolToInt(state)); osv := Self.ORProp.Osvetleni[i]; osv.default_state := state; Self.ORProp.Osvetleni[i] := osv; except end; Exit(); end; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.InitOsv(); var osv:TOsv; begin try for osv in Self.ORProp.Osvetleni do if (RCSi.IsModule(osv.board)) then RCSi.SetOutput(osv.board, osv.port, PrevodySoustav.BoolToInt(osv.default_state)); except end; end; //////////////////////////////////////////////////////////////////////////////// function TOR.PanelGetSprs(Sender:TIdCOntext):string; var i:Integer; begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < read) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit(''); end; Result := '{'; for i := 0 to _MAX_SPR-1 do if ((Assigned(Soupravy.soupravy[i])) and (Soupravy.soupravy[i].stanice = Self)) then Result := Result + '[{' + Soupravy.soupravy[i].GetPanelString() + '}]'; Result := Result + '}'; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelRemoveSpr(Sender:TIDContext; spr_index:integer); begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit(); end; if ((Soupravy.soupravy[spr_index] <> nil) and (Soupravy.soupravy[spr_index].stanice = Self)) then begin Soupravy.RemoveSpr(spr_index); ORTCPServer.SendInfoMsg(Sender, 'Souprava smazána'); Exit(); end; end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelHVAdd(Sender:TIDContext; str:string); begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; try HVDb.Add(str, Self); except on e:Exception do begin ORTCPServer.SendInfoMsg(Sender, e.Message); Exit(); end; end; ORTCPServer.SendInfoMsg(Sender, 'Loko přidáno'); end;//procedure procedure TOR.PanelHVRemove(Sender:TIDContext; addr:Integer); var ret:Integer; begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; if (HVDb.HVozidla[addr] = nil) then begin ORTCPServer.SendInfoMsg(Sender, 'Loko neexsituje'); Exit(); end; if (HVDb.HVozidla[addr].Stav.stanice <> self) then begin ORTCPServer.SendInfoMsg(Sender, 'Loko se nenachází ve stanici '+Self.Name); Exit(); end; ret := HVDb.Remove(addr); if (ret > 0) then ORTCPServer.SendInfoMsg(Sender, 'Nelze smazat loko - chyba '+IntToStr(ret)) else ORTCPServer.SendInfoMsg(Sender, 'Loko '+IntToStr(addr)+' smazáno'); end;//procedure procedure TOR.PanelHVEdit(Sender:TIDContext; str:string); var data:TStrings; addr:Integer; begin //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; data := nil; try data := TStringList.Create(); ExtractStringsEx(['|'], [], str, data); addr := StrToInt(data[4]); data.Free(); if (HVDb.HVozidla[addr] = nil) then begin ORTCPServer.SendInfoMsg(Sender, 'Loko neexistuje'); Exit(); end; if (HVDb.HVozidla[addr].Stav.stanice <> self) then begin ORTCPServer.SendInfoMsg(Sender, 'Loko se nenachází ve stanici '+Self.Name); Exit(); end; HVDb.HVozidla[addr].UpdateFromPanelString(str); if ((HVDb.HVozidla[addr].Slot.prevzato) and (not HVDb.HVozidla[addr].Slot.stolen)) then TrkSystem.LokSetFunc(Self, HVDb.HVozidla[addr], HVDb.HVozidla[addr].Stav.funkce); except on e:Exception do begin ORTCPServer.SendInfoMsg(Sender, e.Message); if (Assigned(data)) then data.Free(); Exit(); end; end; ORTCPServer.SendInfoMsg(Sender, 'Loko '+IntToStr(addr)+' aktualizováno'); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.BroadcastData(data:string; min_rights:TORControlRights = read); var i:Integer; begin for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights >= min_rights) then ORTCPServer.SendLn(Self.Connected[i].Panel, Self.id+';'+data); end;//procedure procedure TOR.BroadcastGlobalData(data:string; min_rights:TORControlRights = read); var i:Integer; begin for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Rights >= min_rights) then ORTCPServer.SendLn(Self.Connected[i].Panel, '-;'+data); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.ORDKClickServer(callback:TBlkCallback); begin Self.ORStav.dk_click_callback := callback; Self.BroadcastData('DK-CLICK;1', TORControlRights.write); end;//procedure procedure TOR.ORDKClickClient(); begin if (not Assigned(Self.ORStav.dk_click_callback)) then Exit(); Self.ORStav.dk_click_callback := nil; Self.BroadcastData('DK-CLICK;0', TORControlRights.write); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelDKClick(SenderPnl:TIdContext; Button:TPanelButton); begin if (Assigned(Self.ORStav.dk_click_callback)) then Self.ORStav.dk_click_callback(SenderPnl, Self, Button); end;//procedure // Tato procedura parsuje "LOK-REQ" z panelu. procedure TOR.PanelLokoReq(Sender:TIdContext; str:TStrings); var data:TStrings; i, j:Integer; HV:THV; rights:TORControlRights; line:string; Blk:TBlk; spri:Integer; begin // or;LOK-REQ;PLEASE;addr1|addr2|... - zadost o vydani tokenu // or;LOK-REQ;PLEASE-U;blk_id - zadost o vydani tokenu pro vozidla soupravy na danem techologickem bloku // or;LOK-REQ;LOK;addr1|addr2|... - lokomotivy pro rucni rizeni na zaklade PLEASE regulatoru vybrany // or;LOK-REQ;DENY; - odmitnuti pozadavku na rucni rizeni //kontrola opravneni klienta rights := Self.PnlDGetRights(Sender); if (rights < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; str[2] := UpperCase(str[2]); // zadost o vydani tokenu // odpovedi: // or;LOK-TOKEN;OK;[addr|token][addr|token] - odpověď na žádost o token, je posílano také při RUČ loko // or;LOK-TOKEN;ERR;addr1|addr2...;comment - chybova odpoved na zadost o token if (str[2] = 'PLEASE') then begin // parsing loko try data := TStringList.Create(); ExtractStringsEx(['|'], [], str[3], data); // zkontrolujeme vsechna LOKO for i := 0 to data.Count-1 do begin HV := HVDb.HVozidla[StrToInt(data[i])]; // kontrola existence loko if (HV = nil) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-TOKEN;ERR;'+str[3]+';Loko '+data[i]+' neexistuje'); Exit(); end; // kontrola, zda se loko nachazi u me ve stanici // pokud je uzvatel pripojen jako superuser, muze prevzit i loko, ktere se nenachazi ve stanici if ((HV.Stav.stanice <> Self) and (rights < TORControlRights.superuser)) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-TOKEN;ERR;'+str[3]+';Loko '+data[i]+' se nenachází ve stanici'); Exit(); end; // nelze vygenerovat token pro loko, ktere je uz v regulatoru if ((HV.Stav.regulators.Count > 0) and (rights < TORControlRights.superuser)) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-TOKEN;ERR;'+str[3]+';Loko '+data[i]+' již otevřeno v regulátoru'); Exit(); end; end;//for i // kontrola OK -> generujeme zpravu z tokeny a zpravu odesleme line := Self.id+';LOK-TOKEN;OK;'; for i := 0 to data.Count-1 do begin HV := HVDb.HVozidla[StrToInt(data[i])]; line := line + '[' + IntToStr(HV.adresa) + '|' + HV.GetToken() + ']'; end;//for i ORTCPServer.SendLn(Sender, line); data.Free(); except ORTCPServer.SendLn(Sender, Self.id+';LOK-TOKEN;ERR;Neplatný formát argumentů'); end; end // klient vybral lokomotivy pro rucni rizeni // odpovedi, ktere muzu poslat panelu: // or;LOK-REQ;OK - seznam loko na rucni rizeni schvalen serverem // or;LOK-REQ;ERR;comment - seznam loko na rucni rizeni odmitnut serverem else if (str[2] = 'LOK') then begin try // nejdriv musi probihat zadost o loko if (Self.ORStav.reg_please = nil) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;ERR;Neprobíhá žádná žádost z regulátoru'); Exit(); end; data := TStringList.Create(); ExtractStringsEx(['|'], [], str[3], data); // zkontrolujeme vsechna LOKO for i := 0 to data.Count-1 do begin HV := HVDb.HVozidla[StrToInt(data[i])]; // kontrola existence loko if (HV = nil) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;ERR;Loko '+data[i]+' neexistuje'); Exit(); end; // kontrola, zda se loko nachazi u me ve stanici // pokud je uzvatel pripojen jako superuser, muze prevzit i loko, ktere se nenachazi ve stanici if ((HV.Stav.stanice <> Self) and (rights < TORControlRights.superuser)) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;ERR;Loko '+data[i]+' se nenachází ve stanici'); Exit(); end; // nelze vygenerovat token pro loko, ktere je uz v regulatoru if ((HV.Stav.regulators.Count > 0) and (rights < TORControlRights.superuser)) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;ERR;Loko '+data[i]+' již otevřeno v regulátoru'); Exit(); end; end;//for i // kontrola OK -> odesleme panelu zpravu o tom, ze je vse OK ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;OK;'); // vsem ostatnim panelum jeste posleme, ze doslo ke zruseni zadosti for i := 0 to Self.Connected.Count-1 do if ((Self.Connected[i].Rights >= TORControlRights.read) and (Self.Connected[i].Panel <> Sender)) then ORTCPServer.SendLn(Self.Connected[i].Panel, Self.id+';LOK-REQ;CANCEL;'); // lokomotivy priradime regulatoru for i := 0 to data.Count-1 do begin HV := HVDb.HVozidla[StrToInt(data[i])]; TCPRegulator.LokToRegulator(Self.ORStav.reg_please, HV); end;//for i // zrusit zadost regulatoru (Self.ORStav.reg_please.Data as TTCPORsRef).regulator_zadost := nil; Self.ORStav.reg_please := nil; data.Free(); except ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;ERR;Neplatný formát argumentů'); end; end // relief odmitl zadost regulatoru o lokomotivu else if (str[2] = 'DENY') then begin ORTCPServer.SendLn(Self.ORStav.reg_please, '-;LOK;G;PLEASE-RESP;err;Dispečer odmítl žádost'); Self.BroadcastData('LOK-REQ;CANCEL;'); (Self.ORStav.reg_please.Data as TTCPORsRef).regulator_zadost := nil; Self.ORStav.reg_please := nil; end // or;LOK-REQ;U-PLEASE;blk_id;spr_index - zadost o vydani seznamu hnacich vozidel na danem useku // mozne odpovedi: // or;LOK-REQ;U-OK;[hv1][hv2]... - seznamu hnacich vozidel v danem useku // or;LOK-REQ;U-ERR;info - chyba odpoved na pozadavek na seznam loko v danem useku else if (str[2] = 'U-PLEASE') then begin try Blky.GetBlkByID(StrToInt(str[3]), Blk); if ((Blk = nil) or ((Blk.typ <> _BLK_USEK) and (Blk.typ <> _BLK_TU))) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;U-ERR;Neplatný blok'); Exit(); end; if (not (Blk as TBlkUsek).IsSouprava()) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;U-ERR;Žádná souprava na bloku'); Exit(); end; spri := -1; if (str.Count > 4) then begin spri := StrToIntDef(str[4], -1); if ((spri < -1) or (spri >= (Blk as TBlkUsek).Soupravs.Count)) then begin ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;U-ERR;Tato souprava na úseku neexistuje'); Exit(); end; end; // generujeme zpravu s tokeny line := Self.id+';LOK-REQ;U-OK;{'; if (spri = -1) then begin // vsechny soupravy na useku for j := 0 to (Blk as TBlkUsek).Soupravs.Count-1 do for i := 0 to Soupravy.soupravy[(Blk as TBlkUsek).Soupravs[j]].sdata.HV.cnt-1 do begin HV := HVDb.HVozidla[Soupravy.soupravy[(Blk as TBlkUsek).Soupravs[j]].sdata.HV.HVs[i]]; line := line + '[{' + HV.GetPanelLokString() + '}]'; end; end else begin // konkretni souprava for i := 0 to Soupravy.soupravy[(Blk as TBlkUsek).Soupravs[spri]].sdata.HV.cnt-1 do begin HV := HVDb.HVozidla[Soupravy.soupravy[(Blk as TBlkUsek).Soupravs[spri]].sdata.HV.HVs[i]]; line := line + '[{' + HV.GetPanelLokString() + '}]'; end; end; line := line + '}'; ORTCPServer.SendLn(Sender, line); except ORTCPServer.SendLn(Sender, Self.id+';LOK-REQ;U-ERR;Neplatný formát argumentů'); end; end; end;//procedure //////////////////////////////////////////////////////////////////////////////// // odesle status oblasti rizeni po prihlaseni klienta procedure TOR.SendStatus(panel:TIdContext); var user:TUser; begin // kliknuti na dopravni kancelar if (Assigned(Self.ORStav.dk_click_callback)) then ORTCPServer.SendLn(panel, Self.id+';DK-CLICK;1') else ORTCPServer.SendLn(panel, Self.id+';DK-CLICK;0'); // pripradna zadost o lokomotivu if (Self.reg_please <> nil) then begin user := (Self.reg_please.Data as TTCPORsRef).regulator_user; if (user <> nil) then ORTCPServer.SendLn(panel, Self.id+';LOK-REQ;REQ;'+user.id+';'+user.firstname+';'+user.lastname+';'); end; if ((Assigned(Self.hlaseni)) and (Self.hlaseni.available)) then ORTCPServer.SendLn(panel, Self.id+';SHP;AVAILABLE;1'); if ((Self.NUZblkCnt > 0) and (not Self.NUZtimer)) then ORTCPServer.SendLn(panel, Self.id + ';NUZ;1;'); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.ClearVb(); var i:Integer; begin for i := 0 to Self.vb.Count-1 do (Self.vb[i] as TBlkUsek).KonecJC := TZaver.no; Self.vb.Clear(); end;//procedure //////////////////////////////////////////////////////////////////////////////// function TOR.GetORPanel(conn:TIdContext; var ORPanel:TORPanel):Integer; var i:Integer; begin for i := 0 to Self.Connected.Count-1 do if (Self.Connected[i].Panel = conn) then begin ORPanel := Self.Connected[i]; Exit(0); end; Result := 1; end;//fucction //////////////////////////////////////////////////////////////////////////////// class function TOR.GetRightsString(rights:TORControlRights):string; begin case (rights) of TORControlRights.null : Result := 'null'; TORControlRights.read : Result := 'read'; TORControlRights.write : Result := 'write'; TORControlRights.superuser : Result := 'superuser'; else Result := ''; end; end;//function //////////////////////////////////////////////////////////////////////////////// // je volano v pripade, ze dojde ke zmene opravenni za behu programu procedure TOR.UserUpdateRights(user:TObject); var i:Integer; rights:TORControlRights; begin for i := 0 to Self.Connected.Count-1 do begin // je pripojeny uzivatel s vyssimi opravevnimi, nez jsou mu pridelena? rights := TUser(user).GetRights(Self.id); if ((Self.Connected[i].user = TUser(user).id) and ((Self.Connected[i].Rights > rights) or (TUser(user).ban))) then begin if (TUser(user).ban) then rights := TORControlRights.null; Self.PnlDAdd(Self.Connected[i].Panel, rights, TUser(user).id); Self.ORAuthoriseResponse(Self.Connected[i].Panel, rights, 'Snížena oprávnění uživatele', ''); end; end;//for i end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.UserDelete(userid:string); var i:Integer; begin for i := Self.Connected.Count-1 downto 0 do begin if (Self.Connected[i].user = userid) then begin Self.ORAuthoriseResponse(Self.Connected[i].Panel, TORControlRights.null, 'Uživatel smazán', ''); Self.PnlDRemove(Self.Connected[i].Panel); end; end;//for i end;//procedure //////////////////////////////////////////////////////////////////////////////// // vraci 1 pokud zadost jiz probiha // vraci 0 pokud prikaz probehl vporadku function TOR.LokoPlease(Sender:TIDContext; user:TObject; comment:string):Integer; var str:string; begin if (Self.ORStav.reg_please <> nil) then Exit(1); Self.ORStav.reg_please := Sender; //format: or;LOK-REQ;REQ;username;firstname;lastname;comment str := 'LOK-REQ;REQ;'+TUser(user).id+';'; if (TUser(user).firstname <> '') then str := str + TUser(user).firstname + ';' else str := str + '-;'; if (TUser(user).lastname <> '') then str := str + TUser(user).lastname + ';' else str := str + '-;'; if (comment <> '') then str := str + comment + ';' else str := str + '-;'; Self.BroadcastData(str); Result := 0; end;//procedure procedure TOR.LokoCancel(Sender:TIdContext); begin if (Self.ORStav.reg_please = nil) then Exit(); Self.ORStav.reg_please := nil; //format: or;LOK-REQ;CANCEL; Self.BroadcastData('LOK-REQ;CANCEL;'); end;//procedure //////////////////////////////////////////////////////////////////////////////// procedure TOR.AuthReadToWrite(panel:TIdContext); begin if (Self.ZkratBlkCnt > 2) then ORTCPServer.PlaySound(panel, _SND_PRETIZENI, true); if (Self.ZadostBlkCnt > 0) then ORTCPServer.PlaySound(panel, _SND_TRAT_ZADOST, true); if (Self.PrivolavackaBlkCnt > 0) then ORTCPServer.PlaySound(panel, _SND_PRIVOLAVACKA, true); if (Self.TimerCnt > 0) then ORTCPServer.PlaySound(panel, _SND_TIMEOUT, true); end;//procedure procedure TOR.AuthWriteToRead(panel:TIdContext); begin if (Self.ZkratBlkCnt > 2) then ORTCPServer.DeleteSound(panel, _SND_PRETIZENI); if (Self.ZadostBlkCnt > 0) then ORTCPServer.DeleteSound(panel, _SND_TRAT_ZADOST); if (Self.PrivolavackaBlkCnt > 0) then ORTCPServer.DeleteSound(panel, _SND_PRIVOLAVACKA); if (Self.TimerCnt > 0) then ORTCPServer.DeleteSound(panel, _SND_TIMEOUT); Self.stack.OnWriteToRead(panel); end;//procedure //////////////////////////////////////////////////////////////////////////////// class function TOR.ORRightsToString(rights:TORControlRights):string; begin case (rights) of null : Result := 'žádná oprávnění'; read : Result := 'oprávnění ke čtení'; write : Result := 'oprávnění k zápisu'; superuser : Result := 'superuser'; else Result := ''; end; end;//function //////////////////////////////////////////////////////////////////////////////// class function TOR.GetPSPodminka(blok:TObject; podminka:string):TPSPodminka; begin Result.blok := blok; Result.podminka := podminka; end;//function class function TOR.GetPSPodminky(podm:TPSPodminka):TPSPodminky; begin Result := TList<TPSPodminka>.Create(); Result.Add(podm); end;//function //////////////////////////////////////////////////////////////////////////////// procedure TOR.OnHlaseniAvailable(Sender:TObject; available:boolean); begin if (available) then Self.BroadcastData('SHP;AVAILABLE;1') else Self.BroadcastData('SHP;AVAILABLE;0'); end; //////////////////////////////////////////////////////////////////////////////// procedure TOR.PanelHlaseni(Sender:TIDContext; str:TStrings); begin if (not Assigned(Self.hlaseni)) then Exit(); if (str.Count < 3) then Exit(); //kontrola opravneni klienta if (Self.PnlDGetRights(Sender) < write) then begin ORTCPServer.SendInfoMsg(Sender, _COM_ACCESS_DENIED); Exit; end; str[2] := UpperCase(str[2]); if (str[2] = 'SPEC') then begin Self.hlaseni.Spec(str[3]); end; end; //////////////////////////////////////////////////////////////////////////////// end.//unit
unit uZbutton; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TDrawButtonEvent = procedure(Control: TWinControl; Rect: TRect; State: TOwnerDrawState) of object; ZButton = class(TButton) private { Private declarations } zb_left, zb_right, zb_center: TBitmap; zb_left_f, zb_right_f, zb_center_f: TBitmap; bmp: TBitmap; FBlinked: Boolean; FBlink_light: Boolean; FTimer: TTimer; FCanvas: TCanvas; IsFocused: Boolean; FOnDrawButton: TDrawButtonEvent; procedure CreateParams(var Params: TCreateParams); override; procedure SetButtonStyle(ADefault: Boolean); override; procedure CNMeasureItem(var Message: TWMMeasureItem); message CN_MEASUREITEM; procedure DrawButton(Rect: TRect; State: UINT); procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure SetBlinked(iblinked: boolean); procedure DoBlink(Sender: TObject); protected { Protected declarations } public { Public declarations } constructor Create(AOwner:TComponent); override; destructor Destroy; override; published property Action; property Align; property Anchors; property BiDiMode; property Caption; property Constraints; property Enabled; property ModalResult; property ParentShowHint; property ParentBiDiMode; property ShowHint; property TabOrder; property TabStop; property Visible; property OnEnter; property OnExit; property Blink: Boolean read FBlinked write SetBlinked default false; end; procedure Register; implementation {$R ZButton.dcr} procedure Register; begin RegisterComponents('Freedom', [ZButton]); end; constructor ZButton.Create(AOwner:TComponent); begin inherited Create(AOwner); FBlink_light := false; zb_left := TBitmap.Create; zb_left.Handle := LoadBitmap(hInstance, 'ZBT_LEFT'); zb_right := TBitmap.Create; zb_right.Handle := LoadBitmap(hInstance, 'ZBT_RIGHT'); zb_center := TBitmap.Create; zb_center.Handle := LoadBitmap(hInstance, 'ZBT_CENTER'); zb_left_f := TBitmap.Create; zb_left_f.Handle := LoadBitmap(hInstance, 'ZBT_LEFT_F'); zb_right_f := TBitmap.Create; zb_right_f.Handle := LoadBitmap(hInstance, 'ZBT_RIGHT_F'); zb_center_f := TBitmap.Create; zb_center_f.Handle := LoadBitmap(hInstance, 'ZBT_CENTER_F'); bmp := TBitmap.Create; bmp.PixelFormat := pf32bit; bmp.Transparent := true; bmp.TransparentColor := clWhite; Font.Height := 18; FCanvas := TCanvas.Create; end; destructor ZButton.Destroy; begin inherited Destroy; FCanvas.Free; zb_left.Free; zb_right.Free; zb_center.Free; zb_left_f.Free; zb_right_f.Free; zb_center_f.Free; bmp.Free; end; procedure ZButton.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do Style := Style or BS_OWNERDRAW; end; procedure ZButton.SetButtonStyle(ADefault: Boolean); begin if ADefault <> IsFocused then begin IsFocused := ADefault; Refresh; end; end; procedure ZButton.CNMeasureItem(var Message: TWMMeasureItem); begin with Message.MeasureItemStruct^ do begin itemWidth := Width; itemHeight := Height; end; end; procedure ZButton.CNDrawItem(var Message: TWMDrawItem); var SaveIndex: Integer; begin with Message.DrawItemStruct^ do begin SaveIndex := SaveDC(hDC); FCanvas.Lock; try FCanvas.Handle := hDC; FCanvas.Font := Font; FCanvas.Brush := Brush; DrawButton(rcItem, itemState); finally FCanvas.Handle := 0; FCanvas.Unlock; RestoreDC(hDC, SaveIndex); end; end; Message.Result := 1; end; procedure ZButton.CMEnabledChanged(var Message: TMessage); begin inherited; Invalidate; end; procedure ZButton.CMFontChanged(var Message: TMessage); begin inherited; Invalidate; end; procedure ZButton.WMLButtonDblClk(var Message: TWMLButtonDblClk); begin Perform(WM_LBUTTONDOWN, Message.Keys, Longint(Message.Pos)); end; procedure ZButton.DrawButton(Rect: TRect; State: UINT); var rect_center, rect_left, rect_right: TRect; Flags, OldMode: Longint; IsDown, IsDefault, IsDisabled: Boolean; OldColor: TColor; OrgRect: TRect; begin OrgRect := Rect; Flags := DFCS_BUTTONPUSH or DFCS_ADJUSTRECT; IsDown := State and ODS_SELECTED <> 0; IsDefault := State and ODS_FOCUS <> 0; IsDisabled := State and ODS_DISABLED <> 0; if IsDown then Flags := Flags or DFCS_PUSHED; if IsDisabled then Flags := Flags or DFCS_INACTIVE; bmp.Width := Width; bmp.Height := Height; bmp.Canvas.Rectangle(self.ClientRect); bmp.PixelFormat := pf32bit; rect_left.Top := 0; rect_left.Left := 0; rect_left.Bottom := Height; rect_left.Right := 8; rect_center := self.ClientRect; rect_center.Left := 8; rect_center.Right := rect_center.Right - 8; rect_right := self.ClientRect; rect_right.Left := rect_right.Right - 8; if IsFocused or FBlink_light then begin bmp.Canvas.StretchDraw(rect_left, zb_left_f); bmp.Canvas.StretchDraw(rect_center, zb_center_f); bmp.Canvas.StretchDraw(rect_right, zb_right_f); end else begin bmp.Canvas.StretchDraw(rect_left, zb_left); bmp.Canvas.StretchDraw(rect_center, zb_center); bmp.Canvas.StretchDraw(rect_right, zb_right); end; bmp.Canvas.Font := Font; if Enabled then bmp.Canvas.Font.Color := clBlack else bmp.Canvas.Font.Color := clGray; SetBkMode(bmp.Canvas.Handle, TRANSPARENT); bmp.Canvas.TextOut(round((Width - bmp.Canvas.TextWidth(Caption))/2), 2, Caption); FCanvas.Draw(0, 0, bmp); if IsFocused and IsDefault then begin Rect := OrgRect; InflateRect(Rect, - 4, - 4); FCanvas.Pen.Color := clWindowFrame; FCanvas.Brush.Color := clBtnFace; DrawFocusRect(FCanvas.Handle, Rect); end; end; procedure ZButton.SetBlinked(iblinked: boolean); begin if (not FBlinked) and iblinked and (FTimer = nil) then begin FTimer := TTimer.Create(self); FTimer.OnTimer := DoBlink; FTimer.Interval := 600; FTimer.Enabled := true; FBlinked := true; end; if FBlinked and (not iblinked) then begin if (FTimer <> nil) then begin FTimer.Free; FTimer := nil; FBlink_light := false; end; FBlinked := false; end end; procedure ZButton.DoBlink(Sender: TObject); begin FBlink_light := not FBlink_light; Repaint; end; end.
unit rVarList; interface uses SysUtils, Classes; type ERVarListError = class (Exception); const VarDate = 'Date:YYYY.MM.DD HH:NN:SS'; VarDayOfWeek = 'WeekDay'; VarComputerName = 'ComputerName'; VarComputerIp = 'ComputerIp'; VarUserName = 'UserName'; VarWindowsName = 'WindowsName'; VarWindowsNumber = 'WindowsNumber'; VarWindowsVersion = 'WindowsVersion'; VarWindowsVersionLng = 'WindowsVersionLng'; VarWindowsProductType = 'WindowsType'; VarWindowsDir = 'WindowsDirectory'; VarWindowsSysDir = 'WindowsSystemDirectory'; VarWindowsPrograms = 'WindowsPrograms'; VarWindowsPrograms86 = 'WindowsPrograms_x86'; VarWindowsPrgCommon = 'WindowsProgramsCommon'; VarWindowsPrgCommon86 = 'WindowsProgramsCommon_x86'; VarWindowsDirSh = 'WinDir'; VarWindowsSysDirSh = 'WinSysDir'; VarAllUsersAppData = 'WSD_AllUsers_AppData'; VarAllUsersDesktop = 'WSD_AllUsers_Desktop'; VarAllUsersStartMenu = 'WSD_AllUsers_StartMenu'; VarAllUsersStartUp = 'WSD_AllUsers_StartUp'; VarAllUsersPrograms = 'WSD_AllUsers_Programs'; VarAllUsersDocuments = 'WSD_AllUsers_Documents'; VarAllUsersTemplates = 'WSD_AllUsers_Templates'; VarAllUsersFavorites = 'WSD_AllUsers_Favorites'; VarCurrUserProfile = 'WSD_CurrUser_Profile'; VarCurrUserAppData = 'WSD_CurrUser_AppData'; VarCurrUserDesktop = 'WSD_CurrUser_Desktop'; VarCurrUserStartMenu = 'WSD_CurrUser_StartMenu'; VarCurrUserStartUp = 'WSD_CurrUser_StartUp'; VarCurrUserPrograms = 'WSD_CurrUser_Programs'; VarCurrUserDocuments = 'WSD_CurrUser_Documents'; VarCurrUserTemplates = 'WSD_CurrUser_Templates'; VarCurrUserFavorites = 'WSD_CurrUser_Favorites'; VarCurrUserLocalData = 'WSD_CurrUser_LocalAppData'; VarCurrUserNetHood = 'WSD_CurrUser_NetHood'; VarCurrUserTemp = 'WSD_CurrUser_Temp'; DateTag = 'DATE'; WeekTag = 'WEEKDAY'; CharTag = '$'; DateChar = ':'; OffsChar = '!'; VarsChar = '='; TagsDefC = '%'; DigChars = ['0'..'9','.',',','+','-']; function FixTags(const InText: string; const TagsChar: Char = TagsDefC): string; { == Выделяем из строки имя и значение переменной ============================== } procedure StrToVariable(const FullStr: string; var VarName, VarValue: string); function VariableToStr(const VarName, VarValue: string): string; { == Выделение имени переменной из описания ==================================== } function ExtractVarName(const FullVarName: string; const TagsChar: Char = TagsDefC): string; function UpdateVarName(const VarName: string; const TagsChar: Char = TagsDefC): string; { == Добавление переменной в список ============================================ } procedure AddVariable(Vars: TStrings; const VarName, VarValue: string); overload; procedure AddVariable(Vars: TStrings; const VarText: string); overload; procedure DelVariable(Vars: TStrings; const VarName: string); { == Добавление списка переменной в список ===================================== } procedure AddVariableList(Vars: TStrings; const AddVars: TStrings); overload; procedure AddVariableList(Vars: TStrings; const AddVars: string); overload; { == Добавление стандартных переменных ========================================= } procedure AddStandartVariables(Vars: TStrings; const AddUsersFolders: Boolean); procedure DelStandartVariables(Vars: TStrings; const DelAllUsersFolders, DelCurrUserFolders: Boolean); { == Получение имени переменной ================================================ } function GetVariableName(Vars: TStrings; Index: Integer): string; { == Получение переменной по имени ============================================= } function GetVariableValue(Vars: TStrings; const VarName: string; const CheckExists: Boolean = False): string; { == Получение переменной по имени с преобразованием =========================== } function GetVariable(Vars: TStrings; const VarName: string; const VDate: TDateTime = 0; const TagsChar: Char = '%'): string; function GetVariableNoErrors(Vars: TStrings; const VarName: string; const VDate: TDateTime = 0; const TagsChar: Char = '%'): string; { == Замена тегов в строке из произвольного списка ============================= } function ReplaceTags(Vars: TStrings; const Source: string; const RaiseError: Boolean; const VDate: TDateTime = 0; const TagsChar: Char = TagsDefC; const ProcessDate: Boolean = True): string; overload; function ReplaceTags(const Source, ExtVars: string; const RaiseError: Boolean): string; overload; { == Замена тегов в списке строк =============================================== } procedure ReplaceList(Vars: TStrings; List: TStrings; const VDate: TDateTime = 0; const ProcessDate: Boolean = True); implementation uses rSysUtils, rIpTools, rWinVer, rDialogs, rVclUtils, DateUtils, Windows, ShellApi, ShlObj; resourcestring rsErrTagNotFound = 'Переменная ''%%%s%%'' не найдена в списке переменных!'; rsErrTagUnterminatedTag = 'Незавершенная переменная в строке ''%s''!'; rsErrTagSymbolError = 'Некорректный символ: ''%s''! Символ должен содержать префикс $ и код символа от 0 до 255.'; function FixTags(const InText: string; const TagsChar: Char = TagsDefC): string; begin Result := StringReplace(InText, TagsChar, TagsChar + TagsChar, [rfReplaceAll]); end; { == Выделяем из строки имя и значение переменной ============================== } procedure StrToVariable(const FullStr: string; var VarName, VarValue: string); begin if Pos(VarsChar, FullStr) > 0 then begin VarName := Trim(Copy(FullStr, 1, Pos(VarsChar, FullStr) - 1)); VarValue := Copy(FullStr, Pos(VarsChar, FullStr) + 1, Length(FullStr) - Pos(VarsChar, FullStr)); end else begin VarName := FullStr; VarValue := EmptyStr; end; end; function VariableToStr(const VarName, VarValue: string): string; begin Result := VarName + VarsChar + VarValue; end; { == Выделение имени переменной из описания ==================================== } function ExtractVarName(const FullVarName: string; const TagsChar: Char = TagsDefC): string; begin Result := Trim(FullVarName); while (Length(Result) > 0) and (Result[1] = TagsChar) do Delete(Result, 1, 1); while (Length(Result) > 0) and (Result[Length(Result)] = TagsChar) do Delete(Result, Length(Result), 1); end; function UpdateVarName(const VarName: string; const TagsChar: Char = TagsDefC): string; begin Result := ExtractVarName(VarName, TagsChar); if Result <> EmptyStr then Result := TagsChar + Result + TagsChar; end; { == Добавление переменной в список ============================================ } procedure AddVariable(Vars: TStrings; const VarName, VarValue: string); begin if Vars.IndexOfName(VarName) = -1 then Vars.Add(VariableToStr(VarName, VarValue)) else begin Vars.Values[VarName] := VarValue; // Bug fixed: Если значение переменной пустое, переменная удалялась if VarValue = EmptyStr then Vars.Add(VariableToStr(VarName, VarValue)) end; end; procedure AddVariable(Vars: TStrings; const VarText: string); var VarName, VarValue: string; begin StrToVariable(VarText, VarName, VarValue); AddVariable(Vars, VarName, VarValue); end; procedure DelVariable(Vars: TStrings; const VarName: string); overload; var Idx: Integer; begin Idx := Vars.IndexOfName(VarName); if Idx > -1 then Vars.Delete(Idx); end; { == Добавление списка переменной в список ===================================== } procedure AddVariableList(Vars: TStrings; const AddVars: TStrings); var i, iCount: Integer; begin Vars.BeginUpdate; try iCount := AddVars.Count - 1; for i := 0 to iCount do AddVariable(Vars, AddVars.Names[i], AddVars.Values[AddVars.Names[i]]); finally Vars.EndUpdate; end; end; procedure AddVariableList(Vars: TStrings; const AddVars: string); var VarBuff: TStringList; begin VarBuff := TStringList.Create; try VarBuff.Text := AddVars; AddVariableList(Vars, VarBuff); finally VarBuff.Free; end; end; { == Добавление стандартных переменных ========================================= } procedure AddStandartVariables(Vars: TStrings; const AddUsersFolders: Boolean); begin Vars.BeginUpdate; try // Имя компьютера, IP-адрес, имя пользователя AddVariable(Vars, VarComputerName, GetComputerNetName); AddVariable(Vars, VarComputerIp, GetIPAddressOnName(GetComputerNetName)); AddVariable(Vars, VarUserName, GetCurrentUserName); // Идентификаторы ОС AddVariable(Vars, VarWindowsName, GetWindowsVersion(GetWindowsVersionData, sFmtWindowsVersionAbbr)); AddVariable(Vars, VarWindowsNumber, GetWindowsVersion(GetWindowsVersionData, sFmtWindowsVersionNumber)); AddVariable(Vars, VarWindowsProductType, GetWindowsVersion(GetWindowsVersionData, sFmtWindowsVersionProdType)); AddVariable(Vars, VarWindowsVersion, GetWindowsVersion(GetWindowsVersionData, sFmtWindowsVersionName)); AddVariable(Vars, VarWindowsVersionLng, GetWindowsVersion(GetWindowsVersionData, sFmtWindowsVersionNameLng)); // Системные папки Windows AddVariable(Vars, VarWindowsDir, GetWindowsDir); AddVariable(Vars, VarWindowsDirSh, GetWindowsDir); AddVariable(Vars, VarWindowsSysDir, GetShellFolder(CSIDL_SYSTEM, False)); AddVariable(Vars, VarWindowsSysDirSh, GetShellFolder(CSIDL_SYSTEM, False)); // Папки программ AddVariable(Vars, VarWindowsPrograms, GetShellFolder(CSIDL_PROGRAM_FILES, False)); // if GetShellFolder(CSIDL_PROGRAM_FILESX86, False) <> EmptyStr then AddVariable(Vars, VarWindowsPrograms86, GetShellFolder(CSIDL_PROGRAM_FILESX86, False)); AddVariable(Vars, VarWindowsPrgCommon, GetShellFolder(CSIDL_PROGRAM_FILES_COMMON, False)); // if GetShellFolder(CSIDL_PROGRAM_FILES_COMMONX86, False) <> EmptyStr then AddVariable(Vars, VarWindowsPrgCommon86, GetShellFolder(CSIDL_PROGRAM_FILES_COMMONX86, False)); if AddUsersFolders then begin // Все пользователи AddVariable(Vars, VarAllUsersAppData, GetShellFolder(CSIDL_COMMON_APPDATA, False)); AddVariable(Vars, VarAllUsersStartMenu, GetShellFolder(CSIDL_COMMON_STARTMENU, False)); AddVariable(Vars, VarAllUsersPrograms, GetShellFolder(CSIDL_COMMON_PROGRAMS, False)); AddVariable(Vars, VarAllUsersStartUp, GetShellFolder(CSIDL_COMMON_STARTUP, False)); AddVariable(Vars, VarAllUsersDesktop, GetShellFolder(CSIDL_COMMON_DESKTOPDIRECTORY, False)); AddVariable(Vars, VarAllUsersDocuments, GetShellFolder(CSIDL_COMMON_DOCUMENTS, False)); AddVariable(Vars, VarAllUsersTemplates, GetShellFolder(CSIDL_COMMON_TEMPLATES, False)); // Текущий пользователь AddVariable(Vars, VarCurrUserProfile, GetShellFolder(CSIDL_PROFILE, False)); AddVariable(Vars, VarCurrUserAppData, GetShellFolder(CSIDL_APPDATA, False)); AddVariable(Vars, VarCurrUserLocalData, GetShellFolder(CSIDL_LOCAL_APPDATA, False)); AddVariable(Vars, VarCurrUserStartMenu, GetShellFolder(CSIDL_STARTMENU, False)); AddVariable(Vars, VarCurrUserPrograms, GetShellFolder(CSIDL_PROGRAMS, False)); AddVariable(Vars, VarCurrUserStartUp, GetShellFolder(CSIDL_STARTUP, False)); AddVariable(Vars, VarCurrUserDesktop, GetShellFolder(CSIDL_DESKTOPDIRECTORY, False)); AddVariable(Vars, VarCurrUserDocuments, GetShellFolder(CSIDL_PERSONAL, False)); AddVariable(Vars, VarCurrUserTemplates, GetShellFolder(CSIDL_TEMPLATES, False)); AddVariable(Vars, VarCurrUserFavorites, GetShellFolder(CSIDL_FAVORITES, False)); AddVariable(Vars, VarCurrUserNetHood, GetShellFolder(CSIDL_NETHOOD, False)); AddVariable(Vars, VarCurrUserTemp, GetTempDir); end; finally Vars.EndUpdate; end; end; procedure DelStandartVariables(Vars: TStrings; const DelAllUsersFolders, DelCurrUserFolders: Boolean); begin Vars.BeginUpdate; try // Имя компьютера, IP-адрес, имя пользователя DelVariable(Vars, VarComputerName); DelVariable(Vars, VarComputerIp); DelVariable(Vars, VarUserName); // Идентификаторы ОС DelVariable(Vars, VarWindowsName); DelVariable(Vars, VarWindowsVersion); DelVariable(Vars, VarWindowsVersionLng); // Системные папки Windows DelVariable(Vars, VarWindowsDir); DelVariable(Vars, VarWindowsDirSh); DelVariable(Vars, VarWindowsSysDir); DelVariable(Vars, VarWindowsSysDirSh); // Папки программ DelVariable(Vars, VarWindowsPrograms); DelVariable(Vars, VarWindowsPrograms86); DelVariable(Vars, VarWindowsPrgCommon); DelVariable(Vars, VarWindowsPrgCommon86); if DelAllUsersFolders then begin // Все пользователи DelVariable(Vars, VarAllUsersAppData); DelVariable(Vars, VarAllUsersStartMenu); DelVariable(Vars, VarAllUsersPrograms); DelVariable(Vars, VarAllUsersStartUp); DelVariable(Vars, VarAllUsersDesktop); DelVariable(Vars, VarAllUsersDocuments); DelVariable(Vars, VarAllUsersTemplates); end; if DelCurrUserFolders then begin // Текущий пользователь DelVariable(Vars, VarCurrUserProfile); DelVariable(Vars, VarCurrUserAppData); DelVariable(Vars, VarCurrUserLocalData); DelVariable(Vars, VarCurrUserStartMenu); DelVariable(Vars, VarCurrUserPrograms); DelVariable(Vars, VarCurrUserStartUp); DelVariable(Vars, VarCurrUserDesktop); DelVariable(Vars, VarCurrUserDocuments); DelVariable(Vars, VarCurrUserTemplates); DelVariable(Vars, VarCurrUserFavorites); DelVariable(Vars, VarCurrUserNetHood); end; finally Vars.EndUpdate; end; end; { == Получение имени переменной ================================================ } function GetVariableName(Vars: TStrings; Index: Integer): string; begin Result := Vars.Names[Index]; end; { == Получение переменной по имени ============================================= } function GetVariableValue(Vars: TStrings; const VarName: string; const CheckExists: Boolean = False): string; var Index: Integer; begin if CheckExists then begin Index := Vars.IndexOfName(VarName); if Index > -1 then Result := Vars.Values[VarName] else raise ERVarListError.CreateFmt(rsErrTagNotFound, [VarName]); end else Result := Vars.Values[VarName]; end; { == Получение переменной по имени с преобразованием =========================== } function GetVariable(Vars: TStrings; const VarName: string; const VDate: TDateTime = 0; const TagsChar: Char = '%'): string; begin if Vars.IndexOfName(VarName) > -1 then Result := ReplaceTags(Vars, Vars.Values[VarName], True, VDate, TagsChar) else Result := EmptyStr; end; function GetVariableNoErrors(Vars: TStrings; const VarName: string; const VDate: TDateTime = 0; const TagsChar: Char = '%'): string; begin if Vars.IndexOfName(VarName) > -1 then Result := ReplaceTags(Vars, Vars.Values[VarName], False, VDate, TagsChar) else Result := EmptyStr; end; { == Замена тегов в строке из произвольного списка ============================= } function ReplaceTags(Vars: TStrings; const Source: string; const RaiseError: Boolean; const VDate: TDateTime = 0; const TagsChar: Char = '%'; const ProcessDate: Boolean = True): string; var i, iCount, v, vCount, DatePos: Integer; Tagged, Repl: Boolean; Tag, Rep, OffsetS: string; Val: Byte; OffsetF: Double; begin Result := EmptyStr; Tag := EmptyStr; Tagged := False; iCount := Length(Source); for i := 1 to iCount do begin if Source[i] = TagsChar then begin if Tagged then begin Tagged := False; if Tag = EmptyStr then begin // Два символа подряд Rep := TagsChar; Repl := True; end else begin Repl := False; Rep := TagsChar + Tag + TagsChar; Tag := AnsiUpperCase(Tag); // Вставляем дату if Pos(DateTag, Tag) = 1 then begin if ProcessDate then begin OffsetF := 0; DatePos := Length(DateTag) + 1; // считываем смещение значения if Tag[DatePos] = OffsChar then begin OffsetS := EmptyStr; Inc(DatePos); while CharInSet(Tag[DatePos], DigChars) and (DatePos <= Length(Tag)) do begin OffsetS := OffsetS + Tag[DatePos]; Inc(DatePos); end; OffsetF := RStrToFloatDef(OffsetS, 0); end; // считываем формат даты if Tag[DatePos] = DateChar then Inc(DatePos); if VDate = 0 then Rep := FormatDateTime(Copy(Tag, DatePos, Length(Tag) - DatePos + 1), Now + OffsetF) else Rep := FormatDateTime(Copy(Tag, DatePos, Length(Tag) - DatePos + 1), VDate + OffsetF); end; Repl := True; end; // Вставляем день недели if Pos(WeekTag, Tag) = 1 then begin if ProcessDate then begin DatePos := Length(WeekTag) + 1; if Tag[DatePos] = OffsChar then Inc(DatePos); // считываем смещение значения OffsetS := EmptyStr; Inc(DatePos); while CharInSet(Tag[DatePos], DigChars) and (DatePos <= Length(Tag)) do begin OffsetS := OffsetS + Tag[DatePos]; Inc(DatePos); end; OffsetF := RStrToFloatDef(OffsetS, 0); // возвращаем номер дня недели if VDate = 0 then Rep := IntToStr(DayOfTheWeek(Now + OffsetF)) else Rep := IntToStr(DayOfTheWeek(VDate + OffsetF)); end; Repl := True; end; // Код символа if Pos(CharTag, Tag) = 1 then begin Tag := Copy(Tag, 2, Length(Tag) - 1); if Pos(CharTag, Tag) = 1 then Rep := TagsChar + Tag + TagsChar else begin try Val := StrToInt(Tag); except if RaiseError then raise ERVarListError.CreateFmt(rsErrTagSymbolError, [Tag]) else Val := 32; end; Rep := Chr(Val); Repl := True; end; end; // "Постоянные" теги if Assigned(Vars) then begin vCount := Vars.Count - 1; for v := 0 to vCount do if Tag = AnsiUpperCase(Vars.Names[v]) then begin Rep := ReplaceTags(Vars, Vars.ValueFromIndex[v], RaiseError, VDate); Repl := True; Break; end; end; end; Result := Result + Rep; if RaiseError and not Repl then raise ERVarListError.CreateFmt(rsErrTagNotFound, [Tag]); end else begin Tag := EmptyStr; Tagged := True; end; end else begin if Tagged then Tag := Tag + Source[i] else Result := Result + Source[i]; end; end; // 2012-02-19: Fixed bug // При одиночном TagsChar возвращалась только часть строки до TagsChar if Tagged then begin if RaiseError then raise ERVarListError.CreateFmt(rsErrTagUnterminatedTag, [Source]); Result := Result + TagsChar + Tag; end; end; function ReplaceTags(const Source, ExtVars: string; const RaiseError: Boolean): string; var slVars: TStringList; begin slVars := TStringList.Create; try AddStandartVariables(slVars, True); if ExtVars <> EmptyStr then AddVariableList(slVars, ExtVars); Result := ReplaceTags(slVars, Source, RaiseError, Now); finally slVars.Free; end; end; { == Замена тегов в списке строк =============================================== } procedure ReplaceList(Vars: TStrings; List: TStrings; const VDate: TDateTime = 0; const ProcessDate: Boolean = True); var i, iCount: Integer; begin iCount := List.Count - 1; for i := 0 to iCount do List[i] := ReplaceTags(Vars, List[i], True, VDate, TagsDefC, ProcessDate); end; end.
unit dmCalendario; interface uses SysUtils, Classes, Controls, DB, IBCustomDataSet, IBQuery, dmThreadDataModule; type TCalendario = class(TThreadDataModule) qMaxDate: TIBQuery; qMinDate: TIBQuery; qDias: TIBQuery; qDiasFECHA: TDateField; qMinDateFECHA: TDateField; qMaxDateFECHA: TDateField; protected FMinDate: TDate; ano, mes: word; function GetMaxDate: TDate; virtual; function GetMinDate: TDate; virtual; function GetCurrentDate: TDate; procedure BuscarFechas; virtual; public constructor Create(AOwner: TComponent); override; procedure CambiarMes(const ano, mes: word); function existeDia(const dia: word): boolean; property MaxDate: TDate read GetMaxDate; property MinDate: TDate read GetMinDate; property CurrentDate: TDate read GetCurrentDate; end; implementation uses dmBD, dmData, dmConfiguracion, UtilDB; {$R *.dfm} { TCalendario } function TCalendario.GetCurrentDate: TDate; begin result := Data.CotizacionFECHA.Value; end; function TCalendario.GetMaxDate: TDate; begin result := qMaxDateFECHA.Value; end; function TCalendario.GetMinDate: TDate; begin result := FMinDate; end; procedure TCalendario.BuscarFechas; var tipo: string; begin tipo := Data.TipoCotizacionAsString; // Se cachea la fecha mínima porque la query de buscar la fecha mínima es lenta FMinDate := Configuracion.ReadDateTime('Calendario.Min', tipo, 0); if FMinDate = 0 then begin OpenDataSet(qMinDate); FMinDate := qMinDateFECHA.Value; qMinDate.Close; Configuracion.WriteDateTime('Calendario.Min', tipo, FMinDate); end; qMaxDate.Open; end; procedure TCalendario.CambiarMes(const ano, mes: word); var ini: TDate; begin Self.ano := ano; Self.mes := mes; qDias.Close; ini := EncodeDate(ano, mes, 1); qDias.ParamByName('FECHA1').AsDate := ini; qDias.ParamByName('FECHA2').AsDate := IncMonth(ini); OpenDataSet(qDias); end; constructor TCalendario.Create(AOwner: TComponent); begin inherited Create(AOwner); BuscarFechas; end; function TCalendario.existeDia(const dia: word): boolean; var fecha: TDate; begin fecha := EncodeDate(ano, mes, dia); result := Locate(qDias, 'FECHA', fecha, []); end; end.
unit Model.LanguageDictionary; interface uses System.Classes, JvDBGrid, Data.DB, Vcl.DBGrids; type TLanguageDictionaryType = (ldtMessage, ldtComponentStr, ldtComponentList, ldtComponentListNameValue); IBaseDictionary = Interface ['{232D6C14-5B50-4948-A1A0-3E6152A502A4}'] function GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; function GetMessage(const AMessageName : string) : string; procedure GetTextNamesAndValues(const AFormName, AControlName : string; var ANames : string; var AValues : string); procedure AssignGridColumnTitles(const AFormName : string; aDBGrid : TJvDBGrid); end; TLanguageDictionaryFunction = reference to function(AFileName : string): IBaseDictionary; function MessageDictionary(AFileName : string = '') : IBaseDictionary; function ComponentDictionary(AFileName : string = '') : IBaseDictionary; function ComponentListDictionary(AFileName : string = '') : IBaseDictionary; function ComponentListNameDictionary(AFileName : string = '') : IBaseDictionary; function GridColumnDictionary(AFileName : string = '') : IBaseDictionary; implementation uses System.IOUtils, System.SysUtils, Spring.Collections; const LanguageDictinaryFileName = 'BM.LANG'; MessageFormName = 'MessagesForAppropriateLanguage'; type TBaseDictionary = class(TInterfacedObject, IBaseDictionary) private //FDict : TStringList; //FFileName : string; //FFile : TStream; public function GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; virtual; abstract; function GetMessage(const AMessageName : string) : string; virtual; abstract; procedure GetTextNamesAndValues(const AFormName, AControlName : string; var ANames : string; var AValues : string); virtual; abstract; procedure AssignGridColumnTitles(const AFormName : string; aDBGrid : TJvDBGrid); virtual; abstract; end; type {$REGION TLanguageDictionaryFactory} TLanguageDictionaryFactory = class private class var FDictionary: IDictionary<TLanguageDictionaryType, TLanguageDictionaryFunction>; public class constructor Create; class procedure AddLanguageDictionary(aType : TLanguageDictionaryType; aFunction : TLanguageDictionaryFunction); class function GetLanguageDictionary(aType : TLanguageDictionaryType) : IBaseDictionary; end; class constructor TLanguageDictionaryFactory.Create; begin FDictionary := TCollections.CreateDictionary<TLanguageDictionaryType, TLanguageDictionaryFunction>; end; class procedure TLanguageDictionaryFactory.AddLanguageDictionary(aType : TLanguageDictionaryType; aFunction : TLanguageDictionaryFunction); begin FDictionary.AddOrSetValue(aType, aFunction); end; class function TLanguageDictionaryFactory.GetLanguageDictionary(aType : TLanguageDictionaryType) : IBaseDictionary; begin Result := FDictionary.Items[aType](''); end; {$ENDREGION TLanguageDictionaryFactory} function SetCR(s : String) : string; var i : Integer; begin Result := s; i := Pos('\n', Result); if i=0 then i := Pos('\N', Result); while (i>0) do begin Result[i] := #13; Result[i+1] := #10; i := Pos('\n', Result); if i=0 then i := Pos('\N', Result); end; end; type {$REGION TComponentDictionary} { TComponentDictionary } TComponentDictionary = class(TBaseDictionary) private FDict : TStringList; FFileName : string; //FFile : TStream; public constructor Create(AFileName : string); function GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; override; function GetMessage(const AMessageName : string) : string; override; abstract; procedure GetTextNamesAndValues(const AFormName, AControlName : string; var ANames : string; var AValues : string); override; abstract; end; constructor TComponentDictionary.Create(AFileName : string); begin if AFileName='' then FFileName := ExtractFilePath(ParamStr(0))+TPath.GetFileNameWithoutExtension(ParamStr(0))+'.lang' else FFileName := AFileName; FDict := TStringList.Create; FDict.LoadFromFile(FFileName); end; function TComponentDictionary.GetText(const AFormName, AControlName: string; ADefaultValue: string): string; var aName : string; begin if AControlName='' then aName := AFormName else aName := AFormName+'.'+AControlName; if FDict.IndexOfName(aName)>=0 then Result := SetCR(FDict.Values[aName]) else Result := ADefaultValue; end; {$ENDREGION TComponentDictionary} {$REGION TListDictionary} type TListDictionary = class(TComponentDictionary) public function GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; override; end; function TListDictionary.GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; begin Result := inherited GetText(AFormName, AControlName, ADefaultValue); Result := SetCR(Result); end; {$ENDREGION TListDictionary} {$REGION TListNameValueDictionary} type TListNameValueDictionary = class(TListDictionary) public function GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; override; procedure GetTextNamesAndValues(const AFormName, AControlName : string; var ANames : string; var AValues : string); override; end; function TListNameValueDictionary.GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; begin Result := inherited GetText(AFormName, AControlName, ADefaultValue); Result := SetCR(Result); end; procedure TListNameValueDictionary.GetTextNamesAndValues(const AFormName, AControlName : string; var ANames : string; var AValues : string); var s : string; sl : TStringList; I : integer; ws : string; begin s := inherited GetText(AFormName, AControlName); if s='' then Exit; s := SetCR(s); sl := TStringList.Create; try sl.Text := s; ANames := ''; AValues := ''; for I := 0 to sl.Count-1 do begin if ANames='' then ANames := sl.Names[I] else ANames := ANames + #13#10 + sl.Names[I]; if AValues='' then AValues := sl.Values[sl.Names[I]] else AValues := AValues + #13#10 + sl.Values[sl.Names[I]]; end; finally sl.Free; end; end; {$ENDREGION TListNameValueDictionary} {$REGION TMessageDictionary} type TMessageDictionary = class(TComponentDictionary) public function GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; override; function GetMessage(const AMessageName : string) : string; override; end; function TMessageDictionary.GetMessage(const AMessageName: string): string; begin Result := GetText(MessageFormName, AMessageName, AMessageName); end; function TMessageDictionary.GetText(const AFormName: string; const AControlName: string; ADefaultValue: string = '') : string; begin Result := inherited GetText(AFormName, AControlName, ADefaultValue); end; {$ENDREGION TMessageDictionary} {$REGION TGridColumnDictionary} type TGridColumnDictionary = class(TComponentDictionary) public function GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; override; procedure AssignGridColumnTitles(const AFormName : string; aDBGrid : TJvDBGrid); override; end; function TGridColumnDictionary.GetText(const AFormName, AControlName : string; ADefaultValue : string='') : string; begin Result := inherited GetText(AFormName, AControlName, ADefaultValue); Result := SetCR(Result); end; procedure TGridColumnDictionary.AssignGridColumnTitles(const AFormName : string; aDBGrid : TJvDBGrid); var i: Integer; col : TCollectionItem; //TColumn; fld : TField; begin for col in aDBGrid.Columns do if ((col as TColumn).Field<>nil) and ((col as TColumn).FieldName<>'') then (col as TColumn).Title.Caption := GetText(AFormName, aDBGrid.Name+'['+(col as TColumn).FieldName+'].Caption', (col as TColumn).Title.Caption); end; {$ENDREGION TGridColumnDictionary} var FMessageDictionary : IBaseDictionary = nil; FComponentDictionary : IBaseDictionary = nil; FComponentListDictionary : IBaseDictionary = nil; FComponentListNameDictionary : IBaseDictionary = nil; FGridColumnDictionary : IBaseDictionary = nil; function MessageDictionary(AFileName : string = '') : IBaseDictionary; begin if FMessageDictionary=nil then FMessageDictionary := TMessageDictionary.Create(AFileName); Result := FMessageDictionary; end; function ComponentDictionary(AFileName : string = '') : IBaseDictionary; begin if FComponentDictionary=nil then FComponentDictionary := TComponentDictionary.Create(AFileName); Result := FComponentDictionary; end; function ComponentListDictionary(AFileName : string = '') : IBaseDictionary; begin if FComponentListDictionary=nil then FComponentListDictionary := TListDictionary.Create(AFileName); Result := FComponentListDictionary; end; function ComponentListNameDictionary(AFileName : string = '') : IBaseDictionary; begin if FComponentListNameDictionary=nil then FComponentListNameDictionary := TListNameValueDictionary.Create(AFileName); Result := FComponentListNameDictionary; end; function GridColumnDictionary(AFileName : string = '') : IBaseDictionary; begin if FGridColumnDictionary=nil then FGridColumnDictionary := TGridColumnDictionary.Create(AFileName); Result := FGridColumnDictionary; end; var LDF : TLanguageDictionaryFunction; initialization LDF := function(AFileName : string) : IBaseDictionary begin Result := TMessageDictionary.Create(AFileName); end; TLanguageDictionaryFactory.AddLanguageDictionary(TLanguageDictionaryType.ldtMessage, LDF); LDF := function(AFileName : string) : IBaseDictionary begin Result := TComponentDictionary.Create(AFileName); end; TLanguageDictionaryFactory.AddLanguageDictionary(TLanguageDictionaryType.ldtComponentStr, LDF); LDF := function(AFileName : string) : IBaseDictionary begin Result := TListDictionary.Create(AFileName); end; TLanguageDictionaryFactory.AddLanguageDictionary(TLanguageDictionaryType.ldtComponentList, LDF); LDF := function(AFileName : string) : IBaseDictionary begin Result := TListNameValueDictionary.Create(AFileName); end; TLanguageDictionaryFactory.AddLanguageDictionary(TLanguageDictionaryType.ldtComponentListNameValue, LDF); end.
unit treelistview; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget, systryparent; type TOnClickTreeListItem = procedure(Sender: TObject; itemIndex: integer; itemCaption: string) of object; {Draft Component code by "Lazarus Android Module Wizard" [19/02/2018 09:45:17]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jVisualControl template} jTreeListView = class(jVisualControl) private FOnClickTreeViewItem: TOnClickTreeListItem; FOnLongClickTreeViewItem: TOnClickTreeListItem; FLevels: integer; FFocusedNode: integer; procedure SetVisible(Value: Boolean); procedure SetColor(Value: TARGBColorBridge); //background procedure SetFocusedNode(id: integer); procedure SetLevels(count: integer); function GetNodeHasChildren(id: integer): boolean; function GetRootNode: integer; function GetParentNode(id: integer): integer; function GetNodeData(id: integer): string; procedure SetNodeCaption(id: integer; caption: string); protected FjPRLayoutHome: jObject; //Save parent origin public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; procedure Refresh; procedure UpdateLayout; override; procedure GenEvent_OnClickTreeViewItem(Obj: TObject; position: integer; caption: string); procedure GenEvent_OnLongClickTreeViewItem(Obj: TObject; position: integer; caption: string); function jCreate(): jObject; procedure jFree(); procedure SetViewParent(_viewgroup: jObject); override; function GetParent(): jObject; procedure RemoveFromViewParent(); override; function GetView(): jObject; override; procedure SetLParamWidth(_w: integer); procedure SetLParamHeight(_h: integer); function GetLParamWidth(): integer; function GetLParamHeight(): integer; procedure SetLGravity(_g: integer); procedure SetLWeight(_w: single); procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure AddLParamsAnchorRule(_rule: integer); procedure AddLParamsParentRule(_rule: integer); procedure SetLayoutAll(_idAnchor: integer); procedure ClearLayout(); function AddChild(AParent: integer): integer; procedure Clear; function GetFirstChild(parent_id: integer): integer; function GetNextSibling(id :integer): integer; procedure ToggleNode(id: integer); property FocusedNode: integer read FFocusedNode write SetFocusedNode; property HasChildren[node: integer]: boolean read GetNodeHasChildren; property Levels: integer read FLevels write SetLevels; property NodeData[node: integer]: string read GetNodeData write SetNodeCaption; property ParentNode[node: integer]: integer read GetParentNode; property RootNode: integer read GetRootNode; published property BackgroundColor: TARGBColorBridge read FColor write SetColor; property OnClickItem: TOnClickTreeListItem read FOnClickTreeViewItem write FOnClickTreeViewItem; property OnLongClickItem: TOnClickTreeListItem read FOnLongClickTreeViewItem write FOnLongClickTreeViewItem; end; function jTreeListView_jCreate(env: PJNIEnv; _Self: int64; this: JObject): jObject; procedure jTreeListView_jFree(env: PJNIEnv; _jtreelistview: JObject); procedure jTreeListView_SetViewParent(env: PJNIEnv; _jtreelistview: JObject; _viewgroup: jObject); function jTreeListView_GetParent(env: PJNIEnv; _jtreelistview: JObject): jObject; procedure jTreeListView_RemoveFromViewParent(env: PJNIEnv; _jtreelistview: JObject); function jTreeListView_GetView(env: PJNIEnv; _jtreelistview: JObject): jObject; procedure jTreeListView_SetLParamWidth(env: PJNIEnv; _jtreelistview: JObject; _w: integer); procedure jTreeListView_SetLParamHeight(env: PJNIEnv; _jtreelistview: JObject; _h: integer); function jTreeListView_GetLParamWidth(env: PJNIEnv; _jtreelistview: JObject): integer; function jTreeListView_GetLParamHeight(env: PJNIEnv; _jtreelistview: JObject): integer; procedure jTreeListView_SetLGravity(env: PJNIEnv; _jtreelistview: JObject; _g: integer); procedure jTreeListView_SetLWeight(env: PJNIEnv; _jtreelistview: JObject; _w: single); procedure jTreeListView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jtreelistview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure jTreeListView_AddLParamsAnchorRule(env: PJNIEnv; _jtreelistview: JObject; _rule: integer); procedure jTreeListView_AddLParamsParentRule(env: PJNIEnv; _jtreelistview: JObject; _rule: integer); procedure jTreeListView_SetLayoutAll(env: PJNIEnv; _jtreelistview: JObject; _idAnchor: integer); procedure jTreeListView_ClearLayoutAll(env: PJNIEnv; _jtreelistview: JObject); procedure jTreeListView_SetId(env: PJNIEnv; _jtreelistview: JObject; _id: integer); procedure jTreeListView_SetLevels(env: PJNIEnv; _jtreelistview: JObject; _count: integer); procedure jTreeListView_Clear(env: PJNIEnv; _jtreelistview: JObject); function jTreeListView_AddChild(env: PJNIEnv; _jtreelistview: JObject; _id: integer): integer; procedure jTreeListView_SetNodeCaption(env: PJNIEnv; _jtreelistview: JObject; _id: integer; _caption: string); function jTreeListView_GetNodeData(env: PJNIEnv; _jtreelistview: JObject; id: integer): string; function jTreeListView_GetFirstChild(env: PJNIEnv; _jtreelistview: JObject; parent_id: integer): integer; function jTreeListView_GetNextSibling(env: PJNIEnv; _jtreelistview: JObject; id :integer): integer; function jTreeListView_GetNodeHasChildren(env: PJNIEnv; _jtreelistview: JObject; id :integer): boolean; procedure jTreeListView_ToggleNode(env: PJNIEnv; _jtreelistview: JObject; id :integer); procedure jTreeListView_SetFocusedNode(env: PJNIEnv; _jtreelistview: JObject; id :integer); function jTreeListView_GetRootNode(env: PJNIEnv; _jtreelistview: JObject): integer; function jTreeListView_GetParentNode(env: PJNIEnv; _jtreelistview: JObject; _id: integer): integer; implementation {--------- jTreeListView --------------} constructor jTreeListView.Create(AOwner: TComponent); begin inherited Create(AOwner); if gapp <> nil then FId := gapp.GetNewId(); FMarginLeft := 10; FMarginTop := 10; FMarginBottom := 10; FMarginRight := 10; FHeight := 96; //?? FWidth := 96; //?? FLParamWidth := lpMatchParent; //lpWrapContent FLParamHeight := lpWrapContent; //lpMatchParent FAcceptChildrenAtDesignTime:= False; //your code here.... FLevels := 0; FFocusedNode:=0; end; destructor jTreeListView.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jTreeListView.Init; var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin if not FInitialized then begin inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; if FParent <> nil then sysTryNewParent( FjPRLayout, FParent); FjPRLayoutHome:= FjPRLayout; jTreeListView_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout); jTreeListView_SetId(gApp.jni.jEnv, FjObject, Self.Id); end; jTreeListView_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject , FMarginLeft,FMarginTop,FMarginRight,FMarginBottom, sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ), sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom )); for rToA := raAbove to raAlignRight do begin if rToA in FPositionRelativeToAnchor then begin jTreeListView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA)); end; end; for rToP := rpBottom to rpCenterVertical do begin if rToP in FPositionRelativeToParent then begin jTreeListView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP)); end; end; if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id else Self.AnchorId:= -1; //dummy jTreeListView_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId); if not FInitialized then begin FInitialized:= True; if FColor <> colbrDefault then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; end; procedure jTreeListView.SetColor(Value: TARGBColorBridge); begin FColor:= Value; if (FInitialized = True) and (FColor <> colbrDefault) then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); end; procedure jTreeListView.SetVisible(Value : Boolean); begin FVisible:= Value; if FInitialized then View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; procedure jTreeListView.UpdateLayout; begin if not FInitialized then exit; ClearLayout(); inherited UpdateLayout; init; end; procedure jTreeListView.Refresh; begin if FInitialized then View_Invalidate(gApp.jni.jEnv, FjObject); end; //Event : Java -> Pascal procedure jTreeListView.GenEvent_OnClickTreeViewItem(Obj: TObject; position: integer; caption: string); begin if Assigned(FOnClickTreeViewItem) then FOnClickTreeViewItem(Obj, position, caption); end; procedure jTreeListView.GenEvent_OnLongClickTreeViewItem(Obj: TObject; position: integer; caption: string); begin if Assigned(FOnLongClickTreeViewItem) then FOnLongClickTreeViewItem(Obj, position, caption); end; function jTreeListView.jCreate(): jObject; begin //in designing component state: result value here... Result:= jTreeListView_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jTreeListView.jFree(); begin //in designing component state: set value here... if FInitialized then jTreeListView_jFree(gApp.jni.jEnv, FjObject); end; procedure jTreeListView.SetViewParent(_viewgroup: jObject); begin //in designing component state: set value here... if FInitialized then jTreeListView_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup); end; function jTreeListView.GetParent(): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jTreeListView_GetParent(gApp.jni.jEnv, FjObject); end; procedure jTreeListView.RemoveFromViewParent(); begin //in designing component state: set value here... if FInitialized then jTreeListView_RemoveFromViewParent(gApp.jni.jEnv, FjObject); end; function jTreeListView.GetView(): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jTreeListView_GetView(gApp.jni.jEnv, FjObject); end; procedure jTreeListView.SetLParamWidth(_w: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_SetLParamWidth(gApp.jni.jEnv, FjObject, _w); end; procedure jTreeListView.SetLParamHeight(_h: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_SetLParamHeight(gApp.jni.jEnv, FjObject, _h); end; function jTreeListView.GetLParamWidth(): integer; begin //in designing component state: result value here... if FInitialized then Result:= jTreeListView_GetLParamWidth(gApp.jni.jEnv, FjObject); end; function jTreeListView.GetLParamHeight(): integer; begin //in designing component state: result value here... if FInitialized then Result:= jTreeListView_GetLParamHeight(gApp.jni.jEnv, FjObject); end; procedure jTreeListView.SetLGravity(_g: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_SetLGravity(gApp.jni.jEnv, FjObject, _g); end; procedure jTreeListView.SetLWeight(_w: single); begin //in designing component state: set value here... if FInitialized then jTreeListView_SetLWeight(gApp.jni.jEnv, FjObject, _w); end; procedure jTreeListView.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h); end; procedure jTreeListView.AddLParamsAnchorRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jTreeListView.AddLParamsParentRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jTreeListView.SetLayoutAll(_idAnchor: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor); end; procedure jTreeListView.ClearLayout(); var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin //in designing component state: set value here... if FInitialized then begin jTreeListView_clearLayoutAll(gApp.jni.jEnv, FjObject); for rToP := rpBottom to rpCenterVertical do if rToP in FPositionRelativeToParent then jTreeListView_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP)); for rToA := raAbove to raAlignRight do if rToA in FPositionRelativeToAnchor then jTreeListView_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA)); end; end; procedure jTreeListView.SetLevels(count: integer); begin //in designing component state: set value here... FLevels := count; if FInitialized then jTreeListView_SetLevels(gApp.jni.jEnv, FjObject, FLevels); end; procedure jTreeListView.Clear; begin //in designing component state: set value here... if FInitialized then jTreeListView_Clear(gApp.jni.jEnv, FjObject); end; function jTreeListView.AddChild(AParent: integer): integer; begin Result := -1; if FInitialized then Result:= jTreeListView_AddChild(gApp.jni.jEnv, FjObject, AParent); end; procedure jTreeListView.SetNodeCaption(id: integer; caption: string); begin if FInitialized then jTreeListView_SetNodeCaption(gApp.jni.jEnv, FjObject, id, caption); end; function jTreeListView.GetNodeData(id: integer): string; begin if FInitialized then Result := jTreeListView_GetNodeData(gApp.jni.jEnv, FjObject, id); end; function jTreeListView.GetFirstChild(parent_id: integer): integer; begin if FInitialized then Result := jTreeListView_GetFirstChild(gApp.jni.jEnv, FjObject, parent_id); end; function jTreeListView.GetNextSibling(id :integer): integer; begin if FInitialized then Result := jTreeListView_GetNextSibling(gApp.jni.jEnv, FjObject, id); end; function jTreeListView.GetNodeHasChildren(id: integer): boolean; begin if FInitialized then Result := jTreeListView_GetNodeHasChildren(gApp.jni.jEnv, FjObject, id); end; procedure jTreeListView.ToggleNode(id: integer); begin //in designing component state: set value here... if FInitialized then jTreeListView_ToggleNode(gApp.jni.jEnv, FjObject, id); end; procedure jTreeListView.SetFocusedNode(id: integer); begin //in designing component state: set value here... FFocusedNode := id; if FInitialized then jTreeListView_SetFocusedNode(gApp.jni.jEnv, FjObject, FFocusedNode); end; function jTreeListView.GetRootNode: integer; begin if FInitialized then Result := jTreeListView_GetRootNode(gApp.jni.jEnv, FjObject); end; function jTreeListView.GetParentNode(id: integer): integer; begin if FInitialized then Result := jTreeListView_GetParentNode(gApp.jni.jEnv, FjObject, id); end; {-------- jTreeListView_JNI_Bridge ----------} function jTreeListView_jCreate(env: PJNIEnv; _Self: int64; this: JObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jTreeListView_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; procedure jTreeListView_jFree(env: PJNIEnv; _jtreelistview: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetViewParent(env: PJNIEnv; _jtreelistview: JObject; _viewgroup: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= _viewgroup; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetParent(env: PJNIEnv; _jtreelistview: JObject): jObject; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetParent', '()Landroid/view/ViewGroup;'); Result:= env^.CallObjectMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_RemoveFromViewParent(env: PJNIEnv; _jtreelistview: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V'); env^.CallVoidMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetView(env: PJNIEnv; _jtreelistview: JObject): jObject; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;'); Result:= env^.CallObjectMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetLParamWidth(env: PJNIEnv; _jtreelistview: JObject; _w: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _w; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetLParamHeight(env: PJNIEnv; _jtreelistview: JObject; _h: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _h; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetLParamWidth(env: PJNIEnv; _jtreelistview: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetLParamWidth', '()I'); Result:= env^.CallIntMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetLParamHeight(env: PJNIEnv; _jtreelistview: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetLParamHeight', '()I'); Result:= env^.CallIntMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetLGravity(env: PJNIEnv; _jtreelistview: JObject; _g: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _g; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetLGravity', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetLWeight(env: PJNIEnv; _jtreelistview: JObject; _w: single); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].f:= _w; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetLWeight', '(F)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jtreelistview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); var jParams: array[0..5] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _left; jParams[1].i:= _top; jParams[2].i:= _right; jParams[3].i:= _bottom; jParams[4].i:= _w; jParams[5].i:= _h; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_AddLParamsAnchorRule(env: PJNIEnv; _jtreelistview: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_AddLParamsParentRule(env: PJNIEnv; _jtreelistview: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetLayoutAll(env: PJNIEnv; _jtreelistview: JObject; _idAnchor: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _idAnchor; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_ClearLayoutAll(env: PJNIEnv; _jtreelistview: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V'); env^.CallVoidMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetId(env: PJNIEnv; _jtreelistview: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'setId', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetLevels(env: PJNIEnv; _jtreelistview: JObject; _count: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _count; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetLevels', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_Clear(env: PJNIEnv; _jtreelistview: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'Clear', '()V'); env^.CallVoidMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_AddChild(env: PJNIEnv; _jtreelistview: JObject; _id: integer): integer; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'AddChild', '(I)I'); Result := env^.CallIntMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetNodeCaption(env: PJNIEnv; _jtreelistview: JObject; _id: integer; _caption: string); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //TreeViewList_Log('Creating caption "'+_caption+'" for node '+IntToStr(_id)); jParams[0].i:= _id; jParams[1].l:= env^.NewStringUTF(env, pchar(_caption) ); jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetNodeCaption', '(ILjava/lang/String;)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); env^.DeleteLocalRef(env, jParams[1].l); end; function jTreeListView_GetNodeData(env: PJNIEnv; _jtreelistview: JObject; id: integer): string; begin Result:= jni_func_i_out_t(env, _jtreelistview, 'GetNodeData', id); end; function jTreeListView_GetFirstChild(env: PJNIEnv; _jtreelistview: JObject; parent_id: integer): integer; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= parent_id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetFirstChild', '(I)I'); Result := env^.CallIntMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetNextSibling(env: PJNIEnv; _jtreelistview: JObject; id :integer): integer; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetNextSibling', '(I)I'); Result := env^.CallIntMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetNodeHasChildren(env: PJNIEnv; _jtreelistview: JObject; id :integer): boolean; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; _jBoolean: jBoolean; begin jParams[0].i:= id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetNodeHasChildren', '(I)Z'); _jBoolean := env^.CallBooleanMethodA(env, _jtreelistview, jMethod, @jParams); Result := Boolean(_jBoolean); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_ToggleNode(env: PJNIEnv; _jtreelistview: JObject; id :integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'ToggleNode', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jTreeListView_SetFocusedNode(env: PJNIEnv; _jtreelistview: JObject; id :integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'SetFocusedNode', '(I)V'); env^.CallVoidMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetRootNode(env: PJNIEnv; _jtreelistview: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'RootNode', '()I'); Result:= env^.CallIntMethod(env, _jtreelistview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jTreeListView_GetParentNode(env: PJNIEnv; _jtreelistview: JObject; _id: integer): integer; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jtreelistview); jMethod:= env^.GetMethodID(env, jCls, 'GetParentNode', '(I)I'); Result := env^.CallIntMethodA(env, _jtreelistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; end.
unit Figure; interface Uses graphics,ExtCtrls,Forms,Windows; Procedure Setting(asetx:integer); Type TFigure=class x,y,dx,dy:integer; turnkey:integer; Image:TImage; col:TColor; constructor Create(ax,ay:integer;aImage:TImage;acol:TColor); procedure Draw;virtual;abstract; Procedure NewDraw(x1,y1,x2,y2:integer); procedure Move(t:single);virtual; procedure Search(t:single); procedure Motion(flag:boolean);virtual; procedure Turn;virtual; function CheckandDel(yn,minyn:integer;Var score:integer):integer;virtual; end; Type TFigure1=class(TFigure) procedure Draw;override; procedure Move(t:single);override; procedure Motion(flag:boolean);override; Function CheckandDel(yn,minyn:integer;Var score:integer):integer;override; end; Type TFigure2=class(TFigure) procedure Draw;override; procedure Move(t:single);override; procedure Motion(flag:boolean);override; Function CheckandDel(yn,minyn:integer;Var score:integer):integer;override; procedure Turn;override; end; Type TFigure3=class(TFigure) procedure Draw;override; procedure Move(t:single);override; procedure Motion(flag:boolean);override; Function CheckandDel(yn,minyn:integer;Var score:integer):integer;override; procedure Turn;override; end; Type TFigure4=class(TFigure) procedure Draw;override; procedure Move(t:single);override; procedure Motion(flag:boolean);override; Function CheckandDel(yn,minyn:integer;Var score:integer):integer;override; procedure Turn;override; end; Type TFigure5=class(TFigure) procedure Draw;override; procedure Move(t:single);override; procedure Motion(flag:boolean);override; Function CheckandDel(yn,minyn:integer;Var score:integer):integer;override; procedure Turn;override; end; Type TFigure6=class(TFigure) procedure Draw;override; procedure Move(t:single);override; procedure Motion(flag:boolean);override; Function CheckandDel(yn,minyn:integer;Var score:integer):integer;override; procedure Turn;override; end; Type TFigure7=class(TFigure) procedure Draw;override; procedure Move(t:single);override; procedure Motion(flag:boolean);override; Function CheckandDel(yn,minyn:integer;Var score:integer):integer;override; procedure Turn;override; end; Var stop:boolean=false; setx:integer=640; implementation Procedure Setting; begin setx:=asetx; end; Constructor TFigure.Create; Begin inherited Create; x:=ax; y:=ay; Image:=aImage; col:=acol; dx:=0;dy:=0; turnkey:=0; End; Procedure TFigure.NewDraw; begin Image.Canvas.Rectangle(x1,y1,x2,y2); Image.Canvas.Rectangle(x1+2,y1+2,x2-2,y2-2); Image.Canvas.Rectangle(x1+4,y1+4,x2-4,y2-4); end; Procedure TFigure.Move; Begin Image.Canvas.Pen.Color:=clWhite; Image.Canvas.Brush.Color:=clWhite; Draw; Image.Canvas.Pen.Color:=clBlack; Image.Canvas.Brush.Color:=col; Search(t); Draw; end; Procedure TFigure.Search; begin dy:=round(t*10); end; Procedure TFigure.Motion; begin Image.Canvas.Pen.Color:=clWhite; Image.Canvas.Brush.Color:=clWhite; Draw; if flag then dx:=dx+40 else dx:=dx-40; end; Procedure TFigure.Turn; begin Image.Canvas.Pen.Color:=clWhite; Image.Canvas.Brush.Color:=clWhite; Draw; Image.Canvas.Pen.Color:=clBlack; Image.Canvas.Brush.Color:=col; turnkey:=turnkey+1; Draw; end; Function TFigure.CheckandDel; var count: word; i,j:integer; begin Image.Canvas.Pen.Color:=ClWhite; Image.Canvas.Brush.Color:=ClWhite; count:=0; for i := 1 to 12 do begin if Image.Canvas.Pixels[40*i-20,yn+20]<>clWhite then count:=count+1; end; if count=12 then begin for i := 1 to 12 do for j := yn div 40 downto minyn div 40 do begin Image.Canvas.Pen.Color:=Image.Canvas.Pixels[i*40-40,j*40-20]; Image.Canvas.Brush.Color:=Image.Canvas.Pixels[i*40-20,j*40-20]; NewDraw(i*40-40,j*40,i*40,j*40+40); end; minyn:=minyn+40; score:=score+1; end; Result:=minyn; end; Procedure TFigure1.Draw; begin NewDraw(x+dx,y+dy,x+dx+40,y+dy+40); NewDraw(x+dx,y+dy+40,x+dx+40,y+dy+80); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); end; Procedure TFigure1.Move; begin if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+82]=clWhite)then inherited Move(t) else stop:=true; end; Procedure TFigure1.Motion; begin if (Image.Canvas.Pixels[x+dx-2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+40]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+72]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+40]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+72]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; Function TFigure1.CheckandDel; begin inherited CheckandDel(y+dy,minyn,score); inherited CheckandDel(y+dy+40,minyn,score); Result:=minyn; end; Procedure TFigure2.Draw; begin case turnkey mod 2 of 0:begin NewDraw(x+dx,y+dy,x+dx+160,y+dy+40); NewDraw(x+dx,y+dy,x+dx+40,y+dy+40); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx+120,y+dy,x+dx+160,y+dy+40); end; 1:begin NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+40,y+dy+80,x+dx+80,y+dy+120); NewDraw(x+dx+40,y+dy+120,x+dx+80,y+dy+160); end; end; end; Procedure TFigure2.Move; begin case turnkey mod 2 of 0:if (dy<(setx-40)) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) then inherited Move(t) else stop:=true; 1:if (dy<(setx-160)) and (Image.Canvas.Pixels[x+dx+42,y+dy+162]=clWhite) then inherited Move(t) else stop:=true; end; end; Procedure TFigure2.Motion; begin case turnkey mod 2 of 0:begin if (Image.Canvas.Pixels[x+dx-2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+38]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+44]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+162,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+162,y+dy+38]=clWhite) and (Image.Canvas.Pixels[x+dx+162,y+dy+44]=clWhite) and (dx<160) and (flag) then inherited Motion(flag); end; 1:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+40]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+78]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+116]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+154]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+164]=clWhite) and (dx>-220) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+40]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+78]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+116]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+154]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+164]=clWhite) and (dx<220) and flag then inherited Motion(flag); end; end; end; Procedure TFigure2.Turn; begin case turnkey mod 2 of 0:if (Image.Canvas.Pixels[x+dx+50,y+dy+78]=clWhite) and (Image.Canvas.Pixels[x+dx+50,y+dy+117]=clWhite) and (Image.Canvas.Pixels[x+dx+50,y+dy+150]=clWhite) and (Image.Canvas.Pixels[x+dx+50,y+dy+162]=clWhite) then inherited Turn; 1:if (Image.Canvas.Pixels[x+dx-2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+90,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+130,y+dy+42]=clWhite) then inherited Turn; end; end; Function TFigure2.CheckandDel; begin if turnkey mod 2=0 then Inherited CheckandDel(y+dy,minyn,score) else begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); Inherited CheckandDel(y+dy+120,minyn,score); end; Result:=minyn; end; Procedure TFigure3.Draw; begin case turnkey mod 4 of 0:begin NewDraw(x+dx,y+dy,x+dx+40,y+dy+40); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx,y+dy+40,x+dx+40,y+dy+80); end; 1:begin NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+40,y+dy+80,x+dx+80,y+dy+120); NewDraw(x+dx+80,y+dy+80,x+dx+120,y+dy+120); end; 2:begin NewDraw(x+dx,y+dy+40,x+dx+40,y+dy+80); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); end; 3:begin NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); NewDraw(x+dx+80,y+dy+80,x+dx+120,y+dy+120); end; end; end; Procedure TFigure3.Move; begin case turnkey mod 4 of 0:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) then inherited Move(t) else stop:=true; 1:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) then inherited Move(t) else stop:=true; 2:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Move(t) else stop:=true; 3:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) then inherited Move(t) else stop:=true; end; end; Procedure TFigure3.Motion; begin case turnkey mod 4 of 0:begin if (Image.Canvas.Pixels[x+dx-2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+38]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+78]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+84]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+42,y+dy+44]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+44]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+44]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 1:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+118,y+dy+122]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+126]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; 2:begin if (Image.Canvas.Pixels[x+dx-2,y+dy+38]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+78]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+2]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 3:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+118,y+dy+122]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; end; end; Procedure TFigure3.Turn; begin case turnkey mod 4 of 0:if (Image.Canvas.Pixels[x+dx+44,y+dy+44]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+44,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy+124]=clWhite) and (Image.Canvas.Pixels[x+dx+44,y+dy+124]=clWhite) then inherited Turn; 1:if (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) then inherited Turn; 2:if (Image.Canvas.Pixels[x+dx+42,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+118]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) then inherited Turn; 3:if (Image.Canvas.Pixels[x+dx+2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+42]=clWhite) then inherited Turn; end; end; Function TFigure3.CheckandDel; begin case turnkey mod 4 of 0:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 1:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; 2:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 3:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; end; Result:=minyn; end; Procedure TFigure4.Draw; begin case turnkey mod 4 of 0:begin NewDraw(x+dx,y+dy+40,x+dx+40,y+dy+80); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); end; 1:begin NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); NewDraw(x+dx+80,y+dy+80,x+dx+120,y+dy+120); end; 2:begin NewDraw(x+dx,y+dy,x+dx+40,y+dy+40); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); end; 3:begin NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+40,y+dy+80,x+dx+80,y+dy+120); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); end; end; end; Procedure TFigure4.Move; begin case turnkey mod 4 of 0:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Move(t) else stop:=true; 1:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) then inherited Move(t) else stop:=true; 2:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) then inherited Move(t) else stop:=true; 3:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Move(t) else stop:=true; end; end; Procedure TFigure4.Motion; begin case turnkey mod 4 of 0:begin if (Image.Canvas.Pixels[x+dx+2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+82]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 1:begin if (Image.Canvas.Pixels[x+dx+42,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; 2:begin if (Image.Canvas.Pixels[x+dx-2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 3:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; end; end; Procedure TFigure4.Turn; begin case turnkey mod 4 of 0:if (Image.Canvas.Pixels[x+dx+44,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+118,y+dy+124]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy+124]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy]=clWhite) then inherited Turn; 1:if (Image.Canvas.Pixels[x+dx+2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+2]=clWhite) then inherited Turn; 2:if (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Turn; 3:if (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) then inherited Turn; end; end; Function TFigure4.CheckandDel; begin case turnkey mod 4 of 0:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 1:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; 2:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 3:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; end; Result:=minyn; end; Procedure TFigure5.Draw; begin case turnkey mod 2 of 0:begin NewDraw(x+dx,y+dy,x+dx+40,y+dy+40); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); end; 1:begin NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); NewDraw(x+dx+40,y+dy+80,x+dx+80,y+dy+120); end; end; end; Procedure TFigure5.Move; begin case turnkey mod 2 of 0:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Move(t) else stop:=true; 1:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Move(t) else stop:=true; end; end; Procedure TFigure5.Motion; begin case turnkey mod 2 of 0:begin if (Image.Canvas.Pixels[x+dx-2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+118,y+dy+82]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 1:begin if (Image.Canvas.Pixels[x+dx+42,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+118]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; end; end; Procedure TFigure5.Turn; begin case turnkey mod 2 of 0:if (Image.Canvas.Pixels[x+dx+44,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+44,y+dy+124]=clWhite) and (Image.Canvas.Pixels[x+dx+118,y+dy+2]=clWhite) then inherited Turn; 1:if (Image.Canvas.Pixels[x+dx+2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+2]=clWhite) then inherited Turn; end; end; Function TFigure5.CheckandDel; begin case turnkey mod 2 of 0:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 1:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; end; Result:=minyn; end; Procedure TFigure6.Draw; begin case turnkey mod 2 of 0:begin NewDraw(x+dx,y+dy+40,x+dx+40,y+dy+80); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); end; 1:begin NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy+80,x+dx+120,y+dy+120); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); end; end; end; Procedure TFigure6.Move; begin case turnkey mod 2 of 0:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) then inherited Move(t) else stop:=true; 1:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) then inherited Move(t) else stop:=true; end; end; Procedure TFigure6.Motion; begin case turnkey mod 2 of 0:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+82]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+118,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 1:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+118]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; end; end; Procedure TFigure6.Turn; begin case turnkey mod 2 of 0:if (Image.Canvas.Pixels[x+dx+44,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy+44]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+84,y+dy+124]=clWhite) then inherited Turn; 1:if (Image.Canvas.Pixels[x+dx+84,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) then inherited Turn; end; end; Function TFigure6.CheckandDel; begin case turnkey mod 2 of 0:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 1:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; end; Result:=minyn; end; Procedure TFigure7.Draw; begin case turnkey mod 4 of 0:begin NewDraw(x+dx,y+dy,x+dx+40,y+dy+40); NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); end; 1:begin NewDraw(x+dx+40,y+dy,x+dx+80,y+dy+40); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+40,y+dy+80,x+dx+80,y+dy+120); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); end; 2:begin NewDraw(x+dx,y+dy,x+dx+40,y+dy+40); NewDraw(x+dx,y+dy+40,x+dx+40,y+dy+80); NewDraw(x+dx+40,y+dy+40,x+dx+80,y+dy+80); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); end; 3:begin NewDraw(x+dx+40,y+dy+80,x+dx+80,y+dy+120); NewDraw(x+dx+80,y+dy,x+dx+120,y+dy+40); NewDraw(x+dx+80,y+dy+40,x+dx+120,y+dy+80); NewDraw(x+dx+80,y+dy+80,x+dx+120,y+dy+120); end; end; end; Procedure TFigure7.Move; begin case turnkey mod 4 of 0:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Move(t) else stop:=true; 1:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) then inherited Move(t) else stop:=true; 2:if (dy<(setx-80)) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) then inherited Move(t) else stop:=true; 3:if (dy<(setx-120)) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) then inherited Move(t) else stop:=true; end; end; Procedure TFigure7.Motion; begin case turnkey mod 4 of 0:begin if (Image.Canvas.Pixels[x+dx-2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 1:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+122]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; 2:begin if (Image.Canvas.Pixels[x+dx-2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx-2,y+dy+82]=clWhite) and (dx>-160) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+42,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (dx<200) and (flag) then inherited Motion(flag); end; 3:begin if (Image.Canvas.Pixels[x+dx+38,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+38,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+78,y+dy+42]=clWhite) and (dx>-200) and (not flag) then inherited Motion(flag); if (Image.Canvas.Pixels[x+dx+122,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+122,y+dy+82]=clWhite) and (dx<200) and flag then inherited Motion(flag); end; end; end; Procedure TFigure7.Turn; begin case turnkey mod 4 of 0:if (Image.Canvas.Pixels[x+dx+44,y+dy+44]=clWhite) and (Image.Canvas.Pixels[x+dx+44,y+dy+84]=clWhite) and (Image.Canvas.Pixels[x+dx+44,y+dy+124]=clWhite) then inherited Turn; 1:if (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+2]=clWhite) then inherited Turn; 2:if (Image.Canvas.Pixels[x+dx+42,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+82]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+122]=clWhite) and (Image.Canvas.Pixels[x+dx+82,y+dy+2]=clWhite) then inherited Turn; 3:if (Image.Canvas.Pixels[x+dx+2,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+2,y+dy+42]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+2]=clWhite) and (Image.Canvas.Pixels[x+dx+42,y+dy+42]=clWhite) then inherited Turn; end; end; Function TFigure7.CheckandDel; begin case turnkey mod 4 of 0:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 1:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; 2:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); end; 3:begin Inherited CheckandDel(y+dy,minyn,score); Inherited CheckandDel(y+dy+40,minyn,score); Inherited CheckandDel(y+dy+80,minyn,score); end; end; Result:=minyn; end; end.
unit Transit_HardCodeVisitors_Svr; interface uses tiVisitorDB , tiLog , tiOPFManager , tiObject , Transit_BOM ; type TVisPeriod_Read = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisPeriod_ReadFromPK = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisPeriod_Create = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisPeriod_Update = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisPeriod_Delete = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisShowMethod_Read = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisShowMethod_ReadFromPK = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisShowMethod_Create = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisShowMethod_Update = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisShowMethod_Delete = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisMidpointList_Read = class( TtiVisitorSelect ) private FMaster: TMidpointList; protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisMidpointList_ReadFromPK = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisMidpointList_Create = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisMidpointList_Update = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisMidpointList_Delete = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure Final(const AVisited: TtiObject); override ; end; TVisMidpoint_ReadFromPK = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisMidpoint_Create = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisMidpoint_Update = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisMidpoint_Delete = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisRTSQuestion_Read = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisRTSQuestion_ReadFromPK = class( TtiVisitorSelect ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; procedure MapRowToObject; override; end; TVisRTSQuestion_Create = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisRTSQuestion_Update = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; TVisRTSQuestion_Delete = class( TtiVisitorUpdate ) protected function AcceptVisitor: Boolean; override; procedure Init; override; procedure SetupParams; override; end; procedure RegisterVisitors; implementation procedure RegisterVisitors; begin gTIOPFManager.RegReadVisitor(TVisPeriod_Read); gTIOPFManager.RegReadVisitor(TVisPeriod_ReadFromPK); gTIOPFManager.RegSaveVisitor(TVisPeriod_Create); gTIOPFManager.RegSaveVisitor(TVisPeriod_Update); gTIOPFManager.RegSaveVisitor(TVisPeriod_Delete); gTIOPFManager.RegReadVisitor(TVisShowMethod_Read); gTIOPFManager.RegReadVisitor(TVisShowMethod_ReadFromPK); gTIOPFManager.RegSaveVisitor(TVisShowMethod_Create); gTIOPFManager.RegSaveVisitor(TVisShowMethod_Update); gTIOPFManager.RegSaveVisitor(TVisShowMethod_Delete); //One-2-Many visitor order is important gTIOPFManager.RegReadVisitor(TVisMidpointList_Read); gTIOPFManager.RegReadVisitor(TVisMidpointList_ReadFromPK); gTIOPFManager.RegReadVisitor(TVisMidpoint_ReadFromPK); gTIOPFManager.RegSaveVisitor(TVisMidpointList_Create); gTIOPFManager.RegSaveVisitor(TVisMidpointList_Update); gTIOPFManager.RegSaveVisitor(TVisMidpoint_Create); gTIOPFManager.RegSaveVisitor(TVisMidpoint_Update); gTIOPFManager.RegSaveVisitor(TVisMidpoint_Delete); gTIOPFManager.RegSaveVisitor(TVisMidpointList_Delete); // gTIOPFManager.RegSaveVisitor(TVisMidpoint_Create); // gTIOPFManager.RegSaveVisitor(TVisMidpointList_Create); //association - is order important? gTIOPFManager.RegReadVisitor(TVisRTSQuestion_Read); gTIOPFManager.RegReadVisitor(TVisRTSQuestion_ReadFromPK); gTIOPFManager.RegSaveVisitor(TVisRTSQuestion_Create); gTIOPFManager.RegSaveVisitor(TVisRTSQuestion_Update); gTIOPFManager.RegSaveVisitor(TVisRTSQuestion_Delete); end; { TVisPeriod_Read } function TVisPeriod_Read.AcceptVisitor: Boolean; begin Result := (Visited is TPeriodCollection) and (Visited.ObjectState = posEmpty); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisPeriod_Read.Init; begin Query.SQLText := 'select OID from period'; end; procedure TVisPeriod_Read.MapRowToObject; var LData: TPeriod; begin LData := TPeriodCollection(Visited).Add; LData.OID.AssignFromTIQuery('OID',Query); LData.ObjectState := posClean ; end; procedure TVisPeriod_Read.SetupParams; begin //do nothing end; { TVisPeriod_ReadFromPK } function TVisPeriod_ReadFromPK.AcceptVisitor: Boolean; begin Result := (Visited is TPeriod) and (Visited.ObjectState = posPK); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisPeriod_ReadFromPK.Init; begin Query.SQLText := 'select OID from period' + 'where OID = :OID'; end; procedure TVisPeriod_ReadFromPK.MapRowToObject; begin //nothing to read in this class, since period doesn't have any non-PK fields TPeriod(Visited).ObjectState := posClean; end; procedure TVisPeriod_ReadFromPK.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisPeriod_Create } function TVisPeriod_Create.AcceptVisitor: Boolean; begin Result := (Visited is TPeriod) and (Visited.ObjectState = posCreate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisPeriod_Create.Init; begin Query.SQLText := 'Insert into period ( OID ) ' + 'Values ' + '( :OID )'; end; procedure TVisPeriod_Create.SetupParams; var LData: TPeriod; begin LData := Visited as TPeriod; LData.OID.AssignToTIQuery('OID', Query); end; { TVisPeriod_Update } function TVisPeriod_Update.AcceptVisitor: Boolean; begin Result := (Visited is TPeriod) and (Visited.ObjectState = posUpdate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisPeriod_Update.Init; begin Query.SQLText := 'Update period Set ' + 'where ' + ' OID = :OID'; //there are no non-PK fields, so there's nothing to ever update end; procedure TVisPeriod_Update.SetupParams; var LData: TPeriod; begin LData := Visited as TPeriod; lData.OID.AssignToTIQuery('OID', Query); end; { TVisPeriod_Delete } function TVisPeriod_Delete.AcceptVisitor: Boolean; begin Result := (Visited is TPeriod) and (Visited.ObjectState = posDelete); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisPeriod_Delete.Init; begin Query.SQLText := 'delete from period where oid = :oid'; end; procedure TVisPeriod_Delete.SetupParams; var LData: TPeriod; begin lData := Visited as TPeriod; lData.OID.AssignToTIQuery('OID', Query); end; { TVisShowMethod_Read } function TVisShowMethod_Read.AcceptVisitor: Boolean; begin Result := (Visited is TShowMethodCollection) and (Visited.ObjectState = posEmpty); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisShowMethod_Read.Init; begin Query.SQLText := 'select OID, show_method_name from show_method'; end; procedure TVisShowMethod_Read.MapRowToObject; var LData: TShowMethod; begin LData := TShowMethodCollection(Visited).Add; LData.OID.AssignFromTIQuery('OID',Query); LData.Name := Query.FieldAsString['show_method_name']; LData.ObjectState := posClean; end; procedure TVisShowMethod_Read.SetupParams; begin // Do nothing end; { TVisShowMethod_ReadFromPK } function TVisShowMethod_ReadFromPK.AcceptVisitor: Boolean; begin Result := (Visited is TShowMethod) and (Visited.ObjectState = posPK); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisShowMethod_ReadFromPK.Init; begin Query.SQLText := 'select OID, show_method_name from show_method' + 'where ' + ' OID = :OID'; end; procedure TVisShowMethod_ReadFromPK.MapRowToObject; var LData: TShowMethod; begin LData := Visited as TShowMethod; LData.Name := Query.FieldAsString['show_method_name']; LData.ObjectState := posClean; end; procedure TVisShowMethod_ReadFromPK.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisShowMethod_Create } function TVisShowMethod_Create.AcceptVisitor: Boolean; begin Result := (Visited is TShowMethod) and (Visited.ObjectState = posCreate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisShowMethod_Create.Init; begin Query.SQLText := 'Insert into show_method ( OID, show_method_name ) ' + 'Values ' + '( :OID, :show_method_name )'; end; procedure TVisShowMethod_Create.SetupParams; var LData: TShowMethod; begin LData := Visited as TShowMethod; LData.OID.AssignToTIQuery('OID', Query); Query.ParamAsString['show_method_name'] := LData.Name; end; { TVisShowMethod_Update } function TVisShowMethod_Update.AcceptVisitor: Boolean; begin Result := (Visited is TShowMethod) and (Visited.ObjectState = posUpdate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisShowMethod_Update.Init; begin Query.SQLText := 'Update show_method Set ' + ' show_method_name = :show_method_name ' + 'where ' + ' OID = :OID'; end; procedure TVisShowMethod_Update.SetupParams; var LData: TShowMethod; begin LData := Visited as TShowMethod; LData.OID.AssignToTIQuery('OID', Query); Query.ParamAsString['show_method_name'] := LData.Name; end; { TVisShowMethod_Delete } function TVisShowMethod_Delete.AcceptVisitor: Boolean; begin Result := (Visited is TShowMethod) and (Visited.ObjectState = posDelete); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisShowMethod_Delete.Init; begin Query.SQLText := 'delete from show_method where oid = :oid'; end; procedure TVisShowMethod_Delete.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisMidpointList_Read } function TVisMidpointList_Read.AcceptVisitor: Boolean; begin Result := (Visited is TMidpointListCollection) and (Visited.ObjectState = posEmpty); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpointList_Read.Init; begin Query.SQL.Text := 'select ' + ' ml.OID as midpoint_list_oid ' + ' ,ml.midpoint_list_name as midpoint_list_name ' + ' ,m.OID as midpoint_oid ' + ' ,m.midpoint_name as midpoint_name ' + ' ,m.midpoint_value as midpoint_value ' + ' ,m.midpoint_value as midpoint_punch ' + 'from ' + ' rts_midpoint_list ml ' + 'left join rts_midpoint m on m.rts_midpoint_list_oid = ml.OID ' + 'order by ' + 'midpoint_list_name ' ; end; procedure TVisMidpointList_Read.MapRowToObject; var LDetail: TMidpoint; begin if (FMaster = nil) or (FMaster.OID.AsString <> Query.FieldAsString['midpoint_list_oid']) then begin FMaster := TMidpointListCollection(Visited).Add; FMaster.OID.AssignFromTIQuery('midpoint_list_oid', Query); FMaster.Name := Query.FieldAsString['midpoint_list_name']; FMaster.ObjectState := posClean; FMaster.Midpoints.ObjectState := posClean; end ; if Query.FieldAsString['midpoint_oid'] <> '' then begin LDetail := FMaster.Midpoints.Add; LDetail.OID.AssignFromTIQuery('midpoint_oid', Query ); LDetail.Name := Query.FieldAsString['midpoint_name']; LDetail.Value := Query.FieldAsFloat['midpoint_value']; LDetail.Punch := Query.FieldAsInteger['midpoint_punch']; LDetail.ObjectState := posClean ; end ; end; procedure TVisMidpointList_Read.SetupParams; begin // Do nothing end; { TVisMidpointList_ReadFromPK } function TVisMidpointList_ReadFromPK.AcceptVisitor: Boolean; begin Result := (Visited is TMidpointList) and (Visited.ObjectState = posPK); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpointList_ReadFromPK.Init; begin Query.SQLText := 'select OID, midpoint_list_name from rts_midpoint_list' + 'where ' + ' OID = :OID'; end; procedure TVisMidpointList_ReadFromPK.MapRowToObject; var LData: TMidpointList; begin LData := Visited as TMidpointList; LData.Name := Query.FieldAsString['midpoint_list_name']; LData.ObjectState := posClean; end; procedure TVisMidpointList_ReadFromPK.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisMidpointList_Create } function TVisMidpointList_Create.AcceptVisitor: Boolean; begin Result := (Visited is TMidpointList) and (Visited.ObjectState = posCreate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpointList_Create.Init; begin Query.SQLText := 'Insert into rts_midpoint_list ( OID, midpoint_list_name ) ' + 'Values ' + '( :OID, :midpoint_list_name )'; end; procedure TVisMidpointList_Create.SetupParams; var LData: TMidpointList; begin LData := Visited as TMidpointList; LData.OID.AssignToTIQuery('OID', Query); Query.ParamAsString['midpoint_list_name'] := LData.Name; end; { TVisMidpointList_Update } function TVisMidpointList_Update.AcceptVisitor: Boolean; begin Result := (Visited is TMidpointList) and (Visited.ObjectState = posUpdate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpointList_Update.Init; begin Query.SQLText := 'Update rts_midpoint_list Set ' + ' midpoint_list_name = :midpoint_list_name ' + 'where ' + ' OID = :OID'; end; procedure TVisMidpointList_Update.SetupParams; var LData: TMidpointList; begin LData := Visited as TMidpointList; LData.OID.AssignToTIQuery('OID', Query); Query.ParamAsString['midpoint_list_name'] := LData.Name; end; { TVisMidpointList_Delete } function TVisMidpointList_Delete.AcceptVisitor: Boolean; begin Result := (Visited is TMidpointList) and (Visited.ObjectState = posDelete); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpointList_Delete.Final(const AVisited: TtiObject); var LData: TMidpointList; begin inherited Final(AVisited); LData := Visited as TMidpointList; lData.Midpoints.ObjectState := posClean ; end; procedure TVisMidpointList_Delete.Init; begin Query.SQLText := 'delete from rts_midpoint_list where oid = :oid'; end; procedure TVisMidpointList_Delete.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisMidpoint_ReadFromPK } function TVisMidpoint_ReadFromPK.AcceptVisitor: Boolean; begin Result := (Visited is TMidpoint) and (Visited.ObjectState = posPK); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpoint_ReadFromPK.Init; begin Query.SQLText := 'select OID, midpoint_name from rts_midpoint' + 'where ' + ' OID = :OID'; end; procedure TVisMidpoint_ReadFromPK.MapRowToObject; var LData: TMidpoint; begin LData := Visited as TMidpoint; LData.Name := Query.FieldAsString['midpoint_name']; LData.ObjectState := posClean; end; procedure TVisMidpoint_ReadFromPK.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisMidpoint_Create } function TVisMidpoint_Create.AcceptVisitor: Boolean; begin Result := (Visited is TMidpoint) and (Visited.ObjectState = posCreate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpoint_Create.Init; begin Query.SQLText := 'Insert into rts_midpoint ( OID, rts_midpoint_list_oid, midpoint_name, midpoint_value, midpoint_punch ) ' + 'Values ' + '( :OID, :rts_midpoint_list_oid, :midpoint_name, :midpoint_value, :midpoint_punch )'; end; procedure TVisMidpoint_Create.SetupParams; var LData: TMidpoint; begin LData := Visited as TMidpoint; LData.OID.AssignToTIQuery('OID', Query); LData.Owner.OID.AssignToTIQuery('rts_midopoint_list_oid', Query); Query.ParamAsString['midpoint_name'] := LData.Name; Query.ParamAsFloat['midpoint_value'] := LData.Value; Query.ParamAsInteger['midpoint_punch'] := LData.Punch; end; { TVisMidpoint_Update } function TVisMidpoint_Update.AcceptVisitor: Boolean; begin Result := (Visited is TMidpoint) and (Visited.ObjectState = posUpdate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpoint_Update.Init; begin Query.SQLText := 'Update rts_midpoint Set ' + ' midpoint_name = :midpoint_name ' + ' ,rts_midpoint_list_oid = :rts_midpoint_list_oid ' + ' ,midpoint_value = :midpoint_value ' + ' ,midpoint_punch = :midpoint_punch ' + 'where ' + ' OID = :OID'; end; procedure TVisMidpoint_Update.SetupParams; var LData: TMidpoint; begin LData := Visited as TMidpoint; LData.OID.AssignToTIQuery('OID', Query); LData.Owner.OID.AssignToTIQuery('rts_midopoint_list_oid', Query); Query.ParamAsString['midpoint_name'] := LData.Name; Query.ParamAsFloat['midpoint_value'] := LData.Value; Query.ParamAsInteger['midpoint_punch'] := LData.Punch; end; { TVisMidpoint_Delete } function TVisMidpoint_Delete.AcceptVisitor: Boolean; begin Result := (Visited is TMidpoint) and (Visited.ObjectState = posDelete); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisMidpoint_Delete.Init; begin Query.SQLText := 'delete from rts_midpoint where oid = :oid'; end; procedure TVisMidpoint_Delete.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisRTSQuestion_Read } function TVisRTSQuestion_Read.AcceptVisitor: Boolean; begin Result := (Visited is TRTSQuestionCollection) and (Visited.ObjectState = posEmpty); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisRTSQuestion_Read.Init; begin Query.SQLText := 'select OID, rts_question_name, rts_question_number, rts_midpoint_list_oid from rts_question'; end; procedure TVisRTSQuestion_Read.MapRowToObject; var LData: TRTSQuestion; AssocOID: String; begin LData := TRTSQuestionCollection(Visited).Add; LData.OID.AssignFromTIQuery('OID',Query); LData.Name := Query.FieldAsString['rts_question_name']; LData.Number := Query.FieldAsString['rts_question_number']; //locate association AssocOID := Query.FieldAsString['rts_midpoint_list_oid']; LData.MidpointList := MapRTSQuestionToMidpointList(LData, AssocOID); LData.ObjectState := posClean; end; procedure TVisRTSQuestion_Read.SetupParams; begin // Do nothing end; { TVisRTSQuestion_ReadFromPK } function TVisRTSQuestion_ReadFromPK.AcceptVisitor: Boolean; begin Result := (Visited is TRTSQuestion) and (Visited.ObjectState = posPK); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisRTSQuestion_ReadFromPK.Init; begin Query.SQLText := 'select OID, rts_question_name, rts_question_number, rts_midpoint_list_oid from rts_question' + 'where ' + ' OID = :OID'; end; procedure TVisRTSQuestion_ReadFromPK.MapRowToObject; var LData: TRTSQuestion; AssocOID: String; begin LData := Visited as TRTSQuestion; LData.Name := Query.FieldAsString['rts_question_name']; LData.Number := Query.FieldAsString['rts_question_number']; //locate association AssocOID := Query.FieldAsString['rts_midpoint_list_oid']; LData.MidpointList := MapRTSQuestionToMidpointList(LData, AssocOID); LData.ObjectState := posClean; end; procedure TVisRTSQuestion_ReadFromPK.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; { TVisRTSQuestion_Create } function TVisRTSQuestion_Create.AcceptVisitor: Boolean; begin Result := (Visited is TRTSQuestion) and (Visited.ObjectState = posCreate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisRTSQuestion_Create.Init; begin Query.SQLText := 'Insert into rts_question ( OID, rts_question_name, rts_question_number, rts_midpoint_list_oid ) ' + 'Values ' + '( :OID, :rts_question_name, :rts_question_number, :rts_midpoint_list_oid )'; end; procedure TVisRTSQuestion_Create.SetupParams; var LData: TRTSQuestion; begin LData := Visited as TRTSQuestion; LData.OID.AssignToTIQuery('OID', Query); Query.ParamAsString['rts_question_name'] := LData.Name; Query.ParamAsString['rts_question_number'] := LData.Number; LData.Owner.OID.AssignToTIQuery('rts_midopoint_list_oid', Query); end; { TVisRTSQuestion_Update } function TVisRTSQuestion_Update.AcceptVisitor: Boolean; begin Result := (Visited is TRTSQuestion) and (Visited.ObjectState = posUpdate); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisRTSQuestion_Update.Init; begin Query.SQLText := 'Update rts_question Set ' + ' rts_question_name = :rts_question_name ' + ' rts_question_number = :rts_question_number ' + ' rts_midpoint_list_oid = :rts_midpoint_list_oid ' + 'where ' + ' OID = :OID'; end; procedure TVisRTSQuestion_Update.SetupParams; var LData: TRTSQuestion; begin LData := Visited as TRTSQuestion; LData.OID.AssignToTIQuery('OID', Query); Query.ParamAsString['rts_question_name'] := LData.Name; Query.ParamAsString['rts_question_number'] := LData.Number; LData.Owner.OID.AssignToTIQuery('rts_midopoint_list_oid', Query); end; { TVisRTSQuestion_Delete } function TVisRTSQuestion_Delete.AcceptVisitor: Boolean; begin Result := (Visited is TRTSQuestion) and (Visited.ObjectState = posDelete); Log([ClassName, Visited.ClassName, Visited.ObjectStateAsString, Result]); end; procedure TVisRTSQuestion_Delete.Init; begin Query.SQLText := 'delete from rts_question where oid = :oid'; end; procedure TVisRTSQuestion_Delete.SetupParams; begin TtiObject(Visited).OID.AssignToTIQuery('OID', Query); end; end.
unit Service.Laboratory; interface uses System.SysUtils, System.Classes, REST.Backend.ServiceTypes, REST.Backend.EMSServices, System.JSON, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.EndPoint, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Response.Adapter, FireDAC.Stan.Async, FireDAC.DApt, UDM, UAppSharedUtils; type TsrvServiceLaboratory = class(TDataModule) backEndPointLaboratoryItem: TBackendEndpoint; rRespLaboratoryItem: TRESTResponse; rdsarLaboratoryItem: TRESTResponseDataSetAdapter; tblLaboratoryItem: TFDMemTable; backEndPointLabs: TBackendEndpoint; rRespLabs: TRESTResponse; rdsarLabs: TRESTResponseDataSetAdapter; tblLabs: TFDMemTable; tblLabslab_nid: TIntegerField; tblLabslab_cname: TWideStringField; tblLabslab_cemail: TWideStringField; tblLabslab_cadminid: TWideStringField; tblLabslab_cdbhost: TWideStringField; tblLabslab_cdbname: TWideStringField; tblLabslab_clogin: TWideStringField; tblLabslab_cusername: TWideStringField; tblLabslab_cdbpassword: TWideStringField; tblLabslab_cdbport: TWideStringField; tblLabslab_caccessurl: TWideStringField; backEndPointLabsGet: TBackendEndpoint; rRespLabsGet: TRESTResponse; rdsarLabsGet: TRESTResponseDataSetAdapter; tblLabsGet: TFDMemTable; tblLabsGetlab_nid: TIntegerField; tblLabsGetlab_cname: TWideStringField; tblLaboratoryItemunit_cname: TWideStringField; tblLaboratoryItemunit_ccep: TWideStringField; tblLaboratoryItemunit_ccodcity: TWideStringField; tblLaboratoryItemunit_ccodcity_1: TWideStringField; tblLaboratoryItemunit_nid: TWideStringField; tblLaboratoryItemunit_address: TWideStringField; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } FModule : TDM; public { Public declarations } end; var srvServiceLaboratory: TsrvServiceLaboratory; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} procedure TsrvServiceLaboratory.DataModuleCreate(Sender: TObject); begin if (FModule = nil) then begin FModule := Tdm.Create(nil); end; TAppSharedUtils.SetProvider(TDataModule(Self), FModule.emsLAPProvider); end; procedure TsrvServiceLaboratory.DataModuleDestroy(Sender: TObject); begin FModule.DisposeOf; end; end.
{***************************************************************************} { } { DelphiUIAutomation } { } { Copyright 2015 JHC Systems Limited } { } {***************************************************************************} { } { 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 StringGridRow; interface uses ActiveX, UIAutomationCore_TLB, classes; type TAutomationStringGridRow = class (TInterfacedPersistent, IRawElementProviderSimple, ISelectionItemProvider, IValueProvider, IGridItemProvider) strict private FOwner: TComponent; FValue: string; FRow: integer; FColumn: integer; FSelected : boolean; private procedure SetColumn(const Value: integer); procedure SetRow(const Value: integer); procedure SetTheValue(const Value: string); procedure SetSelected(const Value: boolean); function GetTheValue: string; public property Row : integer read FRow write SetRow; property Column : integer read FColumn write SetColumn; property Value : string read GetTheValue write SetTheValue; property Selected : boolean read FSelected write SetSelected; // IRawElementProviderSimple function Get_ProviderOptions(out pRetVal: ProviderOptions): HResult; stdcall; function GetPatternProvider(patternId: SYSINT; out pRetVal: IUnknown): HResult; stdcall; function GetPropertyValue(propertyId: SYSINT; out pRetVal: OleVariant): HResult; stdcall; function Get_HostRawElementProvider(out pRetVal: IRawElementProviderSimple): HResult; stdcall; // ISelectionItemProvider function Select: HResult; stdcall; function AddToSelection: HResult; stdcall; function RemoveFromSelection: HResult; stdcall; function Get_IsSelected(out pRetVal: Integer): HResult; stdcall; function Get_SelectionContainer(out pRetVal: IRawElementProviderSimple): HResult; stdcall; // IValueProvider function Get_Value(out pRetVal: WideString): HResult; stdcall; function SetValue(val: PWideChar): HResult; stdcall; function Get_IsReadOnly(out pRetVal: Integer): HResult; stdcall; // IGridItemProvider function Get_row(out pRetVal: SYSINT): HResult; stdcall; function Get_column(out pRetVal: SYSINT): HResult; stdcall; function Get_RowSpan(out pRetVal: SYSINT): HResult; stdcall; function Get_ColumnSpan(out pRetVal: SYSINT): HResult; stdcall; function Get_ContainingGrid(out pRetVal: IRawElementProviderSimple): HResult; stdcall; constructor Create(AOwner: TComponent; ACol, ARow : integer; AValue : String);// override; end; implementation uses sysutils; { TAutomationStringGridRow } function TAutomationStringGridRow.AddToSelection: HResult; begin result := (self as ISelectionItemProvider).Select; end; constructor TAutomationStringGridRow.Create(AOwner: TComponent; ACol, ARow : integer; AValue : String); begin inherited create;// (AOwner); FOwner := AOwner; self.Column := ACol; self.Row := ARow; self.Value := AValue; end; function TAutomationStringGridRow.GetPatternProvider(patternId: SYSINT; out pRetVal: IInterface): HResult; begin pRetval := nil; result := S_FALSE; if ((patternID = UIA_SelectionItemPatternId) or (patternID = UIA_GridItemPatternId) or (patternID = UIA_ValuePatternId)) then begin pRetVal := self; result := S_OK; end end; function TAutomationStringGridRow.GetPropertyValue(propertyId: SYSINT; out pRetVal: OleVariant): HResult; begin if(propertyId = UIA_ControlTypePropertyId) then begin TVarData(pRetVal).VType := varWord; TVarData(pRetVal).VWord := UIA_DataItemControlTypeId; result := S_OK; end else if (propertyId = UIA_NamePropertyId) then begin TVarData(pRetVal).VType := varOleStr; TVarData(pRetVal).VOleStr := PWideChar(self.Value); result := S_OK; end else if(propertyId = UIA_ClassNamePropertyId) then begin TVarData(pRetVal).VType := varOleStr; TVarData(pRetVal).VOleStr := pWideChar(self.ClassName); result := S_OK; end else result := S_FALSE; end; function TAutomationStringGridRow.GetTheValue: string; begin result := self.FValue; end; function TAutomationStringGridRow.Get_HostRawElementProvider( out pRetVal: IRawElementProviderSimple): HResult; begin pRetVal := nil; result := S_OK; end; function TAutomationStringGridRow.Get_IsReadOnly( out pRetVal: Integer): HResult; begin pRetVal := 1; result := S_OK; end; function TAutomationStringGridRow.Get_IsSelected( out pRetVal: Integer): HResult; begin result := S_OK; if self.FSelected then pRetVal := 0 else pRetVal := 1; end; function TAutomationStringGridRow.Get_ProviderOptions( out pRetVal: ProviderOptions): HResult; begin pRetVal:= ProviderOptions_ServerSideProvider; Result := S_OK; end; function TAutomationStringGridRow.Get_Value(out pRetVal: WideString): HResult; begin pRetVal := self.FValue; result := S_OK; end; function TAutomationStringGridRow.RemoveFromSelection: HResult; begin result := S_OK; end; function TAutomationStringGridRow.Select: HResult; begin self.FSelected := true; result := S_OK; end; procedure TAutomationStringGridRow.SetColumn(const Value: integer); begin FColumn := Value; end; procedure TAutomationStringGridRow.SetRow(const Value: integer); begin FRow := Value; end; procedure TAutomationStringGridRow.SetSelected(const Value: boolean); begin FSelected := Value; end; function TAutomationStringGridRow.SetValue(val: PWideChar): HResult; begin result := S_OK; self.FValue := val; end; procedure TAutomationStringGridRow.SetTheValue(const Value: string); begin FValue := Value; end; function TAutomationStringGridRow.Get_row(out pRetVal: SYSINT): HResult; begin pRetVal := self.Row; result := S_OK; end; function TAutomationStringGridRow.Get_column(out pRetVal: SYSINT): HResult; begin pRetVal := self.Column; result := S_OK; end; function TAutomationStringGridRow.Get_RowSpan(out pRetVal: SYSINT): HResult; begin pRetVal := 1; result := S_OK; end; function TAutomationStringGridRow.Get_SelectionContainer( out pRetVal: IRawElementProviderSimple): HResult; begin result := S_OK; pRetVal := FOwner as IRawElementProviderSimple; end; function TAutomationStringGridRow.Get_ColumnSpan(out pRetVal: SYSINT): HResult; begin pRetVal := 1; result := S_OK; end; function TAutomationStringGridRow.Get_ContainingGrid(out pRetVal: IRawElementProviderSimple): HResult; begin pRetVal := nil; result := S_OK; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Originally developed and released by Peter Hinrichsen, TechInsite Pty. Ltd. as the tiOPF (TechInsite Object Persistence Framework) 23 Victoria Pde, Collingwood, Melbourne, Victoria 3066 Australia PO Box 429, Abbotsford, Melbourne, Victoria 3067 Australia Phone: +61 3 9419 6456 Fax: +61 3 9419 1682 Latest source: www.techinsite.com.au/tiOPF/Download.htm Documentation: www.techinsite.com.au/tiOPF/Doc/ Support: www.techinsite.com.au/tiOPF/MailingList.htm Please submit changes to tiOPF@techinsite.com.au Revision history: Purpose: ToDo: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$I tiDefines.inc} unit FEditParam; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FtiPerEditDialog, StdCtrls, Buttons, ExtCtrls, tiPerAwareCtrls, tiObject, tiReadOnly, tiFocusPanel; type TFormEditParams = class(TFormTIPerEditDialog) paeParams: TtiPerAwareMemo; paeDescription: TtiPerAwareMemo; paeDisplayText: TtiPerAwareEdit; procedure FormShow(Sender: TObject); private protected procedure SetData(const Value: TtiObject); override ; function FormIsValid : boolean ; override ; public end; var FormEditParams: TFormEditParams; implementation {$R *.DFM} { TFormTIPerEditDialog1 } function TFormEditParams.FormIsValid: boolean; begin result := paeParams.Value <> '' ; end; procedure TFormEditParams.SetData(const Value: TtiObject); begin inherited SetData( Value ) ; paeParams.LinkToData( DataBuffer, 'ParamStr' ) ; paeDescription.LinkToData( DataBuffer, 'Description' ) ; paeDisplayText.LinkToData( DataBuffer, 'DisplayText' ) ; end; procedure TFormEditParams.FormShow(Sender: TObject); begin inherited; paeParams.SetFocus ; end; end.
unit uMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, strutils, Vcl.ExtCtrls, Winapi.ActiveX; const SpotifyExecutable = '\Spotify.exe'; type TStatus = (stUnknown, stFound, stMuted); TMainForm = class(TForm) Timer: TTimer; procedure TimerTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FStatus: TStatus; FSpotifyHandle: THandle; procedure Mute(); procedure Unmute(); { Private declarations } public { Public declarations } property Status: TStatus read FStatus write FStatus; property SpotifyHandle: THandle read FSpotifyHandle write FSpotifyHandle; end; var MainForm: TMainForm; implementation {$R *.dfm} uses uMutify; var AudioEndpoints: IMMDeviceEnumerator; Speakers: IMMDevice; SessionManager: IAudioSessionManager2; GroupingString: string; function ProcessWindows(wHnd: THandle; Form: TMainForm): Bool; stdcall; var WindowName, WindowTitle: array [0 .. 255] of char; msg: string; info: TWindowInfo; begin Result := True; Form.SpotifyHandle := 0; if IsWindow(wHnd) then begin GetClassName(wHnd, WindowName, 255); if (WindowName = 'Chrome_WidgetWin_0') then begin GetWindowText(wHnd, WindowTitle, 255); if (WindowTitle <> '') then begin if (WindowTitle = 'Advertisement') or (WindowTitle = 'Spotify') or (WindowTitle = 'Spotify Free') then begin Form.Status := stFound; Form.SpotifyHandle := wHnd; end; Result := False; end; end; end; end; procedure TMainForm.TimerTimer(Sender: TObject); var CurrentVolume: Single; WindowTitle: array [0 .. 255] of char; begin if IsWindow(FSpotifyHandle) then begin if (FStatus = stMuted) then begin GetWindowText(FSpotifyHandle, WindowTitle, 255); if (WindowTitle <> 'Advertisement') and (WindowTitle <> 'Spotify') and (WindowTitle <> 'Spotify Free') then Unmute; end else begin GetWindowText(FSpotifyHandle, WindowTitle, 255); if (WindowTitle = 'Advertisement') or (WindowTitle = 'Spotify') or (WindowTitle = 'Spotify Free') then Mute(); end; end else begin EnumWindows(@ProcessWindows, LParam(Self)); if (FStatus = stFound) then Mute(); end; end; procedure TMainForm.FormCreate(Sender: TObject); var HR: HResult; begin HR := CoCreateInstance(CLSID_MMDeviceEnumerator, nil, CLSCTX_INPROC_SERVER, IID_IMMDeviceEnumerator, AudioEndpoints); HR := AudioEndpoints.GetDefaultAudioEndpoint(0, 1, Speakers); HR := Speakers.Activate(IID_IAudioSessionManager2, 0, nil, SessionManager); if HR <> S_OK then begin // ShowMessage('Soemthing wrong here'); end; end; procedure TMainForm.Mute; var SessionEnumerator: IAudioSessionEnumerator; SessionCount: integer; SessionControl: IAudioSessionControl; SessionControl2: IAudioSessionControl2; SimpleAudioVolume: ISimpleAudioVolume; SessionName: PWideChar; IconPath: PWideChar; SessionIdentifier: PWideChar; Grouping: TGUID; Context: TGUID; i: integer; begin SessionManager.GetSessionEnumerator(SessionEnumerator); SessionEnumerator.GetCount(SessionCount); Context := GUID_NULL; for i := 0 to SessionCount - 1 do begin SessionEnumerator.GetSession(i, SessionControl); if SessionControl <> nil then begin SessionControl.GetIconPath(IconPath); SessionControl.GetDisplayName(SessionName); SessionControl.GetGroupingParam(Grouping); SessionControl.QueryInterface(IID_IAudioSessionControl2, SessionControl2); SessionControl2.GetSessionInstanceIdentifier(SessionIdentifier); if Pos(SpotifyExecutable, SessionIdentifier) > 0 then begin SessionControl.QueryInterface(IID_ISimpleAudioVolume, SimpleAudioVolume); if SimpleAudioVolume <> nil then begin SimpleAudioVolume.SetMute(True, Context); SimpleAudioVolume := nil; FStatus := stMuted; end; end; CoTaskMemFree(IconPath); CoTaskMemFree(SessionName); CoTaskMemFree(SessionIdentifier); SessionControl2 := nil; SessionControl := nil; end; end; SessionEnumerator := nil; end; procedure TMainForm.Unmute; var SessionEnumerator: IAudioSessionEnumerator; SessionCount: integer; SessionControl: IAudioSessionControl; SessionControl2: IAudioSessionControl2; SimpleAudioVolume: ISimpleAudioVolume; SessionName: PWideChar; IconPath: PWideChar; SessionIdentifier: PWideChar; Grouping: TGUID; Context: TGUID; i: integer; begin // TODO: Unmute Google Chrome in Windows mixer SessionManager.GetSessionEnumerator(SessionEnumerator); SessionEnumerator.GetCount(SessionCount); Context := GUID_NULL; for i := 0 to SessionCount - 1 do begin SessionEnumerator.GetSession(i, SessionControl); if SessionControl <> nil then begin SessionControl.GetIconPath(IconPath); SessionControl.GetDisplayName(SessionName); SessionControl.GetGroupingParam(Grouping); SessionControl.QueryInterface(IID_IAudioSessionControl2, SessionControl2); SessionControl2.GetSessionInstanceIdentifier(SessionIdentifier); if Pos(SpotifyExecutable, SessionIdentifier) > 0 then begin SessionControl.QueryInterface(IID_ISimpleAudioVolume, SimpleAudioVolume); if SimpleAudioVolume <> nil then begin SimpleAudioVolume.SetMute(False, Context); SimpleAudioVolume := nil; FStatus := stUnknown; end; end; CoTaskMemFree(IconPath); CoTaskMemFree(SessionName); CoTaskMemFree(SessionIdentifier); SessionControl2 := nil; SessionControl := nil; end; end; SessionEnumerator := nil; end; procedure TMainForm.FormDestroy(Sender: TObject); begin SessionManager := nil; Speakers := nil; AudioEndpoints := nil; end; end.
unit uMyListBox; interface uses SmartCL.System, SmartCL.Controls.ListBox, SmartCL.Controls.Label; type TMyListBox = class(TW3ListBox) public function GetTextChild(idx: integer): TW3Label; end; implementation function TMyListBox.GetTextChild(idx: integer): TW3Label; begin Result := nil; var item := Items[idx]; for var iChild := 0 to item.GetChildCount - 1 do begin var obj := item.GetChildObject(iChild); if Assigned(obj) and (obj is TW3Label) then Exit(TW3Label(obj)); end; end; end.
unit Frm_Dialogo2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uADStanIntf, uADStanOption, uADStanParam, uADStanError, uADDatSManager, uADPhysIntf, uADDAptIntf, uADStanAsync, uADDAptManager, Data.DB, uADCompDataSet, uADCompClient, uniGUIBaseClasses, uniEdit, uniDBEdit, uniButton, uniBitBtn, uniToolBar, uniPanel, uniLabel, Funciones, Frm_Browse, UniGuiDialogs, Vcl.Forms; type TEstado=(Consultando,Insertando,Modificando,SinEstado); TFrmDialogo2 = class(TUniForm) ADCliente: TADQuery; DSCliente: TDataSource; UniPanelPrincipal: TUniPanel; UniToolBar1: TUniToolBar; UBAceptar: TUniToolButton; UBCancelar: TUniToolButton; UBSalir: TUniToolButton; UniToolButton4: TUniToolButton; UBPrimero: TUniToolButton; UBAnterior: TUniToolButton; UBSiguiente: TUniToolButton; UBUltimo: TUniToolButton; UniToolButton1: TUniToolButton; procedure UniFormClose(Sender: TObject; var Action: TCloseAction); procedure UBPrimeroClick(Sender: TObject); procedure UBAnteriorClick(Sender: TObject); procedure UBSiguienteClick(Sender: TObject); procedure UBAceptarClick(Sender: TObject); procedure UBCancelarClick(Sender: TObject); procedure UniFormCreate(Sender: TObject); procedure UBUltimoClick(Sender: TObject); procedure UBSalirClick(Sender: TObject); procedure UniFormShow(Sender: TObject); procedure UniFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DatasetReconcileError(DataSet: TADDataSet; E: EADException; UpdateKind: TADDatSRowState; var Action: TADDAptReconcileAction); procedure ADClienteAfterGetRecord(DataSet: TADDataSet); procedure UniFormAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); procedure UBAceptarAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); procedure ADClienteAfterInsert(DataSet: TDataSet); private { Private declarations } Detalles:array of TADDataSet; procedure Cancelar; procedure ConfirmacionCancelacion(Sender: Tcomponent;AResult:Integer); procedure SetBrowse(const Value: TFrmBrowse); protected FSeguirAnadiendo:Boolean; FControlDeClave:TUniControl; FMensajeDeClave:string; FBrowse:TFrmBrowse; function Modificado:Boolean; function EstaModificado:Boolean;virtual; function FiltroRegistroActual:String;Virtual; function EjecutarAceptar:Boolean;virtual; procedure ProcesosDespuesdeCancelar; virtual; function ProcesosDespuesdeGrabar(Modo:TUpdateStatus):boolean; virtual; procedure ProcesoDespuesDeLocalizar; virtual; procedure ProcesoAntesDeLocalizar; virtual; function PermitirLocalizar:boolean; virtual; function AntesdeGrabar:boolean; virtual; function CancelacionPersonalizada:boolean; virtual; function AceptacionPersonalizada:boolean; virtual; function LocalizarPorEliminacion:boolean; virtual; procedure MensajeDeClave(mensaje:string); virtual; public { Public declarations } Muestra,AdicionCaption:Boolean; Estado:TEstado; Campo:TField; FCallBack:TProcedimientoH; NombreCampo:String; ComponenteAActualizar:TUniComponent; property Browse:TFrmBrowse read FBrowse write SetBrowse; function Guardar(Localizar:Boolean=True):Boolean; procedure AddListaDetalles(Detalle:TADDataSet); procedure AbrirDetalles; procedure ActualizaDetalles;Virtual; procedure AnulaListaDeDetalles; procedure RefrescaRegistro; end; implementation uses uniGUIApplication, StrUtils; {$R *.dfm} { TFrmDialogo2 } procedure TFrmDialogo2.AbrirDetalles; var i:integer; begin for i := 0 to length(Detalles)-1 do begin if Assigned(Detalles[i].MasterSource) and Assigned(Detalles[i].MasterSource.DataSet) and (not Detalles[i].MasterSource.DataSet.Active) then Detalles[i].MasterSource.DataSet.Open; if Detalles[i].Active then Detalles[i].Close; Detalles[i].Open; end; end; function TFrmDialogo2.AceptacionPersonalizada: boolean; begin Result:=true; end; procedure TFrmDialogo2.ActualizaDetalles; var i:Integer; begin for i:=0 to length(Detalles)-1 do if not Detalles[i].Active then Detalles[i].Open; end; procedure TFrmDialogo2.ADClienteAfterGetRecord(DataSet: TADDataSet); begin ActualizaDetalles; end; procedure TFrmDialogo2.ADClienteAfterInsert(DataSet: TDataSet); begin ActualizaDetalles; end; procedure TFrmDialogo2.DatasetReconcileError(DataSet: TADDataSet; E: EADException; UpdateKind: TADDatSRowState; var Action: TADDAptReconcileAction); var msg:string; clave:boolean; begin clave:=False; if (Pos('DUPLICATE VALUE',UpperCase(E.Message))>0) or (Pos('PRIMARY OR UNIQUE KEY',UpperCase(E.Message))>0) then begin msg:='Está intentando grabar un registro duplicado'; clave:=True; end else if (Pos('AT TRIGGER',UpperCase(E.Message))>0) then msg:='La acción que intenta no se puede ejecutar posiblemente por mantener alguna dependencia sobre otra tabla '+#13+#10+E.Message Else msg:=E.Message; if clave then begin if Assigned(FControlDeClave) then UniGuiDialogs.ShowMessage(msg+#13+#10+FMensajeDeClave, procedure (Sender: Tcomponent;AResult: Integer) begin if FControlDeClave.CanFocus then FControlDeClave.SetFocus; end) Else UniGuiDialogs.ShowMessage(msg); end Else UniGuiDialogs.ShowMessage(msg); Action:=raCorrect; end; procedure TFrmDialogo2.AddListaDetalles(Detalle:TADDataSet); var i:Integer; begin i:=0; while (i<length(Detalles)) and (Detalles[i]<>Detalle) do Inc(i); if i=length(Detalles) then begin SetLength(Detalles,length(Detalles)+1); Detalles[length(Detalles)-1]:=Detalle; Detalles[length(Detalles)-1].OnReconcileError:=DatasetReconcileError; end; end; function TFrmDialogo2.AntesdeGrabar:boolean; begin result:=True; end; procedure TFrmDialogo2.AnulaListaDeDetalles; begin SetLength(Detalles,0); end; function TFrmDialogo2.CancelacionPersonalizada: boolean; begin result:=True; end; procedure TFrmDialogo2.Cancelar; var i:integer; begin for i := 0 to High(Detalles) do if Assigned(Detalles[i]) then begin Detalles[i].Cancel; if Detalles[i].CachedUpdates and (Detalles[i].ChangeCount>0) then Detalles[i].CancelUpdates; end; ADCliente.Cancel; if ADCliente.CachedUpdates and (ADCliente.ChangeCount>0) then ADCliente.CancelUpdates; if assigned(campo) then begin if not (Campo.Dataset.State in dsEditModes) then Campo.Dataset.Edit; Campo.Clear; end; end; procedure TFrmDialogo2.ConfirmacionCancelacion(Sender: Tcomponent;AResult: Integer); begin if AResult=mrYes then begin Cancelar; ProcesosDespuesDeCancelar; Close; end; end; function TFrmDialogo2.EjecutarAceptar: Boolean; begin result:=True; end; function TFrmDialogo2.EstaModificado: Boolean; begin result:=False; end; function TFrmDialogo2.FiltroRegistroActual: String; var i:Integer; begin //Localizamos el registro que acabamos de insertar Result:=''; for i:=0 to ADCliente.Fields.Count-1 do if pfInKey in ADCliente.Fields.Fields[i].ProviderFlags then begin if Result<>'' then Result:=Result+' AND '; if ADCliente.Fields.Fields[i].IsNull then Result:=Result+(ADCliente as IProviderSupport).PSGetTableName+'.'+ADCliente.Fields.Fields[i].FieldName+' IS NULL' else begin Result:=Result+(ADCliente as IProviderSupport).PSGetTableName+'.'+ADCliente.Fields.Fields[i].FieldName+'='; case ADCliente.Fields.Fields[i].DataType of ftString:Result:=Result+QuotedStr(ADCliente.Fields.Fields[i].AsString); ftDate,ftDateTime:Result:=Result+QuotedStr(FormatDateTime('mm/dd/yyyy',ADCliente.Fields.Fields[i].AsDateTime)); ftFloat,ftCurrency,ftFMTBcd:Result:=Result+Replacetext(FloatToStr(ADCliente.Fields.Fields[i].AsFloat),',','.'); else Result:=Result+ADCliente.Fields.Fields[i].AsString; end; end; end; end; function TFrmDialogo2.Guardar(Localizar:Boolean):Boolean; var i:integer; Modo:TUpdateStatus; Filtro:String; begin Result:=AntesDeGrabar; if EstaModificado or (not ADCliente.CachedUpdates) or Modificado then begin if Result then begin //Primero se graba la tabla maestra ADCLiente.CheckBrowseMode; Modo:=ADCliente.UpdateStatus; if ADCliente.CachedUpdates and (ADCliente.ChangeCount>0) then begin result:=ADCliente.ApplyUpdates(0)=0; ADCliente.CommitUpdates; end; if result then begin i:=0; while result and (i<length(Detalles)) do begin Detalles[i].CheckBrowseMode; if Detalles[i].CachedUpdates and (Detalles[i].ChangeCount>0) then begin result:=Detalles[i].ApplyUpdates(0)=0; if result then Detalles[i].CommitUpdates; end; Inc(i); end; if result then begin result:=ProcesosDespuesDeGrabar(Modo); if Localizar and PermitirLocalizar then begin if assigned(FBrowse) and (((EstaModificado or (not (Modo in [usUnmodified,usDeleted]))) and (not ADCliente.CachedUpdates or EstaModificado or (Modo in [usInserted,usModified]))) or LocalizarPorEliminacion) then begin ProcesoAntesDeLocalizar; FBrowse.Localizar(FiltroRegistroActual,True); ProcesoDespuesDeLocalizar; end; end; end; end; end end; if Result and assigned(campo) then begin if not (Campo.Dataset.State in dsEditModes) then Campo.Dataset.Edit; Campo.Value:=ADCliente.FieldByName(NombreCampo).Value; end; if result and assigned(FCallBack) then FCallBack(Campo); end; function TFrmDialogo2.LocalizarPorEliminacion: boolean; begin Result:=False; end; procedure TFrmDialogo2.MensajeDeClave(mensaje: string); begin UniGuiDialogs.ShowMessage(mensaje); end; function TFrmDialogo2.Modificado: Boolean; var i:integer; begin Result:=ADCliente.Modified or (ADCliente.ChangeCount>0); i:=0; while (not result) and (i<length(Detalles)) do begin result:=Assigned(Detalles[i]) and Detalles[i].Active and ((Detalles[i].ChangeCount>0) or Detalles[i].Modified); i:=i+1; end; end; function TFrmDialogo2.PermitirLocalizar: boolean; begin Result:=True; end; procedure TFrmDialogo2.ProcesoAntesDeLocalizar; begin end; procedure TFrmDialogo2.ProcesoDespuesDeLocalizar; begin end; procedure TFrmDialogo2.ProcesosDespuesdeCancelar; begin end; function TFrmDialogo2.ProcesosDespuesdeGrabar(Modo: TUpdateStatus):boolean; begin result:=True; end; procedure TFrmDialogo2.RefrescaRegistro; begin if Assigned(Browse) and Assigned(ADCLiente.MasterSource) then begin ADCliente.MasterSource:=nil; try Browse.Localizar(FiltroRegistroActual); finally ADCLiente.MasterSource:=Browse.DSVista; end; end; ADCliente.Refresh; end; procedure TFrmDialogo2.SetBrowse(const Value: TFrmBrowse); begin FBrowse := Value; end; procedure TFrmDialogo2.UBAceptarAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); begin if SameText(EventName,'FOCUS') then UniSession.AddJS('ajaxRequest('+Self.Name+'.form,''ACEPTAR'',[]);'); end; procedure TFrmDialogo2.UBAceptarClick(Sender: TObject); var aceptarcambios: boolean; begin aceptarcambios:=AceptacionPersonalizada; if aceptarcambios then begin if Guardar then begin if FSeguirAnadiendo then ADCliente.Insert else ModalResult:=mrOk; end; end; end; procedure TFrmDialogo2.UBAnteriorClick(Sender: TObject); begin if Guardar(False) then begin FBrowse.UBAnteriorCLick(Sender); ProcesoAntesDeLocalizar; FBrowse.Localizar(FiltroRegistroActual); ProcesoDespuesDeLocalizar; UBAnterior.SetFocus; end; end; procedure TFrmDialogo2.UBCancelarClick(Sender: TObject); var cancelarcambios: boolean; begin cancelarcambios:=CancelacionPersonalizada; if cancelarcambios then begin if not UBCancelar.Focused then UBCancelar.SetFocus; if not Modificado then Close else Funciones.MessageDlg('¿Abandonar los cambios realizados?',mtConfirmation,mbYesNo,ConfirmacionCancelacion); end; end; procedure TFrmDialogo2.UBPrimeroClick(Sender: TObject); begin if Guardar(False) then begin //Se cierra y se abre el Query ADCliente.Close; try FBrowse.UBPrimeroClick(Sender); ProcesoAntesDeLocalizar; FBrowse.Localizar(FiltroRegistroActual); ProcesoDespuesDeLocalizar; UBPrimero.SetFocus; finally ADCliente.Open; end; end; end; procedure TFrmDialogo2.UBSalirClick(Sender: TObject); begin Close; end; procedure TFrmDialogo2.UBSiguienteClick(Sender: TObject); begin if Guardar(False) then begin FBrowse.UBSiguienteClick(Sender); ProcesoAntesDeLocalizar; FBrowse.Localizar(FiltroRegistroActual); ProcesoDespuesDeLocalizar; UBSiguiente.SetFocus; end; end; procedure TFrmDialogo2.UBUltimoClick(Sender: TObject); begin if Guardar(False) then begin //Se cierra y se abre el Query ADCliente.Close; try FBrowse.UBUltimoClick(Sender); ProcesoAntesDeLocalizar; FBrowse.Localizar(FiltroRegistroActual); ProcesoDespuesDeLocalizar; UBUltimo.SetFocus; finally ADCliente.Open; end; end; end; procedure TFrmDialogo2.UniFormAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); begin if SameText(EventName,'ACEPTAR') then UBAceptarClick(nil) else if SameText(EventName,'SALIR') then end; procedure TFrmDialogo2.UniFormClose(Sender: TObject; var Action: TCloseAction); var i:integer; begin if not Modificado then begin if assigned(FBrowse) then begin FBrowse.Contenedor.Enabled:=True; FBrowse.MiEditor:=nil; end; for i:=0 to Length(Detalles)-1 do Detalles[i].Close; ADCliente.Close; Action:=caFree; end else begin Funciones.MessageDlg('¿Abandonar los cambios realizados?',mtConfirmation,mbYesNo,ConfirmacionCancelacion); Action:=caNone; end; end; procedure TFrmDialogo2.UniFormCreate(Sender: TObject); begin FSeguirAnadiendo:=False; ModalResult:=mrCancel; MonitorizarTeclas(Self,[VK_ESCAPE,VK_RETURN],False); Estado:=SinEstado; end; procedure TFrmDialogo2.UniFormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Enabled then case Key of VK_RETURN:if EjecutarAceptar then begin if UBAceptar.Visible then UniSession.AddJS(UBAceptar.JSName+'.focus();'+#13+ 'ajaxRequest('+UBAceptar.JSName+',''FOCUS'',[]);') else if UBSalir.Visible then UBSalirClick(nil); end; VK_ESCAPE:UBCancelarClick(nil); end; end; procedure TFrmDialogo2.UniFormShow(Sender: TObject); begin if Assigned(FBrowse) then ClientEvents.ExtEvents.Values['window.activate']:='function window.activate(sender, eOpts){'+#13+ ' '+FBrowse.Name+'.window.suspendEvent(''activate'');'+#13+ ' '+Self.Name+'.window.suspendEvent(''activate'');'+#13+ ' try{'+#13+ ' '+FBrowse.Name+'.window.toFront(false);'+#13+ ' '+Self.Name+'.window.toFront(false);'+#13+ ' }finally{'+#13+ ' '+Self.Name+'.window.resumeEvent(''activate'');'+#13+ ' '+FBrowse.Name+'.window.resumeEvent(''activate'');'+#13+ ' }'+#13+ '}'; end; end.
unit IncrustedDatosLineLayer; interface uses GraficoZoom, GR32, Contnrs, Grafico, LinePainter; type TIncrustedDatosLineLayer = class(TIncrustedDatosZoomLayer) private LinePainter: TLinePainter; procedure SetColor(const Value: TColor32); function GetColor: TColor32; protected procedure Paint(Buffer: TBitmap32); override; public constructor Create(const Grafico: TGrafico; const layerBefore: boolean); override; destructor Destroy; override; property Color: TColor32 read GetColor write SetColor; end; implementation uses Tipos; { TIncrustedDatosLineLayer } constructor TIncrustedDatosLineLayer.Create(const Grafico: TGrafico; const layerBefore: boolean); begin inherited; LinePainter := TLinePainter.Create; LinePainter.Datos := DatosLayer; end; destructor TIncrustedDatosLineLayer.Destroy; begin LinePainter.Free; inherited; end; function TIncrustedDatosLineLayer.GetColor: TColor32; begin Result := LinePainter.Color; end; procedure TIncrustedDatosLineLayer.Paint(Buffer: TBitmap32); var iDesde, iHasta: integer; begin if Grafico is TZoomGrafico then begin with TZoomGrafico(Grafico).ZoomInterval do begin iDesde := ZoomFrom; iHasta := ZoomTo; end; end else begin iDesde := 0; iHasta := DatosLayer.DataCount - 1; end; LinePainter.Paint(Buffer, iDesde, iHasta); end; procedure TIncrustedDatosLineLayer.SetColor(const Value: TColor32); begin LinePainter.Color := Value; if PDatosLayer <> nil then Update; end; end.
// "Show Image" // // Earl F. Glynn, April 1998. Updated September 1998. unit ShowImageForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ExtDlgs, ColorLibrary; // TColorPlane type TFormShow = class(TForm) Button1: TButton; ImageBig: TImage; LabelLocation: TLabel; LabelIntensity: TLabel; LabelRGB: TLabel; LabelHSV: TLabel; LabelFilename: TLabel; ImageHistogram: TImage; RadioGroupColorPlane: TRadioGroup; LabelLightness: TLabel; RadioGroupColorSpace: TRadioGroup; ButtonPrint: TButton; LabelAttributes: TLabel; LabelColorPlane: TLabel; SavePictureDialog: TSavePictureDialog; ButtonSave: TButton; LabelCMYK: TLabel; CheckBoxStretch: TCheckBox; LabelHLS: TLabel; LabelYIQ: TLabel; CheckBoxInvert: TCheckBox; CheckBoxMonochrome: TCheckBox; LabelUniqueColors: TLabel; OpenPictureDialog: TOpenPictureDialog; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RadioGroupColorPlaneClick(Sender: TObject); procedure RadioGroupColorSpaceClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ButtonPrintClick(Sender: TObject); procedure ButtonSaveClick(Sender: TObject); procedure ImageBigMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure CheckBoxStretchClick(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure CheckBoxInvertClick(Sender: TObject); private ColorPlane: TColorPlane; PROCEDURE UpdateDisplay (CONST ColorPlane: TColorPlane); public BitmapPrint: TBitmap; BitmapBig : TBitMap; end; var FormShow: TFormShow; implementation {$R *.DFM} uses {$IFDEF GIF} GIFImage, // TGIFImage {$ENDIF} RealColorLibrary, // RGBToHSV GraphicsConversionsLibrary, // LoadGraphicFile HistogramLibrary, // THistogram ImageProcessingPrimitives, // GetBitmapDimensionsString IniFiles, // TIniFile ScreenPrint; CONST KeywordSetup = 'Setup'; KeywordDirectory = 'Directory'; procedure TFormShow.Button1Click(Sender: TObject); VAR Filename: STRING; IniFile : TIniFile; NewPath : STRING; begin IF OpenPictureDialog.Execute THEN BEGIN BitmapBig.Free; BitmapBig := TBitmap.Create; BitmapBig := LoadGraphicsFile(OpenPictureDialog.Filename); // Update INI file for next time Filename := ChangeFileExt(ParamStr(0), '.INI'); NewPath := ExtractFilePath(OpenPictureDialog.Filename); OpenPictureDialog.InitialDir := NewPath; IniFile := TIniFile.Create(Filename); TRY Inifile.WriteString(KeywordSetup, KeywordDirectory, NewPath) FINALLY IniFile.Free END; // Flush INI cache WritePrivateProfileString(NIL, NIL, NIL, pChar(Filename)); LabelFilename.Caption := OpenPictureDialog.Filename; // Update this label before forcing PixelFormat LabelAttributes.Caption := GetBitmapDimensionsString(BitmapBig); // Force to pf24bit if necessary. Make other logic much more simple by // not having to worry aboug various PixelFormats. IF BitmapBig.PixelFormat <> pf24bit THEN BitmapBig.PixelFormat := pf24bit; // Clear old histogram (some of the following may be unnecessary now that // pf24bit is being forced and it's no longer necessary to hide certain // features. ImageHistogram.Visible := TRUE; ImageHistogram.Picture := NIL; RadioGroupColorSpace.ItemIndex := 0; {Select RGB color space} RadioGroupColorSpace.Enabled := TRUE; RadioGroupColorPlane.Enabled := TRUE; ButtonPrint.Enabled := TRUE; FormPrint.ButtonHistograms.Enabled := TRUE; FormPrint.ButtonColorSpaceArray.Enabled := TRUE; RadioGroupColorSpace.Visible := TRUE; RadioGroupColorPlane.Visible := TRUE; UpdateDisplay(cpRGB); LabelUniqueColors.Caption := 'Unique Colors = ' + IntToStr( CountColors(BitmapBig) ); END end; procedure TFormShow.ImageBigMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); VAR CC,MM,YY,KK: INTEGER; // CMYK variables Intensity : INTEGER; Lightness : INTEGER; RGB : TColor; RGBTriple : TRGBTriple; R,G,B : BYTE; H,S,V, L : TReal; xActual : INTEGER; yActual : INTEGER; begin IF CheckBoxStretch.Checked THEN BEGIN xActual := MulDiv(X, BitmapBig.Width, ImageBig.Width); yActual := MulDiv(Y, BitmapBig.Height, ImageBig.Height) END ELSE BEGIN xActual := X; yActual := Y END; // If bitmap is smaller than image area, only show values if inside bitmap. IF (xActual < ImageBig.Picture.Bitmap.Width) AND (yActual < ImageBig.Picture.Bitmap.Height) THEN BEGIN LabelLocation.Caption := '[I, J] = [' + IntToStr(xActual) + ', ' + IntToStr(yActual) + ']'; // Get values from original bitmap, which is not necessarily being displayed // in RGB format. Use Pixels so this will work with pf8bit or pf24bit BMPs. RGB := BitmapBig.Canvas.Pixels[xActual, yActual]; R := GetRValue(RGB); G := GetGValue(RGB); B := GetBValue(RGB); RGBTriple := ColorToRGBTriple(RGB); LabelRGB.Caption := Format('[R, G, B] = [%d, %d, %d] = [%.3f, %.3f, %.3f]', [ R, G, B, R/255, G/255, B/255]); RGBToHSV(GetRValue(RGB) / 255, GetGValue(RGB) / 255, GetBValue(RGB) / 255, H, S, V); LabelHSV.Caption := Format('[H, S, V] = [%.0f, %.0f, %.0f] = [ %.1f, %.3f, %.3f]', [255*H/360, 255*S, 255*V, H, S, V]); RGBToHLS(GetRValue(RGB) / 255, GetGValue(RGB) / 255, GetBValue(RGB) / 255, H, L, S); LabelHLS.Caption := Format('[H, L, S] = [%.0f, %.0f, %.0f] = [ %.1f, %.3f, %.3f]', [255*H/360, 255*L, 255*S, H, L, S]); RGBTripleToCMYK(RGBTriple, CC,MM,YY,KK); LabelCMYK.Caption := Format('[C, M, Y, K] = [%d, %d, %d, %d]', [ CC,MM,YY,KK ]); {// Windows API calls don't seem to work LabelCMYK.Caption := Format('[C, M, Y, K] = [%d, %d, %d, %d]', [ GetCValue(ColorToRGB(RGB)), GetMValue(RGB), GetYValue(RGB), GetKValue(RGB) ]); } Intensity := RGBTripleToIntensity(RGBTriple); LabelIntensity.Caption := Format('Intensity = %d = %.3f', [Intensity, Intensity/255]); Lightness := RGBTripleToLightness(RGBTriple); LabelLightness.Caption := Format('Lightness = %d = %.3f', [Lightness, Lightness/255]); // See [Foley96, pp. 589] LabelYIQ.Caption := Format('[Y, I, Q] = [%.3f, %.3f, %.3f]', [(0.299*R + 0.587*G + 0.114*B) / 255, (0.596*R - 0.275*G - 0.321*B) / 255, (0.212*B - 0.523*G + 0.311*B) / 255 ]) END ELSE BEGIN LabelLocation.Caption := ''; LabelRGB.Caption := ''; LabelHSV.Caption := ''; LabelHLS.Caption := ''; LabelCMYK.Caption := ''; LabelIntensity.Caption := ''; LabelLightness.Caption := ''; LabelYIQ.Caption := ''; END end; procedure TFormShow.FormCreate(Sender: TObject); VAR IniFile : TIniFile; {$IFDEF GIF} s : STRING; {$ENDIF} begin {$IFDEF GIF} s := OpenPictureDialog.Filter + '|GIFs (*.gif)|*.gif'; Insert('*.gif;',s, POS('(',s)+1); // Put GIF in "All" selection Insert('*.gif;',s, POS('|',s)+1); OpenPictureDialog.Filter := s; {$ENDIF} IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.INI')); TRY OpenPictureDialog.InitialDir := Inifile.ReadString(KeywordSetup, KeywordDirectory, ExtractFilePath(ParamStr(0))) FINALLY IniFile.Free END; ImageHistogram.Picture := NIL; // Allocate this bitmap so histograms still work without image present BitmapBig := TBitmap.Create; BitmapBig.Width := ImageBig.Width; BitmapBig.Height := ImageBig.Height; BitmapBig.PixelFormat := pf24bit; ImageBig.Picture.Graphic := BitmapBig; BitmapPrint := TBitmap.Create; BitmapPrint.Width := ImageBig.Width; BitmapPrint.Height := ImageBig.Height; BitmapPrint.PixelFormat := pf24bit; end; procedure TFormShow.RadioGroupColorPlaneClick(Sender: TObject); begin ImageHistogram.Canvas.Brush.Color := clLtGray; // Clear old histogram ImageHistogram.Canvas.FillRect(ImageHistogram.Canvas.ClipRect); ColorPlane := cpIntensity; // avoid compiler warning CASE RadioGroupColorSpace.ItemIndex OF 0: // csRGB BEGIN CASE RadioGroupColorPlane.ItemIndex OF 0: ColorPlane := cpRGB; 1: ColorPlane := cpRed; 2: ColorPlane := cpGreen; 3: ColorPlane := cpBlue END; CheckBoxMonochrome.Visible := TRUE END; 1: // csHSV BEGIN CASE RadioGroupColorPlane.ItemIndex OF 0: ColorPlane := cpHueHSV; 1: ColorPlane := cpSaturationHSV; 2: ColorPlane := cpValue END; CheckBoxMonochrome.Visible := (ColorPlane = cpHueHSV); END; 2: // csHLS BEGIN CASE RadioGroupColorPlane.ItemIndex OF 0: ColorPlane := cpHueHLS; 1: ColorPlane := cpLightness; 2: ColorPlane := cpSaturationHLS; END; CheckBoxMonochrome.Visible := (ColorPlane = cpHueHLS); END; 3: // csCMYK BEGIN CASE RadioGroupColorPlane.ItemIndex OF 0: ColorPlane := cpCyan; 1: ColorPlane := cpMagenta; 2: ColorPlane := cpYellow; 3: ColorPlane := cpBlack; END; CheckBoxMonochrome.Visible := FALSE; END; END; UpdateDisplay (ColorPlane); ButtonSave.Enabled := TRUE end; PROCEDURE TFormShow.UpdateDisplay (CONST ColorPlane: TColorPlane); VAR BitmapProcessed: TBitmap; Histogram : THistogram; BEGIN Screen.Cursor := crHourGlass; TRY LabelColorPlane.Caption := GetColorPlaneString(ColorPlane); Histogram := THistogram.Create; TRY GetHistogram(BitmapBig, ColorPlane, Histogram); DrawHistogram(ColorPlane, Histogram, ImageHistogram.Canvas) FINALLY Histogram.Free END; BitmapProcessed := ExtractImagePlane(ColorPlane, CheckBoxMonochrome.Visible AND NOT CheckBoxMonochrome.Checked, CheckBoxInvert.Checked, BitmapBig); TRY BitmapPrint.Assign(BitmapProcessed); ImageBig.Picture.Graphic := BitmapProcessed; FINALLY BitmapProcessed.Free END FINALLY Screen.Cursor := crDefault END END {UpdateDisplay}; procedure TFormShow.RadioGroupColorSpaceClick(Sender: TObject); begin RadioGroupColorPlane.Items.Clear; CASE RadioGroupColorSpace.ItemIndex OF 0: // RGB BEGIN WITH RadioGroupColorPlane.Items DO BEGIN Add ('RGB Composite'); Add ('Red'); Add ('Green'); Add ('Blue') END END; 1: // HSV BEGIN WITH RadioGroupColorPlane.Items DO BEGIN Add ('Hue'); Add ('Saturation'); Add ('Value') END END; 2: // HLS BEGIN WITH RadioGroupColorPlane.Items DO BEGIN Add ('Hue'); Add ('Lightness'); Add ('Saturation') END END; 3: // CMYK BEGIN WITH RadioGroupColorPlane.Items DO BEGIN Add ('Cyan'); Add ('Magenta'); Add ('Yellow'); Add ('blacK') END END; END; RadioGroupColorPlane.ItemIndex := 0 end; procedure TFormShow.FormDestroy(Sender: TObject); begin BitmapPrint.Free; BitmapBig.Free; end; procedure TFormShow.ButtonPrintClick(Sender: TObject); begin FormPrint.ShowModal end; procedure TFormShow.ButtonSaveClick(Sender: TObject); begin IF SavePictureDialog.Execute THEN BitmapPrint.SaveToFile(SavePictureDialog.Filename) end; procedure TFormShow.CheckBoxStretchClick(Sender: TObject); begin ImageBig.Stretch := CheckBoxStretch.Checked end; // A better way would be to trap CM_MouseLeave of the ImageBig TImage, but // this requires a slightly modified version of a TImage. procedure TFormShow.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin LabelLocation.Caption := ''; LabelRGB.Caption := ''; LabelHSV.Caption := ''; LabelHLS.Caption := ''; LabelCMYK.Caption := ''; LabelIntensity.Caption := ''; LabelLightness.Caption := ''; LabelYIQ.Caption := '' end; procedure TFormShow.CheckBoxInvertClick(Sender: TObject); begin UpdateDisplay (ColorPlane); end; end.
unit ConvertUtils; {********************************************** Kingstar Delphi Library Copyright (C) Kingstar Corporation <Unit>ConvertUtils <What>数据类型转换的函数 <Written By> Huang YanLai (黄燕来) <History> **********************************************} interface uses SysUtils; (****************************** 转换 *******************************) // Bool to String Conversion const BoolStrs : array[boolean] of String[5] = ('false','true'); function BoolToStr(b:boolean):string; // Enums To Flags convert. // Enums likes TSmallSet type TSmallSet = set of 0..(sizeof(LongWord)*8-1); function EnumsToFlags(const Enums; const ConvertTable : array of LongWord): LongWord; // Enum is integer or Enum // TheSet is integer or a samll set function EnumInSet(const Enum,TheSet): boolean; function HexToInt(const s:string): longword; { TextToInt examples : s result 123 123 $12AB 4779 } function TextToInt(const s:string): longword; type TFractionType=(ftRound,ftTrunc); const DigtalStr:array[0..9] of String=('零','壹','贰','叁','肆','伍','陆','柒','捌','玖'); PlusMoneyStr:array[0..6] of String=('元','拾','佰','仟','万','亿','佶'); NegativeMoneyStr:array[0..2] of String=('角','分','厘'); // Function: 大写金额显示 // Written: Zeng ChuangNeng // Date: 2001.8.16 function MoneyToStr(Value: Extended;ShowZero:Boolean=true;Decimals:integer=2;FractionType:TFractionType=ftRound): string; implementation function BoolToStr(b:boolean):string; begin result := BoolStrs[b]; end; function EnumsToFlags(const Enums; const ConvertTable : array of LongWord): LongWord; var i : integer; begin result := 0; for i:=low(ConvertTable) to high(ConvertTable) do if i in TSmallSet(Enums) then result := result or ConvertTable[i]; end; function EnumInSet(const Enum,TheSet): boolean; begin result := Integer(Enum) in TSmallSet(TheSet); end; function HexToInt(const s:string): longword; var i : integer; c : char; dig : longword; begin if length(s)>8 then Raise EConvertError.Create('Hex string is too long.'); result := 0; for i:=1 to length(s) do begin c := UpCase(s[i]); if (c>='0') and (c<='9') then dig:=ord(c)-ord('0') else if (c>='A') and (c<='F') then dig:=ord(c)-ord('A')+10 else Raise EConvertError.Create('Hex string is bad.'); result := (result shl 4) or dig; end; end; function TextToInt(const s:string): longword; begin if s='' then raise EConvertError.Create('Error in : TextToInt'); if s[1]='$' then result:=HexToInt(copy(s,2,length(s)-1)) else result := StrToInt(s); end; function GetNegativeMoneyStr(Value: Extended;ShowZero:Boolean;Decimals:integer;FractionType:TFractionType): string; var i:integer; MonNegative:Int64; s:string; P,Dig:integer; begin s:=''; Value:=Frac(Abs(Value)); if Decimals=0 then begin Result:='整'; exit; end; for i:=1 to Decimals do Value:=Value*10; if FractionType=ftRound then MonNegative:=Round(Value) else MonNegative:=Trunc(Value); if MonNegative=0 then s:='整' else begin P:=Decimals-1; if Decimals>0 then while MonNegative<>0 do begin Dig:=Round(Frac(MonNegative/10)*10); MonNegative:=MonNegative div 10; if Dig>0 then s:=DigtalStr[Dig]+NegativeMoneyStr[P]+s; P:=P-1; end; end; Result:=s; end; function GetStrPos(AStr:string):integer; var i:integer; begin Result:=-1; for i:=0 to High(PlusMoneyStr) do if AStr=PlusMoneyStr[i] then begin Result:=i; Break; end; end; procedure DeleteZero(Var AStr:WideString); var i,sum,m,n:integer; begin i:=1; sum:=Length(AStr); while i<=sum do begin if AStr[i]='0' then begin if AStr[i+1]='元' then Delete(Astr,i,1) else if AStr[i+1]='0' then Delete(Astr,i+1,1) else begin m:=GetStrPos(AStr[i-1]); n:=GetStrPos(AStr[i+1]); if (m<0) or (n<0) then begin i:=i+1; Continue; end; if m<n then Delete(Astr,i,1) else Delete(Astr,i+1,1); end; sum:=sum-1; Continue; end; i:=i+1; end; end; procedure ReplaceDigtal(Var AStr:WideString); var i:integer; MyS:WideString; Cell:string; begin MyS:=''; for i:=1 to Length(Astr) do begin Cell:=Astr[i]; if Length(Cell)=1 then MyS:=MyS+DigtalStr[StrToInt(Cell)] else MyS:=MyS+Cell; end; Astr:=MyS; end; function MoneyToStr(Value: Extended;ShowZero:Boolean=true;Decimals:integer=2;FractionType:TFractionType=ftRound): string; var MonPlus:Int64; s:WideString; Dig:0..9; P:integer; StepStr:string; PStr:integer; PStop:integer; Max:integer; Temp:Extended; begin if Value=0 then begin if ShowZero then Result:='零' else Result:=''; exit; end; Temp:=ABS(Value); if (Decimals=0) and (FractionType=ftRound) then MonPlus:=Round(Temp) else MonPlus:=Trunc(Temp); s:=''; StepStr:='01234'; PStr:=1; PStop:=5; Max:=4; while MonPlus<>0 do begin P:=StrToInt(StepStr[PStr]); Dig:=Round(Frac(MonPlus/10)*10); MonPlus:=MonPlus div 10; s:=IntToStr(Dig)+PlusMoneyStr[P]+s; if PStr=PStop then begin PStop:=2*PStop-1; StepStr:=StepStr+Copy(StepStr,2,Length(StepStr)-2)+IntToStr(Max+1); Max:=Max+1; end; PStr:=PStr+1; end; DeleteZero(s); ReplaceDigtal(s); s:=s+GetNegativeMoneyStr(Value,ShowZero,Decimals,FractionType); if Value<0 then s:='负'+s; Result:=s; end; end.
unit YOTM.Form.Dialog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, YOTM.Form.ModalEdit, Vcl.ExtCtrls, HGM.Button, Vcl.StdCtrls, HGM.Controls.PanelExt; type TFormAnswer = class(TFormModalEdit) LabelQuestion: TLabel; private { Private declarations } public class function GetAnswer(Question:string; NearMouse:Boolean = False):Boolean; class function ShowNeedAction(NeedAction:string; NearMouse:Boolean = False):Boolean; end; var FormAnswer: TFormAnswer; function GetAnswer(Question:string; NearMouse:Boolean = False):Boolean; function ShowNeedAction(NeedAction:string; NearMouse:Boolean = False):Boolean; implementation {$R *.dfm} function GetAnswer(Question:string; NearMouse:Boolean = False):Boolean; begin Result:=TFormAnswer.GetAnswer(Question, NearMouse); end; function ShowNeedAction(NeedAction:string; NearMouse:Boolean = False):Boolean; begin Result:=TFormAnswer.ShowNeedAction(NeedAction, NearMouse); end; { TFormAnswer } class function TFormAnswer.GetAnswer(Question: string; NearMouse:Boolean = False): Boolean; begin with TFormAnswer.Create(nil) do begin Caption:='Вопрос'; LabelQuestion.Caption:=Question; if NearMouse then begin Position:=poDesigned; Left:=Mouse.CursorPos.X - Width div 2; Top:=Mouse.CursorPos.Y - Height div 2; end else Position:=poMainFormCenter; Result:=ShowModal = mrOk; Free; end; end; class function TFormAnswer.ShowNeedAction(NeedAction: string; NearMouse:Boolean = False): Boolean; begin with TFormAnswer.Create(nil) do begin Caption:='Внимание'; LabelQuestion.Caption:=NeedAction; ButtonFlatOK.Caption:='Ок'; ButtonFlatCancel.Hide; if NearMouse then begin Position:=poDesigned; Left:=Mouse.CursorPos.X - Width div 2; Top:=Mouse.CursorPos.Y - Height div 2; end else Position:=poMainFormCenter; ShowModal; Result:=True; Free; end; end; end.
unit ImageMD; { TImageMetaData Auteur : ThWilliam Date : 13 octobre 2007 } interface uses Windows, SysUtils, Classes, Graphics, Controls, jpeg, StdCtrls, Math; type TExifTag = record ID: word; // type de la donnée (ex : $010F = fabricant de l'appareil) Typ: word; // format du type : 2 = Pchar; 3 = Word, 4 = Cardinal... Count: cardinal; //nombre de données du type défini Offset: cardinal; // valeur de la donnée ou Offset vers cette valeur si celle-ci ne peut pas être stockée sur 4 octets end; TExifFileStream = class(TFileStream) private FMotorolaOrder: boolean; FExifStart: cardinal; FNbDirEntries: word; FIfd0Start: cardinal; function ReadString(Count: integer): string; function ReadWord: word; function ReadLong: cardinal; function ReadTag: TExifTag; function HasExif: boolean; function HasThumbNail(var ThumbStart, ThumbLen: cardinal): boolean; function GetThumbNail(ThumbStart, ThumbLen: cardinal; Bitmap: TBitmap): boolean; public constructor Create(const FileName: string; Mode: Word); end; TExifTagItem = record Name: string; Id: word; Typ: word; Count: cardinal; Dir: byte; // 0 = répertoire IFD0, 1 = sous-répertoire de l'IFD0 Value: variant; Value2: variant; end; TExifTagsArray = array[0..17] of TExifTagItem; TImageMetaData = class(Tobject) private FFileStream: TExifFileStream; TagsArray: TExifTagsArray; TagThumb1: TExifTag; TagThumb2: TExifTag; TagThumb3: TExifTag; TagThumb4: TExifTag; TagThumb5: TExifTag; TagSubdir: TExifTag; procedure ReadTagValues(ExifTag: TExifTag); public constructor Create; function ReadExif(FileName: string; ThumbNail: TBitmap): boolean; procedure InitializeTags; function SaveToJpeg(Bitmap: TBitmap; FileName: string; ThumbMaxSize: integer): boolean; procedure DisplayTags(Memo: TMemo); procedure GetExifTag(TagID: word; var Value1, Value2: variant); procedure SetExifTag(TagID: word; Value1, Value2: variant); procedure SetDescription(Value: string); end; const // ceci ne fait que simplifier la manipulation des Tags TagID_Description = $010E; TagID_Maker = $010F; TagID_Model = $0110; TagID_Date = $0132; TagID_Speed = $829A; TagID_Aperture = $829D; TagID_ExpoProgram = $8822; TagID_Iso = $8827; TagID_OriginalDate = $9003; TagID_MeteringMode = $9207; TagID_Focal = $920A; TagID_ImageWidth = $A002; TagID_ImageHeight = $A003; TagID_WhiteBalance = $A403; TagID_Focal35mm = $A405; TagID_Contrast = $A408; TagID_Saturation = $A409; TagID_Sharpness = $A40A; // accentuation TagID_SubDir = $8769; // sous-répertoire de l'IFD0 TagID_ThumbOffset = $0201; // offset vers vignette TagID_ThumbLen = $0202; // taille de la vignette implementation { la procedure SwapBytes est de Florenth. Merci à lui} procedure SwapBytes(var Data; Count: Byte); var B: PByte; E: PByte; T: Byte; begin B := PByte(@Data); E := PByte(Integer(B) + Count - 1); while Integer(B) < Integer(E) do begin T := E^; E^:= B^; B^:= T; Inc(B); Dec(E); end; end; function SwapLong(Value: Cardinal): Cardinal; begin SwapBytes(Value, SizeOf(Cardinal)); Result:= Value; end; function SwapWord(Value: Word): Word; begin SwapBytes(Value, SizeOf(Word)); Result:= Value; end; {TExifFileStream} constructor TExifFileStream.Create(const FileName: string; Mode: Word); begin inherited Create(FileName, Mode); FMotorolaOrder:= false; FNbDirEntries:= 0; FExifStart:= 0; FIfd0Start:= 0; end; function TExifFileStream.ReadString(Count: integer): string; begin SetLength(Result, Count); ReadBuffer(Result[1], Count); end; function TExifFileStream.ReadWord: word; begin ReadBuffer(Result, SizeOf(Result)); if FMotorolaOrder then Result:= SwapWord(Result); end; function TExifFileStream.ReadLong: cardinal; begin ReadBuffer(Result, SizeOf(Result)); if FMotorolaOrder then Result:= SwapLong(Result); end; function TExifFileStream.ReadTag: TExifTag; begin ReadBuffer(Result,SizeOf(Result)); if FMotorolaOrder then with Result do begin ID:= SwapWord(Id); Typ:= SwapWord(Typ); Count:= SwapLong(Count); if Typ = 3 then Offset:= (Offset shr 8) and $FF else Offset:= SwapLong(Offset); end; end; function TExifFileStream.HasExif: boolean; const IOrder: string = #$49#$49#$2A#$00; MOrder: string = #$4D#$4D#$00#$2A; var BufByte: byte; S: string; ExifOffset: cardinal; I: integer; begin Result:= false; if ReadString(2) = #$FF#$D8 then // c'est un fichier Jpeg, commence par $FF$D8 begin // recherche du marqueur Exif APP1 (= $FF$E1) I:= 0; while (I < 5) and (Position < Size - 100) do begin ReadBuffer(BufByte, SizeOf(BufByte)); if BufByte = $FF then begin Inc(I); ReadBuffer(BufByte, SizeOf(BufByte)); if BufByte = $E1 then // on a trouvé le marqueur begin // on saute l'en-tête $45$78$69$66$00$00 + les 2 octets contenant la longueur de la section APP1 Seek(8, soFromCurrent); // lecture de l'alignement S:= ReadString(4); if S = IOrder then FMotorolaOrder:= false else if S = MOrder then FMotorolaOrder:= true else Exit; // mémorise le départ des données Exif : tous les offset sont calculés // à partir de $49 ou $4D FExifStart:= Position -4; // lecture de l'offset vers le répertoire IFD0 (en général = 8) ExifOffset:= ReadLong; Position:= FExifStart + ExifOffset; // lecture du nombre d'entrées de l'IFD0 FNbDirEntries:= ReadWord; Result:= (FNbDirEntries > 0); FIfd0Start:= Position; // départ des entrées de l'IFD0; Exit; end; end; end; end else begin Position:= 0; S:= ReadString(4); if S = IOrder then FMotorolaOrder:= false // fichier TIFF alignement Intel else if S = MOrder then FMotorolaOrder:= true // fichier TIFF alignement Motorola else Exit; ExifOffset:= ReadLong; Position:= ExifOffset; FNbDirEntries:= ReadWord; FExifStart:= 0; Result:= (FNbDirEntries > 0); FIfd0Start:= Position; // départ des entrées de l'IFD0; end; end; function TExifFileStream.HasThumbNail(var ThumbStart, ThumbLen: cardinal): boolean; var ExifTag: TExifTag; Ifd1: cardinal; I: integer; NbEntries: word; begin Result:= false; ThumbStart:= 0; ThumbLen:= 0; try Position:= FIfd0Start + (FNbDirEntries * 12); Ifd1:= ReadLong; //on obtient l'offset de l'IFD1 (répertoire vignette) Position:= FExifStart + Ifd1; NbEntries:= ReadWord; // nombre d'entrées de l'IFD1 for I:= 1 to NbEntries do begin ExifTag:= ReadTag; if ExifTag.Id = TagID_ThumbOffset then ThumbStart:= ExifTag.Offset; if ExifTag.Id = TagID_ThumbLen then ThumbLen:= ExifTag.Offset; if (ThumbStart > 0) and (ThumbLen > 0) then Break; end; if (ThumbStart > 0) and (ThumbLen > 0) then begin ThumbStart:= FExifStart + ThumbStart; Position:= ThumbStart; Result:= (ReadString(2) = #$FF#$D8); // la vignette est au format Jpeg end; except end; end; function TExifFileStream.GetThumbNail(ThumbStart, ThumbLen: cardinal; Bitmap: TBitmap): boolean; var Jpeg: TJpegImage; Stream: TMemoryStream; begin Result:= false; Stream:= TMemoryStream.Create; Jpeg:= TJpegImage.Create; try try Position:= ThumbStart; Stream.CopyFrom(Self, ThumbLen); Stream.Position:= 0; Jpeg.LoadFromStream(Stream); Bitmap.Assign(Jpeg); Result:= true; except end; finally Stream.Free; JPeg.Free; end; end; {TImageMetaData} constructor TImageMetaData.Create; begin inherited Create; // définition des Tags utilisés with TagsArray[0] do begin Name:= 'description'; Id:= TagID_Description; Typ:= 2; Count:= 0; Dir:= 0; end; with TagsArray[1] do begin Name:= 'fabricant'; Id:= TagID_Maker; Typ:= 2; Count:= 0; Dir:= 0; end; with TagsArray[2] do begin Name:= 'modèle'; Id:= TagID_Model; Typ:= 2; Count:= 0; Dir:= 0; end; with TagsArray[3] do begin Name:= 'date'; Id:= TagID_Date; Typ:= 2; Count:= 20; Dir:= 0; end; with TagsArray[4] do begin Name:= 'vitesse'; Id:= TagID_Speed; Typ:= 5; Count:= 1; Dir:= 1; end; with TagsArray[5] do begin Name:= 'ouverture'; Id:= TagID_Aperture; Typ:= 5; Count:= 1; Dir:= 1; end; with TagsArray[6] do begin Name:= 'programme expo'; Id:= TagID_ExpoProgram; Typ:= 3; Count:= 1; Dir:= 1; end; with TagsArray[7] do begin Name:= 'iso'; Id:= TagID_Iso; Typ:= 3; Count:= 1; Dir:= 1; end; with TagsArray[8] do begin Name:= 'date original'; Id:= TagID_OriginalDate; Typ:= 2; Count:= 20; Dir:= 1; end; with TagsArray[9] do begin Name:= 'mesure lumière'; Id:= TagID_MeteringMode; Typ:= 3; Count:= 1; Dir:= 1; end; with TagsArray[10] do begin Name:= 'focale'; Id:= TagID_Focal; Typ:= 5; Count:= 1; Dir:= 1; end; with TagsArray[11] do begin Name:= 'largeur'; Id:= TagID_ImageWidth; Typ:= 4; Count:= 1; Dir:= 1; end; with TagsArray[12] do begin Name:= 'hauteur'; Id:= TagID_ImageHeight; Typ:= 4; Count:= 1; Dir:= 1; end; with TagsArray[13] do begin Name:= 'balance des blancs'; Id:= TagID_WhiteBalance; Typ:= 3; Count:= 1; Dir:= 1; end; with TagsArray[14] do begin Name:= 'focale équivalent 35mm'; Id:= TagID_Focal35mm; Typ:= 3; Count:= 1; Dir:= 1; end; with TagsArray[15] do begin Name:= 'contraste'; Id:= TagID_Contrast; Typ:= 3; Count:= 1; Dir:= 1; end; with TagsArray[16] do begin Name:= 'saturation'; Id:= TagID_Saturation; Typ:= 3; Count:= 1; Dir:= 1; end; with TagsArray[17] do begin Name:= 'accentuation'; Id:= TagID_Sharpness; Typ:= 3; Count:= 1; Dir:= 1; end; // Tags concernant la vignette with TagThumb1 do begin Id:= $0100; Typ:= 4; Count:= 1; end; // largeur vignette with TagThumb2 do begin Id:= $0101; Typ:= 4; Count:= 1; end; // hauteur vignette with TagThumb3 do begin Id:= $0103; Typ:= 3; Count:= 1; end; //compression vignette with TagThumb4 do begin Id:= $0201; Typ:= 4; Count:= 1; end; // offset vers vignette with TagThumb5 do begin Id:= $0202; Typ:= 4; Count:= 1; end; // taille de la vignette with TagSubdir do begin Id:= $8769; Typ:= 4; Count:= 1; end; // Offset du sous-répertoire // initialisation des valeurs des Tags InitializeTags; end; procedure TImageMetaData.InitializeTags; var I: integer; begin for I:= 0 to High(TagsArray) do with TagsArray[I] do begin Value:= ''; Value2:= ''; end; TagThumb1.Offset:= 0; TagThumb2.Offset:= 0; TagThumb3.Offset:= 6; //compression vignette: 6= Jpeg TagThumb4.Offset:= 0; TagThumb5.Offset:= 0; TagSubdir.Offset:= 0; end; procedure TImageMetaData.ReadTagValues(ExifTag: TExifTag); var I: integer; CurPos: Cardinal; begin for I:= 0 to High(TagsArray) do if TagsArray[I].Id = ExifTag.Id then begin case TagsArray[I].Typ of 2: begin CurPos:= FFileStream.Position; FFileStream.Position:= FFileStream.FExifStart + ExifTag.Offset; TagsArray[I].Value:= FFileStream.ReadString(ExifTag.Count); FFileStream.Position:= CurPos; end; 3,4: TagsArray[I].Value:= ExifTag.Offset; 5: begin CurPos:= FFileStream.Position; FFileStream.Position:= FFileStream.FExifStart + ExifTag.Offset; TagsArray[I].Value:= FFileStream.ReadLong; TagsArray[I].Value2:= FFileStream.ReadLong; FFileStream.Position:= CurPos; end; end; Break; end; end; {lecture des données Exif la fonction peut être appelée avec ThumbNail = nil pour ne pas extraire la vignette} function TImageMetaData.ReadExif(FileName: string; ThumbNail: TBitmap): boolean; var Position: Cardinal; I,J: integer; ExifTag: TExifTag; SubDirEntries: word; ThumbStart, ThumbLen: cardinal; begin Result:= false; InitializeTags; FFileStream:= TExifFileStream.Create(FileName, fmOpenRead); try try Result:= FFileStream.HasExif; if Result then begin for I:= 1 to FFileStream.FNbDirEntries do begin ExifTag:= FFileStream.ReadTag; if ExifTag.ID = TagID_SubDir then begin Position:= FFileStream.Position; FFileStream.Position:= FFileStream.FExifStart + ExifTag.Offset; SubDirEntries:= FFileStream.ReadWord; for J:= 1 to SubDirEntries do begin ExifTag:= FFileStream.ReadTag; ReadTagValues(ExifTag); end; FFileStream.Position:= Position; end else ReadTagValues(ExifTag); end; if ThumbNail <> nil then if FFileStream.HasThumbNail(ThumbStart, ThumbLen) then FFileStream.GetThumbNail(ThumbStart, ThumbLen, ThumbNail); end; except end; finally FFileStream.Free; end; end; {Sauvegarde avec données exif Si ThumbMaxSize = 0 , la vignette ne sera pas incorporée} function TImageMetaData.SaveToJpeg(Bitmap: TBitmap; FileName: string; ThumbMaxSize: integer): boolean; const JpegHeader: array[0..19] of byte = ($FF,$D8,$FF,$E1, 0,0, $45,$78,$69,$66,0,0, $49,$49,$2A,0,$08,0,0,0); var F, ImageStream, ThumbStream: TMemoryStream; N: integer; DirEntries, SubDirEntries, LenExif: word; JpegImage: TJpegImage; Ifd1Offset: cardinal; BufLong: cardinal; DirValuesOffset: cardinal; SubDirOffset: cardinal; procedure WriteEntries(Dir: byte); var I: integer; ExifTag: TExifTag; begin for I:= 0 to High(TagsArray) do if (TagsArray[I].Dir = Dir) and (string(TagsArray[I].Value) <> '') then begin ExifTag.Id:= TagsArray[I].Id; ExifTag.Typ:= TagsArray[I].Typ; ExifTag.Count:= TagsArray[I].Count; case TagsArray[I].Typ of 2: begin ExifTag.Count:= Length(string(TagsArray[I].Value)); ExifTag.Offset:= DirValuesOffset; DirValuesOffset:= DirValuesOffset + ExifTag.Count; end; 3,4: ExifTag.Offset:= Cardinal(TagsArray[I].Value); 5: begin ExifTag.Offset:= DirValuesOffset; DirValuesOffset:= DirValuesOffset + 8; end; end; F.WriteBuffer(ExifTag, SizeOf(ExifTag)); end; end; procedure WriteOffsetValues(Dir: byte); // valeurs placées en offset var I: integer; Buf: cardinal; S: string; begin for I:= 0 to High(TagsArray) do if (TagsArray[I].Dir = Dir) and (string(TagsArray[I].Value) <> '') then begin case TagsArray[I].Typ of 2: begin S:= string(TagsArray[I].Value); F.WriteBuffer(S[1], Length(S)); end; 5: begin Buf:= Cardinal(TagsArray[I].Value); F.WriteBuffer(buf,4); Buf:= Cardinal(TagsArray[I].Value2); F.WriteBuffer(Buf,4); end; end; end; end; procedure MakeThumbNail; var ThumbBitmap: TBitmap; ThumbJpeg: TJpegImage; Percent: double; begin ThumbBitmap:= TBitmap.Create; ThumbJpeg:= TJpegImage.Create; ThumbStream:= TMemoryStream.Create; try Percent:= Min(ThumbMaxSize / Bitmap.Width, ThumbMaxSize / Bitmap.Height); with ThumbBitmap do begin Width:= Round(Bitmap.Width * Percent); Height:= Round(Bitmap.Height * Percent); PixelFormat:= Bitmap.PixelFormat; end; SetStretchBltMode(ThumbBitmap.Canvas.Handle, HALFTONE); StretchBlt(ThumbBitmap.Canvas.Handle, 0, 0, ThumbBitmap.Width, ThumbBitmap.Height, Bitmap.Canvas.Handle, 0, 0, Bitmap.Width, Bitmap.Height, SRCCOPY); ThumbJpeg.Assign(ThumbBitmap); ThumbJpeg.SaveToStream(ThumbStream); TagThumb1.Offset:= ThumbBitmap.Width; TagThumb2.Offset:= ThumbBitmap.Height; TagThumb5.Offset:= ThumbStream.Size; finally ThumbBitmap.Free; ThumbJpeg.Free; end; end; begin Result:= false; ThumbStream:= nil; ImageStream:= TMemoryStream.Create; F:= TMemoryStream.Create; JpegImage:= TJpegImage.Create; try try if ThumbMaxSize > 0 then MakeThumbNail; //compte le nb d'entrées du répertoire IFD0 et du sous-répertoire éventuel DirEntries:= 0; SubDirEntries:= 0; SubDirOffset:= 0; for N:= 0 to High(TagsArray) do if string(TagsArray[N].Value) <> '' then if TagsArray[N].Dir = 0 then Inc(DirEntries) else Inc(SubDirEntries); if SubDirEntries > 0 then Inc(DirEntries); if DirEntries = 0 then // il faut au moins une entrée begin SetDescription(' ' + #0); DirEntries:= 1; end; // écriture du header F.WriteBuffer(JpegHeader, sizeof(JpegHeader)); // écriture du nombre d'entrées du répertoire IFD0 F.WriteBuffer(DirEntries, 2); // calcul du départ des valeurs placées en offset DirValuesOffset:= 10 + (DirEntries * 12) + 4; // + 4 pcq on doit stocker le pointeur vers IFD1 // écriture des entrées du répertoire principal IFD0 WriteEntries(0); // écriture de l'entrée pointant sur le sous-répertoire // on mémorise sa position pour corriger par après l'offset if SubDirEntries > 0 then begin F.WriteBuffer(TagSubDir, sizeof(TagSubDir)); SubDirOffset:= F.Position - 4; end; // écriture de l'offset de IFD1 (vignette) // on mémorise sa position pour corriger par après l'offset Ifd1Offset:= F.Position; BufLong:= 1; F.WriteBuffer(BufLong, 4); // écriture des valeurs placées en offset du répertoire principal WriteOffsetValues(0); // sous-répertoire de IFD0 if SubDirEntries > 0 then begin // correction de l'offset du sous-répertoire BufLong:= F.Position - 12; F.Position:= SubDirOffset; F.WriteBuffer(BufLong, SizeOf(BufLong)); F.Position:= BufLong + 12; // écriture du nb d'entrées du sous répertoire F.WriteBuffer(SubDirEntries,2); //calcul du départ des valeurs placées en offset DirValuesOffset:= F.Position - 12 + (SubDirEntries * 12); // écriture des entrées du sous-répertoire de IFD0 WriteEntries(1); // écriture des valeurs placées en offset WriteOffsetValues(1); end; // IFD1 = répertoire vignette if ThumbMaxSize > 0 then begin // correction de l'offset du début d'IFD1 BufLong:= F.Position-12; F.Position:= Ifd1Offset; F.WriteBuffer(BufLong, SizeOf(BufLong)); F.Position:= BufLong + 12; // écriture du nombre d'entrées de l'IFD1 DirEntries:= 5; F.WriteBuffer(DirEntries, SizeOf(DirEntries)); // écriture des tags de IFD1 F.WriteBuffer(TagThumb1, SizeOf(TagThumb1)); F.WriteBuffer(TagThumb2, SizeOf(TagThumb2)); F.WriteBuffer(TagThumb3, SizeOf(TagThumb3)); TagThumb4.Offset:= F.Position + 12; //+12 = -12 (header) + 24: écriture des tagthumb 4 et 5 F.WriteBuffer(TagThumb4, SizeOf(TagThumb4)); F.WriteBuffer(TagThumb5, SizeOf(TagThumb5)); // écriture de la vignette ThumbStream.Position:= 0; F.CopyFrom(ThumbStream, ThumbStream.Size); end; // On est à la fin de l'EXIF, on mémorise sa longeur LenExif:= SwapWord(F.Size - 2); // écriture de l'image principale JpegImage.Assign(Bitmap); JpegImage.SaveToStream(ImageStream); ImageStream.Position:= 0; F.CopyFrom(ImageStream, ImageStream.Size); // correction de la longueur de l'exif F.Position:= 4; F.WriteBuffer(LenExif, SizeOf(LenExif)); // on n'a plus qu'à sauver le fichier F.SaveToFile(FileName); Result:= true; except end; finally if ThumbStream <> nil then ThumbStream.Free; JpegImage.Free; ImageStream.Free; F.Free; end; end; {affiche les données Exif dans un TMemo} procedure TImageMetaData.DisplayTags(Memo: TMemo); var I: integer; D: double; S: string; begin try Memo.Clear; for I:= 0 to High(TagsArray) do if string(TagsArray[I].Value) <> '' then begin S:= ''; case TagsArray[I].Id of TagID_ExpoProgram: case Cardinal(TagsArray[I].Value) of 1: S:= 'manuel'; 2: S:= 'normal'; 3: S:= 'priorité ouverture'; 4: S:= 'priorité vitesse'; 7: S:= 'mode portrait'; 8: S:= 'mode paysage'; else S:= 'inconnu'; end; TagID_MeteringMode: case Cardinal(TagsArray[I].Value) of 1: S:= 'moyenne'; 2: S:= 'moyenne avec prépondérance au centre'; 3: S:= 'spot'; 4: S:= 'multispot'; 5: S:= 'matricielle'; 6: S:= 'partielle'; else S:= 'inconnu'; end; TagID_Speed: S:= IntToStr(TagsArray[I].Value) + '/' + IntToStr(TagsArray[I].Value2); TagID_WhiteBalance: if Cardinal(TagsArray[I].Value) = 0 then S:= 'auto' else S:= 'manuelle'; TagID_Contrast, TagID_Saturation, TagID_Sharpness: case Cardinal(TagsArray[I].Value) of 0: S:= 'normal'; 1: S:= 'adouci'; 2: S:= 'renforcé'; end; end; if S = '' then case TagsArray[I].Typ of 2: S:= string(TagsArray[I].Value); 3,4: S:= IntToStr(cardinal(TagsArray[I].Value)); 5: begin D:= cardinal(TagsArray[I].Value) / cardinal(TagsArray[I].Value2); S:= FloatToStr(D); end; end; S:= TagsArray[I].Name + ': ' + S; Memo.Lines.Add(S); end; except end; end; procedure TImageMetaData.GetExifTag(TagID: word; var Value1, Value2: variant); var I: integer; begin Value1:= ''; Value2:= ''; for I:= 0 to High(TagsArray) do if TagsArray[I].Id = TagID then begin Value1:= TagsArray[I].Value; Value2:= TagsArray[I].Value2; Break; end; end; procedure TImageMetaData.SetExifTag(TagID: word; Value1, Value2: variant); var I: integer; S: string; begin for I:= 0 to High(TagsArray) do if TagsArray[I].Id = TagID then case TagsArray[I].Typ of 2: begin S:= String(Value1); if (S <> '') and (S[Length(S)] <> #0) then S:= S + #0; TagsArray[I].Value:= S; end; else begin TagsArray[I].Value:= Value1; TagsArray[I].Value2:= Value2; end; Break; end; end; procedure TImageMetaData.SetDescription(Value: string); begin SetExifTag(TagID_Description, Value, ''); end; end.
unit BaseOkCancelDialogController; interface uses Classes, SysUtils, Controls, tiObject, mapper, mvc_base, widget_controllers, AppModel, BaseDialogViewFrm, EventsConsts; type // ----------------------------------------------------------------- // Class Objects // ----------------------------------------------------------------- {: Application base controller for dialogs. } TBaseOkCancelDialogController = class(TMVCController) private FModalResult: TModalResult; function GetCancel: boolean; function GetOk: boolean; protected procedure DoAfterInit; override; procedure DoCreateMediators; override; procedure SetActive(const AValue: Boolean); override; procedure HandleOKClick(Sender: TObject); virtual; procedure HandleCancelClick(Sender: TObject); virtual; procedure HandleKeyPress(Sender: TObject; var Key: Char); virtual; public constructor Create(AModel: TMapProject; AView: TBaseDialogView); reintroduce; overload; virtual; destructor Destroy; override; procedure ChangeModel(ANewModel: TObject); override; procedure Update(ASubject: TtiObject); override; procedure Update(ASubject: TtiObject; AOperation: TNotifyOperation); override; function Model: TBaseMapObject; virtual; function View: TBaseDialogView; reintroduce; property Ok: boolean read GetOk; property Cancel: boolean read GetCancel; end; implementation uses vcl_controllers, Forms, Dialogs; { TProjectSettingsController } procedure TBaseOkCancelDialogController.ChangeModel(ANewModel: TObject); begin Model.DetachObserver(Self); inherited; if Assigned(ANewModel) then Model.AttachObserver(Self); end; constructor TBaseOkCancelDialogController.Create(AModel: TMapProject; AView: TBaseDialogView); begin inherited Create(AModel, AView); FModalResult := mrNone; end; destructor TBaseOkCancelDialogController.Destroy; begin if Initialized and (Model <> nil) then Model.DetachObserver(Self); View.Hide; View.Free; inherited; end; procedure TBaseOkCancelDialogController.DoAfterInit; begin inherited; Model.AttachObserver(Self); // Signals observers Model.NotifyObservers; end; procedure TBaseOkCancelDialogController.DoCreateMediators; begin // hook up native event View.btnOK.OnClick := Self.HandleOKClick; View.btnCancel.OnClick := Self.HandleCancelClick; View.OnKeyPress := Self.HandleKeyPress; end; function TBaseOkCancelDialogController.GetCancel: boolean; begin result := FModalResult = mrCancel; end; function TBaseOkCancelDialogController.GetOk: boolean; begin result := FModalResult = mrOk; end; procedure TBaseOkCancelDialogController.HandleCancelClick(Sender: TObject); begin View.ModalResult := mrCancel; end; procedure TBaseOkCancelDialogController.HandleKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then begin View.ModalResult := mrCancel; end; end; procedure TBaseOkCancelDialogController.HandleOKClick(Sender: TObject); begin // Model.NotifyObservers; View.ModalResult := mrOk; end; function TBaseOkCancelDialogController.Model: TBaseMapObject; begin result := inherited Model as TBaseMapObject; end; procedure TBaseOkCancelDialogController.SetActive(const AValue: Boolean); begin inherited; if AValue then FModalResult := View.ShowModal; end; procedure TBaseOkCancelDialogController.Update(ASubject: TtiObject); begin end; procedure TBaseOkCancelDialogController.Update(ASubject: TtiObject; AOperation: TNotifyOperation); begin inherited; end; function TBaseOkCancelDialogController.View: TBaseDialogView; begin Result := inherited View as TBaseDialogView; end; end.
unit UMainFMX; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, System.ImageList, FMX.ImgList, FMX.Objects, FMX.MultiresBitmap, System.Rtti, System.Messaging, FMX.IconFontsImageList, FMX.ListBox, FMX.Colors, FMX.Layouts, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Edit, FMX.EditBox, FMX.SpinBox; type TIconFontImageListForm = class(TForm) NextButton: TButton; BottomPanel: TPanel; edtColor: TColorComboBox; IconFontsImageList: TIconFontsImageList; RandomButton: TButton; IconsLabel: TLabel; CurrentLabel: TLabel; AutoSizeCheckBox: TCheckBox; PrevButton: TButton; ShowEditorButton: TButton; ImageView: TListBox; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; SpinBox1: TSpinBox; ListBoxItem3: TListBoxItem; TopPanel: TPanel; Glyph2: TGlyph; Glyph1: TGlyph; Glyph: TGlyph; procedure FormCreate(Sender: TObject); procedure NextButtonClick(Sender: TObject); procedure edtColorChange(Sender: TObject); procedure RandomButtonClick(Sender: TObject); procedure AutoSizeCheckBoxChange(Sender: TObject); procedure PrevButtonClick(Sender: TObject); procedure ShowEditorButtonClick(Sender: TObject); procedure SpinBox1Change(Sender: TObject); private procedure UpdateGUI; public { Public declarations } end; var IconFontImageListForm: TIconFontImageListForm; implementation uses System.Math , FMX.Consts {$IFDEF MSWINDOWS}, FMX.IconFontsImageListEditorUnit{$ENDIF} ; {$R *.fmx} procedure TIconFontImageListForm.NextButtonClick(Sender: TObject); begin if IconFontsImageList.Count-1 = Glyph.ImageIndex then Glyph.ImageIndex := 0 else Glyph.ImageIndex := Glyph.ImageIndex +1; UpdateGUI; end; procedure TIconFontImageListForm.PrevButtonClick(Sender: TObject); begin if Glyph.ImageIndex = 0 then Glyph.ImageIndex := IconFontsImageList.Count-1 else Glyph.ImageIndex := Glyph.ImageIndex -1; UpdateGUI; end; procedure TIconFontImageListForm.RandomButtonClick(Sender: TObject); var LRand1, LRand2: Integer; LRandomCount: Integer; begin LRandomCount := 100; LRand1 := $F0001+Random(5000); LRand2 := LRand1+LRandomCount-1; //Generate Icons Glyph.ImageIndex := -1; IconFontsImageList.AddIcons(LRand1, LRand2); Glyph.ImageIndex := IconFontsImageList.Count - LRandomCount; UpdateGUI; end; procedure TIconFontImageListForm.ShowEditorButtonClick(Sender: TObject); begin {$IFDEF MSWINDOWS}EditIconFontsImageList(IconFontsImageList);{$ENDIF} end; procedure TIconFontImageListForm.SpinBox1Change(Sender: TObject); begin IconFontsImageList.Size := Round(SpinBox1.Value); end; procedure TIconFontImageListForm.UpdateGUI; begin IconsLabel.Text := Format('Total icons: %d', [IconFontsImageList.Count]); CurrentLabel.Text := Format('Current: %d', [Glyph.ImageIndex]); end; procedure TIconFontImageListForm.AutoSizeCheckBoxChange(Sender: TObject); begin IconFontsImageList.AutoSizeBitmaps := AutoSizeCheckBox.IsChecked; end; procedure TIconFontImageListForm.edtColorChange(Sender: TObject); begin //Change colors of any icons that don't have specific color IconFontsImageList.FontColor := edtColor.Color; //Change colors of any icons with the new color //IconFontsImageList.UpdateIconAttributes(edtColor.Color, True); end; procedure TIconFontImageListForm.FormCreate(Sender: TObject); begin {$IFNDEF MSWINDOWS}ShowEditorButton.Visible := False;{$ENDIF} UpdateGUI; end; initialization {$IFDEF DEBUG} ReportMemoryLeaksOnShutdown := True; {$ENDIF} end.
//Модуль для создания записей о дочерних окнах unit uChild; interface uses Classes, Forms; type TChildActions = ( childFilterPanel, childAdd, childAddPattern, childEdit, childDelete, childRefresh, childToExcel ); //описание для всех MDI Child программы PChildInfo = ^TChildInfo; TChildInfo = record //Bof: boolean; //признак что текущая запись - первая //Eof: boolean; //признак что текущая запись - последняя haFilterPanelOn: boolean; //отображение панели быстрого фильтра haAdd: boolean; //признак возможности дабавлять записи haAddPattern: boolean; //признак возможности дабавлять записи по образцу haEdit: boolean; //признак возможности редактировать записи haDelete: boolean; //признак возможности удалять записи haRefresh: boolean; //признак возможности обновлять записи Actions: array[TChildActions] of TNotifyEvent; end; //создает запись для хранения свойств дочернего окна procedure NewChildInfo(var p: PChildInfo); overload; procedure NewChildInfo(var p: PChildInfo; frm: TForm); overload; implementation procedure NewChildInfo(var p: PChildInfo); var i: TChildActions; begin new(p); for i := low(TChildActions) to high(TChildActions) do p.Actions[i] := nil; end; procedure NewChildInfo(var p: PChildInfo; frm: TForm); begin NewChildInfo(p); frm.Tag := integer(p); end; end.
unit Cliente; interface type TCliente = class private FId: Integer; FNome: String; protected function GetId: Integer; procedure SetId(Value: Integer); function GetNome: String; procedure SetNome(Value: String); public property Id: Integer read GetId write SetId; property Nome: String read GetNome write SetNome; end; implementation { TCliente } function TCliente.GetId: Integer; begin Result := FId; end; function TCliente.GetNome: String; begin Result := FNome; end; procedure TCliente.SetId(Value: Integer); begin FId := Value; end; procedure TCliente.SetNome(Value: String); begin FNome := Value; end; end.
unit ClientAccount; interface uses SysUtils, Classes; type TClientAccount = class public Identity: Variant; constructor Create; virtual; end; TClientAccountClass = class of TClientAccount; TUserAccount = class (TClientAccount) public UserName: String; UserFriendlyName: String; end; TUserAccountClass = class of TUserAccount; TUserRoleAccount = class (TUserAccount) public RoleIdentity: Variant; RoleFriendlyName: String; constructor Create; end; implementation uses Variants; { TClientAccount } constructor TClientAccount.Create; begin inherited; Identity := Null; end; { TUserRoleAccount } constructor TUserRoleAccount.Create; begin inherited; RoleIdentity := Null; end; end.