text
stringlengths
14
6.51M
program fibonacci; var n: integer; procedure fib (a, b, i, n: integer); begin if i < n then begin write (a + b); fib (a + b, a, i + 1, n) end end; begin read (n); fib (0, 1, 0, n) end.
unit Cplx; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math; type Complex = object public // variables re, im: real; // constructor & destructor constructor init(x, y: real); destructor free; // methods function mag: real; function mag2: real; function phs: real; function phsd: real; function conj: complex; procedure print(m, n: integer); procedure println(m, n: integer); end; implementation constructor complex.init(x, y: real); begin re:= x; im:= y; end; destructor complex.free; begin end; // Returns magnitude of the complex number // Domain: any Range: [0; +infty) function complex.mag: real; begin mag:= sqrt(re*re + im*im); end; // Returns magnitude squared // Domain: any Range: [0; +infty) function complex.mag2: real; begin mag2:= re*re + im*im; end; // Returns phase of the complex number in radians // Domain: any Range: (-pi; pi] function complex.phs: real; begin phs:= arctan2(im, re); end; // Returns phase of the complex number in degrees // Domain: any Range: (-180; 180] function complex.phsd: real; begin phsd:= arctan2(im, re)*180/pi; end; // Returns complex conjugate of the complex number // Domain: any Range: any function complex.conj: complex; begin conj.re:= re; conj.im:= -im; end; // Printing complex numbers procedure complex.print(m, n: integer); begin if im >= 0 then write(re:m:n,' + ',abs(im):m:n,'i') else write(re:m:n,' - ',abs(im):m:n,'i'); end; procedure complex.println(m, n: integer); begin if im >= 0 then writeln(re:m:n,' + ',abs(im):m:n,'i') else writeln(re:m:n,' - ',abs(im):m:n,'i'); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, XPMan; type TForm1 = class(TForm) Edit1: TEdit; Button1: TButton; Edit2: TEdit; Edit3: TEdit; Edit4: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Bevel1: TBevel; XPManifest1: TXPManifest; Edit5: TEdit; Label10: TLabel; Edit6: TEdit; Edit7: TEdit; Label6: TLabel; Label7: TLabel; Bevel2: TBevel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; type tColor = (Red, Green, Yellow, Blue); tStr = (Wood, Metall, Cardboard); tCube = record ec: real; color: tColor; material: tStr end; const aColor: array[Red..Blue] of string = ('red','green','yellow','blue'); aStr: array[Wood..Cardboard] of string = ('wood','metall','cardboard'); var Form1: TForm1; x: tCube; f: file of tCube; bColor: array[Red..Blue] of integer; bMaterial: array[Wood..Cardboard] of integer; s:real; i:tColor; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin AssignFile(f, 'f.ini'); Reset(f); for i:=Red to Blue do bColor[i]:=0; s:=0; while (not Eof(f)) do begin Read(f,x); s:=s+x.ec*sqr(x.ec); case x.color of Red: Inc(bColor[Red]); Green: Inc(bColor[Green]); Yellow: Inc(bColor[Yellow]); Blue: Inc(bColor[Blue]); end; case x.material of Wood: if x.ec = 3 then Inc(bMaterial[Wood]); Metall: if x.ec > 5 then Inc(bMaterial[Metall]); end end; CloseFile(f); Edit1.Text:=IntToStr(bColor[Red]); Edit2.Text:=IntToStr(bColor[Green]); Edit3.Text:=IntToStr(bColor[Yellow]); Edit4.Text:=IntToStr(bColor[Blue]); Edit5.Text:=FloatToStrF(s,ffFixed,2,2); Edit6.Text:=IntToStr(bMaterial[Wood]); Edit7.Text:=IntToStr(bMaterial[Metall]); end; procedure TForm1.FormCreate(Sender: TObject); begin Edit1.Clear; Edit2.Clear; Edit3.Clear; Edit4.Clear; Edit5.Clear; Edit6.Clear; Edit7.Clear; end; end.
unit WizMain; interface uses Windows, ToolsAPI, Forms, Dialogs, FrmMain, SysUtils, Graphics; type TMenuIOTATest = class(TNotifierObject, IOTAWIzard, IOTAMenuWizard) public function GetMenuText: string; function GetIDString: string; function GetName: string; function GetState: TWizardState; procedure Execute; end; procedure Register; var PackageTest: IOTAPackageServices; PackageForm: TForm2; implementation procedure Register; begin RegisterPackageWizard(TMenuIOTATest.create as IOTAWizard); end; procedure InitExpert; begin PackageTest := (BorlandIDEServices as IOTAPackageServices); end; procedure DoneExpert; begin { stubbed out } end; { TMenuIOTATest } procedure TMenuIOTATest.Execute; var i: Integer; begin if BorlandIDEServices <> nil then begin PackageForm := TForm2.create(Nil); with PackageForm do {Package information} for i := 0 to PackageTest.GetPackageCount-1 do ListBox1.Items.Add(PackageTest.GetPackageName(i)); PackageForm.ShowModal; PackageForm.Free; end; end; function TMenuIOTATest.GetIDString: string; begin Result := 'PackageInfoMenuId'; end; function TMenuIOTATest.GetMenuText: string; begin Result := 'Packa&ge Info'; end; function TMenuIOTATest.GetName: string; begin Result := 'PackageInfoMenu'; end; function TMenuIOTATest.GetState: TWizardState; begin Result := [wsEnabled]; end; initialization InitExpert; finalization DoneExpert; end.
unit JD.Weather.Services.OnPOINT; interface {$R 'OnPointRes.res' 'OnPointRes.rc'} uses System.SysUtils, System.Classes, System.Generics.Collections, IdHTTP, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, JD.Weather.Intf, JD.Weather.SuperObject; const SVC_CAPTION = 'Weather Source OnPOINT®'; SVC_NAME = 'OnPOINT'; SVC_UID = '{23A3E12A-FB68-4F94-B7AE-53E72915A08F}'; URL_MAIN = 'http://weathersource.com/'; URL_API = 'https://developer.weathersource.com/documentation/rest/'; URL_REGISTER = 'https://developer.weathersource.com/'; URL_LOGIN = 'https://developer.weathersource.com/account/account-login/'; URL_LEGAL = 'https://developer.weathersource.com/documentation/terms-of-use/'; SUP_INFO = [wiConditions, wiForecastHourly, wiForecastDaily]; SUP_LOC = [wlCoords, wlZip]; SUP_UNITS = [wuImperial, wuMetric]; SUP_LOGO = [ltColor, ltColorInvert, ltColorWide, ltColorInvertWide]; SUP_COND_PROP = [wpIcon, wpCaption, wpStation, wpTemp, wpFeelsLike, wpFeelsLikeSun, wpFeelsLikeShade, wpWindDir, wpWindSpeed, wpWindGust, wpWindChill, wpPressure, wpHumidity, wpDewPoint, wpVisibility, wpUVIndex, wpCloudCover, wpPrecipAmt]; SUP_ALERT_TYPE = []; SUP_ALERT_PROP = []; SUP_FOR = [ftHourly, ftDaily]; SUP_FOR_SUM = []; SUP_FOR_HOUR = []; { [fpPressureMB, fpWindSpeed, fpHumidity, fpDewPoint, fpFeelsLike, fpTemp, fpPrecip, fpSnow, fpPrecipChance, fpClouds, fpWetBulb];} SUP_FOR_DAY = []; { [fpPressureMB, fpWindSpeed, fpHumidity, fpDewPoint, fpTempMin, fpTempMax, fpFeelsLike, fpTemp, fpPrecip, fpSnow, fpPrecipChance, fpClouds, fpWetBulb]; SUP_UNITS = [wuImperial, wuMetric];} SUP_MAP = []; SUP_MAP_FOR = []; type TOPEndpoint = (oeForecastDaily, oeForecastHourly, oeHistory); TWeatherSupport = class(TInterfacedObject, IWeatherSupport) public function GetSupportedLogos: TWeatherLogoTypes; function GetSupportedUnits: TWeatherUnitsSet; function GetSupportedInfo: TWeatherInfoTypes; function GetSupportedLocations: TWeatherLocationTypes; function GetSupportedAlerts: TWeatherAlertTypes; function GetSupportedAlertProps: TWeatherAlertProps; function GetSupportedConditionProps: TWeatherPropTypes; function GetSupportedForecasts: TWeatherForecastTypes; function GetSupportedForecastSummaryProps: TWeatherPropTypes; function GetSupportedForecastHourlyProps: TWeatherPropTypes; function GetSupportedForecastDailyProps: TWeatherPropTypes; function GetSupportedMaps: TWeatherMapTypes; function GetSupportedMapFormats: TWeatherMapFormats; property SupportedLogos: TWeatherLogoTypes read GetSupportedLogos; property SupportedUnits: TWeatherUnitsSet read GetSupportedUnits; property SupportedInfo: TWeatherInfoTypes read GetSupportedInfo; property SupportedLocations: TWeatherLocationTypes read GetSupportedLocations; property SupportedAlerts: TWeatherAlertTypes read GetSupportedAlerts; property SupportedAlertProps: TWeatherAlertProps read GetSupportedAlertProps; property SupportedConditionProps: TWeatherPropTypes read GetSupportedConditionProps; property SupportedForecasts: TWeatherForecastTypes read GetSupportedForecasts; property SupportedForecastSummaryProps: TWeatherPropTypes read GetSupportedForecastSummaryProps; property SupportedForecastHourlyProps: TWeatherPropTypes read GetSupportedForecastHourlyProps; property SupportedForecastDailyProps: TWeatherPropTypes read GetSupportedForecastDailyProps; property SupportedMaps: TWeatherMapTypes read GetSupportedMaps; property SupportedMapFormats: TWeatherMapFormats read GetSupportedMapFormats; end; TWeatherURLs = class(TInterfacedObject, IWeatherURLs) public function GetMainURL: WideString; function GetApiURL: WideString; function GetLoginURL: WideString; function GetRegisterURL: WideString; function GetLegalURL: WideString; property MainURL: WideString read GetMainURL; property ApiURL: WideString read GetApiURL; property LoginURL: WideString read GetLoginURL; property RegisterURL: WideString read GetRegisterURL; property LegalURL: WideString read GetLegalURL; end; TWeatherServiceInfo = class(TInterfacedObject, IWeatherServiceInfo) private FSupport: TWeatherSupport; FURLs: TWeatherURLs; FLogos: TLogoArray; procedure SetLogo(const LT: TWeatherLogoType; const Value: IWeatherGraphic); procedure LoadLogos; public constructor Create; destructor Destroy; override; public function GetCaption: WideString; function GetName: WideString; function GetUID: WideString; function GetURLs: IWeatherURLs; function GetSupport: IWeatherSupport; function GetLogo(const LT: TWeatherLogoType): IWeatherGraphic; property Logos[const LT: TWeatherLogoType]: IWeatherGraphic read GetLogo write SetLogo; property Caption: WideString read GetCaption; property Name: WideString read GetName; property UID: WideString read GetUID; property Support: IWeatherSupport read GetSupport; property URLs: IWeatherURLs read GetURLs; end; TWeatherService = class(TWeatherServiceBase, IWeatherService) private FInfo: TWeatherServiceInfo; FSSL: TIdSSLIOHandlerSocketOpenSSL; function GetEndpointUrl(const Endpoint: TOPEndpoint): String; function GetEndpoint(const Endpoint: TOPEndpoint): ISuperObject; function ParseDateTime(const S: String): TDateTime; public constructor Create; override; destructor Destroy; override; public function GetInfo: IWeatherServiceInfo; function GetMultiple(const Info: TWeatherInfoTypes): IWeatherMultiInfo; function GetLocation: IWeatherLocation; function GetConditions: IWeatherProps; function GetAlerts: IWeatherAlerts; function GetForecastSummary: IWeatherForecast; function GetForecastHourly: IWeatherForecast; function GetForecastDaily: IWeatherForecast; function GetMaps: IWeatherMaps; property Info: IWeatherServiceInfo read GetInfo; end; implementation { TWeatherSupport } function TWeatherSupport.GetSupportedUnits: TWeatherUnitsSet; begin Result:= SUP_UNITS; end; function TWeatherSupport.GetSupportedLocations: TWeatherLocationTypes; begin Result:= SUP_LOC; end; function TWeatherSupport.GetSupportedLogos: TWeatherLogoTypes; begin Result:= SUP_LOGO; end; function TWeatherSupport.GetSupportedAlertProps: TWeatherAlertProps; begin Result:= SUP_ALERT_PROP; end; function TWeatherSupport.GetSupportedAlerts: TWeatherAlertTypes; begin Result:= SUP_ALERT_TYPE; end; function TWeatherSupport.GetSupportedConditionProps: TWeatherPropTypes; begin Result:= SUP_COND_PROP; end; function TWeatherSupport.GetSupportedForecasts: TWeatherForecastTypes; begin Result:= SUP_FOR; end; function TWeatherSupport.GetSupportedForecastSummaryProps: TWeatherPropTypes; begin Result:= SUP_FOR_SUM; end; function TWeatherSupport.GetSupportedForecastHourlyProps: TWeatherPropTypes; begin Result:= SUP_FOR_HOUR; end; function TWeatherSupport.GetSupportedForecastDailyProps: TWeatherPropTypes; begin Result:= SUP_FOR_DAY; end; function TWeatherSupport.GetSupportedInfo: TWeatherInfoTypes; begin Result:= SUP_INFO; end; function TWeatherSupport.GetSupportedMaps: TWeatherMapTypes; begin Result:= SUP_MAP; end; function TWeatherSupport.GetSupportedMapFormats: TWeatherMapFormats; begin Result:= SUP_MAP_FOR; end; { TWeatherURLs } function TWeatherURLs.GetApiURL: WideString; begin Result:= URL_API; end; function TWeatherURLs.GetLegalURL: WideString; begin Result:= URL_LEGAL; end; function TWeatherURLs.GetLoginURL: WideString; begin Result:= URL_LOGIN; end; function TWeatherURLs.GetMainURL: WideString; begin Result:= URL_MAIN; end; function TWeatherURLs.GetRegisterURL: WideString; begin Result:= URL_REGISTER; end; { TWeatherServiceInfo } constructor TWeatherServiceInfo.Create; var LT: TWeatherLogoType; begin FSupport:= TWeatherSupport.Create; FSupport._AddRef; FURLs:= TWeatherURLs.Create; FURLs._AddRef; for LT:= Low(TWeatherLogoType) to High(TWeatherLogoType) do begin FLogos[LT]:= TWeatherGraphic.Create; FLogos[LT]._AddRef; end; LoadLogos; end; destructor TWeatherServiceInfo.Destroy; var LT: TWeatherLogoType; begin for LT:= Low(TWeatherLogoType) to High(TWeatherLogoType) do begin FLogos[LT]._Release; end; FURLs._Release; FURLs:= nil; FSupport._Release; FSupport:= nil; inherited; end; function TWeatherServiceInfo.GetCaption: WideString; begin Result:= SVC_CAPTION; end; function TWeatherServiceInfo.GetName: WideString; begin Result:= SVC_NAME; end; function TWeatherServiceInfo.GetSupport: IWeatherSupport; begin Result:= FSupport; end; function TWeatherServiceInfo.GetUID: WideString; begin Result:= SVC_UID; end; function TWeatherServiceInfo.GetURLs: IWeatherURLs; begin Result:= FURLs; end; function TWeatherServiceInfo.GetLogo(const LT: TWeatherLogoType): IWeatherGraphic; begin Result:= FLogos[LT]; end; procedure TWeatherServiceInfo.SetLogo(const LT: TWeatherLogoType; const Value: IWeatherGraphic); begin FLogos[LT].Base64:= Value.Base64; end; procedure TWeatherServiceInfo.LoadLogos; function Get(const N, T: String): IWeatherGraphic; var S: TResourceStream; R: TStringStream; begin Result:= TWeatherGraphic.Create; if ResourceExists(N, T) then begin S:= TResourceStream.Create(HInstance, N, PChar(T)); try R:= TStringStream.Create; try S.Position:= 0; R.LoadFromStream(S); R.Position:= 0; Result.Base64:= R.DataString; finally FreeAndNil(R); end; finally FreeAndNil(S); end; end; end; begin SetLogo(ltColor, Get('LOGO_COLOR', 'PNG')); SetLogo(ltColorInvert, Get('LOGO_COLOR_INVERT', 'PNG')); SetLogo(ltColorWide, Get('LOGO_COLOR_WIDE', 'PNG')); SetLogo(ltColorInvertWide, Get('LOGO_COLOR_INVERT_WIDE', 'PNG')); SetLogo(ltColorLeft, Get('LOGO_COLOR_LEFT', 'PNG')); SetLogo(ltColorRight, Get('LOGO_COLOR_RIGHT', 'PNG')); end; { TWeatherService } constructor TWeatherService.Create; begin inherited; FSSL:= TIdSSLIOHandlerSocketOpenSSL.Create(nil); Web.IOHandler:= FSSL; Web.HandleRedirects:= True; FInfo:= TWeatherServiceInfo.Create; FInfo._AddRef; end; destructor TWeatherService.Destroy; begin FInfo._Release; FInfo:= nil; FSSL.Free; inherited; end; function TWeatherService.GetEndpointUrl(const Endpoint: TOPEndpoint): String; begin case Endpoint of oeForecastDaily: begin case LocationType of wlZip: Result:= 'postal_codes/'+LocationDetail1+',US/forecast.json?period=day'; wlCoords: Result:= 'forecast.json?period=hour&latitude_eq='+ LocationDetail1+'&longitude_eq='+LocationDetail2; end; Result:= Result + '&fields=tempMax,tempAvg,tempMin,precip,precipProb,snowfall,'+ 'snowfallProb,windSpdMax,windSpdAvg,windSpdMin,cldCvrMax,cldCvrAvg,cldCvrMin,'+ 'dewPtMax,dewPtAvg,dewPtMin,feelsLikeMax,feelsLikeAvg,feelsLikeMin,relHumMax,'+ 'relHumAvg,relHumMin,sfcPresMax,sfcPresAvg,sfcPresMin,spcHumMax,spcHumAvg,'+ 'spcHumMin,wetBultMax,wetBulbAvg,wetBulbMin,timestamp'; end; oeForecastHourly: begin case LocationType of wlZip: Result:= 'postal_codes/'+LocationDetail1+',US/forecast.json?period=hour'; wlCoords: Result:= 'forecast.json?period=hour&latitude_eq='+ LocationDetail1+'&longitude_eq='+LocationDetail2; end; Result:= Result + '&fields=temp,precip,precipProb,snowfall,snowfallProb,'+ 'windSpd,windDir,cldCvr,dewPt,feelsLike,relHum,sfcPres,spcHum,wetBulb'; end; oeHistory: begin case LocationType of wlZip: Result:= 'history_by_postal_code.json?period=hour&postal_code_eq='+ LocationDetail1+'&country_eq=US'; wlCoords: Result:= 'history.json?period=hour&latitude_eq='+ LocationDetail1+'&longitude_eq='+LocationDetail2; end; Result:= Result + '&fields=tempMax,tempAvg,tempMin,precip,precipProb,snowfall,'+ 'snowfallProb,windSpdMax,windSpdAvg,windSpdMin,cldCvrMax,cldCvrAvg,cldCvrMin,'+ 'dewPtMax,dewPtAvg,dewPtMin,feelsLikeMax,feelsLikeAvg,feelsLikeMin,relHumMax,'+ 'relHumAvg,relHumMin,sfcPresMax,sfcPresAvg,sfcPresMin,spcHumMax,spcHumAvg,'+ 'spcHumMin,wetBultMax,wetBulbAvg,wetBulbMin,timestamp'; end; end; Result:= 'https://api.weathersource.com/v1/' + Key + '/' + Result; end; function TWeatherService.GetEndpoint(const Endpoint: TOPEndpoint): ISuperObject; var U: String; S: String; begin U:= GetEndpointUrl(Endpoint); S:= Web.Get(U); Result:= SO(S); end; function TWeatherService.GetMultiple(const Info: TWeatherInfoTypes): IWeatherMultiInfo; begin //TODO: Fetch multiple pieces of weather data at once end; function TWeatherService.GetConditions: IWeatherProps; var //O: ISuperObject; R: TWeatherProps; begin R:= TWeatherProps.Create; try //TODO: A WEATHER INFO SERVICE WHICH DOESN'T SUPPORT CURRENT CONDITIONS??!! //I DO NOT COMPREHEND!!! //O:= GetEndpoint(TOPEndpoint.weConditions); //FillConditions(O, R); finally Result:= R; end; end; function TWeatherService.GetAlerts: IWeatherAlerts; begin //NOT SUPPORTED end; function TWeatherService.ParseDateTime(const S: String): TDateTime; begin Result:= 0; //TODO end; function TWeatherService.GetForecastDaily: IWeatherForecast; var O: ISuperObject; A: TSuperArray; F: TWeatherForecast; I: TWeatherProps; X: Integer; begin F:= TWeatherForecast.Create; try O:= GetEndpoint(TOPEndpoint.oeForecastDaily); if Assigned(O) then begin A:= O.AsArray; for X := 0 to A.Length-1 do begin O:= A.O[X]; I:= TWeatherProps.Create; try I.FDateTime:= ParseDateTime(O.S['timestamp']); //TODO: Cloud Cover I.FDewPoint:= O.D['dewPtAvg']; //TODO: Feels Like //TODO: Precipitation I.FHumidity:= O.D['relHumAvg']; I.FPressure:= O.D['sfcPresAvg']; //TODO: Snowfall I.FTempMin:= O.D['tempMin']; I.FTempMax:= O.D['tempMax']; I.FWindSpeed:= O.D['windSpdAvg']; //TODO: Wind Direction (Not Supported???) finally F.FItems.Add(I); end; end; end; finally Result:= F; end; end; function TWeatherService.GetForecastHourly: IWeatherForecast; var O: ISuperObject; F: TWeatherForecast; begin F:= TWeatherForecast.Create; try O:= GetEndpoint(TOPEndpoint.oeForecastHourly); finally Result:= F; end; end; function TWeatherService.GetForecastSummary: IWeatherForecast; begin //NOT SUPPORTED end; function TWeatherService.GetInfo: IWeatherServiceInfo; begin Result:= FInfo; end; function TWeatherService.GetLocation: IWeatherLocation; begin //TODO end; function TWeatherService.GetMaps: IWeatherMaps; begin //NOT SUPPORTED end; end.
(* HashProbing: SWa, modified by MM 2020-03-11 *) (* ------------ *) (* Fun with hashing and linear probing. *) (* ========================================================================= *) UNIT HashProbing; INTERFACE CONST MAX = 5001; TYPE NodePtr = ^Node; Node = RECORD val: STRING; count: INTEGER; del: BOOLEAN; END; (* Node *) HashTable = ARRAY [0 .. MAX - 1] OF NodePtr; PROCEDURE InitHashTable(VAR table: HashTable); PROCEDURE Insert(VAR table: HashTable; val: STRING); FUNCTION GetHighestCount(table: HashTable): NodePtr; FUNCTION Lookup(table: HashTable; val: STRING): INTEGER; IMPLEMENTATION FUNCTION NewNode(val: STRING): NodePtr; VAR n: NodePtr; BEGIN (* NewNode *) New(n); n^.val := val; n^.count := 1; n^.del := FALSE; NewNode := n; END; (* NewNode *) PROCEDURE InitHashTable(VAR table: HashTable); VAR i: INTEGER; BEGIN (* InitHashTable *) FOR i := Low(table) TO High(table) DO BEGIN table[i] := NIL; END; (* FOR *) END; (* InitHashTable *) FUNCTION GetHashCode(val: STRING): INTEGER; var i: INTEGER; h: INTEGER; BEGIN (* GetHashCode *) IF (Length(val) = 0) THEN BEGIN GetHashCode := 0; END ELSE IF (Length(val) = 1) THEN BEGIN GetHashCode := Ord(val[1]) MOD MAX; END ELSE BEGIN h := 0; FOR i := 1 TO Length(val) DO BEGIN h := (h * 256 + Ord(val[i])) MOD MAX; END; (* FOR *) GetHashCode := h; END; (* IF *) END; (* GetHashCode *) PROCEDURE Insert(VAR table: HashTable; val: STRING); VAR hashcode: INTEGER; BEGIN (* Insert *) hashcode := Lookup(table, val); IF hashcode <> -1 THEN BEGIN IF NOT (table[hashcode]^.del) THEN Inc(table[hashcode]^.count); END ELSE BEGIN hashcode := GetHashCode(val); table[hashcode] := NewNode(val); END; (* IF *) END; (* Insert *) FUNCTION Lookup(table: HashTable; val: STRING): INTEGER; VAR hashcode: LONGINT; BEGIN (* Lookup *) hashcode := GetHashCode(val); WHILE ((table[hashcode] <> NIL) AND ((table[hashcode]^.val <> val) OR (table[hashcode]^.del))) DO BEGIN hashcode := (hashcode + 1) MOD MAX; IF (hashcode = GetHashCode(val)) THEN BEGIN WriteLn('ERROR: Hashtable is full'); HALT; END; (* IF *) END; (* WHILE *) IF (table[hashcode] <> NIL) THEN BEGIN Lookup := hashcode; END ELSE BEGIN Lookup := -1; END; (* IF *) END; (* Lookup *) FUNCTION Contains(table: HashTable; val: STRING): BOOLEAN; BEGIN (* Contains *) Contains := Lookup(table, val) <> -1; END; (* Contains *) PROCEDURE Remove(VAR table: HashTable; val: STRING); VAR i: INTEGER; BEGIN (* Remove *) i := Lookup(table, val); IF (i <> -1) THEN BEGIN table[i]^.del := TRUE; END; (* IF *) END; (* Remove *) FUNCTION GetHighestCount(table: HashTable): NodePtr; var highest: NodePtr; i: INTEGER; BEGIN (* GetHighestCount *) highest := table[0]; FOR i := 1 TO (MAX - 1) DO BEGIN IF highest = NIL THEN highest := table[i] ELSE IF table[i] <> NIL THEN BEGIN IF table[i]^.count > highest^.count THEN highest := table[i]; END; (* IF *) END; (* FOR *) GetHighestCount := highest; END; (* GetHighestCount *) BEGIN (* HashChaining *) END. (* HashChaining *)
unit xElecLineBox; interface uses xElecLine, xElecPoint, System.Classes, System.SysUtils; type /// <summary> /// 联合接线盒-电压 /// </summary> TLineBoxVol = class private FIsON: Boolean; FInLineVol: TElecLine; FOutLineVol: TElecLine; FOnChange: TNotifyEvent; procedure SetIsON(const Value: Boolean); procedure OnOffChange(Sender : TObject); public constructor Create; destructor Destroy; override; /// <summary> /// 进线 /// </summary> property InLineVol : TElecLine read FInLineVol write FInLineVol; /// <summary> /// 出线 /// </summary> property OutLineVol : TElecLine read FOutLineVol write FOutLineVol; /// <summary> /// 进线出线是否连接 /// </summary> property IsON : Boolean read FIsON write SetIsON; /// <summary> /// 改变事件 /// </summary> property OnChange : TNotifyEvent read FOnChange write FOnChange; public /// <summary> /// 清空电压值 /// </summary> procedure ClearVolVlaue; /// <summary> /// 清除权值 /// </summary> procedure ClearWValue; /// <summary> /// 清空电流列表 /// </summary> procedure ClearCurrentList; end; type /// <summary> /// 联合接线盒-电流 /// </summary> TLineBoxCurrent = class private FIsLine23On: Boolean; FIsLine12On: Boolean; FOutLineCurrent2: TElecLine; FOutLineCurrent3: TElecLine; FOutLineCurrent1: TElecLine; FInLineCurrent2: TElecLine; FInLineCurrent3: TElecLine; FInLineCurrent1: TElecLine; FOnChange: TNotifyEvent; procedure SetIsLine12On(const Value: Boolean); procedure SetIsLine23On(const Value: Boolean); procedure OnOffChange(Sender : TObject); public constructor Create; destructor Destroy; override; /// <summary> /// 进线1 /// </summary> property InLineCurrent1 : TElecLine read FInLineCurrent1 write FInLineCurrent1; /// <summary> /// 进线2 /// </summary> property InLineCurrent2 : TElecLine read FInLineCurrent2 write FInLineCurrent2; /// <summary> /// 进线3 /// </summary> property InLineCurrent3 : TElecLine read FInLineCurrent3 write FInLineCurrent3; /// <summary> /// 出线1 /// </summary> property OutLineCurrent1 : TElecLine read FOutLineCurrent1 write FOutLineCurrent1; /// <summary> /// 出线2 /// </summary> property OutLineCurrent2 : TElecLine read FOutLineCurrent2 write FOutLineCurrent2; /// <summary> /// 出线2 /// </summary> property OutLineCurrent3 : TElecLine read FOutLineCurrent3 write FOutLineCurrent3; /// <summary> /// 线路1和线路2是否闭合 /// </summary> property IsLine12On : Boolean read FIsLine12On write SetIsLine12On; /// <summary> /// 线路2和线路3是否闭合 /// </summary> property IsLine23On : Boolean read FIsLine23On write SetIsLine23On; /// <summary> /// 改变事件 /// </summary> property OnChange : TNotifyEvent read FOnChange write FOnChange; public /// <summary> /// 清空电压值 /// </summary> procedure ClearVolVlaue; /// <summary> /// 清除权值 /// </summary> procedure ClearWValue; /// <summary> /// 清空电流列表 /// </summary> procedure ClearCurrentList; end; type /// <summary> /// 联合接线盒 /// </summary> TElecLineBox = class private FLineBoxName: string; FBoxUA: TLineBoxVol; FBoxUB: TLineBoxVol; FBoxUC: TLineBoxVol; FBoxUN: TLineBoxVol; FBoxIA: TLineBoxCurrent; FBoxIB: TLineBoxCurrent; FBoxIC: TLineBoxCurrent; FOnChange: TNotifyEvent; procedure OnOffChange(Sender : TObject); public constructor Create; destructor Destroy; override; /// <summary> /// 联合接线盒名称 /// </summary> property LineBoxName : string read FLineBoxName write FLineBoxName; /// <summary> /// A相电压 /// </summary> property BoxUA : TLineBoxVol read FBoxUA write FBoxUA; /// <summary> /// B相电压 /// </summary> property BoxUB : TLineBoxVol read FBoxUB write FBoxUB; /// <summary> /// C相电压 /// </summary> property BoxUC : TLineBoxVol read FBoxUC write FBoxUC; /// <summary> /// N相电压 /// </summary> property BoxUN : TLineBoxVol read FBoxUN write FBoxUN; /// <summary> /// A相电流 /// </summary> property BoxIA : TLineBoxCurrent read FBoxIA write FBoxIA; /// <summary> /// B相电流 /// </summary> property BoxIB : TLineBoxCurrent read FBoxIB write FBoxIB; /// <summary> /// C相电流 /// </summary> property BoxIC : TLineBoxCurrent read FBoxIC write FBoxIC; /// <summary> /// 改变事件 /// </summary> property OnChange : TNotifyEvent read FOnChange write FOnChange; public /// <summary> /// 清空电压值 /// </summary> procedure ClearVolVlaue; /// <summary> /// 清除权值 /// </summary> procedure ClearWValue; /// <summary> /// 清空电流列表 /// </summary> procedure ClearCurrentList; end; implementation { TLineBoxVol } procedure TLineBoxVol.ClearCurrentList; begin FInLineVol.ClearCurrentList; FOutLineVol.ClearCurrentList; end; procedure TLineBoxVol.ClearVolVlaue; begin end; procedure TLineBoxVol.ClearWValue; begin FInLineVol.ClearWValue; FOutLineVol.ClearWValue; end; constructor TLineBoxVol.Create; begin FInLineVol:= TElecLine.Create; FOutLineVol:= TElecLine.Create; FInLineVol.ConnPointAdd(FOutLineVol); FIsON:= True; end; destructor TLineBoxVol.Destroy; begin FInLineVol.Free; FOutLineVol.Free; inherited; end; procedure TLineBoxVol.OnOffChange(Sender: TObject); begin if Assigned(FOnChange) then begin FOnChange(Sender); if FIsON then begin FInLineVol.ConnPointAdd(FOutLineVol); FInLineVol.SendVolValue; end else begin FInLineVol.ConnPointDel(FOutLineVol); FOutLineVol.Voltage.Value := 0; FOutLineVol.SendVolValue; end; end; end; procedure TLineBoxVol.SetIsON(const Value: Boolean); begin if FIsON <> Value then begin FIsON := Value; OnOffChange(Self); end; end; { TLineBoxCurrent } procedure TLineBoxCurrent.ClearCurrentList; begin FOutLineCurrent1.ClearCurrentList; FOutLineCurrent2.ClearCurrentList; FOutLineCurrent3.ClearCurrentList; FInLineCurrent1.ClearCurrentList; FInLineCurrent2.ClearCurrentList; FInLineCurrent3.ClearCurrentList; end; procedure TLineBoxCurrent.ClearVolVlaue; begin end; procedure TLineBoxCurrent.ClearWValue; begin FOutLineCurrent1.ClearWValue; FOutLineCurrent2.ClearWValue; FOutLineCurrent3.ClearWValue; FInLineCurrent1.ClearWValue; FInLineCurrent2.ClearWValue; FInLineCurrent3.ClearWValue; end; constructor TLineBoxCurrent.Create; begin FOutLineCurrent1:= TElecLine.Create; FOutLineCurrent2:= TElecLine.Create; FOutLineCurrent3:= TElecLine.Create; FInLineCurrent1:= TElecLine.Create; FInLineCurrent2:= TElecLine.Create; FInLineCurrent3:= TElecLine.Create; FOutLineCurrent1.ConnPointAdd(FInLineCurrent1); FOutLineCurrent2.ConnPointAdd(FInLineCurrent2); FOutLineCurrent3.ConnPointAdd(FInLineCurrent3); FIsLine12On:= False; FIsLine23On:= True; FInLineCurrent2.ConnPointAdd(FOutLineCurrent3); end; destructor TLineBoxCurrent.Destroy; begin FOutLineCurrent1.Free; FOutLineCurrent2.Free; FOutLineCurrent3.Free; FInLineCurrent1.Free; FInLineCurrent2.Free; FInLineCurrent3.Free; inherited; end; procedure TLineBoxCurrent.OnOffChange(Sender: TObject); begin if Assigned(FOnChange) then begin FOnChange(Sender); end; end; procedure TLineBoxCurrent.SetIsLine12On(const Value: Boolean); begin if FIsLine12On <> Value then begin FIsLine12On := Value; OnOffChange(Self); end; end; procedure TLineBoxCurrent.SetIsLine23On(const Value: Boolean); begin if FIsLine23On <> Value then begin FIsLine23On := Value; OnOffChange(Self); end; end; { TElecLineBox } procedure TElecLineBox.ClearCurrentList; begin FBoxUA.ClearCurrentList; FBoxUB.ClearCurrentList; FBoxUC.ClearCurrentList; FBoxUN.ClearCurrentList; FBoxIA.ClearCurrentList; FBoxIB.ClearCurrentList; FBoxIC.ClearCurrentList; end; procedure TElecLineBox.ClearVolVlaue; begin end; procedure TElecLineBox.ClearWValue; begin FBoxUA.ClearWValue; FBoxUB.ClearWValue; FBoxUC.ClearWValue; FBoxUN.ClearWValue; FBoxIA.ClearWValue; FBoxIB.ClearWValue; FBoxIC.ClearWValue; end; constructor TElecLineBox.Create; begin FLineBoxName:= '联合接线盒'; FBoxUA:= TLineBoxVol.Create; FBoxUB:= TLineBoxVol.Create; FBoxUC:= TLineBoxVol.Create; FBoxUN:= TLineBoxVol.Create; FBoxIA:= TLineBoxCurrent.Create; FBoxIB:= TLineBoxCurrent.Create; FBoxIC:= TLineBoxCurrent.Create; FBoxUA.OnChange := OnOffChange; FBoxUB.OnChange := OnOffChange; FBoxUC.OnChange := OnOffChange; FBoxUN.OnChange := OnOffChange; FBoxIA.OnChange := OnOffChange; FBoxIB.OnChange := OnOffChange; FBoxIC.OnChange := OnOffChange; FBoxUA.InLineVol.LineName := '联合接线盒UA进线'; FBoxUB.InLineVol.LineName := '联合接线盒UB进线'; FBoxUC.InLineVol.LineName := '联合接线盒UC进线'; FBoxUN.InLineVol.LineName := '联合接线盒UN进线'; FBoxUA.OutLineVol.LineName := '联合接线盒UA出线'; FBoxUB.OutLineVol.LineName := '联合接线盒UB出线'; FBoxUC.OutLineVol.LineName := '联合接线盒UC出线'; FBoxUN.OutLineVol.LineName := '联合接线盒UN出线'; FBoxIA.InLineCurrent1.LineName := '联合接线盒IA进线1'; FBoxIA.InLineCurrent2.LineName := '联合接线盒IA进线2'; FBoxIA.InLineCurrent3.LineName := '联合接线盒IA进线3'; FBoxIB.InLineCurrent1.LineName := '联合接线盒IB进线1'; FBoxIB.InLineCurrent2.LineName := '联合接线盒IB进线2'; FBoxIB.InLineCurrent3.LineName := '联合接线盒IB进线3'; FBoxIC.InLineCurrent1.LineName := '联合接线盒IC进线1'; FBoxIC.InLineCurrent2.LineName := '联合接线盒IC进线2'; FBoxIC.InLineCurrent3.LineName := '联合接线盒IC进线3'; FBoxIA.OutLineCurrent1.LineName := '联合接线盒IA出线1'; FBoxIA.OutLineCurrent2.LineName := '联合接线盒IA出线2'; FBoxIA.OutLineCurrent3.LineName := '联合接线盒IA出线3'; FBoxIB.OutLineCurrent1.LineName := '联合接线盒IB出线1'; FBoxIB.OutLineCurrent2.LineName := '联合接线盒IB出线2'; FBoxIB.OutLineCurrent3.LineName := '联合接线盒IB出线3'; FBoxIC.OutLineCurrent1.LineName := '联合接线盒IC出线1'; FBoxIC.OutLineCurrent2.LineName := '联合接线盒IC出线2'; FBoxIC.OutLineCurrent3.LineName := '联合接线盒IC出线3'; end; destructor TElecLineBox.Destroy; begin FBoxUA.Free; FBoxUB.Free; FBoxUC.Free; FBoxUN.Free; FBoxIA.Free; FBoxIB.Free; FBoxIC.Free; inherited; end; procedure TElecLineBox.OnOffChange(Sender: TObject); begin if Assigned(FOnChange) then begin FOnChange(Self); end; end; end.
unit UI.FontGlyphs.Android; interface uses FMX.FontGlyphs, FMX.FontGlyphs.Android, Androidapi.JNI.GraphicsContentViewText; type TAndroidFontGlyphManagerFMXUI = class(TAndroidFontGlyphManager) protected procedure LoadResource; override; end; implementation uses UI.Base, System.IOUtils, System.Types, System.Math, System.Character, System.Generics.Collections, System.UIConsts, System.UITypes, System.Classes, System.SysUtils, FMX.Types, FMX.Surfaces, FMX.Graphics, Androidapi.JNI.JavaTypes, Androidapi.Bitmap, Androidapi.JNIBridge, Androidapi.Helpers; { TAndroidFontGlyphManagerFMXUI } procedure TAndroidFontGlyphManagerFMXUI.LoadResource; var TypefaceFlag: Integer; Typeface: JTypeface; FamilyName: JString; Metrics: JPaint_FontMetricsInt; FPaint: JPaint; FontFile: string; begin FPaint := TView.GetRttiValue<JPaint>(Self, 'FPaint'); FPaint.setAntiAlias(True); FPaint.setTextSize(CurrentSettings.Size * CurrentSettings.Scale); FPaint.setARGB(255, 255, 255, 255); if TOSVersion.Check(4, 0) then FPaint.setHinting(TJPaint.JavaClass.HINTING_ON); //Font try FamilyName := StringToJString(CurrentSettings.Family); {$IF CompilerVersion > 30} if not CurrentSettings.Style.Slant.IsRegular and not CurrentSettings.Style.Weight.IsRegular then TypefaceFlag := TJTypeface.JavaClass.BOLD_ITALIC else if not CurrentSettings.Style.Weight.IsRegular then TypefaceFlag := TJTypeface.JavaClass.BOLD else if not CurrentSettings.Style.Slant.IsRegular then TypefaceFlag := TJTypeface.JavaClass.ITALIC else TypefaceFlag := TJTypeface.JavaClass.NORMAL; {$ELSE} if (TFontStyle.fsBold in CurrentSettings.Style) and (TFontStyle.fsItalic in CurrentSettings.Style) then TypefaceFlag := TJTypeface.JavaClass.BOLD_ITALIC else if (TFontStyle.fsBold in CurrentSettings.Style) then TypefaceFlag := TJTypeface.JavaClass.BOLD else if (TFontStyle.fsItalic in CurrentSettings.Style) then TypefaceFlag := TJTypeface.JavaClass.ITALIC else TypefaceFlag := TJTypeface.JavaClass.NORMAL; {$ENDIF} FontFile := TPath.GetDocumentsPath + PathDelim + CurrentSettings.Family + '.ttf'; if FileExists(FontFile) then Typeface := TJTypeface.JavaClass.createFromFile(StringToJString(FontFile)) else Typeface := TJTypeface.JavaClass.Create(FamilyName, TypefaceFlag); FPaint.setTypeface(Typeface); try Metrics := FPaint.getFontMetricsInt; // TView.SetRttiValue<Integer>(Self, 'FTop', Metrics.top); TView.SetRttiValue<Integer>(Self, 'FAscent', Metrics.ascent); TView.SetRttiValue<Integer>(Self, 'FDescent', Metrics.descent); TView.SetRttiValue<Integer>(Self, 'FBottom', Metrics.bottom); TView.SetRttiValue<Integer>(Self, 'FLeading', Metrics.leading); { FTop := Metrics.top; FAscent := Metrics.ascent; FDescent := Metrics.descent; FBottom := Metrics.bottom; FLeading := Metrics.leading; } finally Metrics := nil; end; finally FamilyName := nil; Typeface := nil; end; end; end.
unit CONFIG_RESTAURANTE; interface uses Classes, DB, SysUtils, Generics.Collections, ormbr.mapping.attributes, ormbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, ormbr.mapping.register; type [Entity] [Table('CONFIG_RESTAURANTE','')] [PrimaryKey('ID', AutoInc, NoSort, True, 'Chave primária')] TCONFIG_RESTAURANTE = class private FOBS: String; FID: Integer; FMESA: Integer; fPedidoAberto: String; { Private declarations } public { Public declarations } [Restrictions([NoUpdate, NotNull])] [Column('ID', ftInteger)] [Dictionary('ID','Mensagem de validação','','','',taCenter)] property id: Integer read FID write FID; [Column('MESA', ftInteger)] //[Dictionary('MESA','Mensagem de validação','','','',taLeftJustify)] property MESA: Integer read FMESA write FMESA; [Column('OBS', ftString, 200)] //[Dictionary('OBS','Mensagem de validação','','','',taLeftJustify)] property OBS:String read FOBS write FOBS; property PedidoAberto:String read fPedidoAberto write fPedidoAberto; end; implementation { TCONFIG_RESTAURANTE } initialization TRegisterClass.RegisterEntity(TCONFIG_RESTAURANTE); end.
unit LazUTF8; { LLCL - FPC/Lazarus Light LCL based upon LVCL - Very LIGHT VCL ---------------------------- This file is a part of the Light LCL (LLCL). This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. Copyright (c) 2015-2016 ChrisF Based upon the Very LIGHT VCL (LVCL): Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr Version 1.02: Version 1.01: * UTF8CompareStr, UTF8CompareText, UTF8LowerCase and UTF8UpperCase added Version 1.00: * File creation. * Some UTF8 functions (not present in LazFileUtils) Notes: - specific to FPC/Lazarus (not used with Delphi). } {$IFDEF FPC} {$define LLCL_FPC_MODESECTION} {$I LLCLFPCInc.inc} // For mode {$undef LLCL_FPC_MODESECTION} {$ENDIF} {$I LLCLOptions.inc} // Options //------------------------------------------------------------------------------ interface function SysErrorMessageUTF8(ErrorCode: integer): string; {$IFDEF UNICODE} function UTF8ToSys(const S: utf8string): ansistring; function SysToUTF8(const S: ansistring): utf8string; function UTF8ToWinCP(const S: utf8string): ansistring; function WinCPToUTF8(const S: ansistring): utf8string; function UTF8CompareStr(const S1, S2: utf8string): integer; function UTF8CompareText(const S1, S2: utf8string): integer; // Note: ALanguage is ignored in UTF8LowerCase and UTF8UpperCase function UTF8LowerCase(const AInStr: utf8string; ALanguage: utf8string=''): utf8string; function UTF8UpperCase(const AInStr: utf8string; ALanguage: utf8string=''): utf8string; {$ELSE UNICODE} function UTF8ToSys(const S: string): string; function SysToUTF8(const S: string): string; function UTF8ToWinCP(const S: string): string; function WinCPToUTF8(const S: string): string; function UTF8CompareStr(const S1, S2: string): integer; function UTF8CompareText(const S1, S2: string): integer; // Note: ALanguage is ignored in UTF8LowerCase and UTF8UpperCase function UTF8LowerCase(const AInStr: string; ALanguage: string=''): string; function UTF8UpperCase(const AInStr: string; ALanguage: string=''): string; {$ENDIF UNICODE} //------------------------------------------------------------------------------ implementation uses LLCLOSInt, SysUtils; {$IFDEF FPC} {$PUSH} {$HINTS OFF} {$ENDIF} //------------------------------------------------------------------------------ function SysErrorMessageUTF8(ErrorCode: integer): string; begin result := string(SysToUTF8(SysErrorMessage(ErrorCode))); end; {$IFDEF UNICODE} function UTF8ToSys(const S: utf8string): ansistring; {$ELSE UNICODE} function UTF8ToSys(const S: string): string; {$ENDIF UNICODE} begin result := LLCLS_UTF8ToSys(S); end; {$IFDEF UNICODE} function SysToUTF8(const S: ansistring): utf8string; {$ELSE UNICODE} function SysToUTF8(const S: string): string; {$ENDIF UNICODE} begin result := LLCLS_SysToUTF8(S); end; {$IFDEF UNICODE} function UTF8ToWinCP(const S: utf8string): ansistring; {$ELSE UNICODE} function UTF8ToWinCP(const S: string): string; {$ENDIF UNICODE} begin result := LLCLS_UTF8ToWinCP(S); end; {$IFDEF UNICODE} function WinCPToUTF8(const S: ansistring): utf8string; {$ELSE UNICODE} function WinCPToUTF8(const S: string): string; {$ENDIF UNICODE} begin result := LLCLS_WinCPToUTF8(S); end; {$IFDEF UNICODE} function UTF8CompareStr(const S1, S2: utf8string): integer; {$ELSE UNICODE} function UTF8CompareStr(const S1, S2: string): integer; {$ENDIF UNICODE} var count, count1, count2: integer; begin count1 := length(S1); count2 := length(S2); if count1 > count2 then count := count2 else count := count1; result := CompareByte(pointer(@s1[1])^, pointer(@s2[1])^, count); if result=0 then if count1 > count2 then result := 1 // Doesn't return count1 - count 2 else if count1 < count2 then result := -1; // Like CompareStr in SysUTils end; {$IFDEF UNICODE} function UTF8CompareText(const S1, S2: utf8string): integer; {$ELSE UNICODE} function UTF8CompareText(const S1, S2: string): integer; {$ENDIF UNICODE} begin result := UTF8CompareStr(UTF8UpperCase(S1), UTF8UpperCase(S2)); end; {$IFDEF UNICODE} function UTF8LowerCase(const AInStr: utf8string; ALanguage: utf8string=''): utf8string; {$ELSE UNICODE} function UTF8LowerCase(const AInStr: string; ALanguage: string=''): string; {$ENDIF UNICODE} begin // (Language ignored) result := LLCLS_UTF8LowerCase(AInStr); end; {$IFDEF UNICODE} function UTF8UpperCase(const AInStr: utf8string; ALanguage: utf8string=''): utf8string; {$ELSE UNICODE} function UTF8UpperCase(const AInStr: string; ALanguage: string=''): string; {$ENDIF UNICODE} begin // (Language ignored) result := LLCLS_UTF8UpperCase(AInStr); end; //------------------------------------------------------------------------------ {$IFDEF FPC} {$POP} {$ENDIF} end.
unit JD.Weather.NOAA; interface uses System.Classes, System.SysUtils, System.Generics.Collections, Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Imaging.PngImage, Vcl.Imaging.GifImg, JD.Weather, JD.Weather.Intf, SuperObject; type TNOAAEndpoint = (noeDatasets, noeDataCategories, noeDataTypes, noeLocationCategories, noeLocations, noeStations, noeData); TNOAAWeatherThread = class(TJDWeatherThread) public function GetEndpointUrl(const Endpoint: TNOAAEndpoint): String; public function GetUrl: String; override; function DoAll(Conditions: TWeatherConditions; Forecast: TWeatherForecast; ForecastDaily: TWeatherForecast; ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; override; function DoConditions(Conditions: TWeatherConditions): Boolean; override; function DoForecast(Forecast: TWeatherForecast): Boolean; override; function DoForecastHourly(Forecast: TWeatherForecast): Boolean; override; function DoForecastDaily(Forecast: TWeatherForecast): Boolean; override; function DoAlerts(Alerts: TWeatherAlerts): Boolean; override; function DoMaps(Maps: TWeatherMaps): Boolean; override; end; implementation uses DateUtils, StrUtils, Math; { TNOAAWeatherThread } function TNOAAWeatherThread.GetUrl: String; begin Result:= 'http://www.ncdc.noaa.gov/cdo-web/api/v2/'; end; function TNOAAWeatherThread.GetEndpointUrl( const Endpoint: TNOAAEndpoint): String; begin Result:= GetUrl; case Endpoint of noeDatasets: Result:= Result + 'datasets/'; noeDataCategories: Result:= Result + 'datacategories/'; noeDataTypes: Result:= Result + 'datatypes/'; noeLocationCategories: Result:= Result + 'locationcategories/'; noeLocations: Result:= Result + 'locations/'; noeStations: Result:= Result + 'stations/'; noeData: Result:= Result + 'data/'; end; end; function TNOAAWeatherThread.DoAlerts(Alerts: TWeatherAlerts): Boolean; begin Result:= False; end; function TNOAAWeatherThread.DoAll(Conditions: TWeatherConditions; Forecast, ForecastDaily, ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; begin Result:= False; end; function TNOAAWeatherThread.DoConditions( Conditions: TWeatherConditions): Boolean; begin Result:= False; end; function TNOAAWeatherThread.DoForecast(Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TNOAAWeatherThread.DoForecastDaily( Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TNOAAWeatherThread.DoForecastHourly( Forecast: TWeatherForecast): Boolean; begin Result:= False; end; function TNOAAWeatherThread.DoMaps(Maps: TWeatherMaps): Boolean; begin Result:= False; end; end.
unit class_ctor_2; interface uses System; type TC1 = class F: int32; constructor Create; destructor Destroy; override; end; implementation var GA, GF: Int32; constructor TC1.Create; begin F := 11; end; destructor TC1.Destroy; begin GF := 12; end; procedure Test; var Obj: TC1; A: Int32; begin Obj := TC1.Create(); A := Obj.F; Obj := nil; GA := A; end; initialization Test(); finalization Assert(GA = 11); Assert(GF = 12); end.
1 unit procs; 2 { Etienne van Delden, 0618959, 03-11-2006 } 3 4 interface 5 6 //**CONSTANT DEFINITION ********** 7 8 const 9 MaxSa = 1000; // maximale sprongafstand 10 MaxSk = 1000; // maximale sprongkosten 11 MaxLen = 10000; // maximale lengte 12 13 //** TYPE DEFINITION ************* 14 15 type 16 17 Run = record 18 sa: 1 .. MaxSa; // sprongafstand 19 sk: 1 .. MaxSk; // sprongkosten 20 len: 1 .. MaxLen; // lengte 21 k: array [ 1 .. MaxLen ] of Integer; 22 end; // end type: Run 23 24 Antwoord = record 25 m: Integer; // minimale kosten voor route naar vakje len 26 end; // end type: Antwoord 27 28 //** INTERFACE: PROCEDURES *************** 29 30 procedure ReadRun ( var f: Text; var r: Run ); 31 { pre: f is geopend voor lezen, leeskop staat vooraan. f is een geldig 32 input bestand. 33 post: leeskop staat achteraan, sa, sk, len en de array k zijn ingevuld } 34 35 procedure ComputeAnswer ( const r: Run; var a: Antwoord ); 36 { pre: de run informatie is ingelzen. 37 post: het antwoord, behorend bij de gegevens van r, is ingevuld. } 38 39 procedure WriteAnswer ( var f: Text; const a: Antwoord ); 40 { pre: het antwoord is uitegerekent, de output file is geopend om te schrijven. 41 post: een bestand is geschreven met alle antwoorden a erin op een aparte regel.} 42 43 implementation 44 45 //** FUNCTIONS **************** 46 function minimum ( k,l: Integer ): Integer; 47 { pre: 2 integers 48 ret: de kleinset van de 2 } 49 50 begin 51 52 if k < l then // als de een groter is dan de andere 53 begin 54 Result := k // word hij het resulataat 55 end 56 else if k > l then // dit was niet het geval 57 begin 58 Result := l // dus wordt de andere het resuktaat 59 end 60 else if k = l then // 2 gelijke getallen 61 begin 62 Result := k // 1 van de 2 word het resultaat 63 end; 64 65 end; // end minimum 66 67 //**PROCEDURES***************** 68 69 procedure ReadRun ( var f: Text; var r: Run ); 70 { zie interface } 71 72 var 73 j: Integer; // hulp var 74 75 begin 76 77 read( f, r.sa ); // lees sprong afstand 78 read( f, r.sk ); // lees sprongkosten 79 read( f, r.len); // lees weglengte 80 81 for j := 1 to r.len do // voor ieder vakje, lees de kosten om naar 82 begin // vakje te lopen 83 read( f, r.k[ j ] ); 84 end; 85 end; // end procedure ReadRun 86 87 procedure ComputeAnswer ( const r: Run; var a: Antwoord ); 88 { zie interface } 89 90 var 91 i: Integer; // hulp var 92 k: Integer; // hulp var 93 l: Integer; // hulp var 94 g: array [ 0 .. MaxLen ] of Integer; // de goedkoopste waardes 95 96 begin 97 98 a.m := 0; // we gaan uit van geen antwoord 99 100 for i := 0 to r.len do // init goedkoopste oplossing: overal 0 101 begin 102 g[ i ] := 0 103 end; 104 105 i := 0; // reset teller var voor hergebruik 106 107 while ( i <> r.len ) do // zolang we niet het einde hebben behaald 108 begin 109 110 i := i + 1; // we zijn 1 vakje verder 111 112 if ( 0 < i ) and ( i < r.sa ) then //als het vakje waar ze zijn onder de 113 begin // sprong afstand zit 114 g[ i ] := r.k[ i ] + g[ i - 1 ]; // dan is de goedkoopste oplossing lopen 115 end 116 else if ( r.sa <= i ) and ( i <= r.len ) then 117 begin // als we bij een vakje zijn, groter dan de 118 // kleinste sprong en niet voorbij het einde 119 120 k := g[ i - 1 ]; // init hulp var 121 l := g[ i - r.sa ] + r.sk; // init hulp var 122 g[ i ] := r.k[ i ] + minimum( k, l ); //bepaal de goedkoopste oplossing 123 end; // end else if 124 125 end; // end while 126 127 a.m := g[ r.len ]; // schrijf het antwoord 128 129 end; 130 131 132 procedure WriteAnswer ( var f: Text; const a: Antwoord ); 133 { zien interface } 134 begin 135 writeln( f, a.m ); // schrijf het antwoord naar output file 136 end; 137 138 end. // end pros.pas
{*******************************************************} { } { Borland Delphi Visual Component Library } { XML Schema Tags } { } { Copyright (c) 2000-2001 Borland Software Corporation } { } {*******************************************************} unit XMLSchemaTags; interface const { XML Schema Tag/Attribute names and values (do not localize) } SAbstract = 'abstract'; SAll = 'all'; SAnnotation = 'annotation'; SAny = 'any'; SAppInfo = 'appinfo'; SAttribute = 'attribute'; SAttributeFormDefault = 'attributeFormDefault'; SAttributeGroup = 'attributeGroup'; SBase = 'base'; SBase64 = 'base64'; SBlockDefault = 'blockDefault'; SChoice = 'choice'; SComplexContent = 'complexContent'; SComplexType = 'complexType'; SDefault = 'default'; SDerivedBy = 'derivedBy'; SDocumentation = 'documentation'; SElement = 'element'; SElementFormDefault = 'elementFormDefault'; SExtension = 'extension'; SFinalDefault = 'finalDefault'; SFixed = 'fixed'; SGroup = 'group'; SHex = 'hex'; SImport = 'import'; SInclude = 'include'; SList = 'list'; SMaxOccurs = 'maxOccurs'; SMinOccurs = 'minOccurs'; SMixed = 'mixed'; SName = 'name'; SNotation = 'notation'; SOptional = 'optional'; SPublic = 'public'; SProhibited = 'prohibited'; SQualified = 'qualified'; SRef = 'ref'; SRequired = 'required'; SRestriction = 'restriction'; SSchema = 'schema'; SSchemaLocation = 'schemaLocation'; SSequence = 'sequence'; SSimpleContent = 'simpleContent'; SSimpleType = 'simpleType'; SSource = 'source'; SSystem = 'system'; STargetNamespace = 'targetNamespace'; SType = 'type'; SUnbounded = 'unbounded'; SUnqualified = 'unqualified'; SUse = 'use'; SValue = 'value'; SVersion = 'version'; { Built-in Data Types (Primative) } xsdString = 'string'; xsdBoolean = 'boolean'; xsdDecimal = 'decimal'; xsdFloat = 'float'; xsdDouble = 'double'; xsdDuration = 'duration'; xsdDateTime = 'dateTime'; xsdTime = 'time'; xsdDate = 'date'; xsdGYearMonth = 'gYearMonth'; xsdGYear = 'gYear'; xsdGMonthDay = 'gMonthDay'; xsdGDay = 'gDay'; xsdGMonth = 'gMonth'; xsdHexBinary = 'hexBinary'; xsdBase64Binary = 'base64Binary'; xsdAnyUri = 'anyURI'; xsdQName = 'QName'; xsdNOTATION = 'NOTATION'; { Built-in Data Types (Derived) } xsdNormalizedString = 'normalizedString'; xsdToken = 'token'; xsdLanguage = 'language'; xsdIDREFS = 'IDREFS'; xsdENTITIES = 'ENTITIES'; xsdNMTOKEN = 'NMTOKEN'; xsdNMTOKENS = 'NMTOKENS'; xsdName = 'Name'; xsdNCName = 'NCName'; xsdID = 'ID'; xsdIDREF = 'IDREF'; xsdENTITY = 'ENTITY'; xsdInteger = 'integer'; xsdNonPositiveInteger = 'nonPositiveInteger'; xsdNegativeInteger = 'negativeInteger'; xsdLong = 'long'; xsdInt = 'int'; xsdShort = 'short'; xsdByte = 'byte'; xsdNonNegativeInteger = 'nonNegativeInteger'; xsdUnsignedLong = 'unsignedLong'; xsdUnsignedInt = 'unsignedInt'; xsdUnsignedShort = 'unsignedShort'; xsdUnsignedByte = 'unsignedByte'; xsdPositiveInteger = 'positiveInteger'; { Legacy Built-in Data Types (pre 2001) } xsdTimeDuration = 'timeDuration'; { duration } xsdBinary = 'binary'; { hexBinary } xsdUriReference = 'uriReference'; { anyURI } xsdTimeInstant = 'timeInstant'; { dateTime } xsdRecurringDate= 'recurringDate'; { gMonthDay } xsdRecurringDay = 'recurringDay'; { gDay } xsdMonth = 'month'; { gMonth } xsdYear = 'year'; { gYear } xsdTimePeriod = 'timePeriod'; { removed } xsdRecurringDuration = 'recurringDuration'; { removed } xsdCentury = 'century'; { removed } xsdanySimpleType = 'anySimpleType'; { Datatype Facets } xsfOrdered = 'ordered'; xsfBounded = 'bounded'; xsfCardinality = 'cardinality'; xsfNumeric = 'numeric'; xsfLength = 'length'; xsfMinLength = 'minLength'; xsfMaxLength = 'maxLength'; xsfPattern = 'pattern'; xsfEnumeration = 'enumeration'; xsfMaxInclusive = 'maxInclusive'; xsfMaxExclusive = 'maxExclusive'; xsfMinInclusive = 'minInclusive'; xsfMinExclusive = 'minExclusive'; xsfWhitespace = 'whiteSpace'; xsfTotalDigits = 'totalDigits'; xsfFractionalDigits = 'fractionalDigits'; { Other strings } BuiltInTypeNames: array[0..44] of WideString = (xsdString, xsdBoolean, xsdDecimal, xsdFloat, xsdDouble, xsdDuration, xsdDateTime, xsdTime, xsdDate, xsdGYearMonth, xsdGYear, xsdGMonthDay, xsdGDay, xsdGMonth, xsdHexBinary, xsdBase64Binary, xsdAnyUri, xsdQName, xsdNOTATION, xsdNormalizedString, xsdToken, xsdLanguage, xsdIDREFS, xsdENTITIES, xsdNMTOKEN, xsdNMTOKENS, xsdName, xsdNCName, xsdID, xsdIDREF, xsdENTITY, xsdInteger, xsdNonPositiveInteger, xsdNegativeInteger, xsdLong, xsdInt, xsdShort, xsdByte, xsdNonNegativeInteger, xsdUnsignedLong, xsdUnsignedInt, xsdUnsignedShort, xsdUnsignedByte, xsdPositiveInteger, xsdanySimpleType); LegacyTypeNames: array[0..10] of WideString = (xsdTimeDuration, xsdBinary, xsdUriReference, xsdTimeInstant, xsdRecurringDate, xsdRecurringDay, xsdMonth, xsdYear, xsdTimePeriod, xsdRecurringDuration, xsdCentury); resourcestring SInvalidSchema = 'Invalid or unsupported XML Schema document'; SNoLocalTypeName = 'Local type declarations cannot have a name. Element: %s'; SUnknownDataType = 'Unknown datatype "%s"'; SInvalidValue = 'Invalid %s value: "%s"'; SInvalidGroupDecl = 'Invalid group declaration in "%s"'; SMissingName = 'Missing Type name'; SInvalidDerivation = 'Invalid complex type derivation: %s'; SNoNameOnRef = 'Name not allowed on a ref item'; SNoGlobalRef = 'Global scheam items may not contain a ref'; SNoRefPropSet = '%s cannot be set on a ref item'; SSetGroupRefProp = 'Set the GroupRef property for the cmGroupRef content model'; SNoContentModel = 'ContentModel not set'; SNoFacetsAllowed = 'Facets and Enumeration not allowed on this kind of datatype "%s"'; SNotBuiltInType = 'Invalid built-in type name "%s"'; SBuiltInType = 'Built-in Type'; implementation end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 系统登录窗口,用户进入系统在此验证 //主要实现: //-----------------------------------------------------------------------------} unit untEasyLoginMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, untEasyPlateBaseForm, ExtCtrls, jpeg, StdCtrls, untEasyLabel, untEasyEdit, untEasyButtons, DB, ADODB, untEasyDBConnection, untEasyBallonControl, untEasyProgressBar, DBClient, Provider, untEasyPlateDBBaseForm; type TLoadEasyDBPkg = function(AHandle: THandle): Integer; stdcall; TfrmEasyLoginMain = class(TfrmEasyPlateDBBaseForm) imgLoginBC: TImage; EasyLabel1: TEasyLabel; edtUserName: TEasyLabelEdit; bbtnCancel: TEasyBitButton; bbtnLogin: TEasyBitButton; lblCopyRight: TEasyLabel; EasyLabel2: TEasyLabel; hintBall: TEasyHintBalloonForm; cdsLogin: TClientDataSet; edtPassWord: TEasyLabelEdit; procedure bbtnCancelClick(Sender: TObject); procedure bbtnLoginClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FLoginUserID: string; FApplicationHandle: Cardinal; procedure SetLoginUserID(const Value: string); function GetLoginUserID: string; public { Public declarations } property EasyLoginUserID: string read GetLoginUserID write SetLoginUserID; end; var frmEasyLoginMain: TfrmEasyLoginMain; implementation uses untEasyUtilConst, untEasyUtilDLL, untEasyPlateMain; {$R *.dfm} procedure TfrmEasyLoginMain.bbtnCancelClick(Sender: TObject); begin Close; end; procedure TfrmEasyLoginMain.bbtnLoginClick(Sender: TObject); var TmpSQL: string; begin if Trim(edtUserName.Text) = '' then begin hintBall.ShowTextHintBalloon(bmtInfo, '提示', '用户名不能为空!', 500, 200, 0, edtUserName, bapBottomRight); Exit; end; if Trim(edtPassWord.Text) = '' then begin hintBall.ShowTextHintBalloon(bmtInfo, '提示', '密码不能为空!', 500, 200, 0, edtPassWord, bapBottomRight); Exit; end; EasyLoginUserID := Trim(edtUserName.Text); try Screen.Cursor := crHourGlass; //开始验证户名和密码 分CS/CAS { TODO : 将系统运行的SQL语句从表sysSQL缓存到本地 } with cdsLogin do begin if UpperCase(DMEasyDBConnection.EasyAppType) = 'CAS' then begin Data := EasyRDMDisp.EasyGetRDMData('SELECT SQLContext FROM sysSQL WHERE IsEnable = 1 AND SQLName = ''UserLoginCheck'''); end else begin cdsLogin.ProviderName := 'DspLogin'; if Active then Close; CommandText := 'SELECT SQLContext FROM sysSQL WHERE IsEnable = 1 AND SQLName = ''UserLoginCheck'''; Open; end; if cdsLogin.RecordCount > 0 then TmpSQL := cdsLogin.fieldbyname('SQLContext').AsString; close; end; if Trim(TmpSQL) <> '' then begin TmpSQL := Format(TmpSQL, [QuotedStr(edtUserName.Text)]); with cdsLogin do begin if UpperCase(DMEasyDBConnection.EasyAppType) = 'CAS' then begin cdsLogin.Data := EasyRDMDisp.EasyGetRDMData(TmpSQL); end else begin Close; CommandText := TmpSQL; cdsLogin.Data := EasyRDMDisp.EasyGetRDMData(TmpSQL); try Open; except on e:Exception do begin cdsLogin.Close; Application.MessageBox(PChar('系统出错,原因:' + e.Message), '错误', MB_OK + MB_ICONSTOP); end; end; end; if cdsLogin.RecordCount > 0 then begin if transfer(edtPassWord.Text) = LowerCase(FieldByName('PassWord').AsString) then begin frmEasyPlateMain.EasyLoginUserID := EasyLoginUserID; frmEasyLoginMain.Close; end else begin edtPassWord.Text := ''; edtUserName.Text := ''; hintBall.ShowTextHintBalloon(bmtError, '提示', '用户名或密码不正确!', 500, 200, 0, edtUserName, bapBottomRight); cdsLogin.Close; end; end else begin edtPassWord.Text := ''; hintBall.ShowTextHintBalloon(bmtWarning, '提示', '此用户不存在或已停用!', 500, 200, 0, edtUserName, bapBottomRight); cdsLogin.Close; end; end; end; finally Screen.Cursor := crDefault; end; end; procedure TfrmEasyLoginMain.SetLoginUserID(const Value: string); begin FLoginUserID := Value; end; function TfrmEasyLoginMain.GetLoginUserID: string; begin Result := FLoginUserID; end; procedure TfrmEasyLoginMain.FormCreate(Sender: TObject); begin // inherited; 此句要删除 end; end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit OriDialogs; {$mode objfpc}{$H+} {$ifndef WINDOWS} {$define CORRECT_COLORS} // for Gtk widgetset {$endif} interface uses Classes, SysUtils, Forms, FGL; type TOriDialog = class(TForm) protected procedure DoFirstShow; override; procedure DoClose(var CloseAction: TCloseAction); override; function CanClose: Boolean; virtual; procedure Populate; virtual; procedure Collect; virtual; {$ifdef CORRECT_COLORS} procedure CorrectColors; {$endif} public constructor Create; reintroduce; function CloseQuery: Boolean; override; function Accepted: Boolean; function Exec: Boolean; end; function ShowDialog(ADialog: TOriDialog): Boolean; implementation uses Controls, {$ifdef CORRECT_COLORS} ButtonPanel, Graphics, {$endif} OriUtils_Gui; type TDialogPropsMap = specialize TFPGMap<string, Longword>; TDialogProps = class private FSize: TDialogPropsMap; FPos: TDialogPropsMap; function GetProp(AMap: TDialogPropsMap; const AKey: String): Longword; public constructor Create; destructor Destroy; override; procedure Store(ADlg: TOriDialog); procedure Restore(ADlg: TOriDialog); end; var SavedProps: TDialogProps; {%region TDialogProps} constructor TDialogProps.Create; begin FSize := TDialogPropsMap.Create; FPos := TDialogPropsMap.Create; end; destructor TDialogProps.Destroy; begin FSize.Free; FPos.Free; inherited; end; function TDialogProps.GetProp(AMap: TDialogPropsMap; const AKey: String): Longword; begin if AMap.IndexOf(AKey) >= 0 then Result := AMap.KeyData[AKey] else Result := 0; end; procedure TDialogProps.Store(ADlg: TOriDialog); var Size, Pos: Longword; begin Size := 0; Pos := 0; // warning supress SaveFormSizePos(ADlg, Size, Pos); FSize.KeyData[ADlg.ClassName] := Size; FPos.KeyData[ADlg.ClassName] := Pos; end; procedure TDialogProps.Restore(ADlg: TOriDialog); begin RestoreFormSizePos(ADlg, GetProp(FSize, ADlg.ClassName), GetProp(FPos, ADlg.ClassName)); end; {%endregion} {%region TOriDialog} function ShowDialog(ADialog: TOriDialog): Boolean; begin Result := ADialog.ShowModal = mrOk; end; constructor TOriDialog.Create; begin inherited Create(Application.MainForm); BorderIcons := [biSystemMenu]; PopupMode := pmAuto; end; function TOriDialog.Accepted: Boolean; begin Result := ModalResult = mrOk; end; function TOriDialog.Exec: Boolean; begin Result := ShowModal = mrOk; end; procedure TOriDialog.DoFirstShow; begin inherited; Populate; {$ifdef CORRECT_COLORS} CorrectColors; {$endif} SavedProps.Restore(Self); end; procedure TOriDialog.DoClose(var CloseAction: TCloseAction); begin inherited DoClose(CloseAction); if Accepted then Collect; SavedProps.Store(Self); CloseAction := caFree; end; function TOriDialog.CloseQuery: Boolean; begin Result := inherited; if Result and Accepted then Result := CanClose; end; procedure TOriDialog.Populate; begin end; procedure TOriDialog.Collect; begin end; function TOriDialog.CanClose: Boolean; begin Result := True; end; {$ifdef CORRECT_COLORS} procedure TOriDialog.CorrectColors; var I: Integer; begin for I := 0 to ControlCount-1 do if Controls[I] is TCustomButtonPanel then begin Controls[I].Color := clForm; break; end; end; {$endif} {%endregion} initialization SavedProps := TDialogProps.Create; finalization SavedProps.Free; end.
unit TabSetImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, Tabs; type TTabSetX = class(TActiveXControl, ITabSetX) private { Private declarations } FDelphiControl: TTabSet; FEvents: ITabSetXEvents; procedure ChangeEvent(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure ClickEvent(Sender: TObject); procedure MeasureTabEvent(Sender: TObject; Index: Integer; var TabWidth: Integer); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_AutoScroll: WordBool; safecall; function Get_BackgroundColor: OLE_COLOR; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Cursor: Smallint; safecall; function Get_DitherBackground: WordBool; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_EndMargin: Integer; safecall; function Get_FirstIndex: Integer; safecall; function Get_Font: IFontDisp; safecall; function Get_SelectedColor: OLE_COLOR; safecall; function Get_StartMargin: Integer; safecall; function Get_Style: TxTabStyle; safecall; function Get_TabHeight: Integer; safecall; function Get_TabIndex: Integer; safecall; function Get_Tabs: IStrings; safecall; function Get_UnselectedColor: OLE_COLOR; safecall; function Get_Visible: WordBool; safecall; function Get_VisibleTabs: Integer; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure SelectNext(Direction: WordBool); safecall; procedure Set_AutoScroll(Value: WordBool); safecall; procedure Set_BackgroundColor(Value: OLE_COLOR); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DitherBackground(Value: WordBool); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_EndMargin(Value: Integer); safecall; procedure Set_FirstIndex(Value: Integer); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_SelectedColor(Value: OLE_COLOR); safecall; procedure Set_StartMargin(Value: Integer); safecall; procedure Set_Style(Value: TxTabStyle); safecall; procedure Set_TabHeight(Value: Integer); safecall; procedure Set_TabIndex(Value: Integer); safecall; procedure Set_Tabs(const Value: IStrings); safecall; procedure Set_UnselectedColor(Value: OLE_COLOR); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation uses ComObj, About35; { TTabSetX } procedure TTabSetX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_TabSetXPage); } end; procedure TTabSetX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as ITabSetXEvents; end; procedure TTabSetX.InitializeControl; begin FDelphiControl := Control as TTabSet; FDelphiControl.OnChange := ChangeEvent; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnMeasureTab := MeasureTabEvent; end; function TTabSetX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TTabSetX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TTabSetX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TTabSetX.Get_AutoScroll: WordBool; begin Result := FDelphiControl.AutoScroll; end; function TTabSetX.Get_BackgroundColor: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.BackgroundColor); end; function TTabSetX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TTabSetX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TTabSetX.Get_DitherBackground: WordBool; begin Result := FDelphiControl.DitherBackground; end; function TTabSetX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TTabSetX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TTabSetX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TTabSetX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TTabSetX.Get_EndMargin: Integer; begin Result := FDelphiControl.EndMargin; end; function TTabSetX.Get_FirstIndex: Integer; begin Result := FDelphiControl.FirstIndex; end; function TTabSetX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TTabSetX.Get_SelectedColor: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.SelectedColor); end; function TTabSetX.Get_StartMargin: Integer; begin Result := FDelphiControl.StartMargin; end; function TTabSetX.Get_Style: TxTabStyle; begin Result := Ord(FDelphiControl.Style); end; function TTabSetX.Get_TabHeight: Integer; begin Result := FDelphiControl.TabHeight; end; function TTabSetX.Get_TabIndex: Integer; begin Result := FDelphiControl.TabIndex; end; function TTabSetX.Get_Tabs: IStrings; begin GetOleStrings(FDelphiControl.Tabs, Result); end; function TTabSetX.Get_UnselectedColor: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.UnselectedColor); end; function TTabSetX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TTabSetX.Get_VisibleTabs: Integer; begin Result := FDelphiControl.VisibleTabs; end; function TTabSetX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TTabSetX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TTabSetX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TTabSetX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TTabSetX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TTabSetX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TTabSetX.AboutBox; begin ShowTabSetXAbout; end; procedure TTabSetX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TTabSetX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TTabSetX.SelectNext(Direction: WordBool); begin FDelphiControl.SelectNext(Direction); end; procedure TTabSetX.Set_AutoScroll(Value: WordBool); begin FDelphiControl.AutoScroll := Value; end; procedure TTabSetX.Set_BackgroundColor(Value: OLE_COLOR); begin FDelphiControl.BackgroundColor := TColor(Value); end; procedure TTabSetX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TTabSetX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TTabSetX.Set_DitherBackground(Value: WordBool); begin FDelphiControl.DitherBackground := Value; end; procedure TTabSetX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TTabSetX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TTabSetX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TTabSetX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TTabSetX.Set_EndMargin(Value: Integer); begin FDelphiControl.EndMargin := Value; end; procedure TTabSetX.Set_FirstIndex(Value: Integer); begin FDelphiControl.FirstIndex := Value; end; procedure TTabSetX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TTabSetX.Set_SelectedColor(Value: OLE_COLOR); begin FDelphiControl.SelectedColor := TColor(Value); end; procedure TTabSetX.Set_StartMargin(Value: Integer); begin FDelphiControl.StartMargin := Value; end; procedure TTabSetX.Set_Style(Value: TxTabStyle); begin FDelphiControl.Style := TTabStyle(Value); end; procedure TTabSetX.Set_TabHeight(Value: Integer); begin FDelphiControl.TabHeight := Value; end; procedure TTabSetX.Set_TabIndex(Value: Integer); begin FDelphiControl.TabIndex := Value; end; procedure TTabSetX.Set_Tabs(const Value: IStrings); begin SetOleStrings(FDelphiControl.Tabs, Value); end; procedure TTabSetX.Set_UnselectedColor(Value: OLE_COLOR); begin FDelphiControl.UnselectedColor := TColor(Value); end; procedure TTabSetX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TTabSetX.ChangeEvent(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); var TempAllowChange: WordBool; begin TempAllowChange := WordBool(AllowChange); if FEvents <> nil then FEvents.OnChange(NewTab, TempAllowChange); AllowChange := Boolean(TempAllowChange); end; procedure TTabSetX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TTabSetX.MeasureTabEvent(Sender: TObject; Index: Integer; var TabWidth: Integer); var TempTabWidth: Integer; begin TempTabWidth := Integer(TabWidth); if FEvents <> nil then FEvents.OnMeasureTab(Index, TempTabWidth); TabWidth := Integer(TempTabWidth); end; initialization TActiveXControlFactory.Create( ComServer, TTabSetX, TTabSet, Class_TabSetX, 35, '{695CDBE3-02E5-11D2-B20D-00C04FA368D4}', 0, tmApartment); end.
unit Ledger; interface uses System.Rtti; type TLedger = class private FDebit: currency; FPrimaryKey: string; FPostingId: string; FRefPostingId: string; FEventObject: string; FValueDate: TDateTime; FCredit: currency; FCaseType: string; FCurrentStatus: string; FNewStatus: string; FFullPayment: boolean; FHasPartial: boolean; FAmortisation: currency; function GetPosted: boolean; function GetStatusChanged: boolean; function GetUnreferencedPayment: boolean; public property PostingId: string read FPostingId write FPostingId; property RefPostingId: string read FRefPostingId write FRefPostingId; property EventObject: string read FEventObject write FEventObject; property PrimaryKey: string read FPrimaryKey write FPrimaryKey; property ValueDate: TDateTime read FValueDate write FValueDate; property Credit: currency read FCredit write FCredit; property Debit: currency read FDebit write FDebit; property CaseType: string read FCaseType write FCaseType; property CurrentStatus: string read FCurrentStatus write FCurrentStatus; property NewStatus: string read FNewStatus write FNewStatus; property Posted: boolean read GetPosted; property StatusChanged: boolean read GetStatusChanged; property UnreferencedPayment: boolean read GetUnreferencedPayment; property FullPayment: boolean read FFullPayment write FFullPayment; property HasPartial: boolean read FHasPartial write FHasPartial; property Amortisation: currency read FAmortisation write FAmortisation; end; implementation uses AppConstants; { TLedger } function TLedger.GetPosted: boolean; begin Result := FPostingId <> ''; end; function TLedger.GetStatusChanged: boolean; begin Result := FNewStatus <> ''; end; function TLedger.GetUnreferencedPayment: boolean; begin Result := (FEventObject = TRttiEnumerationType.GetName<TEventObjects>(TEventObjects.PAY)) and (FRefPostingId = ''); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 2004.02.03 5:45:08 PM czhower Name changes Rev 1.3 1/22/2004 7:10:04 AM JPMugaas Tried to fix AnsiSameText depreciation. Rev 1.2 1/21/2004 3:27:52 PM JPMugaas InitComponent Rev 1.1 10/23/2003 03:50:52 AM JPMugaas TIdEchoUDP Ported. Rev 1.0 11/14/2002 02:19:38 PM JPMugaas } unit IdEchoUDPServer; interface {$i IdCompilerDefines.inc} uses IdAssignedNumbers, IdGlobal, IdSocketHandle, IdUDPBase, IdUDPServer; type TIdEchoUDPServer = class(TIdUDPServer) protected procedure DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); override; procedure InitComponent; override; published property DefaultPort default IdPORT_ECHO; end; implementation { TIdEchoUDPServer } procedure TIdEchoUDPServer.InitComponent; begin inherited InitComponent; DefaultPort := IdPORT_ECHO; end; procedure TIdEchoUDPServer.DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); begin inherited DoUDPRead(AThread, AData, ABinding); with ABinding do begin SendTo(PeerIP, PeerPort, AData); end; end; end.
namespace CirrusTrace; interface type // Aspect declared in CirrusTraceAspectLibrary is applied to this class // Build and start the application to see how it will affect the behaviour of // Sum and Multiply methods [CirrusTraceAspectLibrary.Trace] WorkerClass = class public method Sum(aValueA: Int32; aValueB: Int32): Int32; virtual; method Multiply(aValueA: Int32; aValueB: Int32; aValueC: Int32): Int32; virtual; end; implementation method WorkerClass.Sum(aValueA: Int32; aValueB: Int32): Int32; begin Console.WriteLine('Sum method is processing data'); exit (aValueA + aValueB); end; method WorkerClass.Multiply(aValueA: Int32; aValueB: Int32; aValueC: Int32): Int32; begin Console.WriteLine('Multiply method is processing data'); exit (aValueA * aValueB * aValueC); end; end.
{******************************************} { TPolarSeries Editor Dialog } { Copyright (c) 1996-2004 by David Berneda } {******************************************} unit TeePolarEditor; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} Chart, Series, TeePolar, TeEngine, TeCanvas, TeePenDlg, TeeProcs; type TPolarSeriesEditor = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; BFont: TButton; CBAngleLabels: TCheckBox; CBLabelsRot: TCheckBox; CBClockWise: TCheckBox; CBInside: TCheckBox; Label2: TLabel; EMargin: TEdit; UDMargin: TUpDown; LAngleInc: TLabel; Label8: TLabel; Label1: TLabel; CBClose: TCheckBox; SEAngleInc: TEdit; SERadiusInc: TEdit; UDRadiusInc: TUpDown; UDAngleInc: TUpDown; BPen: TButtonPen; BPiePen: TButtonPen; BBrush: TButton; Edit1: TEdit; UDTransp: TUpDown; BColor: TButtonColor; CBColorEach: TCheckBox; procedure FormShow(Sender: TObject); procedure BPenClick(Sender: TObject); procedure CBCloseClick(Sender: TObject); procedure SEAngleIncChange(Sender: TObject); procedure SERadiusIncChange(Sender: TObject); procedure BBrushClick(Sender: TObject); procedure CBAngleLabelsClick(Sender: TObject); procedure BFontClick(Sender: TObject); procedure CBLabelsRotClick(Sender: TObject); procedure CBClockWiseClick(Sender: TObject); procedure CBInsideClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CBColorEachClick(Sender: TObject); procedure EMarginChange(Sender: TObject); private { Private declarations } PointerForm : TCustomForm; FCircledForm : TCustomForm; procedure EnableLabels; protected Polar : TCustomPolarSeries; procedure HideAngleInc; virtual; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeBrushDlg, TeePoEdi, TeeEdiSeri, TeeCircledEdit, TeeConst; procedure TPolarSeriesEditor.HideAngleInc; begin ShowControls(Polar is TPolarSeries,[LAngleInc,UDAngleInc,SEAngleInc]); end; procedure TPolarSeriesEditor.FormShow(Sender: TObject); begin Polar:=TCustomPolarSeries(Tag); if Assigned(Polar) then begin With Polar do begin CBClose.Checked :=CloseCircle; CBClockWise.Checked :=ClockWiseLabels; UDAngleInc.Position :=Round(AngleIncrement); UDRadiusInc.Position :=Round(RadiusIncrement); CBAngleLabels.Checked :=CircleLabels; CBLabelsRot.Checked :=CircleLabelsRotated; CBInside.Checked :=CircleLabelsInside; BPiePen.LinkPen(CirclePen); BPen.LinkPen(Pen); UDMargin.Position :=LabelsMargin; UDTransp.Position :=Transparency; CBColorEach.Checked :=ColorEachPoint; end; BColor.LinkProperty(Polar,'SeriesColor'); EnableLabels; HideAngleInc; if not Assigned(FCircledForm) then FCircledForm:=TFormTeeSeries(Parent.Owner).InsertSeriesForm( TCircledSeriesEditor, 1,TeeMsg_GalleryCircled, Polar); if not Assigned(PointerForm) then PointerForm:=TeeInsertPointerForm(Parent,Polar.Pointer,TeeMsg_GalleryPoint); end; end; procedure TPolarSeriesEditor.BPenClick(Sender: TObject); begin With Polar do SeriesColor:=Pen.Color; end; procedure TPolarSeriesEditor.CBCloseClick(Sender: TObject); begin Polar.CloseCircle:=CBClose.Checked; end; procedure TPolarSeriesEditor.SEAngleIncChange(Sender: TObject); begin if Showing then Polar.AngleIncrement:=UDAngleInc.Position; end; procedure TPolarSeriesEditor.SERadiusIncChange(Sender: TObject); begin if Showing then Polar.RadiusIncrement:=UDRadiusInc.Position; end; procedure TPolarSeriesEditor.BBrushClick(Sender: TObject); begin EditChartBrush(Self,Polar.Brush); end; procedure TPolarSeriesEditor.CBAngleLabelsClick(Sender: TObject); begin Polar.CircleLabels:=CBAngleLabels.Checked; EnableLabels; end; procedure TPolarSeriesEditor.EnableLabels; begin EnableControls(CBAngleLabels.Checked,[CBLabelsRot,CBClockWise,BFont]) end; procedure TPolarSeriesEditor.BFontClick(Sender: TObject); begin EditTeeFont(Self,Polar.CircleLabelsFont); end; procedure TPolarSeriesEditor.CBLabelsRotClick(Sender: TObject); begin Polar.CircleLabelsRotated:=CBLabelsRot.Checked; end; procedure TPolarSeriesEditor.CBClockWiseClick(Sender: TObject); begin Polar.ClockWiseLabels:=CBClockWise.Checked; end; procedure TPolarSeriesEditor.CBInsideClick(Sender: TObject); begin Polar.CircleLabelsInside:=CBInside.Checked; end; procedure TPolarSeriesEditor.Edit1Change(Sender: TObject); begin if Showing then Polar.Transparency:=UDTransp.Position; end; procedure TPolarSeriesEditor.FormCreate(Sender: TObject); begin Align:=alClient; end; procedure TPolarSeriesEditor.CBColorEachClick(Sender: TObject); begin Polar.ColorEachPoint:=CBColorEach.Checked; end; procedure TPolarSeriesEditor.EMarginChange(Sender: TObject); begin if Showing then Polar.LabelsMargin:=UDMargin.Position; end; initialization RegisterClass(TPolarSeriesEditor); end.
{ ledger Copyright (c) 2018 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit ledger; {$mode delphi}{$H+} interface uses syncobjs, fgl; var Critical : TCriticalSection; type TLedgerType = ( ltCredit, ltDebit ); TLedgerTypes = set of TLedgerType; TLedgerEntry<T> = packed record private FEntry : T; FID : String; FType : TLedgerType; FTimeStamp : TDateTIme; public property ID : String read FID write FID; property Entry : T read FEntry write FEntry; property LedgerType : TLedgerType read FType write FType; property Timestamp : TDateTime read FTimestamp write FTimeStamp; end; TLedgerEntryArray<T> = array of TLedgerEntry<T>; TFilter<T> = function(Const AEntry:T;Const AType:TLedgerType):Boolean; { ILedger } ILedger<T> = interface ['{751BB67C-AA79-40ED-8A11-8034EE997884}'] //property methods function GetBalance: T; function GetCount(const ATypes: TLedgerTypes): Cardinal; function GetCredits: TLedgerEntryArray<T>; function GetDebits: TLedgerEntryArray<T>; function GetEntries(const AID: String): TLedgerEntry<T>; //properties property Balance : T read GetBalance; property Credits : TLedgerEntryArray<T> read GetCredits; property Debits : TLedgerEntryArray<T> read GetDebits; property Entries[Const AID:String] : TLedgerEntry<T> read GetEntries;default; property Count[Const ATypes:TLedgerTypes] : Cardinal read GetCount; //methods function RecordEntry(Const AEntry:T;Const AType:TLedgerType; Const ATimestamp:TDateTime; Out ID:String):ILedger<T>;overload; function RecordEntry(Const AEntry:T;Const AType:TLedgerType; Out ID:String):ILedger<T>;overload; function RecordEntry(Const AEntry:T; Const AType:TLedgerType):ILedger<T>;overload; function RecordEntries(Const AEntries:TLedgerEntryArray<T>):ILedger<T>; function Flatten : ILedger<T>; function Filter(Const AFilter:TFilter<T>; Out Entries:TLedgerEntryArray<T>):ILedger<T>; function Clear(Const AType:TLedgerType):ILedger<T>;overload; function Clear:ILedger<T>;overload; end; { ILedgerImpl } TLedgerImpl<T> = class(TInterfacedObject,ILedger<T>) strict private type { TEntryPair } TEntryPair = packed record private FIndex : Integer; FType : TLedgerType; public property Index : Integer read FIndex write FIndex; property LedgerType : TLedgerType read FType write FType; end; TMap = TFPGMap<String,TEntryPair>; strict private FLastBalance : T; FCredits : TLedgerEntryArray<T>; FDebits : TLedgerEntryArray<T>; FMap : TMap; function GetBalance: T; function GetCount(const ATypes: TLedgerTypes): Cardinal; function GetCredits: TLedgerEntryArray<T>; function GetDebits: TLedgerEntryArray<T>; function GetEntries(const AID: String): TLedgerEntry<T>; procedure Rebalance; strict protected procedure DoBeforeRecord(Const AEntry:T;Const AType:TLedgerType);virtual; procedure DoAfterRecord(Const AEntry:T;Const AType:TLedgerType; Const ABalance:T;Const AID:String);virtual; procedure DoBeforeClear(Const AType:TLedgerType);virtual; procedure DoAfterClear(Const AType:TLedgerType);virtual; function DoGetEmptyBalance:T;virtual; function DoGetPositive(Const AEntry:T):Boolean;virtual;abstract; public property Balance : T read GetBalance; property Credits : TLedgerEntryArray<T> read GetCredits; property Debits : TLedgerEntryArray<T> read GetDebits; property Entries[Const AID:String] : TLedgerEntry<T> read GetEntries;default; property Count[Const ATypes:TLedgerTypes] : Cardinal read GetCount; function RecordEntry(Const AEntry:T;Const AType:TLedgerType; Const ATimestamp:TDateTime; Out ID:String):ILedger<T>;overload; function RecordEntry(Const AEntry:T;Const AType:TLedgerType; Out ID:String):ILedger<T>;overload; function RecordEntry(Const AEntry:T; Const AType:TLedgerType):ILedger<T>;overload; function RecordEntries(Const AEntries:TLedgerEntryArray<T>):ILedger<T>; function Flatten : ILedger<T>; function Filter(Const AFilter:TFilter<T>; Out Entries:TLedgerEntryArray<T>):ILedger<T>; function Clear(Const AType:TLedgerType):ILedger<T>;overload; function Clear:ILedger<T>;overload; constructor Create;virtual; destructor Destroy;override; end; implementation uses SysUtils; { TLedgerImpl } function TLedgerImpl<T>.GetBalance: T; begin Result:=FLastBalance; end; function TLedgerImpl<T>.GetCount(const ATypes: TLedgerTypes): Cardinal; begin if (ATypes=[]) or (ATypes=[ltCredit,ltDebit]) then Result:=Length(FCredits) + Length(FDebits) else if ATypes=[ltCredit] then Result:=Length(FCredits) else Result:=Length(FDebits); end; function TLedgerImpl<T>.GetCredits: TLedgerEntryArray<T>; begin Result:=FCredits; end; function TLedgerImpl<T>.GetDebits: TLedgerEntryArray<T>; begin Result:=FDebits; end; function TLedgerImpl<T>.GetEntries(const AID: String): TLedgerEntry<T>; var I:Integer; LPair:TEntryPair; begin Critical.Enter; try if not FMap.Sorted then FMap.Sort; I:=FMap.IndexOf(AID); if I<0 then raise Exception.Create(AID + ' is not a valid ID'); LPair:=FMap.Data[I]; //now use the type of the pair to determine which array to use if LPair.LedgerType=ltCredit then Result:=FCredits[LPair.Index] else Result:=FDebits[LPair.Index]; finally Critical.Leave; end; end; function TLedgerImpl<T>.RecordEntry(const AEntry: T; const AType: TLedgerType; const ATimestamp: TDateTime; out ID: String): ILedger<T>; var LEntry:TLedgerEntry<T>; LPair:TEntryPair; begin Result:=Self as ILedger<T>; //set local record LEntry.ID:=TGuid.NewGuid().ToString(); LEntry.TimeStamp:=ATimeStamp; LEntry.Entry:=AEntry; LEntry.LedgerType:=AType; Critical.Enter; try try //depending on type, put record in proper array if AType=ltCredit then begin SetLength(FCredits,Succ(Length(FCredits))); FCredits[High(FCredits)]:=LEntry; FLastBalance:=FLastBalance + AEntry; LPair.LedgerType:=ltCredit; LPair.Index:=High(FCredits); end else begin SetLength(FDebits,Succ(Length(FDebits))); FDebits[High(FDebits)]:=LEntry; FLastBalance:=FLastBalance - AEntry; LPair.LedgerType:=ltDebit; LPair.Index:=High(FDebits); end; //store the pair in the map ID:=LEntry.ID; FMap.Add(ID,LPair); except on E:Exception do raise E; end; finally Critical.Leave; end; end; function TLedgerImpl<T>.RecordEntry(const AEntry: T; const AType: TLedgerType; out ID: String): ILedger<T>; begin Result:=RecordEntry(AEntry,AType,Now,ID); end; function TLedgerImpl<T>.RecordEntry(Const AEntry:T; Const AType:TLedgerType):ILedger<T>; var LID:String; begin Result:=RecordEntry(AEntry,AType,LID); end; function TLedgerImpl<T>.RecordEntries( const AEntries: TLedgerEntryArray<T>): ILedger<T>; var I:Integer; LEntry:TLedgerEntry<T>; LPair:TEntryPair; begin Result:=Self as ILedger<T>; if not FMap.Sorted then FMap.Sort; for I:=0 to High(AEntries) do begin LEntry:=AEntries[I]; //allow caller to assign id's, but we have to make sure they are unique if (LEntry.ID.IsEmpty) or (FMap.IndexOf(LEntry.ID)>=0) then LEntry.ID:=TGUID.NewGuid.ToString; LPair.LedgerType:=LEntry.LedgerType; Critical.Enter; try //use corresponding array for type if AEntries[I].LedgerType=ltCredit then begin SetLength(FCredits,Succ(Length(FCredits))); FCredits[High(FCredits)]:=LEntry; LPair.Index:=High(FCredits); end else begin SetLength(FDebits,Succ(Length(FDebits))); FDebits[High(FDebits)]:=LEntry; LPair.Index:=High(FDebits); end; //update the map FMap.AddOrSetData(LEntry.ID,LPair); finally Critical.Leave; end; end; //now rebalance after adding everything Rebalance; end; function TLedgerImpl<T>.Flatten: ILedger<T>; var LEntry:T; LType:TLedgerType; LID:String; begin Critical.Enter; try LEntry:=FLastBalance; Clear; if DoGetPositive(FLastBalance) then LType:=ltCredit else begin LType:=ltDebit; //we record debits as positive numbers so multiply by -1 LEntry:=LEntry * -1; end; Result:=RecordEntry(LEntry,LType,Now,LID); finally Critical.Leave; end; end; function TLedgerImpl<T>.Clear(const AType: TLedgerType):ILedger<T>; var I:Integer; begin Result:=Self as ILedger<T>; DoBeforeClear(AType); Critical.Enter; try if AType=ltCredit then begin for I:=0 to High(FCredits) do FMap.Remove(FCredits[I].ID); SetLength(FCredits,0) end else begin for I:=0 to High(FDebits) do FMap.Remove(FDebits[I].ID); SetLength(FDebits,0); end; finally Critical.Leave; end; //rebalance after a clear has been called Rebalance; DoAfterClear(AType); end; function TLedgerImpl<T>.Clear:ILedger<T>; begin Result := Self as ILedger<T>; Clear(ltCredit); Clear(ltDebit); end; procedure TLedgerImpl<T>.DoBeforeRecord(Const AEntry:T;Const AType:TLedgerType); begin end; procedure TLedgerImpl<T>.DoAfterRecord(Const AEntry:T;Const AType:TLedgerType; Const ABalance:T;Const AID:String); begin end; procedure TLedgerImpl<T>.DoBeforeClear(Const AType:TLedgerType); begin end; procedure TLedgerImpl<T>.DoAfterClear(Const AType:TLedgerType); begin end; procedure TLedgerImpl<T>.Rebalance; var I:Integer; begin Critical.Enter; try //first set balance to empty FLastBalance:=DoGetEmptyBalance; //sum all of the credits and debits for I:=0 to High(FCredits) do FLastBalance:=FLastBalance + FCredits[I].Entry; for I:=0 to High(FDebits) do FLastBalance:=FLastBalance - FDebits[I].Entry; finally Critical.Leave; end; end; function TLedgerImpl<T>.DoGetEmptyBalance:T; begin end; function TLedgerImpl<T>.Filter(Const AFilter:TFilter<T>; Out Entries:TLedgerEntryArray<T>):ILedger<T>; var I:Integer; begin Result:=Self as ILedger<T>; if not Assigned(AFilter) then Exit; Critical.Enter; try //filter credits for I:=0 to High(FCredits) do begin if AFilter(FCredits[I].Entry,FCredits[I].LedgerType) then begin SetLength(Entries,Succ(Length(Entries))); Entries[High(Entries)]:=FCredits[I]; end; end; //filter debits for I:=0 to High(FDebits) do begin if AFilter(FDebits[I].Entry,FDebits[I].LedgerType) then begin SetLength(Entries,Succ(Length(Entries))); Entries[High(Entries)]:=FDebits[I]; end; end; finally Critical.Leave; end; end; constructor TLedgerImpl<T>.Create; begin FMap:=TMap.Create; FLastBalance:=DoGetEmptyBalance; end; destructor TLedgerImpl<T>.Destroy; begin FMap.Free; inherited Destroy; end; initialization Critical:=TCriticalSection.Create; finalization Critical.Free; end.
unit UDbfCommon; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Db, ExtCtrls, DBCtrls, Grids, DBGrids, Menus, Buttons, ComCtrls; type TDbfFieldType = char; {$I _DbfCommon.inc} {$ifndef DELPHI_5} procedure FreeAndNil(var v); {$endif} procedure FileCopy(source,dest:string); const // _MAJOR_VERSION _MAJOR_VERSION = 5; // _MINOR_VERSION _MINOR_VERSION = 002; type EDBFError = Exception; PBookMarkData = ^rBookMarkData; rBookmarkData = record IndexBookmark:longint; RecNo:longint; end; implementation procedure FileCopy(source,dest:string); begin CopyFile(PCHAR(source),PCHAR(dest),FALSE); end; {$ifndef DELPHI_5} procedure FreeAndNil(var v); begin try TObject(v).Free; finally TObject(v):=nil; end; end; {$endif} initialization end.
{ Double Commander ------------------------------------------------------------------------- Multi-Rename path range selector dialog window Copyright (C) 2007-2020 Alexander Koblov (alexx2000@mail.ru) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit fSelectPathRange; {$mode objfpc}{$H+} interface uses //Lazarus, Free-Pascal, etc. Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ButtonPanel, Buttons, ExtCtrls, //DC uOSForms; type { TfrmSelectPathRange } TfrmSelectPathRange = class(TModalForm) lblSelectDirectories: TLabel; lbDirectories: TListBox; pnlChoices: TPanel; gbCountFrom: TGroupBox; rbFirstFromStart: TRadioButton; rbFirstFromEnd: TRadioButton; edSeparator: TLabeledEdit; lblResult: TLabel; lblValueToReturn: TLabel; ButtonPanel: TButtonPanel; procedure FormCreate(Sender: TObject); procedure edtSelectTextKeyUp(Sender: TObject; var {%H-}Key: word; {%H-}Shift: TShiftState); procedure edtSelectTextMouseUp(Sender: TObject; {%H-}Button: TMouseButton; {%H-}Shift: TShiftState; {%H-}X, {%H-}Y: integer); procedure lbDirectoriesSelectionChange(Sender: TObject; {%H-}User: boolean); procedure SomethingChange(Sender: TObject); private FPrefix: string; procedure ResfreshHint; public property Prefix: string read FPrefix write FPrefix; end; function ShowSelectPathRangeDlg(TheOwner: TCustomForm; const ACaption, AText, sPrefix: string; var sResultingMaskValue: string): boolean; implementation {$R *.lfm} uses //Lazarus, Free-Pascal, etc. //DC uGlobs; { TfrmSelectPathRange } { TfrmSelectPathRange.FormCreate } procedure TfrmSelectPathRange.FormCreate(Sender: TObject); begin InitPropStorage(Self); end; { TfrmSelectPathRange.edtSelectTextKeyUp } procedure TfrmSelectPathRange.edtSelectTextKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); begin SomethingChange(Sender); end; { TfrmSelectPathRange.edtSelectTextMouseUp } procedure TfrmSelectPathRange.edtSelectTextMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin SomethingChange(Sender); end; { TfrmSelectPathRange.lbDirectoriesSelectionChange } procedure TfrmSelectPathRange.lbDirectoriesSelectionChange(Sender: TObject; User: boolean); begin SomethingChange(Sender); end; { TfrmSelectPathRange.SomethingChange } procedure TfrmSelectPathRange.SomethingChange(Sender: TObject); begin ResfreshHint; end; { TfrmSelectPathRange.ResfreshHint } procedure TfrmSelectPathRange.ResfreshHint; var sTempo: string; iSeeker: integer; begin rbFirstFromEnd.Checked := not rbFirstFromStart.Checked; sTempo := ''; for iSeeker := 0 to pred(lbDirectories.Items.Count) do if lbDirectories.Selected[iSeeker] then begin if sTempo <> '' then sTempo += edSeparator.Text; if rbFirstFromStart.Checked then sTempo += '[' + Prefix + IntToStr(iSeeker) + ']' else sTempo += '[' + Prefix + '-' + IntToStr(lbDirectories.Items.Count - iSeeker) + ']'; end; lblValueToReturn.Caption := sTempo; end; { ShowSelectPathRangeDlg } function ShowSelectPathRangeDlg(TheOwner: TCustomForm; const ACaption, AText, sPrefix: string; var sResultingMaskValue: string): boolean; var Directories: TStringArray; sDirectory: string; begin with TfrmSelectPathRange.Create(TheOwner) do try Result := False; rbFirstFromEnd.Checked := not rbFirstFromStart.Checked; edSeparator.Text := gMulRenPathRangeSeparator; Caption := ACaption; Directories := (Trim(AText)).Split([PathDelim]); for sDirectory in Directories do lbDirectories.Items.Add(sDirectory); Prefix := sPrefix; if ShowModal = mrOk then begin if lblValueToReturn.Caption <> '' then begin gMulRenPathRangeSeparator := edSeparator.Text; sResultingMaskValue := lblValueToReturn.Caption; Result := True; end; end; finally Free; end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileHDR<p> HDR File support for GLScene. <b>History : </b><font size=-1><ul> <li>04/11/10 - DaStr - Added Delphi5 and Delphi6 compatibility <li>23/08/10 - Yar - Replaced OpenGL1x to OpenGLTokens <li>08/05/10 - Yar - Removed check for residency in AssignFromTexture <li>22/04/10 - Yar - Fixes after GLState revision <li>23/11/10 - DaStr - Added $I GLScene.inc <li>23/01/10 - Yar - Added to AssignFromTexture CurrentFormat parameter <li>20/01/10 - Yar - Creation </ul><p> } unit GLFileHDR; {$I GLScene.inc} interface uses System.Classes, System.SysUtils, //GLS OpenGLTokens, GLContext, GLGraphics, GLTextureFormat, GLApplicationFileIO, GLCrossPlatform, GLSRGBE, GLVectorTypes, GLVectorGeometry; type TGLHDRImage = class(TGLBaseImage) private function GetProgramType: Ansistring; procedure SetProgramType(aval: Ansistring); protected fGamma: Single; // image has already been gamma corrected with // given gamma. defaults to 1.0 (no correction) */ fExposure: Single; // a value of 1.0 in an image corresponds to // <exposure> watts/steradian/m^2. // defaults to 1.0 fProgramType: string[16]; public class function Capabilities: TDataFileCapabilities; override; procedure LoadFromFile(const filename: string); override; procedure LoadFromStream(stream: TStream); override; procedure AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: Boolean; const intFormat: TGLInternalFormat); reintroduce; property Gamma: Single read fGamma; property Exposure: Single read fExposure; property ProgramType: Ansistring read GetProgramType write SetProgramType; end; //--------------------------------------------------------------------- //--------------------------------------------------------------------- //--------------------------------------------------------------------- implementation //--------------------------------------------------------------------- //--------------------------------------------------------------------- //--------------------------------------------------------------------- // ------------------ // ------------------ TGLHDRImage ------------------ // ------------------ // LoadFromFile // procedure TGLHDRImage.LoadFromFile(const filename: string); var fs: TStream; begin if FileStreamExists(fileName) then begin fs := CreateFileStream(fileName, fmOpenRead); try LoadFromStream(fs); finally fs.Free; ResourceName := filename; end; end else raise EInvalidRasterFile.CreateFmt('File %s not found', [filename]); end; procedure TGLHDRImage.LoadFromStream(stream: TStream); const cRgbeFormat32bit = 'FORMAT=32-bit_rle_rgbe'; cGamma = 'GAMMA='; cEXPOSURE = 'EXPOSURE='; cY = '-Y '; var buf: array[0..1023] of AnsiChar; header: TStringList; s, sn: string; lineSize: integer; tempBuf, top, bottom: PByte; i, j, err: Integer; formatDefined: boolean; function CmpWord(const word: string): boolean; var l: Integer; ts: string; begin Result := false; ts := header.Strings[i]; if Length(word) > Length(ts) then Exit; for l := 1 to Length(word) do if word[l] <> ts[l] then Exit; Result := true; end; begin fProgramtype := ''; fGamma := 1.0; fExposure := 1.0; UnMipmap; // Read HDR header stream.Read(buf, Length(buf) * sizeOf(AnsiChar)); header := TStringList.Create; s := ''; i := 0; j := 0; while i < Length(buf) do begin if buf[i] = #0 then Break; if buf[i] = #10 then begin header.Add(s); s := ''; Inc(i); j := i; Continue; end; s := s + string(buf[i]); Inc(i); end; if i < Length(buf) then stream.Position := j else raise EInvalidRasterFile.Create('Can''t find HDR header end.'); if (header.Strings[0][1] <> '#') or (header.Strings[0][2] <> '?') then begin header.Free; raise EInvalidRasterFile.Create('Bad HDR initial token.'); end; // Get program type SetProgramtype(AnsiString(Copy(header.Strings[0], 3, Length(header.Strings[0]) - 2))); formatDefined := false; for i := 1 to header.Count - 1 do begin if header.Strings[i] = cRgbeFormat32bit then formatDefined := true else if CmpWord(cGamma) then begin j := Length(cGamma); s := Copy(header.Strings[i], j + 1, Length(header.Strings[i]) - j); val(s, fGamma, err); if err <> 0 then raise EInvalidRasterFile.Create('Bad HDR header.'); end else if CmpWord(cEXPOSURE) then begin j := Length(cEXPOSURE); s := Copy(header.Strings[i], j + 1, Length(header.Strings[i]) - j); val(s, fExposure, err); if err <> 0 then raise EInvalidRasterFile.Create('Bad HDR header.'); end else if CmpWord(cY) then begin j := Length(cY); s := Copy(header.Strings[i], j + 1, Length(header.Strings[i]) - j); j := Pos(' ', s); sn := Copy(s, 1, j - 1); val(sn, FLOD[0].Height, err); Delete(s, 1, j + 3); // scip '+X ' val(s, FLOD[0].Width, err); if err <> 0 then raise EInvalidRasterFile.Create('Bad HDR header.'); end end; // for i header.Free; if not formatDefined then raise EInvalidRasterFile.Create('no FORMAT specifier found.'); if (FLOD[0].Width = 0) or (FLOD[0].Height = 0) then raise EInvalidRasterFile.Create('Bad image dimension.'); //set all the parameters FLOD[0].Depth := 0; fColorFormat := GL_RGB; fInternalFormat := tfRGBA_FLOAT32; fDataType := GL_FLOAT; fCubeMap := false; fTextureArray := false; fElementSize := GetTextureElementSize(tfFLOAT_RGB32); ReallocMem(fData, DataSize); LoadRLEpixels(stream, PSingle(fData), FLOD[0].Width, FLOD[0].Height); //hdr images come in upside down then flip it lineSize := fElementSize * FLOD[0].Width; GetMem(tempBuf, lineSize); top := PByte(fData); bottom := top; Inc(bottom, lineSize * (FLOD[0].Height - 1)); for j := 0 to (FLOD[0].Height div 2) - 1 do begin Move(top^, tempBuf^, lineSize); Move(bottom^, top^, lineSize); Move(tempBuf^, bottom^, lineSize); Inc(top, lineSize); Dec(bottom, lineSize); end; FreeMem(tempBuf); end; function TGLHDRImage.GetProgramType: Ansistring; begin Result := fProgramType; end; procedure TGLHDRImage.SetProgramType(aval: Ansistring); var i: integer; begin for i := 1 to Length(fProgramType) do fProgramType[i] := aval[i]; end; // AssignFromTexture // procedure TGLHDRImage.AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: Boolean; const intFormat: TGLInternalFormat); var oldContext: TGLContext; contextActivate: Boolean; texFormat: Cardinal; residentFormat: TGLInternalFormat; glTarget: TGLEnum; begin glTarget := DecodeGLTextureTarget(textureTarget); if not ((glTarget = GL_TEXTURE_2D) or (glTarget = GL_TEXTURE_RECTANGLE)) then Exit; oldContext := CurrentGLContext; contextActivate := (oldContext <> textureContext); if contextActivate then begin if Assigned(oldContext) then oldContext.Deactivate; textureContext.Activate; end; try textureContext.GLStates.TextureBinding[0, textureTarget] := textureHandle; fLevelCount := 0; fCubeMap := false; fTextureArray := false; fColorFormat := GL_RGB; fDataType := GL_FLOAT; // Check level existence GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_INTERNAL_FORMAT, @texFormat); if texFormat > 1 then begin GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_WIDTH, @FLOD[0].Width); GL.GetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_HEIGHT, @FLOD[0].Height); FLOD[0].Depth := 0; residentFormat := OpenGLFormatToInternalFormat(texFormat); if CurrentFormat then fInternalFormat := residentFormat else fInternalFormat := intFormat; Inc(fLevelCount); end; if fLevelCount > 0 then begin fElementSize := GetTextureElementSize(fColorFormat, fDataType); ReallocMem(FData, DataSize); GL.GetTexImage(glTarget, 0, fColorFormat, fDataType, fData); end else fLevelCount := 1; GL.CheckError; finally if contextActivate then begin textureContext.Deactivate; if Assigned(oldContext) then oldContext.Activate; end; end; end; // Capabilities // class function TGLHDRImage.Capabilities: TDataFileCapabilities; begin Result := [dfcRead {, dfcWrite}]; end; initialization { Register this Fileformat-Handler with GLScene } RegisterRasterFormat('hdr', 'High Dynamic Range Image', TGLHDRImage); end.
unit UFormCadastro; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, FireDAC.Comp.Client, Data.DB, Vcl.Buttons, UBarraBotoes, Vcl.DBCtrls, UDBCampoCodigo; type TFFormCadastro = class(TForm) sbDados: TScrollBox; FrBarraBotoes: TFBarraBotoes; procedure FrBarraBotoesbtSalvarClick(Sender: TObject); procedure FrBarraBotoesbtExluirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FrBarraBotoesbtNovoClick(Sender: TObject); procedure FrBarraBotoesdsDadosStateChange(Sender: TObject); procedure FrBarraBotoesbtAlterarClick(Sender: TObject); procedure FrBarraBotoesbtProximoClick(Sender: TObject); procedure FrBarraBotoesbtFecharClick(Sender: TObject); private FiPosQuery : Integer; procedure PreencheCamposDinamicos; procedure MudarComEnter(var Msg: TMsg; var Handled: Boolean); public FPodeCadastrar, FPodeAlterar, FPodeExcluir : Boolean; procedure GravarRegistro; virtual; abstract; procedure ExcluirRegistro; virtual; abstract; procedure PosicionaRegistro; end; var FFormCadastro: TFFormCadastro; implementation uses UTelaInicial, uDmERP, uFuncoes; {$R *.dfm} {$R Icones.res} procedure TFFormCadastro.MudarComEnter(var Msg: TMsg; var Handled: Boolean); begin if not ( (Screen.ActiveControl is TCustomMemo) or // se não for um memo (Screen.ActiveControl is TDBLookupComboBox) or // se não for um DbLookup // (Screen.ActiveControl is TCustomGrid) or // se não for uma grid o controle mudara com enter (Screen.ActiveForm.ClassName = 'TMessageForm') ) then begin if Msg.message = WM_KEYDOWN then begin case Msg.wParam of VK_RETURN,VK_DOWN : Screen.ActiveForm.Perform(WM_NextDlgCtl,0,0); //,VK_TAB VK_UP : Screen.ActiveForm.Perform(WM_NextDlgCtl,1,0); end; end; end; end; procedure TFFormCadastro.FormCreate(Sender: TObject); var i : Integer; begin Application.OnMessage := MudarComEnter; FrBarraBotoes.btAnterior.Glyph.LoadFromResourceName(HInstance, 'IMGBTANTERIOR_32X32'); FrBarraBotoes.btProximo.Glyph.LoadFromResourceName(HInstance, 'IMGBTPROXIMO_32X32'); FrBarraBotoes.btNovo.Glyph.LoadFromResourceName(HInstance, 'IMGBTNOVO_32X32'); FrBarraBotoes.btAlterar.Glyph.LoadFromResourceName(HInstance, 'IMGBTALTERAR_32X32'); FrBarraBotoes.btSalvar.Glyph.LoadFromResourceName(HInstance, 'IMGBTSALVAR_32X32'); FrBarraBotoes.btCancelar.Glyph.LoadFromResourceName(HInstance, 'IMGBTCANCELAR_32X32'); FrBarraBotoes.btExluir.Glyph.LoadFromResourceName(HInstance, 'IMGBTEXCLUIR_32X32'); FrBarraBotoes.btFechar.Glyph.LoadFromResourceName(HInstance, 'IMGBTFECHAR_32X32'); FrBarraBotoes.btImprimir.Glyph.LoadFromResourceName(HInstance, 'IMGBTIMPRIMIR_32X32'); { for i := 0 to DmERP.ComponentCount - 1 do begin if (DmERP.Components[i].ClassName = 'TFDQuery') and (DmERP.Components[i].Name = FrBarraBotoes.dsDados.DataSet.Name) then begin (DmERP.Components[i] as TFDQuery).MacroByName('filtro').Clear; if (Trim(FTelaInicial.FNomeCampoChave) <> '') and (Trim(FTelaInicial.FValorFiltroCampoChave) <> '') then (DmERP.Components[i] as TFDQuery).MacroByName('filtro').Value := ' WHERE ' + Trim(FTelaInicial.FNomeCampoChave) + ' = ' + Trim(FTelaInicial.FValorFiltroCampoChave); (DmERP.Components[i] as TFDQuery).Open(); // (DmERP.Components[i] as TFDQuery).FetchNext; FiPosQuery := i; Break; end; end; } PosicionaRegistro; FTelaInicial.FNomeCampoChave := ''; FTelaInicial.FValorFiltroCampoChave := ''; FrBarraBotoes.HabilitaDesabilitaBotoes; if DmERP.qyPermissaoUsuario.Active then DmERP.qyPermissaoUsuario.Close; DmERP.qyPermissaoUsuario.MacroByName('filtro').Clear; DmERP.qyPermissaoUsuario.ParamByName('cdUsuario').AsInteger := FTelaInicial.FcdUsuario; DmERP.qyPermissaoUsuario.Open(); DmERP.qyPermissaoUsuario.First; if (DmERP.qyPermissaoUsuario.Locate('cdUsuario;nmForm;flAtivo', VarArrayOf( [ FTelaInicial.FcdUsuario, Copy(Self.ClassName, 2, Length(Self.ClassName)-1), 'S' ] ), [] ) ) then begin FPodeCadastrar := (DmERP.qyPermissaoUsuario.FieldByName('flCadastrar').AsString = 'S'); FPodeAlterar := (DmERP.qyPermissaoUsuario.FieldByName('flAlterar').AsString = 'S'); FPodeExcluir := (DmERP.qyPermissaoUsuario.FieldByName('flExcluir').AsString = 'S'); if not FPodeCadastrar then FrBarraBotoes.btNovo.Enabled := False; if not FPodeAlterar then FrBarraBotoes.btAlterar.Enabled := False; if not FPodeExcluir then FrBarraBotoes.btExluir.Enabled := False; end; PreencheCamposDinamicos; end; procedure TFFormCadastro.PreencheCamposDinamicos; var i : Integer; begin if (FPodeCadastrar) and (FTelaInicial.FCamposValoresNovoReg.Count > 0) then begin FrBarraBotoes.dsDados.DataSet.Insert; for i := 0 to FTelaInicial.FCamposValoresNovoReg.Count - 1 do begin if Assigned(FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i])) then begin case FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i]).DataType of ftInteger : FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i]).AsInteger := StrToIntDef(FTelaInicial.FCamposValoresNovoReg.Values[FTelaInicial.FCamposValoresNovoReg.Names[i]], 0); ftFloat : FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i]).AsFloat := StrToFloatDef(FTelaInicial.FCamposValoresNovoReg.Values[FTelaInicial.FCamposValoresNovoReg.Names[i]], 0); ftCurrency: FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i]).AsCurrency := StrToCurrDef(FTelaInicial.FCamposValoresNovoReg.Values[FTelaInicial.FCamposValoresNovoReg.Names[i]], 0); ftDate, ftDateTime: FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i]).AsDateTime := StrToDateTimeDef(FTelaInicial.FCamposValoresNovoReg.Values[FTelaInicial.FCamposValoresNovoReg.Names[i]], 0); ftString, ftWideString: FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i]).AsString := FTelaInicial.FCamposValoresNovoReg.Values[FTelaInicial.FCamposValoresNovoReg.Names[i]]; else FrBarraBotoes.dsDados.DataSet.FieldByName(FTelaInicial.FCamposValoresNovoReg.Names[i]).Value := FTelaInicial.FCamposValoresNovoReg.Values[FTelaInicial.FCamposValoresNovoReg.Names[i]]; end; end; end; end; end; procedure TFFormCadastro.PosicionaRegistro; begin if not FrBarraBotoes.dsDados.DataSet.Active then FrBarraBotoes.dsDados.DataSet.Open; if (Trim(FTelaInicial.FNomeCampoChave) <> '') and (Trim(FTelaInicial.FValorFiltroCampoChave) <> '') then begin FrBarraBotoes.dsDados.DataSet.First; FrBarraBotoes.dsDados.DataSet.Locate(FTelaInicial.FNomeCampoChave, Trim(FTelaInicial.FValorFiltroCampoChave), []); end; end; procedure TFFormCadastro.FrBarraBotoesbtAlterarClick(Sender: TObject); var i : Integer; begin for i := 0 to Self.ComponentCount - 1 do begin if (Self.Components[i].ClassName = 'TDBCampoCodigo') then begin if (Self.Components[i] as TDBCampoCodigo).ERPCampoCodigoPK then begin (Self.Components[i] as TDBCampoCodigo).ERPEdCampoChaveDBEnabled := False; (Self.Components[i] as TDBCampoCodigo).ERPBtProcurarEnabled := False; Break; end; end; end; FrBarraBotoes.btAlterarClick(Sender); end; procedure TFFormCadastro.FrBarraBotoesbtExluirClick(Sender: TObject); begin ExcluirRegistro; end; procedure TFFormCadastro.FrBarraBotoesbtFecharClick(Sender: TObject); begin FTelaInicial.FCamposValoresNovoReg.Clear; FrBarraBotoes.btFecharClick(Sender); end; procedure TFFormCadastro.FrBarraBotoesbtNovoClick(Sender: TObject); var i : Integer; begin FrBarraBotoes.btNovoClick(Sender); PreencheCamposDinamicos; for i := 0 to Self.ComponentCount - 1 do begin if (Self.Components[i].ClassName = 'TDBCampoCodigo') then begin if (Self.Components[i] as TDBCampoCodigo).ERPCampoCodigoPK then begin (Self.Components[i] as TDBCampoCodigo).ERPEdCampoChaveSetFocus; Break; end; end; end; end; procedure TFFormCadastro.FrBarraBotoesbtProximoClick(Sender: TObject); begin // if (DmERP.Components[FiPosQuery] as TFDQuery).Eof then // (DmERP.Components[FiPosQuery] as TFDQuery).FetchNext; FrBarraBotoes.btProximoClick(Sender); end; procedure TFFormCadastro.FrBarraBotoesbtSalvarClick(Sender: TObject); begin GravarRegistro; end; procedure TFFormCadastro.FrBarraBotoesdsDadosStateChange(Sender: TObject); var i : Integer; begin FrBarraBotoes.dsDadosStateChange(Sender); if FrBarraBotoes.dsDados.State = dsBrowse then begin for i := 0 to Self.ComponentCount - 1 do begin if (Self.Components[i].ClassName = 'TDBCampoCodigo') then begin if (Self.Components[i] as TDBCampoCodigo).ERPCampoCodigoPK then begin (Self.Components[i] as TDBCampoCodigo).ERPEdCampoChaveDBEnabled := True; (Self.Components[i] as TDBCampoCodigo).ERPBtProcurarEnabled := True; Break; end; end; end; end; end; end.
unit TestUsesReturns; {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is TestUsesReturns, released Sept 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} { test the feature of adding returns after each item in the uses clause } {$I JcfGlobal.inc} interface uses TestFrameWork, BaseTestProcess; type TTestUsesReturns = class(TBaseTestProcess) private protected procedure SetUp; override; procedure TearDown; override; published procedure Test0; procedure Test1; procedure Test2; procedure Test3; procedure TestComment1; procedure TestComment2; end; implementation uses JcfStringUtils, JcfSettings, TestConstants, ReturnAfter; procedure TTestUsesReturns.Setup; begin inherited; InitTestSettings; JcfFormatSettings.Returns.UsesClauseOnePerLine := True; end; procedure TTestUsesReturns.TearDown; begin inherited; JcfFormatSettings.Returns.UsesClauseOnePerLine := False; end; procedure TTestUsesReturns.Test0; const IN_UNIT_TEXT = UNIT_HEADER + UNIT_FOOTER; OUT_UNIT_TEXT = SPACED_UNIT_HEADER + UNIT_FOOTER; begin TestProcessResult(TReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestUsesReturns.Test1; const IN_UNIT_TEXT = UNIT_HEADER + ' uses foo; ' + UNIT_FOOTER; OUT_UNIT_TEXT = SPACED_UNIT_HEADER + NativeLineBreak + ' uses' + NativeLineBreak + 'foo;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestUsesReturns.Test2; const IN_UNIT_TEXT = UNIT_HEADER + ' uses foo, bar; ' + UNIT_FOOTER; OUT_UNIT_TEXT = SPACED_UNIT_HEADER + NativeLineBreak + ' uses' + NativeLineBreak + 'foo,' + NativeLineBreak + 'bar;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestUsesReturns.Test3; const IN_UNIT_TEXT = UNIT_HEADER + ' uses foo, bar, fish; ' + UNIT_FOOTER; OUT_UNIT_TEXT = SPACED_UNIT_HEADER + NativeLineBreak + ' uses' + NativeLineBreak + 'foo,' + NativeLineBreak + 'bar,' + NativeLineBreak + 'fish;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestUsesReturns.TestComment1; const IN_UNIT_TEXT = UNIT_HEADER + ' uses foo {foo}, bar, fish; ' + UNIT_FOOTER; OUT_UNIT_TEXT = SPACED_UNIT_HEADER + NativeLineBreak + ' uses' + NativeLineBreak + 'foo {foo},' + NativeLineBreak + 'bar,' + NativeLineBreak + 'fish;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; procedure TTestUsesReturns.TestComment2; const IN_UNIT_TEXT = UNIT_HEADER + ' uses foo, {foo} bar, fish; ' + UNIT_FOOTER; OUT_UNIT_TEXT = SPACED_UNIT_HEADER + NativeLineBreak + ' uses' + NativeLineBreak + 'foo, {foo} bar,' + NativeLineBreak + 'fish;' + NativeLineBreak + UNIT_FOOTER; begin TestProcessResult(TReturnAfter, IN_UNIT_TEXT, OUT_UNIT_TEXT); end; initialization TestFramework.RegisterTest('Processes', TTestUsesReturns.Suite); end.
unit mystruct_i; {This file was generated on 11 Aug 2000 20:16:58 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file mystruct.idl. } {Delphi Pascal unit : mystruct_i } {derived from IDL module : default } interface uses CORBA; type MyStructType = interface; Account = interface; MyStructType = interface ['{44AD6CE9-72D0-7AAA-C89D-F121E29DEC57}'] function _get_s : SmallInt; procedure _set_s (const s : SmallInt); function _get_l : Integer; procedure _set_l (const l : Integer); function _get_st : AnsiString; procedure _set_st (const st : AnsiString); property s : SmallInt read _get_s write _set_s; property l : Integer read _get_l write _set_l; property st : AnsiString read _get_st write _set_st; end; Account = interface ['{047D6870-94B0-BEB9-3CBD-817BBAC35C65}'] function balance (const inMyStruct : mystruct_i.MyStructType; out outMyStruct : mystruct_i.MyStructType; var inoutMyStruct : mystruct_i.MyStructType): Single; end; implementation initialization end.
unit ResizerConstsUnit; /////////////////////////////////////////////////////////////////////////////// // // Description: Constants, string or otherwise, useful to Resizer // /////////////////////////////////////////////////////////////////////////////// interface const // Extensions EXTENSION_BMP = '.bmp'; EXTENSION_JPG = '.jpg'; EXTENSION_JPEG = '.jpeg'; // Comparisons COMPARE_BMP = 'BMP'; COMPARE_JPG = 'JPG'; COMPARE_JPEG = 'JPEG'; COMPARE_FILES = 'files'; COMPARE_DIRECTORY = 'directory'; COMPARE_RECURSIVE_DIRECTORY = 'recursive'; COMPARE_FILELIST = 'f'; COMPARE_PRESERVE = 'preserve'; COMPARE_CONVERT = 'convert'; COMPARE_FACTOR = 'factor'; COMPARE_CALCULATE = 'calc'; COMPARE_CONV_JPG = 'jpg'; COMPARE_CONV_BMP = 'bmp'; COMPARE_OVERWRITE = 'overwrite'; COMPARE_SKIP = 'skip'; /////////////////////////// // Not implemented yet : // /////////////////////////// { EXTENSION_GIF = '.gif'; EXTENSION_PNG = '.png'; COMPARE_GIF = 'GIF'; COMPARE_PNG = 'PNG'; COMPARE_CONV_GIF = 'gif'; COMPARE_CONV_PNG = 'png'; } implementation end.
unit cls_TClients; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type TClients = class private { Private declarations } userName : string ; clientName : string ; clientSurname : string ; public { Public declarations } Constructor Create (pUserName, pClientName, pClientSurname : string ); Function GetUserName : string ; Function GetClientName : string ; Function GetClientSurname : string ; end; implementation {$R *.dfm} { TClients } constructor TClients.Create(pUserName, pClientName, pClientSurname: string); begin userName := pUserName ; clientName := pClientName ; clientSurname := pClientSurname ; end; function TClients.GetClientName: string; begin Result := clientSurname ; end; function TClients.GetClientSurname: string; begin Result := clientSurname ; end; function TClients.GetUserName: string; begin Result := userName ; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: Q3MD3<p> Helper classes and methods for Quake3 MD3 actors<p> History : 14/04/03 - SG - Streamlined the TMD3TagList.LoadFromStream a little 04/04/03 - SG - Changes made to LoadQ3Skin procedure (as suggested by Mrqzzz) 03/04/03 - SG - Added LoadQ3Skin procedure 01/04/03 - Mrqzzz - "LEGS_" animations read from .CFG fixed 17/02/03 - SG - Creation } unit Q3MD3; interface uses Classes, SysUtils, GLApplicationFileIO, GLVectorGeometry, GLVectorFileObjects, GLVectorLists, GLMaterial, FileMD3; type // This class is used to extract the tag transform information // stored in the MD3 files. The data is used to offset each // part of the model based on the parent parts animation state. TMD3TagList = class private FTags : array of TMD3Tag; FNumTags, FNumFrames : Integer; function GetTag(index: integer): TMD3Tag; public procedure LoadFromFile(FileName:String); procedure LoadFromStream(AStream:TStream); function GetTransform(TagName:string; Frame:integer):TMatrix; property TagCount : integer read FNumTags; property FrameCount : integer read FNumFrames; property Tags[index:integer]:TMD3Tag read GetTag; end; // These procedures are helpers to load the Quake3 animation file data // into an animation list. The NamePrefix parameter is used to determine // which class of animation is extracted. eg NamePrefix='TORSO' will load // all animations starting with 'TORSO_' like 'TORSO_STAND' procedure LoadQ3Anims(Animations:TActorAnimations; FileName:string; NamePrefix:string); overload; procedure LoadQ3Anims(Animations:TActorAnimations; Strings:TStrings; NamePrefix:string); overload; // Quake3 Skin loading procedure. Use this procedure to apply textures // to a GLActor. This doens't use the actors original preloaded materials so // it may be a good idea to clear the actors material library before // running this to keep everything nice and clean. procedure LoadQ3Skin(FileName:string; Actor:TGLActor); implementation // LoadQ3Anims // procedure LoadQ3Anims(Animations:TActorAnimations; FileName:string; NamePrefix:string); var AnimStrings:TStrings; begin AnimStrings:=TStringList.Create; AnimStrings.LoadFromFile(FileName); LoadQ3Anims(Animations,AnimStrings,NamePrefix); AnimStrings.Free; end; procedure LoadQ3Anims(Animations:TActorAnimations; Strings:TStrings; NamePrefix:string); var anim :TStringList; val : array[0..3] of integer; strindex,valindex,i : integer; GotValues:Boolean; commatext,str1 : string; TorsoStartFrame,LegsStartFrame : integer; // Used to Fix LEGS Frame values red from CFG file function StrIsNumber(str:string):boolean; var i : integer; begin result:=false; for i:=1 to Length(str) do if (Ord(str[i])>=Ord('0')) and (Ord(str[i])<=Ord('9')) then result:=true else begin result:=false; break; end; end; begin anim:=TStringList.Create; TorsoStartFrame := 0; LegsStartFrame := 0; FillChar(val[0], SizeOf(val), $00); for strindex:=0 to Strings.Count-1 do begin commatext:=Strings.Strings[strindex]; while Pos(' ',commatext)>0 do commatext:=StringReplace(commatext,' ',' ',[rfReplaceAll]); commatext:=StringReplace(commatext,' ',',',[rfReplaceAll]); anim.CommaText:=commatext; GotValues:=False; valindex:=0; str1:=''; if anim.Count>=5 then begin for i:=0 to Anim.Count-1 do begin if GotValues then begin // Store start values to Fix LEGS if (TorsoStartFrame=0) and (pos('TORSO_',Uppercase(Anim.Strings[i]))>0) then TorsoStartFrame := val[0]; if (LegsStartFrame=0) and (pos('LEGS_',Uppercase(Anim.Strings[i]))>0) then LegsStartFrame := val[0]; if (Anim.Strings[i]<>'//') and (Pos(NamePrefix+'_',Anim.Strings[i])>0) then begin str1:=StringReplace(Anim.Strings[i],'//','',[rfReplaceAll]); break; end; end else begin if StrIsNumber(Anim.Strings[i]) then begin val[valindex]:=StrToInt(Anim.Strings[i]); Inc(valindex); if valindex=4 then GotValues:=True; end else break; end; end; end; if GotValues and (str1<>'') then begin // Values ready for new animation. with Animations.Add do begin // Fix frame value for Legs if Uppercase(NamePrefix)='LEGS' then val[0] := val[0]-LegsStartFrame+TorsoStartFrame; Name:=str1; StartFrame:=val[0]; EndFrame:=val[0]+val[1]-1; Reference:=aarMorph; // Need a way in TActorAnimation to tell whether it is // a looping type animation or a play once type and // the framerate (interval) it uses. Both of these can // be determined here and loaded. end; end; end; anim.Free; end; // LoadQ3Skin // procedure LoadQ3Skin(FileName:string; Actor:TGLActor); const // This list can be expanded if necessary ExtList : array[0..3] of string = ('.jpg','.jpeg','.tga','.bmp'); var SkinStrings, temp : TStrings; i,j : integer; libmat : TGLLibMaterial; mesh : TMeshObject; texture, textureNoDir : string; textureFound, meshFound : Boolean; function GetMeshObjectByName(MeshObjects:TMeshObjectList; Name:string; var mesh:TMeshObject):Boolean; var i : integer; begin Result:=False; if (trim(Name)='') or not Assigned(MeshObjects) then exit; for i:=0 to MeshObjects.Count-1 do begin if MeshObjects[i].Name=Name then begin mesh:=MeshObjects[i]; Result:=True; break; end; end; end; begin if (not FileExists(FileName)) or (not Assigned(Actor)) then exit; if (not Assigned(Actor.MaterialLibrary)) then exit; SkinStrings:=TStringList.Create; temp:=TStringList.Create; temp.LoadFromFile(FileName); for i:=0 to temp.Count-1 do begin SkinStrings.CommaText:=temp.Strings[i]; if SkinStrings.Count>1 then begin libmat:=Actor.MaterialLibrary.Materials.GetLibMaterialByName(SkinStrings.Strings[1]); meshFound:=GetMeshObjectByName(Actor.MeshObjects,SkinStrings.Strings[0],mesh); if meshFound then begin if not Assigned(libmat) then begin libmat:=Actor.MaterialLibrary.Materials.Add; libmat.Name:=SkinStrings.Strings[1]; // Search for the texture file textureFound:=False; for j:=0 to Length(ExtList)-1 do begin texture:=StringReplace(SkinStrings.Strings[1],'/','\',[rfReplaceAll]); texture:=ChangeFileExt(texture,ExtList[j]); if FileExists(texture) then begin libmat.Material.Texture.Image.LoadFromFile(texture); libmat.Material.Texture.Disabled:=False; textureFound:=True; end else begin textureNoDir:=ExtractFileName(texture); if FileExists(textureNoDir) then begin libmat.Material.Texture.Image.LoadFromFile(textureNoDir); libmat.Material.Texture.Disabled:=False; textureFound:=True; end; end; if textureFound then break; end; end; for j:=0 to mesh.FaceGroups.Count-1 do mesh.FaceGroups[j].MaterialName:=libmat.Name; end; end; end; temp.Free; SkinStrings.Free; end; // ------------------ // ------------------ TMD3TagList ------------------ // ------------------ // LoadFromFile // procedure TMD3TagList.LoadFromFile(FileName:String); var fs : TStream; begin if fileName<>'' then begin fs:=CreateFileStream(FileName, fmOpenRead+fmShareDenyWrite); try LoadFromStream(fs); finally fs.Free; end; end; end; // LoadFromStream // procedure TMD3TagList.LoadFromStream(aStream:TStream); var MD3Header : TMD3Header; begin // Load the MD3 header aStream.Read(MD3Header,SizeOf(MD3Header)); // Test for correct file ID and version Assert(MD3Header.fileID='IDP3','Incorrect MD3 file ID'); Assert(MD3Header.version=15,'Incorrect MD3 version number'); // Get the tags from the file FNumTags:=MD3Header.numTags; FNumFrames:=MD3Header.numFrames; SetLength(FTags,FNumTags*FNumFrames); aStream.Position:=MD3Header.tagStart; aStream.Read(FTags[0],FNumTags*FNumFrames*SizeOf(TMD3Tag)); end; // GetTag // function TMD3TagList.GetTag(index: integer): TMD3Tag; begin Result:=FTags[index]; end; // GetTransform // function TMD3TagList.GetTransform(TagName: string; Frame: integer): TMatrix; var TagIdx,i,j : integer; Tag : TMD3Tag; begin Result:=IdentityHMGMatrix; TagIdx:=-1; for i:=0 to FNumTags do if lowercase(trim(TagName))=lowercase(trim(string(FTags[i].strName))) then begin TagIdx:=i; Break; end; if TagIdx=-1 then exit; Tag:=FTags[TagIdx+Frame*FNumTags]; for j:=0 to 2 do for i:=0 to 2 do Result.V[i].V[j]:=Tag.rotation.V[i].V[j]; for i:=0 to 2 do Result.V[3].V[i]:=Tag.vPosition.V[i]; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FileHistoryAPI; interface uses Winapi.Windows, Winapi.CommCtrl, System.SysUtils, System.Classes, Vcl.Menus, Winapi.ActiveX, ToolsAPI; type {$MINENUMSIZE 4} TOTAHistoryStyle = (hsBuffer, hsFile, hsLocalFile, hsRemoteRevision, hsActiveRevision); {$MINENUMSIZE 1} TOTAFileNameArray = array of WideString; IOTAFileHistoryProvider = interface; IOTAFileHistory = interface; IOTAFileHistoryNotifier = interface; IOTAFileHistoryManager = interface ['{55A2BEE4-A64C-4749-8388-070CAEFDEFA5}'] function AddNotifier(const ANotifier: IOTAFileHistoryNotifier): Integer; procedure AddTemporaryLabel(const ALabelName: WideString; const AFiles: TOTAFileNameArray); function Get_Count: Integer; function GetFileHistoryProvider(Index: Integer): IOTAFileHistoryProvider; function RegisterHistoryProvider(const HistoryProvider: IOTAFileHistoryProvider): Integer; procedure RemoveNotifier(Index: Integer); procedure RevertTemporaryLabel(const ALabelName: WideString); procedure UnregisterHistoryProvider(Index: Integer); procedure UpdateProviders; property Count: Integer read Get_Count; property FileHistoryProvider[Index: Integer]: IOTAFileHistoryProvider read GetFileHistoryProvider; end; IOTAFileHistoryNotifier = interface(IOTANotifier) ['{286AC9E5-875A-4402-AF70-8ACDD6757EC8}'] procedure ProvidersUpdated; end; IOTAAsynchronousHistoryUpdater = interface ['{62711089-2DB3-4C39-B493-CABF73B22174}'] procedure Completed; function UpdateHistoryItems(FileHistory: IOTAFileHistory; FirstNewIndex, LastNewIndex: Integer): Boolean; end; IOTAFileHistoryProvider = interface(IDispatch) ['{B8CDB02D-93D8-4088-AE03-A28052AD0FAD}'] function Get_Ident: WideString; safecall; function Get_Name: WideString; safecall; function GetFileHistory(const AFileName: WideString): IOTAFileHistory; safecall; property Ident: WideString read Get_Ident; property Name: WideString read Get_Name; end; IOTAAsynchronousHistoryProvider = interface ['{BE67C423-C2BC-42D2-BDAF-F859B04A369E}'] procedure StartAsynchronousUpdate(const AFileName: WideString; const AsynchronousHistoryUpdater: IOTAAsynchronousHistoryUpdater); end; IOTAAsynchronousHistoryProvider150 = interface ['{EF5F011A-413C-4B09-92D5-16BC8A8F7C08}'] // This function is called when the history view is hidden or when the // user hits refresh. It is possible for this function to be called even // if the asynchronous update is completed. procedure TerminateAsynchronousUpdate(const AFileName: WideString; WaitForTerminate: Boolean); end; IOTAFileHistory = interface(IDispatch) ['{92E624D2-A7CD-4C89-9B4E-71170955E96C}'] function Get_Count: Integer; safecall; function GetAuthor(Index: Integer): WideString; safecall; function GetComment(Index: Integer): WideString; safecall; function GetContent(Index: Integer): IStream; safecall; function GetDate(Index: Integer): TDateTime; safecall; function GetIdent(Index: Integer): WideString; safecall; function GetHistoryStyle(Index: Integer): TOTAHistoryStyle; safecall; function GetLabelCount(Index: Integer): Integer; safecall; function GetLabels(Index, LabelIndex: Integer): WideString; safecall; property Author[Index: Integer]: WideString read GetAuthor; property Count: Integer read Get_Count; property Comment[Index: Integer]: WideString read GetComment; property Content[Index: Integer]: IStream read GetContent; property Date[Index: Integer]: TDateTime read GetDate; property HistoryStyle[Index: Integer]: TOTAHistoryStyle read GetHistoryStyle; property Ident[Index: Integer]: WideString read GetIdent; property LabelCount[Index: Integer]: Integer read GetLabelCount; property Labels[Index, LabelIndex: Integer]: WideString read GetLabels; end; { This is used whenever the mouse hovers over an entry in the Contents or Diff sub view of the history view. This should be implemented by the same object as IOTAFileHistory. } IOTAFileHistoryHint = interface ['{93437601-728C-4397-83AE-DAA64A9BA3D1}'] function GetHintStr(Index: Integer): string; property HintStr[Index: Integer]: string read GetHintStr; end; IOTAAnnotationLineProvider = interface ['{4443660D-A0D7-4F25-8842-C576E341F2A8}'] function GetCount: Integer; function GetGutterInfo(Index: Integer): string; { Used to show the age of the line. The valid range is 0 - 1000. The oldest code should have a value of 0 with the newest having a value of 1000. Use -1 if you wish to use the default color. } function GetIntensity(Index: Integer): Integer; { Return the maximum number of characters of all the gutter strings. Used to set the fixed gutter width. } function GetMaxGutterWidth: Integer; function GetHintStr(Index: Integer): string; property Count: Integer read GetCount; property GutterInfo[Index: Integer]: string read GetGutterInfo; property MaxGutterWidth: Integer read GetMaxGutterWidth; property HintStr[Index: Integer]: string read GetHintStr; property Intensity[Index: Integer]: Integer read GetIntensity; end; IOTAAnnotationCompletion = interface ['{1888C1E9-CB2F-4889-84F6-0BA01A25EF1F}'] procedure AnnotationComplete(const AnnotationLineProvider: IOTAAnnotationLineProvider); end; { This should be implemented in the same object that implements IOTAFileHistory. } IOTAAsynchronousAnnotationProvider = interface ['{29769D00-295C-43D9-9D7C-4FF0184B850B}'] function CanAnnotateFile(const FileName: string): Boolean; procedure StartAsynchronousUpdate(const FileName: string; FileHistoryIndex: Integer; const AnnotationCompletion: IOTAAnnotationCompletion); end; implementation end.
unit uLembrete; interface uses System.SysUtils; Type TLembrete = class private FTitulo: String; FDataHora: TDateTime; FDescricao: String; FIDLembrete: Integer; procedure SetDataHora(const Value: TDateTime); procedure SetDescricao(const Value: String); procedure SetIDLembrete(const Value: Integer); procedure SetTitulo(const Value: String); { private declarations } protected { protected declarations } public { public declarations } constructor Create; property IDLembrete: Integer read FIDLembrete write SetIDLembrete; property Titulo: String read FTitulo write SetTitulo; property Descricao: String read FDescricao write SetDescricao; property DataHora: TDateTime read FDataHora write SetDataHora; published { published declarations } end; implementation { TLembrete } constructor TLembrete.Create; begin FIDLembrete := 0; FTitulo := ''; FDescricao := ''; FDataHora := EncodeDate(1900,1,1); end; procedure TLembrete.SetDataHora(const Value: TDateTime); begin FDataHora := Value; end; procedure TLembrete.SetDescricao(const Value: String); begin FDescricao := Value; end; procedure TLembrete.SetIDLembrete(const Value: Integer); begin FIDLembrete := Value; end; procedure TLembrete.SetTitulo(const Value: String); begin FTitulo := Value; end; end.
unit MainForm; interface uses DAOTest, ListeningForm, SpeakingForm, SpeakingSQLUnit, WritingForm, ReadingForm, MainSQLUnit, TestClasses, JoanModule, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Generics.Collections; // type TfrMain = class(TForm) PanelTop: TPanel; PanelBottonParent: TPanel; PanelLeft: TPanel; PanelClient: TPanel; btAdd: TButton; btModify: TButton; btDelete: TButton; PageControl: TPageControl; tsListening: TTabSheet; tsReading: TTabSheet; ListViewTest: TListView; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ListViewTestSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btModifyClick(Sender: TObject); procedure btDeleteClick(Sender: TObject); procedure btAddClick(Sender: TObject); private TestInfo: TObjectList<TTest>; DAO: TDAOTest; public ListeningFormWindow : TfrListening; ReadingFormWindow : TfrReading; procedure PrintListView; end; var frMain: TfrMain; implementation {$R *.dfm} procedure TfrMain.btAddClick(Sender: TObject); var Title: string; begin if InputQuery('추가', '새로운 이름을 입력하세요', Title) then begin DAO.Add(Title); PrintListView; end; end; procedure TfrMain.btDeleteClick(Sender: TObject); begin if messagedlg('정말 삭제하시겠습니까?', mtWarning, mbYesNo,0)= mryes then begin DAO.Delete(TTest(ListViewTest.Selected.Data).Idx); PrintListView; end; end; procedure TfrMain.btModifyClick(Sender: TObject); var Title : string; Index : integer; begin if InputQuery('수정', '새로운 이름을 입력하세요', Title) then begin DAO.Edit(TTest(ListViewTest.Selected.Data).Idx,Title); PrintListView; end; end; procedure TfrMain.FormCreate(Sender: TObject); begin DAO := TDAOTest.Create; // Application.CreateForm(TfrListening, frListening); ListeningFormWindow := TfrListening.Create(nil); ListeningFormWindow.Parent := tsListening; ListeningFormWindow.Show; ReadingFormWindow := TfrReading.Create(nil); ReadingFormWindow.Parent := tsReading; ReadingFormWindow.Show; PrintListView; end; procedure TfrMain.FormDestroy(Sender: TObject); begin DAO.Free; TestInfo.Free; end; procedure TfrMain.ListViewTestSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if Selected then begin ListeningFormWindow.DefListening(TTest(Item.Data)); ReadingFormWindow.SetReadingIndex(TTest(Item.Data)); end else begin exit; end; end; procedure TfrMain.PrintListView; var I: Integer; ListItem: TListItem; begin FreeAndNil(TestInfo); TestInfo := DAO.GetList; ListViewTest.Clear; for I := 0 to TestInfo.Count - 1 do begin ListItem := ListViewTest.Items.Add; ListItem.Caption := TestInfo.Items[I].Title; ListItem.Data := TestInfo.Items[I]; end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$Q-} unit System.Hash; interface uses System.Classes, System.SysUtils; type /// <summary> Hash related Exceptions </summary> EHashException = class(Exception); /// <summary> Record with common functionality to all Hash functions</summary> THash = record /// <summary>Convert a Digest into an Integer if it's length its four</summary> class function DigestAsInteger(const ADigest: TBytes): Integer; static; /// <summary>Convert a Digest into a hexadecimal value string</summary> class function DigestAsString(const ADigest: TBytes): string; static; /// <summary>Convert a Digest into a GUID if it's length its sixteen</summary> class function DigestAsStringGUID(const ADigest: TBytes): string; static; /// <summary> Gets a random string with the given length</summary> class function GetRandomString(const ALen: Integer = 10): string; static; /// <summary> Gets the BigEndian memory representation of a cardinal value</summary> class function ToBigEndian(AValue: Cardinal): Cardinal; overload; static; inline; /// <summary> Gets the BigEndian memory representation of a UInt64 value</summary> class function ToBigEndian(AValue: UInt64): UInt64; overload; static; inline; end; /// <summary> Record to generate MD5 Hash values from data. Stores internal state of the process</summary> THashMD5 = record private type TContextState = array [0..15] of Cardinal; TContextBuffer = array [0..63] of Byte; private FPadding: TContextBuffer; FContextState: array [0..3] of Cardinal; FContextCount: array [0..1] of Cardinal; FContextBuffer: TContextBuffer; FFinalized: Boolean; procedure Transform(const ABlock: PByte; AShift: Integer); procedure Decode(const Dst: PCardinal; const Src: PByte; Len: Integer; AShift: Integer); procedure Encode(const Dst: PByte; const Src: PCardinal; Len: Integer); procedure FinalizeHash; procedure Update(const AData: PByte; ALength: Cardinal); overload; function GetDigest: TBytes; public /// <summary> Creates an instance to generate MD5 hashes</summary> class function Create: THashMD5; static; inline; /// <summary> Puts the state machine of the generator in it's initial state.</summary> procedure Reset; /// <summary> Update the Hash with the provided bytes</summary> procedure Update(const AData; ALength: Cardinal); overload; procedure Update(const AData: TBytes; ALength: Cardinal = 0); overload; inline; procedure Update(const Input: string); overload; inline; /// <summary> Returns the BlockSize for this hash instance</summary> function GetBlockSize: Integer; inline; /// <summary> Returns the HashSize for this hash instance</summary> function GetHashSize: Integer; inline; /// <summary> Returns the hash value as a TBytes</summary> function HashAsBytes: TBytes; inline; /// <summary> Returns the hash value as string</summary> function HashAsString: string; inline; /// <summary> Hash the given string and returns it's hash value as TBytes</summary> class function GetHashBytes(const AData: string): TBytes; overload; static; /// <summary> Hash the given string and returns it's hash value as string</summary> class function GetHashString(const AString: string): string; overload; static; inline; /// <summary> Hash the given stream and returns it's hash value as TBytes</summary> class function GetHashBytes(const AStream: TStream): TBytes; overload; static; /// <summary> Hash the given stream and returns it's hash value as string</summary> class function GetHashString(const AStream: TStream): string; overload; static; inline; /// <summary> Hash the file with given FileName and returns it's hash value as TBytes</summary> class function GetHashBytesFromFile(const AFileName: TFileName): TBytes; static; /// <summary> Hash the file with given FileName and returns it's hash value as string</summary> class function GetHashStringFromFile(const AFileName: TFileName): string; static; inline; /// <summary>Gets the string associated to the HMAC authentication</summary> class function GetHMAC(const AData, AKey: string): string; static; inline; /// <summary>Gets the Digest associated to the HMAC authentication</summary> class function GetHMACAsBytes(const AData, AKey: string): TBytes; overload; static; class function GetHMACAsBytes(const AData: string; const AKey: TBytes): TBytes; overload; static; class function GetHMACAsBytes(const AData: TBytes; const AKey: string): TBytes; overload; static; class function GetHMACAsBytes(const AData, AKey: TBytes): TBytes; overload; static; end; /// <summary> Record to generate SHA1 Hash values from data</summary> THashSHA1 = record private FHash: array[0..4] of Cardinal; FBitLength: Int64; FBuffer: array [0..63] of Byte; FIndex: Integer; FFinalized: Boolean; procedure Initialize; procedure CheckFinalized; procedure Compress; procedure Finalize; function GetDigest: TBytes; procedure Update(const AData: PByte; ALength: Cardinal); overload; public /// <summary>Initialize the Record used to calculate the SHA1 Hash</summary> class function Create: THashSHA1; static; inline; /// <summary> Puts the state machine of the generator in it's initial state.</summary> procedure Reset; inline; /// <summary> Update the Hash value with the given Data. </summary> procedure Update(const AData; ALength: Cardinal); overload; procedure Update(const AData: TBytes; ALength: Cardinal = 0); overload; inline; procedure Update(const Input: string); overload; inline; /// <summary> Returns the BlockSize for this hash instance</summary> function GetBlockSize: Integer; inline; /// <summary> Returns the HashSize for this hash instance</summary> function GetHashSize: Integer; inline; /// <summary> Returns the hash value as a TBytes</summary> function HashAsBytes: TBytes; inline; /// <summary> Returns the hash value as string</summary> function HashAsString: string; inline; /// <summary> Hash the given string and returns it's hash value as TBytes</summary> class function GetHashBytes(const AData: string): TBytes; overload; static; /// <summary> Hash the given string and returns it's hash value as string</summary> class function GetHashString(const AString: string): string; overload; static; inline; /// <summary> Hash the given stream and returns it's hash value as TBytes</summary> class function GetHashBytes(const AStream: TStream): TBytes; overload; static; /// <summary> Hash the given stream and returns it's hash value as string</summary> class function GetHashString(const AStream: TStream): string; overload; static; inline; /// <summary> Hash the file with given FileName and returns it's hash value as TBytes</summary> class function GetHashBytesFromFile(const AFileName: TFileName): TBytes; static; /// <summary> Hash the file with given FileName and returns it's hash value as string</summary> class function GetHashStringFromFile(const AFileName: TFileName): string; static; inline; /// <summary>Gets the string associated to the HMAC authentication</summary> class function GetHMAC(const AData, AKey: string): string; static; inline; /// <summary>Gets the Digest associated to the HMAC authentication</summary> class function GetHMACAsBytes(const AData, AKey: string): TBytes; overload; static; class function GetHMACAsBytes(const AData: string; const AKey: TBytes): TBytes; overload; static; class function GetHMACAsBytes(const AData: TBytes; const AKey: string): TBytes; overload; static; class function GetHMACAsBytes(const AData, AKey: TBytes): TBytes; overload; static; end; /// <summary> Record to generate SHA2 Hash values from data</summary> THashSHA2 = record public type TSHA2Version = (SHA224, SHA256, SHA384, SHA512, SHA512_224, SHA512_256); private const CBuffer32Length = 64; CBuffer64Length = 128; private FBuffer: array [0..127] of Byte; FBitLength: UInt64; FIndex: Cardinal; FFinalized: Boolean; procedure Initialize(AVersion: TSHA2Version); procedure CheckFinalized; inline; procedure Compress; inline; procedure Compress32; procedure Compress64; procedure Finalize; inline; procedure Finalize32; procedure Finalize64; function GetDigest: TBytes; procedure Update(const AData: PByte; ALength: Cardinal); overload; public /// <summary>Initialize the Record used to calculate the SHA2 Hash</summary> class function Create(AHashVersion: TSHA2Version = TSHA2Version.SHA256): THashSHA2; static; inline; /// <summary> Puts the state machine of the generator in it's initial state.</summary> procedure Reset; inline; /// <summary> Update the Hash value with the given Data. </summary> procedure Update(const AData; ALength: Cardinal); overload; procedure Update(const AData: TBytes; ALength: Cardinal = 0); overload; inline; procedure Update(const Input: string); overload; inline; /// <summary> Returns the BlockSize for this hash instance</summary> function GetBlockSize: Integer; inline; /// <summary> Returns the HashSize for this hash instance</summary> function GetHashSize: Integer; inline; /// <summary> Returns the hash value as a TBytes</summary> function HashAsBytes: TBytes; inline; /// <summary> Returns the hash value as string</summary> function HashAsString: string; inline; /// <summary> Hash the given string and returns it's hash value as integer</summary> class function GetHashBytes(const AData: string; AHashVersion: TSHA2Version = TSHA2Version.SHA256): TBytes; overload; static; /// <summary> Hash the given string and returns it's hash value as string</summary> class function GetHashString(const AString: string; AHashVersion: TSHA2Version = TSHA2Version.SHA256): string; overload; static; inline; /// <summary> Hash the given stream and returns it's hash value as TBytes</summary> class function GetHashBytes(const AStream: TStream; AHashVersion: TSHA2Version = TSHA2Version.SHA256): TBytes; overload; static; /// <summary> Hash the given stream and returns it's hash value as string</summary> class function GetHashString(const AStream: TStream; AHashVersion: TSHA2Version = TSHA2Version.SHA256): string; overload; static; inline; /// <summary> Hash the file with given FileName and returns it's hash value as TBytes</summary> class function GetHashBytesFromFile(const AFileName: TFileName; AHashVersion: TSHA2Version = TSHA2Version.SHA256): TBytes; static; /// <summary> Hash the file with given FileName and returns it's hash value as string</summary> class function GetHashStringFromFile(const AFileName: TFileName; AHashVersion: TSHA2Version = TSHA2Version.SHA256): string; static; inline; /// <summary>Gets the string associated to the HMAC authentication</summary> class function GetHMAC(const AData, AKey: string; AHashVersion: TSHA2Version = TSHA2Version.SHA256): string; static; inline; /// <summary>Gets the Digest associated to the HMAC authentication</summary> class function GetHMACAsBytes(const AData, AKey: string; AHashVersion: TSHA2Version = TSHA2Version.SHA256): TBytes; overload; static; class function GetHMACAsBytes(const AData: string; const AKey: TBytes; AHashVersion: TSHA2Version = TSHA2Version.SHA256): TBytes; overload; static; class function GetHMACAsBytes(const AData: TBytes; const AKey: string; AHashVersion: TSHA2Version = TSHA2Version.SHA256): TBytes; overload; static; class function GetHMACAsBytes(const AData, AKey: TBytes; AHashVersion: TSHA2Version = TSHA2Version.SHA256): TBytes; overload; static; private case FVersion: TSHA2Version of TSHA2Version.SHA224, TSHA2Version.SHA256: (FHash: array[0..7] of Cardinal); TSHA2Version.SHA384, TSHA2Version.SHA512, TSHA2Version.SHA512_224, TSHA2Version.SHA512_256: (FHash64: array[0..7] of UInt64); end; /// <summary> Record to generate BobJenkins Hash values from data. Stores internal state of the process</summary> THashBobJenkins = record private FHash: Integer; function GetDigest: TBytes; class function HashLittle(const Data; Len, InitVal: Integer): Integer; static; public /// <summary>Initialize the Record used to calculate the BobJenkins Hash</summary> class function Create: THashBobJenkins; static; /// <summary> Puts the state machine of the generator in it's initial state.</summary> procedure Reset(AInitialValue: Integer = 0); /// <summary> Update the Hash value with the given Data. </summary> procedure Update(const AData; ALength: Cardinal); overload; inline; procedure Update(const AData: TBytes; ALength: Cardinal = 0); overload; inline; procedure Update(const Input: string); overload; inline; /// <summary> Returns the hash value as a TBytes</summary> function HashAsBytes: TBytes; /// <summary> Returns the hash value as integer</summary> function HashAsInteger: Integer; /// <summary> Returns the hash value as string</summary> function HashAsString: string; /// <summary> Hash the given string and returns it's hash value as integer</summary> class function GetHashBytes(const AData: string): TBytes; static; /// <summary> Hash the given string and returns it's hash value as string</summary> class function GetHashString(const AString: string): string; static; /// <summary> Hash the given string and returns it's hash value as integer</summary> class function GetHashValue(const AData: string): Integer; overload; static; inline; /// <summary> Hash the given Data and returns it's hash value as integer</summary> class function GetHashValue(const AData; ALength: Integer; AInitialValue: Integer = 0): Integer; overload; static; inline; end; implementation uses System.Types, System.RTLConsts; { THash } class function THash.ToBigEndian(AValue: Cardinal): Cardinal; begin Result := (AValue shr 24) or (AValue shl 24) or ((AValue shr 8) and $FF00) or ((AValue shl 8) and $FF0000); end; class function THash.ToBigEndian(AValue: UInt64): UInt64; begin Result := UInt64(ToBigEndian(Cardinal(AValue))) shl 32 or ToBigEndian(Cardinal(AValue shr 32)); end; class function THash.DigestAsInteger(const ADigest: TBytes): Integer; begin if Length(ADigest) <> 4 then raise EHashException.Create('Digest size must be 4 to Generate a Integer'); Result := PInteger(@ADigest[0])^; end; class function THash.DigestAsString(const ADigest: TBytes): string; const XD: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); var I: Integer; begin Result := ''; for I := 0 to Length(ADigest) - 1 do Result := Result + XD[(ADigest[I] shr 4) and $0f] + XD[ADigest[I] and $0f]; end; class function THash.DigestAsStringGUID(const ADigest: TBytes): string; var LGUID: TGUID; begin LGUID := TGUID.Create(ADigest); LGUID.D1 := ToBigEndian(LGUID.D1); LGUID.D2 := Word((WordRec(LGUID.D2).Lo shl 8) or WordRec(LGUID.D2).Hi); LGUID.D3 := Word((WordRec(LGUID.D3).Lo shl 8) or WordRec(LGUID.D3).Hi); Result := LGUID.ToString; end; class function THash.GetRandomString(const ALen: Integer): string; const ValidChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-/*_'; var I: Integer; begin Result := ''; for I := 1 to ALen do Result := Result + ValidChars[Random(ValidChars.Length) + Low(string)]; end; { THashMD5 } class function THashMD5.Create: THashMD5; begin Result.Reset; end; procedure THashMD5.Reset; begin FillChar(FPadding, 64, 0); FPadding[0] := $80; FContextCount[0] := 0; FContextCount[1] := 0; FContextState[0] := $67452301; FContextState[1] := $efcdab89; FContextState[2] := $98badcfe; FContextState[3] := $10325476; FillChar(FContextBuffer, 64, 0); FFinalized := False; end; procedure THashMD5.Transform(const ABlock: PByte; AShift: Integer); function F(x, y, z: Cardinal): Cardinal; inline; begin Result := (x and y) or ((not x) and z); end; function G(x, y, z: Cardinal): Cardinal; inline; begin Result := (x and z) or (y and (not z)); end; function H(x, y, z: Cardinal): Cardinal; inline; begin Result := x xor y xor z; end; function I(x, y, z: Cardinal): Cardinal; inline; begin Result := y xor (x or (not z)); end; procedure RL(var x: Cardinal; n: Byte); inline; begin x := (x shl n) or (x shr (32 - n)); end; procedure FF(var a: Cardinal; b, c, d, x: Cardinal; s: Byte; ac: Cardinal); begin Inc(a, F(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; procedure GG(var a: Cardinal; b, c, d, x: Cardinal; s: Byte; ac: Cardinal); begin Inc(a, G(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; procedure HH(var a: Cardinal; b, c, d, x: Cardinal; s: Byte; ac: Cardinal); begin Inc(a, H(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; procedure II(var a: Cardinal; b, c, d, x: Cardinal; s: Byte; ac: Cardinal); begin Inc(a, I(b, c, d) + x + ac); RL(a, s); Inc(a, b); end; const S11 = 7; S12 = 12; S13 = 17; S14 = 22; S21 = 5; S22 = 9; S23 = 14; S24 = 20; S31 = 4; S32 = 11; S33 = 16; S34 = 23; S41 = 6; S42 = 10; S43 = 15; S44 = 21; var a, b, c, d: Cardinal; x: TContextState; begin a := FContextState[0]; b := FContextState[1]; c := FContextState[2]; d := FContextState[3]; Decode(PCardinal(@x[0]), ABlock, 64, AShift); { Round 1 } FF( a, b, c, d, x[ 0], S11, $d76aa478); { 1 } FF( d, a, b, c, x[ 1], S12, $e8c7b756); { 2 } FF( c, d, a, b, x[ 2], S13, $242070db); { 3 } FF( b, c, d, a, x[ 3], S14, $c1bdceee); { 4 } FF( a, b, c, d, x[ 4], S11, $f57c0faf); { 5 } FF( d, a, b, c, x[ 5], S12, $4787c62a); { 6 } FF( c, d, a, b, x[ 6], S13, $a8304613); { 7 } FF( b, c, d, a, x[ 7], S14, $fd469501); { 8 } FF( a, b, c, d, x[ 8], S11, $698098d8); { 9 } FF( d, a, b, c, x[ 9], S12, $8b44f7af); { 10 } FF( c, d, a, b, x[10], S13, $ffff5bb1); { 11 } FF( b, c, d, a, x[11], S14, $895cd7be); { 12 } FF( a, b, c, d, x[12], S11, $6b901122); { 13 } FF( d, a, b, c, x[13], S12, $fd987193); { 14 } FF( c, d, a, b, x[14], S13, $a679438e); { 15 } FF( b, c, d, a, x[15], S14, $49b40821); { 16 } { Round 2 } GG( a, b, c, d, x[ 1], S21, $f61e2562); { 17 } GG( d, a, b, c, x[ 6], S22, $c040b340); { 18 } GG( c, d, a, b, x[11], S23, $265e5a51); { 19 } GG( b, c, d, a, x[ 0], S24, $e9b6c7aa); { 20 } GG( a, b, c, d, x[ 5], S21, $d62f105d); { 21 } GG( d, a, b, c, x[10], S22, $2441453); { 22 } GG( c, d, a, b, x[15], S23, $d8a1e681); { 23 } GG( b, c, d, a, x[ 4], S24, $e7d3fbc8); { 24 } GG( a, b, c, d, x[ 9], S21, $21e1cde6); { 25 } GG( d, a, b, c, x[14], S22, $c33707d6); { 26 } GG( c, d, a, b, x[ 3], S23, $f4d50d87); { 27 } GG( b, c, d, a, x[ 8], S24, $455a14ed); { 28 } GG( a, b, c, d, x[13], S21, $a9e3e905); { 29 } GG( d, a, b, c, x[ 2], S22, $fcefa3f8); { 30 } GG( c, d, a, b, x[ 7], S23, $676f02d9); { 31 } GG( b, c, d, a, x[12], S24, $8d2a4c8a); { 32 } { Round 3 } HH( a, b, c, d, x[ 5], S31, $fffa3942); { 33 } HH( d, a, b, c, x[ 8], S32, $8771f681); { 34 } HH( c, d, a, b, x[11], S33, $6d9d6122); { 35 } HH( b, c, d, a, x[14], S34, $fde5380c); { 36 } HH( a, b, c, d, x[ 1], S31, $a4beea44); { 37 } HH( d, a, b, c, x[ 4], S32, $4bdecfa9); { 38 } HH( c, d, a, b, x[ 7], S33, $f6bb4b60); { 39 } HH( b, c, d, a, x[10], S34, $bebfbc70); { 40 } HH( a, b, c, d, x[13], S31, $289b7ec6); { 41 } HH( d, a, b, c, x[ 0], S32, $eaa127fa); { 42 } HH( c, d, a, b, x[ 3], S33, $d4ef3085); { 43 } HH( b, c, d, a, x[ 6], S34, $4881d05); { 44 } HH( a, b, c, d, x[ 9], S31, $d9d4d039); { 45 } HH( d, a, b, c, x[12], S32, $e6db99e5); { 46 } HH( c, d, a, b, x[15], S33, $1fa27cf8); { 47 } HH( b, c, d, a, x[ 2], S34, $c4ac5665); { 48 } { Round 4 } II( a, b, c, d, x[ 0], S41, $f4292244); { 49 } II( d, a, b, c, x[ 7], S42, $432aff97); { 50 } II( c, d, a, b, x[14], S43, $ab9423a7); { 51 } II( b, c, d, a, x[ 5], S44, $fc93a039); { 52 } II( a, b, c, d, x[12], S41, $655b59c3); { 53 } II( d, a, b, c, x[ 3], S42, $8f0ccc92); { 54 } II( c, d, a, b, x[10], S43, $ffeff47d); { 55 } II( b, c, d, a, x[ 1], S44, $85845dd1); { 56 } II( a, b, c, d, x[ 8], S41, $6fa87e4f); { 57 } II( d, a, b, c, x[15], S42, $fe2ce6e0); { 58 } II( c, d, a, b, x[ 6], S43, $a3014314); { 59 } II( b, c, d, a, x[13], S44, $4e0811a1); { 60 } II( a, b, c, d, x[ 4], S41, $f7537e82); { 61 } II( d, a, b, c, x[11], S42, $bd3af235); { 62 } II( c, d, a, b, x[ 2], S43, $2ad7d2bb); { 63 } II( b, c, d, a, x[ 9], S44, $eb86d391); { 64 } Inc(FContextState[0], a); Inc(FContextState[1], b); Inc(FContextState[2], c); Inc(FContextState[3], d); end; procedure THashMD5.Update(const AData; ALength: Cardinal); begin Update(PByte(@AData), ALength); end; procedure THashMD5.Update(const AData: TBytes; ALength: Cardinal = 0); var LLen: Cardinal; begin LLen := ALength; if LLen = 0 then LLen := Length(AData); Update(PByte(AData), LLen); end; procedure THashMD5.Update(const AData: PByte; ALength: Cardinal); var Index, PartLen, I, Start: Cardinal; begin if FFinalized then raise EHashException.CreateRes(@SHashCanNotUpdateMD5); { Compute number of bytes mod 64 } Index := (FContextCount[0] shr 3) and $3f; { Update number of bits } Inc(FContextCount[0], ALength shl 3); if FContextCount[0] < (ALength shl 3) then Inc(FContextCount[1]); Inc(FContextCount[1], ALength shr 29); PartLen := 64 - Index; { Transform (as many times as possible) } if ALength >= PartLen then begin for I := 0 to PartLen - 1 do FContextBuffer[I + Index] := AData[I]; Transform(PByte(@FContextBuffer[0]), 0); I := PartLen; while (I + 63) < ALength do begin Transform(AData, I); Inc(I, 64); end; Index := 0; end else I := 0; { Input remaining input } if I < ALength then begin Start := I; while I < ALength do begin FContextBuffer[Index + I - Start] := AData[I]; Inc(I); end; end; end; procedure THashMD5.Update(const Input: string); begin Update(TEncoding.UTF8.GetBytes(Input)); end; {$POINTERMATH ON} procedure THashMD5.Encode(const Dst: PByte; const Src: PCardinal; Len: Integer); var I, J: Integer; begin I := 0; J := 0; while J < Len do begin Dst[J] := Byte((Src[I] ) and $ff); Dst[J+1] := Byte((Src[I] shr 8) and $ff); Dst[J+2] := Byte((Src[I] shr 16) and $ff); Dst[J+3] := Byte((Src[I] shr 24) and $ff); Inc(J, 4); Inc(I); end; end; function THashMD5.GetBlockSize: Integer; begin Result := 64; end; function THashMD5.GetHashSize: Integer; begin Result := 16; end; function THashMD5.HashAsBytes: TBytes; begin Result := GetDigest; end; function THashMD5.HashAsString: string; begin Result := THash.DigestAsString(GetDigest); end; function THashMD5.GetDigest: TBytes; begin if not FFinalized then FinalizeHash; { Store state in digest } SetLength(Result, GetHashSize); Encode(PByte(Result), PCardinal(@FContextState[0]), GetHashSize); end; class function THashMD5.GetHashBytesFromFile(const AFileName: TFileName): TBytes; var LFile: TFileStream; begin LFile := TFileStream.Create(AFileName, fmShareDenyNone or fmOpenRead); try Result := GetHashBytes(LFile); finally LFile.Free; end; end; class function THashMD5.GetHashStringFromFile(const AFileName: TFileName): string; begin Result := THash.DigestAsString(GetHashBytesFromFile(AFileName)); end; class function THashMD5.GetHashBytes(const AData: string): TBytes; var LMD5: THashMD5; begin LMD5 := THashMD5.Create; LMD5.Update(AData); Result := LMD5.GetDigest; end; class function THashMD5.GetHashString(const AString: string): string; var LMD5: THashMD5; begin LMD5 := THashMD5.Create; LMD5.Update(AString); Result := LMD5.HashAsString; end; class function THashMD5.GetHMAC(const AData, AKey: string): string; begin Result := THash.DigestAsString(GetHMACAsBytes(AData, AKey)); end; class function THashMD5.GetHMACAsBytes(const AData, AKey: string): TBytes; begin Result := GetHMACAsBytes(TEncoding.UTF8.GetBytes(AData), TEncoding.UTF8.GetBytes(AKey)); end; class function THashMD5.GetHMACAsBytes(const AData: string; const AKey: TBytes): TBytes; begin Result := GetHMACAsBytes(TEncoding.UTF8.GetBytes(AData), AKey); end; class function THashMD5.GetHMACAsBytes(const AData: TBytes; const AKey: string): TBytes; begin Result := GetHMACAsBytes(AData, TEncoding.UTF8.GetBytes(AKey)); end; class function THashMD5.GetHMACAsBytes(const AData, AKey: TBytes): TBytes; const CInnerPad : Byte = $36; COuterPad : Byte = $5C; var TempBuffer1: TBytes; TempBuffer2: TBytes; FKey: TBytes; LKey: TBytes; I: Integer; FHash: THashMD5; LBuffer: TBytes; begin FHash := THashMD5.Create; LBuffer := AData; FKey := AKey; if Length(FKey) > FHash.GetBlockSize then begin FHash.Update(FKey); FKey := Copy(FHash.GetDigest); end; LKey := Copy(FKey, 0, MaxInt); SetLength(LKey, FHash.GetBlockSize); SetLength(TempBuffer1, FHash.GetBlockSize + Length(LBuffer)); for I := Low(LKey) to High(LKey) do begin TempBuffer1[I] := LKey[I] xor CInnerPad; end; if Length(LBuffer) > 0 then Move(LBuffer[0], TempBuffer1[Length(LKey)], Length(LBuffer)); FHash.Reset; FHash.Update(TempBuffer1); TempBuffer2 := FHash.GetDigest; SetLength(TempBuffer1, FHash.GetBlockSize + FHash.GetHashSize); for I := Low(LKey) to High(LKey) do begin TempBuffer1[I] := LKey[I] xor COuterPad; end; Move(TempBuffer2[0], TempBuffer1[Length(LKey)], Length(TempBuffer2)); FHash.Reset; FHash.Update(TempBuffer1); Result := FHash.GetDigest; end; class function THashMD5.GetHashBytes(const AStream: TStream): TBytes; const BUFFERSIZE = 4 * 1024; var LMD5: THashMD5; LBuffer: TBytes; LBytesRead: Longint; begin LMD5 := THashMD5.Create; SetLength(LBuffer, BUFFERSIZE); while True do begin LBytesRead := AStream.ReadData(LBuffer, BUFFERSIZE); if LBytesRead = 0 then Break; LMD5.Update(LBuffer, LBytesRead); end; Result := LMD5.GetDigest; end; class function THashMD5.GetHashString(const AStream: TStream): string; begin Result := THash.DigestAsString(GetHashBytes(AStream)); end; procedure THashMD5.FinalizeHash; var Bits: TContextBuffer; Index: Integer; PadLen: Cardinal; begin { Save number of bits } Encode(PByte(@Bits[0]), PCardinal(@FContextCount[0]), 8); { Pad out to 56 mod 64 } Index := (FContextCount[0] shr 3) and $3F; if Index < 56 then PadLen := 56 - Index else PadLen := 120 - Index; Update(PByte(@FPadding[0]), PadLen); { Append length (before padding) } Update(PByte(@Bits[0]), 8); FFinalized := True; end; procedure THashMD5.Decode(const Dst: PCardinal; const Src: PByte; Len: Integer; AShift: Integer); var I, J: Integer; a, b, c, d: Byte; begin J := 0; I := 0; while (J < Len) do begin a := Src[J+AShift]; b := Src[J+AShift+1]; c := Src[J+AShift+2]; d := Src[J+AShift+3]; Dst[I] := Cardinal(a and $ff) or (Cardinal(b and $ff) shl 8) or (Cardinal(c and $ff) shl 16) or (Cardinal(d and $ff) shl 24); Inc(J, 4); Inc(I); end; end; {$POINTERMATH OFF} { THashSHA1 } procedure THashSHA1.CheckFinalized; begin if FFinalized then raise EHashException.CreateRes(@SHashCanNotUpdateSHA1); end; procedure THashSHA1.Compress; function F1(X, Y, Z: Cardinal): Cardinal; inline; begin Result := (X and Y) or ((not X) and Z); end; function F2(X, Y, Z: Cardinal): Cardinal; inline; begin Result := X xor Y xor Z; end; function F3(X, Y, Z: Cardinal): Cardinal; inline; begin Result := (X and Y) or (X and Z) or (Y and Z); end; function LeftRotate(Value: Cardinal; N: Integer): Cardinal; inline; begin Result := (Value shl N) or (Value shr (32 - N)); end; var A, B, C, D, E, T: Cardinal; W: array[0..79] of Cardinal; I: Integer; begin Move(FBuffer, W, Sizeof(FBuffer)); for I := 0 to 15 do W[I] := THash.ToBigEndian(W[I]); for I := 16 to 79 do W[I] := LeftRotate(W[I - 3] xor W[I - 8] xor W[I - 14] xor W[I - 16], 1); A := FHash[0]; B := FHash[1]; C := FHash[2]; D := FHash[3]; E := FHash[4]; for I := 0 to 19 do begin T := LeftRotate(A, 5) + F1(B, C, D) + E + W[I] + $5A827999; E := D; D := C; C := LeftRotate(B, 30); B := A; A := T; end; for I := 20 to 39 do begin T := LeftRotate(A, 5) + F2(B, C, D) + E + W[I] + $6ED9EBA1; E := D; D := C; C := LeftRotate(B, 30); B := A; A := T; end; for I := 40 to 59 do begin T := LeftRotate(A, 5) + F3(B, C, D) + E + W[I] + $8F1BBCDC; E := D; D:= C; C := LeftRotate(B, 30); B := A; A := T; end; for I := 60 to 79 do begin T := LeftRotate(A, 5) + F2(B, C, D) + E + W[I] + $CA62C1D6; E := D; D := C; C := LeftRotate(B, 30); B := A; A := T; end; FHash[0] := FHash[0] + A; FHash[1] := FHash[1] + B; FHash[2] := FHash[2] + C; FHash[3] := FHash[3] + D; FHash[4] := FHash[4] + E; FillChar(FBuffer, Sizeof(FBuffer), 0); end; class function THashSHA1.Create: THashSHA1; begin Result.Initialize; end; function THashSHA1.GetBlockSize: Integer; begin Result := 64; end; function THashSHA1.GetHashSize: Integer; begin Result := 20; end; function THashSHA1.HashAsBytes: TBytes; begin Result := GetDigest; end; function THashSHA1.HashAsString: string; begin Result := THash.DigestAsString(GetDigest); end; procedure THashSHA1.Initialize; begin FillChar(Self, SizeOf(Self), 0); FHash[0] := $67452301; FHash[1] := $EFCDAB89; FHash[2] := $98BADCFE; FHash[3] := $10325476; FHash[4] := $C3D2E1F0; end; procedure THashSHA1.Reset; begin Initialize; end; procedure THashSHA1.Update(const AData: PByte; ALength: Cardinal); var Buffer: PByte; begin CheckFinalized; Buffer := AData; Inc(FBitLength, ALength * 8); while ALength > 0 do begin FBuffer[FIndex] := Buffer[0]; Inc(Buffer); Inc(FIndex); Dec(ALength); if FIndex = 64 then begin FIndex := 0; Compress; end; end; end; procedure THashSHA1.Update(const AData; ALength: Cardinal); begin Update(PByte(@AData), ALength); end; procedure THashSHA1.Update(const AData: TBytes; ALength: Cardinal = 0); var Len: Integer; begin if ALength = 0 then Len := Length(AData) else Len := ALength; Update(PByte(AData), Len); end; procedure THashSHA1.Update(const Input: string); begin Update(TEncoding.UTF8.GetBytes(Input)); end; class function THashSHA1.GetHashBytes(const AData: string): TBytes; var LSHA1: THashSHA1; begin LSHA1 := THashSHA1.Create; LSHA1.Update(AData); Result := LSHA1.GetDigest; end; class function THashSHA1.GetHashString(const AString: string): string; var LSHA1: THashSHA1; begin LSHA1 := THashSHA1.Create; LSHA1.Update(AString); Result := LSHA1.HashAsString; end; class function THashSHA1.GetHMAC(const AData, AKey: string): string; begin Result := THash.DigestAsString(GetHMACAsBytes(AData, AKey)); end; class function THashSHA1.GetHMACAsBytes(const AData: string; const AKey: TBytes): TBytes; begin Result := GetHMACAsBytes(TEncoding.UTF8.GetBytes(AData), AKey); end; class function THashSHA1.GetHMACAsBytes(const AData, AKey: string): TBytes; begin Result := GetHMACAsBytes(TEncoding.UTF8.GetBytes(AData), TEncoding.UTF8.GetBytes(AKey)); end; class function THashSHA1.GetHMACAsBytes(const AData: TBytes; const AKey: string): TBytes; begin Result := GetHMACAsBytes(AData, TEncoding.UTF8.GetBytes(AKey)); end; class function THashSHA1.GetHMACAsBytes(const AData, AKey: TBytes): TBytes; const CInnerPad : Byte = $36; COuterPad : Byte = $5C; var TempBuffer1: TBytes; TempBuffer2: TBytes; FKey: TBytes; LKey: TBytes; I: Integer; FHash: THashSHA1; LBuffer: TBytes; begin FHash := THashSHA1.Create; LBuffer := AData; FKey := AKey; if Length(FKey) > FHash.GetBlockSize then begin FHash.Update(FKey); FKey := Copy(FHash.GetDigest); end; LKey := Copy(FKey, 0, MaxInt); SetLength(LKey, FHash.GetBlockSize); SetLength(TempBuffer1, FHash.GetBlockSize + Length(LBuffer)); for I := Low(LKey) to High(LKey) do begin TempBuffer1[I] := LKey[I] xor CInnerPad; end; if Length(LBuffer) > 0 then Move(LBuffer[0], TempBuffer1[Length(LKey)], Length(LBuffer)); FHash.Reset; FHash.Update(TempBuffer1); TempBuffer2 := FHash.GetDigest; SetLength(TempBuffer1, FHash.GetBlockSize + FHash.GetHashSize); for I := Low(LKey) to High(LKey) do begin TempBuffer1[I] := LKey[I] xor COuterPad; end; Move(TempBuffer2[0], TempBuffer1[Length(LKey)], Length(TempBuffer2)); FHash.Reset; FHash.Update(TempBuffer1); Result := FHash.GetDigest; end; class function THashSHA1.GetHashBytes(const AStream: TStream): TBytes; const BUFFERSIZE = 4 * 1024; var LSHA1: THashSHA1; LBuffer: TBytes; LBytesRead: Longint; begin LSHA1 := THashSHA1.Create; SetLength(LBuffer, BUFFERSIZE); while True do begin LBytesRead := AStream.ReadData(LBuffer, BUFFERSIZE); if LBytesRead = 0 then Break; LSHA1.Update(LBuffer, LBytesRead); end; Result := LSHA1.GetDigest; end; class function THashSHA1.GetHashString(const AStream: TStream): string; begin Result := THash.DigestAsString(GetHashBytes(AStream)); end; procedure THashSHA1.Finalize; begin CheckFinalized; FBuffer[FIndex] := $80; if FIndex >= 56 then Compress; PCardinal(@FBuffer[56])^ := THash.ToBigEndian(Cardinal(FBitLength shr 32)); PCardinal(@FBuffer[60])^ := THash.ToBigEndian(Cardinal(FBitLength)); Compress; FHash[0] := THash.ToBigEndian(FHash[0]); FHash[1] := THash.ToBigEndian(FHash[1]); FHash[2] := THash.ToBigEndian(FHash[2]); FHash[3] := THash.ToBigEndian(FHash[3]); FHash[4] := THash.ToBigEndian(FHash[4]); FFinalized := True; end; function THashSHA1.GetDigest: TBytes; begin if not FFinalized then Finalize; SetLength(Result, GetHashSize); // Size of Hash... Move(PByte(@FHash[0])^, PByte(@Result[0])^, GetHashSize); end; class function THashSHA1.GetHashBytesFromFile(const AFileName: TFileName): TBytes; var LFile: TFileStream; begin LFile := TFileStream.Create(AFileName, fmShareDenyNone or fmOpenRead); try Result := GetHashBytes(LFile); finally LFile.Free; end; end; class function THashSHA1.GetHashStringFromFile(const AFileName: TFileName): string; begin Result := THash.DigestAsString(GetHashBytesFromFile(AFileName)); end; { THashSHA2 } class function THashSHA2.Create(AHashVersion: TSHA2Version): THashSHA2; begin Result.Initialize(AHashVersion); end; procedure THashSHA2.CheckFinalized; begin if FFinalized then raise EHashException.CreateRes(@SHashCanNotUpdateSHA2); end; function THashSHA2.HashAsBytes: TBytes; begin Result := GetDigest; end; function THashSHA2.HashAsString: string; begin Result := THash.DigestAsString(GetDigest); end; procedure THashSHA2.Reset; begin Initialize(FVersion); end; procedure THashSHA2.Update(const AData; ALength: Cardinal); begin Update(PByte(@AData), ALength); end; procedure THashSHA2.Update(const AData: TBytes; ALength: Cardinal = 0); var Len: Integer; begin if ALength = 0 then Len := Length(AData) else Len := ALength; Update(PByte(AData), Len); end; procedure THashSHA2.Update(const Input: string); begin Update(TEncoding.UTF8.GetBytes(Input)); end; procedure THashSHA2.Compress; begin case FVersion of THashSHA2.TSHA2Version.SHA224, THashSHA2.TSHA2Version.SHA256: Compress32; THashSHA2.TSHA2Version.SHA384, THashSHA2.TSHA2Version.SHA512, THashSHA2.TSHA2Version.SHA512_224, THashSHA2.TSHA2Version.SHA512_256: Compress64; end; end; procedure THashSHA2.Compress32; const K_256: array[0..63] of Cardinal = ( $428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5, $d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174, $e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da, $983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967, $27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85, $a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070, $19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3, $748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2); function Ch_(X, Y, Z: Cardinal): Cardinal; inline; begin Result := (X and Y) xor ((not X) and Z); end; function Maj(X, Y, Z: Cardinal): Cardinal; inline; begin Result := (X and Y) xor (X and Z) xor (Y and Z); end; function ROR(x: Cardinal; n: Byte): Cardinal; inline; begin Result := (x shl (32 - n) or (x shr n)); end; var I: Integer; s0, s1, t1, t2: Cardinal; W: array[0..63] of Cardinal; a, b, c, d, e, f, g, h: Cardinal; begin a := FHash[0]; b := FHash[1]; c := FHash[2]; d := FHash[3]; e := FHash[4]; f := FHash[5]; g := FHash[6]; h := FHash[7]; Move(FBuffer, W, CBuffer32Length); // Initialize message schedule for I := 0 to 15 do W[I] := THash.ToBigEndian(W[I]); for I := 16 to 63 do begin s0 := ROR(W[I - 15], 7) xor ROR(W[I - 15], 18) xor (W[I - 15] shr 3); s1 := ROR(W[I - 2], 17) xor ROR(W[I - 2], 19) xor (W[I - 2] shr 10); W[I] := W[I - 16] + s0 + W[I - 7] + s1; end; // Process the data to generate the change for the next intermediate hash for I := 0 to 63 do begin s0 := ROR(a, 2) xor ROR(a, 13) xor ROR(a, 22); t2 := s0 + Maj(a, b, c); s1 := ROR(e, 6) xor ROR(e, 11) xor ROR(e, 25); t1 := h + s1 + Ch_(e, f, g) + K_256[I] + W[I]; h := g; g := f; f := e; e := d + t1; d := c; c := b; b := a; a := t1 + t2; end; // Update hash value. FHash[0] := FHash[0] + a; FHash[1] := FHash[1] + b; FHash[2] := FHash[2] + c; FHash[3] := FHash[3] + d; FHash[4] := FHash[4] + e; FHash[5] := FHash[5] + f; FHash[6] := FHash[6] + g; FHash[7] := FHash[7] + h; end; procedure THashSHA2.Compress64; const K_512: array[0..79] of UInt64 = ( $428a2f98d728ae22, $7137449123ef65cd, $b5c0fbcfec4d3b2f, $e9b5dba58189dbbc, $3956c25bf348b538, $59f111f1b605d019, $923f82a4af194f9b, $ab1c5ed5da6d8118, $d807aa98a3030242, $12835b0145706fbe, $243185be4ee4b28c, $550c7dc3d5ffb4e2, $72be5d74f27b896f, $80deb1fe3b1696b1, $9bdc06a725c71235, $c19bf174cf692694, $e49b69c19ef14ad2, $efbe4786384f25e3, $0fc19dc68b8cd5b5, $240ca1cc77ac9c65, $2de92c6f592b0275, $4a7484aa6ea6e483, $5cb0a9dcbd41fbd4, $76f988da831153b5, $983e5152ee66dfab, $a831c66d2db43210, $b00327c898fb213f, $bf597fc7beef0ee4, $c6e00bf33da88fc2, $d5a79147930aa725, $06ca6351e003826f, $142929670a0e6e70, $27b70a8546d22ffc, $2e1b21385c26c926, $4d2c6dfc5ac42aed, $53380d139d95b3df, $650a73548baf63de, $766a0abb3c77b2a8, $81c2c92e47edaee6, $92722c851482353b, $a2bfe8a14cf10364, $a81a664bbc423001, $c24b8b70d0f89791, $c76c51a30654be30, $d192e819d6ef5218, $d69906245565a910, $f40e35855771202a, $106aa07032bbd1b8, $19a4c116b8d2d0c8, $1e376c085141ab53, $2748774cdf8eeb99, $34b0bcb5e19b48a8, $391c0cb3c5c95a63, $4ed8aa4ae3418acb, $5b9cca4f7763e373, $682e6ff3d6b2b8a3, $748f82ee5defb2fc, $78a5636f43172f60, $84c87814a1f0ab72, $8cc702081a6439ec, $90befffa23631e28, $a4506cebde82bde9, $bef9a3f7b2c67915, $c67178f2e372532b, $ca273eceea26619c, $d186b8c721c0c207, $eada7dd6cde0eb1e, $f57d4f7fee6ed178, $06f067aa72176fba, $0a637dc5a2c898a6, $113f9804bef90dae, $1b710b35131c471b, $28db77f523047d84, $32caab7b40c72493, $3c9ebe0a15c9bebc, $431d67c49c100d4c, $4cc5d4becb3e42b6, $597f299cfc657e2a, $5fcb6fab3ad6faec, $6c44198c4a475817); function Ch_(X, Y, Z: UInt64): UInt64; inline; begin Result := (X and Y) xor ((not X) and Z); end; function Maj(X, Y, Z: UInt64): UInt64; inline; begin Result := (X and Y) xor (X and Z) xor (Y and Z); end; function ROR(x: UInt64; n: Byte): UInt64; inline; begin Result := (x shl (64 - n)) or (x shr n); end; var I: Integer; s0, s1, t1, t2: UInt64; W: array[0..79] of UInt64; a, b, c, d, e, f, g, h: UInt64; begin a := FHash64[0]; b := FHash64[1]; c := FHash64[2]; d := FHash64[3]; e := FHash64[4]; f := FHash64[5]; g := FHash64[6]; h := FHash64[7]; Move(FBuffer, W, CBuffer64Length); // Initialize message schedule for I := 0 to 15 do W[I] := THash.ToBigEndian(W[I]); for I := 16 to 79 do begin s0 := ROR(W[I - 15], 1) xor ROR(W[I - 15], 8) xor (W[I - 15] shr 7); s1 := ROR(W[I - 2], 19) xor ROR(W[I - 2], 61) xor (W[I - 2] shr 6); W[I] := W[I - 16] + s0 + W[I - 7] + s1; end; // Process the data to generate the change for the next intermediate hash for I := 0 to 79 do begin s0 := ROR(a, 28) xor ROR(a, 34) xor ROR(a, 39); t2 := s0 + Maj(a, b, c); s1 := ROR(e, 14) xor ROR(e, 18) xor ROR(e, 41); t1 := h + s1 + Ch_(e, f, g) + K_512[I] + W[I]; h := g; g := f; f := e; e := d + t1; d := c; c := b; b := a; a := t1 + t2; end; FHash64[0] := FHash64[0] + a; FHash64[1] := FHash64[1] + b; FHash64[2] := FHash64[2] + c; FHash64[3] := FHash64[3] + d; FHash64[4] := FHash64[4] + e; FHash64[5] := FHash64[5] + f; FHash64[6] := FHash64[6] + g; FHash64[7] := FHash64[7] + h; end; class function THashSHA2.GetHashBytes(const AData: string; AHashVersion: TSHA2Version): TBytes; var LSHA2: THashSHA2; begin LSHA2 := THashSHA2.Create(AHashVersion); LSHA2.Update(AData); Result := LSHA2.GetDigest; end; function THashSHA2.GetHashSize: Integer; begin case FVersion of TSHA2Version.SHA224: Result := 28; TSHA2Version.SHA256: Result := 32; TSHA2Version.SHA384: Result := 48; TSHA2Version.SHA512: Result := 64; TSHA2Version.SHA512_224: Result := 28; TSHA2Version.SHA512_256: Result := 32; else Result := 0; // This will never happen, but makes happy the compiler about Undefined result of function. end; end; class function THashSHA2.GetHashString(const AString: string; AHashVersion: TSHA2Version): string; var LSHA2: THashSHA2; begin LSHA2 := THashSHA2.Create(AHashVersion); LSHA2.Update(AString); Result := LSHA2.HashAsString; end; class function THashSHA2.GetHMAC(const AData, AKey: string; AHashVersion: TSHA2Version): string; begin Result := THash.DigestAsString(GetHMACAsBytes(AData, AKey, AHashVersion)); end; class function THashSHA2.GetHMACAsBytes(const AData: string; const AKey: TBytes; AHashVersion: TSHA2Version): TBytes; begin Result := THashSHA2.GetHMACAsBytes(TEncoding.UTF8.GetBytes(AData), AKey, AHashVersion); end; class function THashSHA2.GetHMACAsBytes(const AData, AKey: string; AHashVersion: TSHA2Version): TBytes; begin Result := THashSHA2.GetHMACAsBytes(TEncoding.UTF8.GetBytes(AData), TEncoding.UTF8.GetBytes(AKey), AHashVersion); end; class function THashSHA2.GetHMACAsBytes(const AData: TBytes; const AKey: string; AHashVersion: TSHA2Version): TBytes; begin Result := GetHMACAsBytes(AData, TEncoding.UTF8.GetBytes(AKey), AHashVersion); end; class function THashSHA2.GetHMACAsBytes(const AData, AKey: TBytes; AHashVersion: TSHA2Version): TBytes; const CInnerPad : Byte = $36; COuterPad : Byte = $5C; var TempBuffer1: TBytes; TempBuffer2: TBytes; FKey: TBytes; LKey: TBytes; I: Integer; FHash: THashSHA2; LBuffer: TBytes; LHashSize: Integer; LBlockSize: Integer; begin FHash := THashSHA2.Create(AHashVersion); LBlockSize := FHash.GetBlockSize; LBuffer := AData; FKey := AKey; if Length(FKey) > LBlockSize then begin FHash.Update(FKey); FKey := Copy(FHash.GetDigest); end; LKey := Copy(FKey, 0, MaxInt); SetLength(LKey, LBlockSize); SetLength(TempBuffer1, LBlockSize + Length(LBuffer)); for I := Low(LKey) to High(LKey) do TempBuffer1[I] := LKey[I] xor CInnerPad; if Length(LBuffer) > 0 then Move(LBuffer[0], TempBuffer1[Length(LKey)], Length(LBuffer)); FHash.Reset; FHash.Update(TempBuffer1); TempBuffer2 := FHash.GetDigest; LHashSize := Length(TempBuffer2); SetLength(TempBuffer1, LBlockSize + LHashSize); for I := Low(LKey) to High(LKey) do TempBuffer1[I] := LKey[I] xor COuterPad; Move(TempBuffer2[0], TempBuffer1[Length(LKey)], Length(TempBuffer2)); FHash.Reset; FHash.Update(TempBuffer1); Result := FHash.GetDigest; end; class function THashSHA2.GetHashBytes(const AStream: TStream; AHashVersion: TSHA2Version): TBytes; const BUFFERSIZE = 4 * 1024; var LSHA2: THashSHA2; LBuffer: TBytes; LBytesRead: Longint; begin LSHA2 := THashSHA2.Create(AHashVersion); SetLength(LBuffer, BUFFERSIZE); while True do begin LBytesRead := AStream.ReadData(LBuffer, BUFFERSIZE); if LBytesRead = 0 then Break; LSHA2.Update(LBuffer, LBytesRead); end; Result := LSHA2.GetDigest; end; class function THashSHA2.GetHashString(const AStream: TStream; AHashVersion: TSHA2Version): string; begin Result := THash.DigestAsString(GetHashBytes(AStream, AHashVersion)); end; procedure THashSHA2.Finalize; begin CheckFinalized; case FVersion of THashSHA2.TSHA2Version.SHA224, THashSHA2.TSHA2Version.SHA256: Finalize32; THashSHA2.TSHA2Version.SHA384, THashSHA2.TSHA2Version.SHA512, THashSHA2.TSHA2Version.SHA512_224, THashSHA2.TSHA2Version.SHA512_256: Finalize64; end; FFinalized := True; end; procedure THashSHA2.Finalize32; var I: Integer; begin FBuffer[FIndex] := $80; if FIndex >= 56 then begin for I := FIndex + 1 to CBuffer32Length - 1 do FBuffer[I] := $00; Compress; FIndex := 0; end else Inc(FIndex); // No need to clean the bytes used for the BitLength FillChar(FBuffer[FIndex], (CBuffer32Length - 8) - FIndex, 0); PCardinal(@FBuffer[56])^ := THash.ToBigEndian(Cardinal(FBitLength shr 32)); PCardinal(@FBuffer[60])^ := THash.ToBigEndian(Cardinal(FBitLength)); Compress; FHash[0] := THash.ToBigEndian(FHash[0]); FHash[1] := THash.ToBigEndian(FHash[1]); FHash[2] := THash.ToBigEndian(FHash[2]); FHash[3] := THash.ToBigEndian(FHash[3]); FHash[4] := THash.ToBigEndian(FHash[4]); FHash[5] := THash.ToBigEndian(FHash[5]); FHash[6] := THash.ToBigEndian(FHash[6]); FHash[7] := THash.ToBigEndian(FHash[7]); end; procedure THashSHA2.Finalize64; var I: Integer; begin FBuffer[FIndex] := $80; if FIndex >= 112 then begin for I := FIndex + 1 to CBuffer64Length - 1 do FBuffer[I] := $00; Compress; FIndex := 0; end else Inc(FIndex); // No need to clean the bytes used for the BitLength FillChar(FBuffer[FIndex], (CBuffer64Length - 16) - FIndex, 0); PCardinal(@FBuffer[112])^ := 0; //THash.ToBigEndian(Cardinal(FBitLength shr 32)); PCardinal(@FBuffer[116])^ := 0; //THash.ToBigEndian(Cardinal(FBitLength)); PCardinal(@FBuffer[120])^ := THash.ToBigEndian(Cardinal(FBitLength shr 32)); PCardinal(@FBuffer[124])^ := THash.ToBigEndian(Cardinal(FBitLength)); Compress; FHash64[0] := THash.ToBigEndian(FHash64[0]); FHash64[1] := THash.ToBigEndian(FHash64[1]); FHash64[2] := THash.ToBigEndian(FHash64[2]); FHash64[3] := THash.ToBigEndian(FHash64[3]); FHash64[4] := THash.ToBigEndian(FHash64[4]); FHash64[5] := THash.ToBigEndian(FHash64[5]); FHash64[6] := THash.ToBigEndian(FHash64[6]); FHash64[7] := THash.ToBigEndian(FHash64[7]); end; function THashSHA2.GetBlockSize: Integer; begin case FVersion of THashSHA2.TSHA2Version.SHA224, THashSHA2.TSHA2Version.SHA256: Result := 64; THashSHA2.TSHA2Version.SHA384, THashSHA2.TSHA2Version.SHA512, THashSHA2.TSHA2Version.SHA512_224, THashSHA2.TSHA2Version.SHA512_256: Result := 128; else Result := 0; // This will never happen, but makes happy the compiler about Undefined result of function. end; end; function THashSHA2.GetDigest: TBytes; var LHashSize: Integer; begin if not FFinalized then Finalize; LHashSize := GetHashSize; SetLength(Result, LHashSize); Move(PByte(@FHash64[0])^, PByte(@Result[0])^, LHashSize); end; class function THashSHA2.GetHashBytesFromFile(const AFileName: TFileName; AHashVersion: TSHA2Version): TBytes; var LFile: TFileStream; begin LFile := TFileStream.Create(AFileName, fmShareDenyNone or fmOpenRead); try Result := GetHashBytes(LFile, AHashVersion); finally LFile.Free; end; end; class function THashSHA2.GetHashStringFromFile(const AFileName: TFileName; AHashVersion: TSHA2Version): string; begin Result := THash.DigestAsString(GetHashBytesFromFile(AFileName, AHashVersion)); end; procedure THashSHA2.Initialize(AVersion: TSHA2Version); begin FillChar(Self, SizeOf(Self), 0); FVersion := AVersion; case FVersion of TSHA2Version.SHA224: begin FHash[0]:= $c1059ed8; FHash[1]:= $367cd507; FHash[2]:= $3070dd17; FHash[3]:= $f70e5939; FHash[4]:= $ffc00b31; FHash[5]:= $68581511; FHash[6]:= $64f98fa7; FHash[7]:= $befa4fa4; end; TSHA2Version.SHA256: begin FHash[0]:= $6a09e667; FHash[1]:= $bb67ae85; FHash[2]:= $3c6ef372; FHash[3]:= $a54ff53a; FHash[4]:= $510e527f; FHash[5]:= $9b05688c; FHash[6]:= $1f83d9ab; FHash[7]:= $5be0cd19; end; TSHA2Version.SHA384: begin FHash64[0]:= $cbbb9d5dc1059ed8; FHash64[1]:= $629a292a367cd507; FHash64[2]:= $9159015a3070dd17; FHash64[3]:= $152fecd8f70e5939; FHash64[4]:= $67332667ffc00b31; FHash64[5]:= $8eb44a8768581511; FHash64[6]:= $db0c2e0d64f98fa7; FHash64[7]:= $47b5481dbefa4fa4; end; TSHA2Version.SHA512: begin FHash64[0]:= $6a09e667f3bcc908; FHash64[1]:= $bb67ae8584caa73b; FHash64[2]:= $3c6ef372fe94f82b; FHash64[3]:= $a54ff53a5f1d36f1; FHash64[4]:= $510e527fade682d1; FHash64[5]:= $9b05688c2b3e6c1f; FHash64[6]:= $1f83d9abfb41bd6b; FHash64[7]:= $5be0cd19137e2179; end; TSHA2Version.SHA512_224: begin FHash64[0]:= $8C3D37C819544DA2; FHash64[1]:= $73E1996689DCD4D6; FHash64[2]:= $1DFAB7AE32FF9C82; FHash64[3]:= $679DD514582F9FCF; FHash64[4]:= $0F6D2B697BD44DA8; FHash64[5]:= $77E36F7304C48942; FHash64[6]:= $3F9D85A86A1D36C8; FHash64[7]:= $1112E6AD91D692A1; end; TSHA2Version.SHA512_256: begin FHash64[0]:= $22312194FC2BF72C; FHash64[1]:= $9F555FA3C84C64C2; FHash64[2]:= $2393B86B6F53B151; FHash64[3]:= $963877195940EABD; FHash64[4]:= $96283EE2A88EFFE3; FHash64[5]:= $BE5E1E2553863992; FHash64[6]:= $2B0199FC2C85B8AA; FHash64[7]:= $0EB72DDC81C52CA2; end; end; end; procedure THashSHA2.Update(const AData: PByte; ALength: Cardinal); var PBuffer: PByte; I: Integer; Count: Integer; LBufLen: Cardinal; LRest: Integer; begin CheckFinalized; PBuffer := AData; LBufLen := GetBlockSize; Inc(FBitLength, ALength * 8); // Code Option A Count := (ALength + FIndex) div LBufLen; if Count > 0 then begin LRest := LBufLen - FIndex; Move(PBuffer^, FBuffer[FIndex], LRest); Inc(PBuffer, LRest); Dec(ALength, LRest); Compress; for I := 1 to Count - 1 do begin Move(PBuffer^, FBuffer[0], LBufLen); Inc(PBuffer, LBufLen); Dec(ALength, LBufLen); Compress; end; FIndex := 0; end; Move(PBuffer^, FBuffer[FIndex], ALength); Inc(FIndex, ALength); // // Code Option B // while ALength > 0 do // begin // FBuffer[FIndex] := PBuffer^; // Inc(PBuffer); // Inc(FIndex); // Dec(ALength); // if FIndex = LBufLen then // begin // FIndex := 0; // Compress; // end; // end; end; { THashBobJenkins } class function THashBobJenkins.HashLittle(const Data; Len, InitVal: Integer): Integer; function Rot(x, k: Cardinal): Cardinal; inline; begin Result := (x shl k) or (x shr (32 - k)); end; procedure Mix(var a, b, c: Cardinal); inline; begin Dec(a, c); a := a xor Rot(c, 4); Inc(c, b); Dec(b, a); b := b xor Rot(a, 6); Inc(a, c); Dec(c, b); c := c xor Rot(b, 8); Inc(b, a); Dec(a, c); a := a xor Rot(c,16); Inc(c, b); Dec(b, a); b := b xor Rot(a,19); Inc(a, c); Dec(c, b); c := c xor Rot(b, 4); Inc(b, a); end; procedure Final(var a, b, c: Cardinal); inline; begin c := c xor b; Dec(c, Rot(b,14)); a := a xor c; Dec(a, Rot(c,11)); b := b xor a; Dec(b, Rot(a,25)); c := c xor b; Dec(c, Rot(b,16)); a := a xor c; Dec(a, Rot(c, 4)); b := b xor a; Dec(b, Rot(a,14)); c := c xor b; Dec(c, Rot(b,24)); end; {$POINTERMATH ON} var pb: PByte; pd: PCardinal absolute pb; a, b, c: Cardinal; label case_1, case_2, case_3, case_4, case_5, case_6, case_7, case_8, case_9, case_10, case_11, case_12; begin a := Cardinal($DEADBEEF) + Cardinal(Len) + Cardinal(InitVal); b := a; c := a; pb := @Data; // 4-byte aligned data if (Cardinal(pb) and 3) = 0 then begin while Len > 12 do begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2]); Mix(a, b, c); Dec(Len, 12); Inc(pd, 3); end; case Len of 0: Exit(Integer(c)); 1: Inc(a, pd[0] and $FF); 2: Inc(a, pd[0] and $FFFF); 3: Inc(a, pd[0] and $FFFFFF); 4: Inc(a, pd[0]); 5: begin Inc(a, pd[0]); Inc(b, pd[1] and $FF); end; 6: begin Inc(a, pd[0]); Inc(b, pd[1] and $FFFF); end; 7: begin Inc(a, pd[0]); Inc(b, pd[1] and $FFFFFF); end; 8: begin Inc(a, pd[0]); Inc(b, pd[1]); end; 9: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2] and $FF); end; 10: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2] and $FFFF); end; 11: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2] and $FFFFFF); end; 12: begin Inc(a, pd[0]); Inc(b, pd[1]); Inc(c, pd[2]); end; end; end else begin // Ignoring rare case of 2-byte aligned data. This handles all other cases. while Len > 12 do begin Inc(a, pb[0] + pb[1] shl 8 + pb[2] shl 16 + pb[3] shl 24); Inc(b, pb[4] + pb[5] shl 8 + pb[6] shl 16 + pb[7] shl 24); Inc(c, pb[8] + pb[9] shl 8 + pb[10] shl 16 + pb[11] shl 24); Mix(a, b, c); Dec(Len, 12); Inc(pb, 12); end; case Len of 0: Exit(Integer(c)); 1: goto case_1; 2: goto case_2; 3: goto case_3; 4: goto case_4; 5: goto case_5; 6: goto case_6; 7: goto case_7; 8: goto case_8; 9: goto case_9; 10: goto case_10; 11: goto case_11; 12: goto case_12; end; case_12: Inc(c, pb[11] shl 24); case_11: Inc(c, pb[10] shl 16); case_10: Inc(c, pb[9] shl 8); case_9: Inc(c, pb[8]); case_8: Inc(b, pb[7] shl 24); case_7: Inc(b, pb[6] shl 16); case_6: Inc(b, pb[5] shl 8); case_5: Inc(b, pb[4]); case_4: Inc(a, pb[3] shl 24); case_3: Inc(a, pb[2] shl 16); case_2: Inc(a, pb[1] shl 8); case_1: Inc(a, pb[0]); end; Final(a, b, c); Result := Integer(c); end; {$POINTERMATH OFF} class function THashBobJenkins.Create: THashBobJenkins; begin Result.FHash := 0; end; function THashBobJenkins.GetDigest: TBytes; begin SetLength(Result, 4); PCardinal(@Result[0])^ := THash.ToBigEndian(Cardinal(FHash)); end; class function THashBobJenkins.GetHashString(const AString: string): string; begin Result := Integer(GetHashValue(AString)).ToHexString(8); end; class function THashBobJenkins.GetHashValue(const AData: string): Integer; begin Result := HashLittle(PChar(AData)^, AData.Length * SizeOf(Char), 0); end; class function THashBobJenkins.GetHashValue(const AData; ALength: Integer; AInitialValue: Integer): Integer; begin Result := HashLittle(AData, ALength, AInitialValue); end; function THashBobJenkins.HashAsBytes: TBytes; begin Result := GetDigest; end; function THashBobJenkins.HashAsInteger: Integer; begin Result := FHash; end; function THashBobJenkins.HashAsString: string; begin Result := FHash.ToHexString(8); end; class function THashBobJenkins.GetHashBytes(const AData: string): TBytes; var LHash: Integer; begin SetLength(Result, 4); LHash := HashLittle(PChar(AData)^, AData.Length * SizeOf(Char), 0); PCardinal(@Result[0])^ := THash.ToBigEndian(Cardinal(LHash)); end; procedure THashBobJenkins.Reset(AInitialValue: Integer); begin FHash := AInitialValue; end; procedure THashBobJenkins.Update(const Input: string); begin FHash := HashLittle(PChar(Input)^, Input.Length * SizeOf(Char), FHash); end; procedure THashBobJenkins.Update(const AData; ALength: Cardinal); begin FHash := HashLittle(AData, ALength, FHash); end; procedure THashBobJenkins.Update(const AData: TBytes; ALength: Cardinal); begin if ALength = 0 then ALength := Length(Adata); FHash := HashLittle(PByte(AData)^, ALength, FHash); end; end.
(* * <Diff Match and Patch> partial port to Object Pascal by Lin Ling. * * Original license: * * Copyright 2008 Google Inc. All Rights Reserved. * Author: fraser@google.com (Neil Fraser) * Author: mikeslemmer@gmail.com (Mike Slemmer) * * 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. * * Diff Match and Patch * http://code.google.com/p/google-diff-match-patch/ *) unit Diff; {$ifdef fpc} {$mode delphi} {$endif} interface uses Generics.Collections; type TOperation = (DELETE, INSERT, EQUAL); PDiffRec = ^TDiffRec; TDiffRec = record Operation : TOperation; Text : AnsiString; class operator Equal(a, b: TDiffRec) : Boolean; class operator NotEqual(a, b: TDiffRec): Boolean; end; TDiff = class private (* * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param checklines Speedup flag. If false, then don't run a * line-level diff first to identify the changed areas. * If true, then run a faster slightly less optimal diff. * @param deadline Time when the diff should be complete by. * @return Linked List of Diff objects. *) function diff_compute(const text1, text2: AnsiString; deadline:LongWord):TList<PDiffRec>; (* * Do the two texts share a substring which is at least half the length of * the longer text? * This speedup can produce non-minimal diffs. * @param text1 First string. * @param text2 Second string. * @return Five element String array, containing the prefix of text1, the * suffix of text1, the prefix of text2, the suffix of text2 and the * common middle. Or null if there was no match. *) function diff_halfMatch(const text1, text2: AnsiString):TList<AnsiString>; (* * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @return Linked List of Diff objects. *) function diff_bisect(const text1, text2: AnsiString; deadline:LongWord):TList<PDiffRec>; (* * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param x Index of split point in text1. * @param y Index of split point in text2. * @param deadline Time at which to bail if not yet complete. * @return LinkedList of Diff objects. *) function diff_bisectSplit(const text1, text2: AnsiString; x, y: Integer; deadline:LongWord):TList<PDiffRec>; public // Number of seconds to map a diff before giving up (0 for infinity). Diff_Timeout : LongWord; // Cost of an empty edit operation in terms of edit characters. Diff_EditCost : ShortInt; (* * Find the differences between two texts. * Run a faster slightly less optimal diff. * This method allows the 'checklines' of diff_main() to be optional. * Most of the time checklines is wanted, so default to true. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @return Linked List of Diff objects. *) function diff_main(const text1, text2: AnsiString):TList<PDiffRec>;overload; (* * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param text1 Old string to be diffed. * @param text2 New string to be diffed. * @param deadline Time when the diff should be complete by. * @return Linked List of Diff objects. *) function diff_main(const text1, text2: AnsiString; deadline:LongWord):TList<PDiffRec>;overload; (* * Determine the common prefix of two strings. * @param text1 First string. * @param text2 Second string. * @return The number of characters common to the start of each string. *) function diff_commonPrefix(const text1, text2: AnsiString):Integer; (* * Determine the common suffix of two strings. * @param text1 First string. * @param text2 Second string. * @return The number of characters common to the end of each string. *) function diff_commonSuffix(const text1, text2: AnsiString):Integer; (* * Reduce the number of edits by eliminating operationally trivial equalities. * @param diffs LinkedList of Diff objects. *) procedure diff_cleanupEfficiency(diffs:TList<PDiffRec>); (* * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param diffs LinkedList of Diff objects. *) procedure diff_cleanupMerge(diffs:TList<PDiffRec>); constructor Create; end; function CreateDiffRec:PDiffRec;overload; function CreateDiffRec(Op: TOperation; txt: AnsiString):PDiffRec;overload; implementation uses Windows, AnsiStrings, SysUtils, Math; //TODO: Replace me. procedure CopyList(Target,Source:TList<PDiffRec>);inline; var Rec : PDiffRec; begin Target.Capacity := Target.Count + Source.Count; for Rec in Source do Target.Add(Rec); end; function MidStr(const S: AnsiString; Index: Integer): AnsiString;inline; begin Result := Copy(S, Index, Length(S) - Index + 1); end; function RightStr(const S: AnsiString; Count: Integer): AnsiString;inline; begin Result := Copy(S, Length(S) - Count + 1, Count); end; { TDiffRec } function CreateDiffRec:PDiffRec; begin New(Result); end; function CreateDiffRec(Op: TOperation; txt: AnsiString):PDiffRec; begin New(Result); Result.Operation := op; Result.Text := txt; end; (* * Is this Diff equivalent to another Diff? * @param a Rec a * @param b Compare against * @return true or false *) class operator TDiffRec.Equal(a, b: TDiffRec): Boolean; begin Result := (a.Operation = b.Operation) AND (a.Text = b.Text); end; class operator TDiffRec.NotEqual(a, b: TDiffRec): Boolean; begin Result := NOT (a = b); end; { TDiff } function TDiff.diff_compute(const text1, text2: AnsiString;deadline: LongWord): TList<PDiffRec>; var longtext, shorttext : AnsiString; i : Integer; op : TOperation; hm : TList<AnsiString>; text1_a, text1_b, text2_a, text2_b, mid_common: AnsiString; diffs_a, diffs_b: TList<PDiffRec>; begin if text1 = '' then begin // Just add some text (speedup). Result := TList<PDiffRec>.Create; Result.Add(CreateDiffRec(INSERT, text2)); Exit; end; if text2 = '' then begin // Just delete some text (speedup). Result := TList<PDiffRec>.Create; Result.Add(CreateDiffRec(DELETE, text1)); Exit; end; if Length(text1) > Length(text2) then begin longtext := text1; shorttext := text2; end else begin longtext := text2; shorttext := text1; end; i := AnsiPos(shorttext, LongText); if i <> 0 then begin Result := TList<PDiffRec>.Create; // Shorter text is inside the longer text (speedup). if Length(text1) > Length(text2) then op := DELETE else op := INSERT; Result.Add(CreateDiffRec(op, Copy(longtext, 1, i-1))); Result.Add(CreateDiffRec(EQUAL, shorttext)); Result.Add(CreateDiffRec(op, MidStr(longtext, Length(shorttext) + i))); Exit; end; if Length(shorttext) = 1 then begin Result := TList<PDiffRec>.Create; // Single character string. // After the previous speedup, the character can't be an equality. Result.Add(CreateDiffRec(DELETE, text1)); Result.Add(CreateDiffRec(INSERT, text2)); Exit; end; // Check to see if the problem can be split in two. hm := diff_halfMatch(text1, text2); if hm.Count > 0 then begin // A half-match was found, sort out the return data. text1_a := hm[0]; text1_b := hm[1]; text2_a := hm[2]; text2_b := hm[3]; mid_common := hm[4]; // Send both pairs off for separate processing. diffs_a := diff_main(text1_a, text2_a, deadline); diffs_b := diff_main(text1_b, text2_b, deadline); // // Merge the results. Result := diffs_a; Result.Add(CreateDiffRec(EQUAL, mid_common)); CopyList(Result, diffs_b); diffs_b.Free; Exit; end else hm.Free; Result := diff_bisect(text1, text2, deadline); end; function TDiff.diff_bisect(const text1, text2: AnsiString;deadline: LongWord): TList<PDiffRec>; var text1_length, text2_length, d, max_d, v_offset, v_length : Integer; v1, v2 : array of Integer; x : Integer; delta : Integer; front : Boolean; k1start, k1end, k2start, k2end : Integer; x1, x2, k1, k2, k1_offset, k2_offset, y1, y2 : Integer; begin text1_length := Length(text1); text2_length := Length(text2); max_d := Ceil((text1_length + text2_length + 1) / 2); v_offset := max_d; v_length := 2 * max_d; SetLength(v1, v_length); SetLength(v2, v_length); x := 0; while x < v_length do begin v1[x] := -1; v2[x] := -1; Inc(x); end; v1[v_offset + 1] := 1; v2[v_offset + 1] := 1; delta := text1_length - text2_length; // If the total number of characters is odd, then the front path will // collide with the reverse path. front := delta MOD 2 <> 0; // Offsets for start and end of k loop. // Prevents mapping of space beyond the grid. k1start := 0; k1end := 0; k2start := 0; k2end := 0; d := 0; while d < max_d do begin // Bail out if deadline is reached. // if (clock() > deadline) then // break; // Walk the front path one step. k1 := -d + k1start; while k1 <= d - k1end do begin k1_offset := v_offset + k1; if (k1 = -d) OR ((k1 <> d) AND (v1[k1_offset - 1] < v1[k1_offset + 1])) then x1 := v1[k1_offset + 1] else x1 := v1[k1_offset - 1] + 1; y1 := x1 - k1; while (x1 <= text1_length) AND (y1 <= text2_length) AND (text1[x1] = text2[y1]) do begin Inc(x1); Inc(y1); end; v1[k1_offset] := x1; if x1 > text1_length + 1 then // Ran off the right of the graph. Inc(k1end, 2) else if y1 > text2_length + 1 then // Ran off the bottom of the graph. Inc(k1start, 2) else if front then begin k2_offset := v_offset + delta - k1; if (k2_offset >= 0) AND (k2_offset < v_length) AND (v2[k2_offset] <> -1) then begin // Mirror x2 onto top-left coordinate system. x2 := text1_length - v2[k2_offset]; if x1 > x2 then begin // Overlap detected. Exit(diff_bisectSplit(text1, text2, x1, y1, deadline)); end; end; end; Inc(k1, 2); end; // Walk the reverse path one step. k2 := -d + k2start; while k2 <= d - k2end do begin k2_offset := v_offset + k2; if (k2 = -d) OR ((k2 <> d) AND (v2[k2_offset - 1] < v2[k2_offset + 1])) then x2 := v2[k2_offset + 1] else x2 := v2[k2_offset - 1] + 1; y2 := x2 - k2; while (x2 <= text1_length) AND (y2 <= text2_length) AND (text1[text1_length - x2] = text2[text2_length - y2]) do begin Inc(x2); Inc(y2); end; v2[k2_offset] := x2; if x2 > text1_length + 1 then // Ran off the left of the graph. Inc(k2end, 2) else if y2 > text2_length + 1 then // Ran off the top of the graph. Inc(k2start, 2) else if NOT front then begin k1_offset := v_offset + delta - k2; if (k1_offset >= 0) AND (k1_offset < v_length) AND (v1[k1_offset] <> -1) then begin x1 := v1[k1_offset]; y1 := v_offset + x1 - k1_offset; // Mirror x2 onto top-left coordinate system. x2 := text1_length - x2; if x1 > x2 then begin // Overlap detected. Exit(diff_bisectSplit(text1, text2, x1, y1, deadline)); end; end; end; Inc(k2, 2); end; Inc(d); end; Result := TList<PDiffRec>.Create; Result.Add(CreateDiffRec(DELETE, text1)); Result.Add(CreateDiffRec(INSERT, text2)); end; function TDiff.diff_bisectSplit( const text1, text2: AnsiString; x, y: Integer; deadline: LongWord ): TList<PDiffRec>; var text1a, text1b, text2a, text2b : AnsiString; diffsb : TList<PDiffRec>; begin text1a := Copy(text1,1,x-1); text2a := Copy(text2,1,y-1); text1b := MidStr(text1, x); text2b := MidStr(text2, y); // Compute both diffs serially. Result := diff_main(text1a, text2a, deadline); diffsb := diff_main(text1b, text2b, deadline); CopyList(Result, diffsb); diffsb.Free; end; function TDiff.diff_halfMatch(const text1, text2: AnsiString): TList<AnsiString>; begin Result := TList<AnsiString>.Create; if Diff_Timeout = 0 then // Don't risk returning a non-optimal diff if we have unlimited time. Exit; //TODO end; function TDiff.diff_main(const text1, text2: AnsiString): TList<PDiffRec>; var deadline : LongWord; begin if (Diff_Timeout = 0) then deadline := GetTickCount - 1 else deadline := GetTickCount + Diff_Timeout * 1000; Result := diff_main(text1, text2, deadline); end; function TDiff.diff_main(const text1, text2: AnsiString;deadline: LongWord): TList<PDiffRec>; var commonlength : Integer; commonprefix, commonsuffix : AnsiString; textChopped1, textChopped2 : AnsiString; begin // Check for equality (speedup). if text1 = text2 then begin Result := TList<PDiffRec>.Create; if text1 <> '' then Result.Add(CreateDiffRec(EQUAL, text1)); Exit; end; // Trim off common prefix (speedup). commonlength := diff_commonPrefix(text1, text2); commonprefix := Copy(text1, 1, commonlength); textChopped1 := MidStr(text1, commonlength + 1); textChopped2 := MidStr(text2, commonlength + 1); // Trim off common suffix (speedup). commonlength := diff_commonSuffix(textChopped1, textChopped2); commonsuffix := RightStr(textChopped1, commonlength); textChopped1 := Copy(textChopped1, 1, Length(textChopped1)-commonlength); textChopped2 := Copy(textChopped2, 1, Length(textChopped2)-commonlength); // Compute the diff on the middle block. Result := diff_compute(textChopped1, textChopped2, deadline); // Restore the prefix and suffix. if commonprefix <> '' then Result.Insert(0,CreateDiffRec(EQUAL, commonprefix)); if commonsuffix <> '' then Result.Add(CreateDiffRec(EQUAL, commonsuffix)); diff_cleanupMerge(Result); end; function TDiff.diff_commonPrefix(const text1, text2: AnsiString): Integer; var n, i : Integer; begin // Performance analysis: http://neil.fraser.name/news/2007/10/09/ n := Min(Length(text1), Length(text2)); for i := 1 to n do begin if text1[i] <> text2[i] then Exit(i-1); end; Result := n; end; function TDiff.diff_commonSuffix(const text1, text2: AnsiString): Integer; var text1_length, text2_length : Integer; n, i : Integer; begin // Performance analysis: http://neil.fraser.name/news/2007/10/09/ text1_length := Length(text1); text2_length := Length(text2); n := Min(text1_length, text2_length)-1; for i := 0 to n do begin if text1[text1_length - i] <> text2[text2_length -i] then Exit(i); end; Result := n+1; end; procedure TDiff.diff_cleanupEfficiency(diffs: TList<PDiffRec>); var Index : Integer; changes : Boolean; equalities : TStack<Integer>; lastequality : AnsiString; has_lastequality : Boolean; pre_ins, pre_del, post_ins, post_del : Boolean; thisDiff : PDiffRec; begin if diffs.Count = 0 then Exit; Index := 0; has_lastequality := False; changes := False; equalities := TStack<Integer>.Create; // Is there an insertion operation before the last equality. pre_ins := False; // Is there a deletion operation before the last equality. pre_del := False; // Is there an insertion operation after the last equality. post_ins := False; // Is there a deletion operation after the last equality. post_del := False; if Index >= diffs.Count then thisDiff := nil else thisDiff := diffs[Index]; while thisDiff <> nil do begin if thisDiff.Operation = EQUAL then begin // Equality found. if (Length(thisDiff.Text) < Diff_EditCost) AND (post_ins OR post_del) then begin // Candidate found. equalities.Push(Index); pre_ins := post_ins; pre_del := post_del; lastequality := thisDiff.Text; has_lastequality := True; end else begin // Not a candidate, and can never become one. equalities.Clear; has_lastequality := False; end; post_ins := False; post_del := False; end else begin // An insertion or deletion. if thisDiff.Operation = DELETE then post_del := True else post_ins := True; (* * Five types to be split: * <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> * <ins>A</ins>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<ins>C</ins> * <ins>A</del>X<ins>C</ins><del>D</del> * <ins>A</ins><del>B</del>X<del>C</del> *) if has_lastequality AND ((pre_ins AND pre_del AND post_ins AND post_del) OR ((Length(lastequality) < Diff_EditCost div 2) AND (Byte(pre_ins)+Byte(pre_del)+Byte(post_ins)+Byte(post_del) = 3))) then begin diffs[equalities.Peek].Operation := DELETE; diffs[equalities.Peek].Text := lastequality; diffs.Insert(equalities.Peek+1, CreateDiffRec(INSERT, lastequality)); //diffs[equalities.Peek+1].Operation := INSERT; //Throw away the equality we just deleted. equalities.Pop; lastequality := ''; has_lastequality := False; if pre_ins AND pre_del then begin // No changes made which could affect previous entry, keep going. post_ins := True; post_del := True; equalities.Clear; end else begin //Throw away the previous equality. if equalities.Count > 0 then equalities.Pop; if equalities.Count > 0 then Index := equalities.Peek else Index := 0; post_ins := False; post_del := False; end; changes := True; end; end; if Index+1 >= diffs.Count then thisDiff := nil else begin Inc(Index); thisDiff := diffs[Index]; end; end; equalities.Free; if changes then diff_cleanupMerge(diffs); end; procedure TDiff.diff_cleanupMerge(diffs: TList<PDiffRec>); var Index : Integer; count_delete, count_insert : Integer; commonlength : Integer; text_delete, text_insert : AnsiString; thisDiff, prevEqual, prevDiff, nextDiff : PDiffRec; both_types, changes : Boolean; begin diffs.Add(CreateDiffRec(EQUAL, '')); // Add a dummy entry at the end. Index := 0; count_delete := 0; count_insert := 0; text_delete := ''; text_insert := ''; prevEqual := nil; if Index >= diffs.Count then thisDiff := nil else thisDiff := diffs[Index]; while thisDiff <> nil do begin case thisDiff.Operation of INSERT:begin Inc(count_insert); text_insert := text_insert + thisDiff.Text; prevEqual := nil; end; DELETE:begin Inc(count_delete); text_delete := text_delete + thisDiff.Text; prevEqual := nil; end; EQUAL:begin if (count_delete + count_insert > 1) then begin both_types := (count_delete <> 0) AND (count_insert <> 0); // Delete the offending records. while count_delete > 0 do begin Dec(count_delete); Dec(Index); Dispose(diffs[Index]); Diffs.Delete(Index); end; while count_insert > 0 do begin Dec(count_insert); Dec(Index); Dispose(diffs[Index]); Diffs.Delete(Index); end; if both_types then begin // Factor out any common prefixies. commonlength := diff_commonPrefix(text_insert, text_delete); if commonlength <> 0 then begin if Index > 0 then begin thisDiff := diffs[Index-1]; if thisDiff.Operation <> EQUAL then raise Exception.Create('Previous diff should have been an equality.'); thisDiff.Text := thisDiff.Text + Copy(text_insert, 1, commonlength); end else begin diffs.Insert(Index, CreateDiffRec(EQUAL, Copy(text_insert, 1, commonlength))); end; text_insert := MidStr(text_insert, commonlength); text_delete := MidStr(text_delete, commonlength); end; // Factor out any common suffixies. commonlength := diff_commonSuffix(text_insert, text_delete); if commonlength <> 0 then begin thisDiff := diffs[Index+1]; thisDiff.Text := MidStr(text_insert, Length(text_insert) - commonlength) + thisDiff.Text; text_insert := Copy(text_insert, 1, Length(text_insert) - commonlength); text_delete := Copy(text_delete, 1, Length(text_delete) - commonlength); end; end; // Insert the merged records. if text_delete <> '' then begin diffs.Insert(Index, CreateDiffRec(DELETE, text_delete)); Inc(Index); end; if text_insert <> '' then begin diffs.Insert(Index, CreateDiffRec(INSERT, text_insert)); Inc(Index); end; // Step forward to the equality. //if Index+1 >= diffs.Count then thisDiff := nil else begin Inc(Index); thisDiff := diffs[Index]; end; end else if prevEqual <> nil then begin // Merge this equality with the previous one. prevEqual.text := prevEqual.text + thisDiff.text; Dispose(diffs[diffs.Count-1]); diffs.Delete(Index); thisDiff := diffs[Index-1]; end; count_insert := 0; count_delete := 0; text_delete := ''; text_insert := ''; prevEqual := thisDiff; end; end; if Index+1 >= diffs.Count then thisDiff := nil else begin Inc(Index); thisDiff := diffs[Index]; end; end; if diffs[diffs.Count-1].Text = '' then begin Dispose(diffs[diffs.Count-1]); diffs.Delete(diffs.Count-1); // Remove the dummy entry at the end. end; (* * Second pass: look for single edits surrounded on both sides by equalities * which can be shifted sideways to eliminate an equality. * e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC *) changes := False; // Create a new iterator at the start. // (As opposed to walking the current one back.) Index := 0; if Index >= diffs.Count then prevDiff := nil else begin prevDiff := diffs[Index];end; if Index+1 >= diffs.Count then thisDiff := nil else begin Inc(Index); thisDiff := diffs[Index]; end; if Index+1 >= diffs.Count then nextDiff := nil else begin nextDiff := diffs[Index+1]; end; // Intentionally ignore the first and last element (don't need checking). while nextDiff <> nil do begin if (prevDiff.Operation = EQUAL) AND (nextDiff.Operation = EQUAL) then begin // This is a single edit surrounded by equalities. if EndsStr(prevDiff.Text, thisDiff.Text) then begin thisDiff.Text := prevDiff.Text + Copy(thisDiff.Text, 1, Length(thisDiff.Text)- Length(prevDiff.Text)); nextDiff.Text := prevDiff.Text + nextDiff.Text; //Dec(Index, 3); Dispose(diffs[Index-1]); diffs.Delete(Index-1); changes := True; end else if StartsStr(nextDiff.Text, thisDiff.Text) then begin // Shift the edit over the next equality. prevDiff.Text := prevDiff.Text + nextDiff.Text; thisDiff.Text := MidStr(thisDiff.text, Length(nextDiff.Text)) + nextDiff.text; Dispose(diffs[Index+1]); diffs.Delete(Index+1); // Delete nextDiff. changes := True; end; end; prevDiff := thisDiff; thisDiff := nextDiff; Inc(Index); if Index+1 >= diffs.Count then nextDiff := nil else begin nextDiff := diffs[Index+1]; end; end; // If shifts were made, the diff needs reordering and another shift sweep. if changes then diff_cleanupMerge(diffs); end; constructor TDiff.Create; begin inherited; Diff_Timeout := 1; Diff_EditCost := 4; end; end.
unit SpinEditImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, Spin; type TSpinEditX = class(TActiveXControl, ISpinEditX) private { Private declarations } FDelphiControl: TSpinEdit; FEvents: ISpinEditXEvents; procedure ChangeEvent(Sender: TObject); procedure ClickEvent(Sender: TObject); procedure DblClickEvent(Sender: TObject); procedure KeyPressEvent(Sender: TObject; var Key: Char); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_AutoSelect: WordBool; safecall; function Get_AutoSize: WordBool; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_CanUndo: WordBool; safecall; function Get_Color: OLE_COLOR; safecall; function Get_Ctl3D: WordBool; safecall; function Get_Cursor: Smallint; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_EditorEnabled: WordBool; safecall; function Get_Enabled: WordBool; safecall; function Get_Font: IFontDisp; safecall; function Get_Increment: Integer; safecall; function Get_MaxLength: Integer; safecall; function Get_MaxValue: Integer; safecall; function Get_MinValue: Integer; safecall; function Get_Modified: WordBool; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_ReadOnly: WordBool; safecall; function Get_SelLength: Integer; safecall; function Get_SelStart: Integer; safecall; function Get_SelText: WideString; safecall; function Get_Text: WideString; safecall; function Get_Value: Integer; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure Clear; safecall; procedure ClearSelection; safecall; procedure ClearUndo; safecall; procedure CopyToClipboard; safecall; procedure CutToClipboard; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure PasteFromClipboard; safecall; procedure SelectAll; safecall; procedure Set_AutoSelect(Value: WordBool); safecall; procedure Set_AutoSize(Value: WordBool); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Color(Value: OLE_COLOR); safecall; procedure Set_Ctl3D(Value: WordBool); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_EditorEnabled(Value: WordBool); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_Increment(Value: Integer); safecall; procedure Set_MaxLength(Value: Integer); safecall; procedure Set_MaxValue(Value: Integer); safecall; procedure Set_MinValue(Value: Integer); safecall; procedure Set_Modified(Value: WordBool); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_ReadOnly(Value: WordBool); safecall; procedure Set_SelLength(Value: Integer); safecall; procedure Set_SelStart(Value: Integer); safecall; procedure Set_SelText(const Value: WideString); safecall; procedure Set_Text(const Value: WideString); safecall; procedure Set_Value(Value: Integer); safecall; procedure Set_Visible(Value: WordBool); safecall; procedure Undo; safecall; end; implementation uses ComObj, About30; { TSpinEditX } procedure TSpinEditX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_SpinEditXPage); } end; procedure TSpinEditX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as ISpinEditXEvents; end; procedure TSpinEditX.InitializeControl; begin FDelphiControl := Control as TSpinEdit; FDelphiControl.OnChange := ChangeEvent; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnDblClick := DblClickEvent; FDelphiControl.OnKeyPress := KeyPressEvent; end; function TSpinEditX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TSpinEditX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TSpinEditX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TSpinEditX.Get_AutoSelect: WordBool; begin Result := FDelphiControl.AutoSelect; end; function TSpinEditX.Get_AutoSize: WordBool; begin Result := FDelphiControl.AutoSize; end; function TSpinEditX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TSpinEditX.Get_CanUndo: WordBool; begin Result := FDelphiControl.CanUndo; end; function TSpinEditX.Get_Color: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.Color); end; function TSpinEditX.Get_Ctl3D: WordBool; begin Result := FDelphiControl.Ctl3D; end; function TSpinEditX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TSpinEditX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TSpinEditX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TSpinEditX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TSpinEditX.Get_EditorEnabled: WordBool; begin Result := FDelphiControl.EditorEnabled; end; function TSpinEditX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TSpinEditX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TSpinEditX.Get_Increment: Integer; begin Result := FDelphiControl.Increment; end; function TSpinEditX.Get_MaxLength: Integer; begin Result := FDelphiControl.MaxLength; end; function TSpinEditX.Get_MaxValue: Integer; begin Result := FDelphiControl.MaxValue; end; function TSpinEditX.Get_MinValue: Integer; begin Result := FDelphiControl.MinValue; end; function TSpinEditX.Get_Modified: WordBool; begin Result := FDelphiControl.Modified; end; function TSpinEditX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TSpinEditX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TSpinEditX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TSpinEditX.Get_ReadOnly: WordBool; begin Result := FDelphiControl.ReadOnly; end; function TSpinEditX.Get_SelLength: Integer; begin Result := FDelphiControl.SelLength; end; function TSpinEditX.Get_SelStart: Integer; begin Result := FDelphiControl.SelStart; end; function TSpinEditX.Get_SelText: WideString; begin Result := WideString(FDelphiControl.SelText); end; function TSpinEditX.Get_Text: WideString; begin Result := WideString(FDelphiControl.Text); end; function TSpinEditX.Get_Value: Integer; begin Result := FDelphiControl.Value; end; function TSpinEditX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TSpinEditX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TSpinEditX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TSpinEditX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TSpinEditX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TSpinEditX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TSpinEditX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TSpinEditX.AboutBox; begin ShowSpinEditXAbout; end; procedure TSpinEditX.Clear; begin FDelphiControl.Clear; end; procedure TSpinEditX.ClearSelection; begin FDelphiControl.ClearSelection; end; procedure TSpinEditX.ClearUndo; begin FDelphiControl.ClearUndo; end; procedure TSpinEditX.CopyToClipboard; begin FDelphiControl.CopyToClipboard; end; procedure TSpinEditX.CutToClipboard; begin FDelphiControl.CutToClipboard; end; procedure TSpinEditX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TSpinEditX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TSpinEditX.PasteFromClipboard; begin FDelphiControl.PasteFromClipboard; end; procedure TSpinEditX.SelectAll; begin FDelphiControl.SelectAll; end; procedure TSpinEditX.Set_AutoSelect(Value: WordBool); begin FDelphiControl.AutoSelect := Value; end; procedure TSpinEditX.Set_AutoSize(Value: WordBool); begin FDelphiControl.AutoSize := Value; end; procedure TSpinEditX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TSpinEditX.Set_Color(Value: OLE_COLOR); begin FDelphiControl.Color := TColor(Value); end; procedure TSpinEditX.Set_Ctl3D(Value: WordBool); begin FDelphiControl.Ctl3D := Value; end; procedure TSpinEditX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TSpinEditX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TSpinEditX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TSpinEditX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TSpinEditX.Set_EditorEnabled(Value: WordBool); begin FDelphiControl.EditorEnabled := Value; end; procedure TSpinEditX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TSpinEditX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TSpinEditX.Set_Increment(Value: Integer); begin FDelphiControl.Increment := Value; end; procedure TSpinEditX.Set_MaxLength(Value: Integer); begin FDelphiControl.MaxLength := Value; end; procedure TSpinEditX.Set_MaxValue(Value: Integer); begin FDelphiControl.MaxValue := Value; end; procedure TSpinEditX.Set_MinValue(Value: Integer); begin FDelphiControl.MinValue := Value; end; procedure TSpinEditX.Set_Modified(Value: WordBool); begin FDelphiControl.Modified := Value; end; procedure TSpinEditX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TSpinEditX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TSpinEditX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TSpinEditX.Set_ReadOnly(Value: WordBool); begin FDelphiControl.ReadOnly := Value; end; procedure TSpinEditX.Set_SelLength(Value: Integer); begin FDelphiControl.SelLength := Value; end; procedure TSpinEditX.Set_SelStart(Value: Integer); begin FDelphiControl.SelStart := Value; end; procedure TSpinEditX.Set_SelText(const Value: WideString); begin FDelphiControl.SelText := String(Value); end; procedure TSpinEditX.Set_Text(const Value: WideString); begin FDelphiControl.Text := TCaption(Value); end; procedure TSpinEditX.Set_Value(Value: Integer); begin FDelphiControl.Value := Value; end; procedure TSpinEditX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TSpinEditX.Undo; begin FDelphiControl.Undo; end; procedure TSpinEditX.ChangeEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnChange; end; procedure TSpinEditX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TSpinEditX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; procedure TSpinEditX.KeyPressEvent(Sender: TObject; var Key: Char); var TempKey: Smallint; begin TempKey := Smallint(Key); if FEvents <> nil then FEvents.OnKeyPress(TempKey); Key := Char(TempKey); end; initialization TActiveXControlFactory.Create( ComServer, TSpinEditX, TSpinEdit, Class_SpinEditX, 30, '{695CDBBD-02E5-11D2-B20D-00C04FA368D4}', 0, tmApartment); end.
{ Invokable implementation File for TUsers which implements IUsers } unit UsersImpl; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd, System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes, System.Variants, FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr, UsersIntf; type { TUsers } TUsers = class(TInvokableClass, IUsers) public function CheckUser(NameOrPass: String): Boolean; procedure UserRegistration(Item: UserServer); procedure SelectUserFromDb(name: string); procedure UpDatingCount(name: string; ActionCount: integer); function ConnectToDb: TSQLConnection; function LogInCheck(name, Password: string): Boolean; end; implementation { TUsers } function TUsers.CheckUser(NameOrPass: String): Boolean; var connect: TSQLConnection; query: TSQLQuery; begin connect := ConnectToDb; query := TSQLQuery.Create(nil); try query.SQLConnection := connect; query.SQL.Text := 'select Login from users where Login = "' + NameOrPass + '"'; query.Open; if query.Eof then begin result := false; connect.Close; end else begin result := true; connect.Close; end; finally FreeAndNil(query); end; FreeAndNil(connect); end; function TUsers.ConnectToDb: TSQLConnection; var ASQLConnection: TSQLConnection; Path: string; begin ASQLConnection := TSQLConnection.Create(nil); ASQLConnection.ConnectionName := 'SQLITECONNECTION'; ASQLConnection.DriverName := 'Sqlite'; ASQLConnection.LoginPrompt := false; ASQLConnection.Params.Values['Host'] := 'localhost'; ASQLConnection.Params.Values['FailIfMissing'] := 'False'; ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False'; Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb')); Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb') + 'ExampleDb.db'; ASQLConnection.Params.Values['Database'] := Path; ASQLConnection.Execute('CREATE TABLE if not exists Users(' + 'Id TEXT,' + 'Login TEXT,' + 'Password TEXT,' + 'ActionCount INTEGER' + ');', nil); ASQLConnection.Open; result := ASQLConnection; end; function TUsers.LogInCheck(name, Password: string): Boolean; var ASQLConnection: TSQLConnection; connect: TSQLQuery; query: string; i, j: integer; begin i := 0; j := 0; ASQLConnection := ConnectToDb; connect := TSQLQuery.Create(nil); try connect.SQLConnection := ASQLConnection; connect.SQL.Text := 'select Login from Users where Login = "' + name + '"'; connect.Open; if not connect.Eof then i := 1; connect.Close; connect.SQL.Text := 'select Password from Users where Password = "' + Password + '"'; connect.Open; if not connect.Eof then j := 1; connect.Close; if (i + j) = 2 then result := true else result := false; finally FreeAndNil(connect); end; FreeAndNil(ASQLConnection); end; procedure TUsers.SelectUserFromDb(name: string); var ASQLConnection: TSQLConnection; RS: TDataset; i: integer; Item: UserServer; begin i := 0; ASQLConnection := ConnectToDb; try ASQLConnection.Execute ('select Id, Login, Password,ActionCount from Users WHERE Login = "' + name + '"', nil, RS); while not RS.Eof do begin Item.Id := RS.FieldByName('Id').Value; Item.Login := RS.FieldByName('Login').Value; Item.Password := RS.FieldByName('Password').Value; Item.ActionCount := RS.FieldByName('ActionCount').Value; RS.Next; end; finally FreeAndNil(ASQLConnection); end; FreeAndNil(RS); end; procedure TUsers.UpDatingCount(name: string; ActionCount: integer); const cInsertQuery = 'UPDATE Users SET `ActionCount` =:ActionCount WHERE Login="%s"'; var query: String; querity: TSQLQuery; connect: TSQLConnection; begin connect := ConnectToDb; querity := TSQLQuery.Create(nil); try querity.SQLConnection := connect; query := Format(cInsertQuery, [Name]); querity.Params.CreateParam(TFieldType.ftInteger, 'ActionCount', ptInput); querity.Params.ParamByName('ActionCount').AsInteger := ActionCount; querity.SQL.Text := query; querity.ExecSQL(); finally FreeAndNil(querity); end; FreeAndNil(connect); end; procedure TUsers.UserRegistration(Item: UserServer); var DB: TSQLConnection; Params: TParams; query: string; begin query := 'INSERT INTO Users (Id,Login,Password,ActionCount) VALUES (:Id,:Login,:Password,:ActionCount)'; DB := ConnectToDb; try Params := TParams.Create; Params.CreateParam(TFieldType.ftString, 'id', ptInput); Params.ParamByName('id').AsString := Item.Id; Params.CreateParam(TFieldType.ftString, 'Login', ptInput); Params.ParamByName('Login').AsString := Item.Login; Params.CreateParam(TFieldType.ftString, 'Password', ptInput); Params.ParamByName('Password').AsString := Item.Password; Params.CreateParam(TFieldType.ftInteger, 'ActionCount', ptInput); Params.ParamByName('ActionCount').AsInteger := Item.ActionCount; DB.Execute(query, Params); FreeAndNil(Params); finally FreeAndNil(DB); end; end; initialization { Invokable classes must be registered } InvRegistry.RegisterInvokableClass(TUsers); end.
unit frmTarifaMensual; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DateUtils, Grids, DBGrids, ExtCtrls, DBCtrls, ZAbstractRODataset, ZAbstractDataset, ZAbstractTable, ZDataset, NxScrollControl, NxCustomGridControl, NxCustomGrid, NxDBGrid, frm_Connection, NxDBColumns, NxColumns, StdCtrls, Mask, frm_barra, ComObj, UnitExcel, UDbGrid; type Tfrm_TarifaMensual = class(TForm) dsTarifaMensual: TDataSource; qryTarifaMensual: TZQuery; grid_Comunidades: TDBGrid; frmBarra1: TfrmBarra; Label1: TLabel; txtLimiteInferior: TDBEdit; Label2: TLabel; txtLimiteSuperior: TDBEdit; Label3: TLabel; txtCuotaFija: TDBEdit; Label6: TLabel; txtPorcentaje: TDBEdit; qryTarifaMensualiIdTarifaMensual: TIntegerField; qryTarifaMensualfLimiteInferior: TFloatField; qryTarifaMensualfLimiteSuperior: TFloatField; qryTarifaMensualfCuotaFija: TFloatField; qryTarifaMensualfPorcentaje: TFloatField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure frmBarra1btnAddClick(Sender: TObject); procedure frmBarra1btnEditClick(Sender: TObject); procedure frmBarra1btnPostClick(Sender: TObject); procedure frmBarra1btnCancelClick(Sender: TObject); procedure frmBarra1btnDeleteClick(Sender: TObject); procedure frmBarra1btnExitClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure txtLimiteInferiorKeyPress(Sender: TObject; var Key: Char); procedure txtLimiteSuperiorKeyPress(Sender: TObject; var Key: Char); procedure txtCuotaFijaKeyPress(Sender: TObject; var Key: Char); procedure frmBarra1btnRefreshClick(Sender: TObject); procedure txtPorcentajeKeyPress(Sender: TObject; var Key: Char); procedure frmBarra1btnPrinterClick(Sender: TObject); procedure FormatoEncabezado; procedure FormatoDefault; function Obtener_Letra(y : integer) : String; procedure grid_ComunidadesMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure grid_ComunidadesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure grid_ComunidadesTitleClick(Column: TColumn); private { Private declarations } public { Public declarations } end; var frm_TarifaMensual: Tfrm_TarifaMensual; Excel, Libro: Variant; utgrid:ticdbgrid; implementation uses frmTablaIMSS; {$R *.dfm} procedure Tfrm_TarifaMensual.FormClose(Sender: TObject; var Action: TCloseAction); begin utgrid.Destroy; action := cafree ; end; procedure Tfrm_TarifaMensual.FormShow(Sender: TObject); begin UtGrid:=TicdbGrid.create(grid_Comunidades); qryTarifaMensual.Active := False ; qryTarifaMensual.Open ; end; procedure Tfrm_TarifaMensual.frmBarra1btnAddClick(Sender: TObject); begin frmBarra1.btnAddClick(Sender); qryTarifaMensual.Append; txtLimiteInferior.SetFocus end; procedure Tfrm_TarifaMensual.frmBarra1btnCancelClick(Sender: TObject); begin qryTarifaMensual.Cancel ; frmBarra1.btnCancelClick(Sender); end; procedure Tfrm_TarifaMensual.frmBarra1btnDeleteClick(Sender: TObject); begin If qryTarifaMensual.RecordCount > 0 then if MessageDlg('Desea eliminar el Registro?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin try qryTarifaMensual.Delete ; except MessageDlg('Ocurrio un error al eliminar el registro.', mtInformation, [mbOk], 0); end end end; procedure Tfrm_TarifaMensual.frmBarra1btnEditClick(Sender: TObject); begin frmBarra1.btnEditClick(Sender); If qryTarifaMensual.RecordCount > 0 Then begin qryTarifaMensual.Edit ; txtLimiteInferior.SetFocus end ; end; procedure Tfrm_TarifaMensual.frmBarra1btnExitClick(Sender: TObject); begin frmBarra1.btnExitClick(Sender); close end; procedure Tfrm_TarifaMensual.frmBarra1btnPostClick(Sender: TObject); begin qryTarifaMensual.Post ; frmBarra1.btnPostClick(Sender); end; procedure Tfrm_TarifaMensual.frmBarra1btnPrinterClick(Sender: TObject); var I, x, y, Cta : integer; verdadero: Boolean; letra, porciento, signo_pesos : string; begin if qryTarifaMensual.RecordCount > 0 then begin Try Try Excel := CreateOleObject('Excel.Application'); Except On E: Exception do begin FreeAndNil(Excel); ShowMessage(E.Message); Exit; end; End; Excel.Visible := True; Excel.DisplayAlerts:= False; Excel.WorkBooks.Add; Excel.WorkBooks[1].WorkSheets[1].Name := 'Reporte'; Libro := Excel.WorkBooks[1].WorkSheets['Reporte']; for I := 1 to 5 do begin Excel.Columns[I].ColumnWidth := 12; end; Try Libro.Range['B1:E1'].Select; Excel.Selection.Value := 'Tarifa Mensual'; FormatoEncabezado; Libro.Range['B2:B2'].Select; Excel.Selection.Value := 'Límite Inferior'; FormatoEncabezado; Libro.Range['C2:C2'].Select; Excel.Selection.Value := 'Límite Superior'; FormatoEncabezado; Libro.Range['D2:D2'].Select; Excel.Selection.Value := 'Cuota Fija'; FormatoEncabezado; Libro.Range['E2:E2'].Select; Excel.Selection.Value := 'Porcentaje'; FormatoEncabezado; x := 3; qryTarifaMensual.First; while not qryTarifaMensual.Eof do begin y := 2; for Cta := 0 to qryTarifaMensual.FieldDefs.Count - 1 do begin //showMessage(qryTablaImss.FieldDefs.Items[Cta].Name); if qryTarifaMensual.FieldDefs.Items[Cta].Name <> 'iIdTarifaMensual' then begin porciento := ''; signo_pesos := '$ '; if qryTarifaMensual.FieldDefs.Items[Cta].Name = 'fPorcentaje' then begin porciento := '%'; signo_pesos := ''; end; letra := Obtener_Letra(y); Inc(y); Libro.Range[letra + IntToStr(x) +':'+ letra + IntToStr(x)].Select; if trim(qryTarifaMensual.FieldByName(qryTarifaMensual.FieldDefs.Items[Cta].Name).AsString) <> '' then begin Excel.Selection.Value := signo_pesos + qryTarifaMensual.FieldByName(qryTarifaMensual.FieldDefs.Items[Cta].Name).AsString + porciento; end else Excel.Selection.Value := signo_pesos + '0' + porciento; begin end; FormatoDefault; end; end; Inc(x); qryTarifaMensual.Next; end; Finally //qryTarifaMensual.Free; End; Excel.Visible:=True; Finally Excel := Unassigned; End; end; end; procedure Tfrm_TarifaMensual.frmBarra1btnRefreshClick(Sender: TObject); begin qryTarifaMensual.Refresh end; procedure Tfrm_TarifaMensual.grid_ComunidadesMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin UtGrid.dbGridMouseMoveCoord(x,y); end; procedure Tfrm_TarifaMensual.grid_ComunidadesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin UtGrid.DbGridMouseUp(Sender,Button,Shift,X, Y); end; procedure Tfrm_TarifaMensual.grid_ComunidadesTitleClick(Column: TColumn); begin UtGrid.DbGridTitleClick(Column); end; procedure Tfrm_TarifaMensual.txtCuotaFijaKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then txtPorcentaje.SetFocus end; procedure Tfrm_TarifaMensual.txtLimiteInferiorKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then txtLimiteSuperior.SetFocus end; procedure Tfrm_TarifaMensual.txtLimiteSuperiorKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then txtCuotaFija.SetFocus end; procedure Tfrm_TarifaMensual.txtPorcentajeKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then txtLimiteInferior.SetFocus end; procedure Tfrm_TarifaMensual.FormatoEncabezado; begin Excel.Selection.MergeCells := True; Excel.Selection.HorizontalAlignment := xlCenter; Excel.Selection.VerticalAlignment := xlCenter; Excel.Selection.Font.Size := 10; Excel.Selection.Font.Bold := True; Excel.Selection.Font.Name := 'Calibri'; Excel.Selection.Borders.Color := clBlack; Excel.Selection.Interior.Color := $00EBEBEB; end; procedure Tfrm_TarifaMensual.FormatoDefault; begin Excel.Selection.MergeCells := True; Excel.Selection.HorizontalAlignment := xlRight; Excel.Selection.VerticalAlignment := xlCenter; Excel.Selection.Font.Size := 10; Excel.Selection.Font.Bold := False; Excel.Selection.Font.Name := 'Calibri'; end; function Tfrm_TarifaMensual.Obtener_Letra(y : integer) : String; var letra : String; begin if y = 1 then letra := 'A'; if y = 2 then letra := 'B'; if y = 5 then letra := 'E'; if y = 8 then letra := 'H'; if y = 11 then letra := 'K'; if y = 14 then letra := 'N'; if y = 17 then letra := 'Q'; if y = 20 then letra := 'T'; if y = 23 then letra := 'W'; if y = 3 then letra := 'C'; if y = 6 then letra := 'F'; if y = 9 then letra := 'I'; if y = 12 then letra := 'L'; if y = 15 then letra := 'O'; if y = 18 then letra := 'R'; if y = 21 then letra := 'U'; if y = 24 then letra := 'X'; if y = 4 then letra := 'D'; if y = 7 then letra := 'G'; if y = 10 then letra := 'J'; if y = 13 then letra := 'M'; if y = 16 then letra := 'P'; if y = 19 then letra := 'S'; if y = 22 then letra := 'V'; if y = 25 then letra := 'Y'; if y = 26 then letra := 'Z'; Result := letra; end; end.
unit PayPosTermProcess; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorDialog, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.ExtCtrls, Vcl.StdCtrls, cxButtons, cxGroupBox, cxRadioGroup, cxLabel, cxTextEdit, cxCurrencyEdit, Vcl.ActnList, dsdAction, cxClasses, cxPropertiesStore, dsdAddOn, CashInterface, AncestorBase, dsdDB, dxSkinsCore, dxSkinsDefaultPainters, PosInterface, Vcl.ComCtrls, cxProgressBar; type TPosTermThread = class(TThread) private FPosTerm: IPos; FSalerCash : currency; FPeyResult: Boolean; FShowInfo : TThreadProcedure; FEndPayPosTerm : TThreadProcedure; FMsgDescription : string; procedure Execute; override; public { Public declarations } constructor Create; destructor Destroy; override; procedure MsgDescriptionProc(AMsgDescription : string); procedure UpdateMsgDescription; function GetLastPosError : string; end; TPayPosTermProcessForm = class(TForm) edMsgDescription: TEdit; cxProgressBar1: TcxProgressBar; Timer: TTimer; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FPosTermThread : TPosTermThread; public { Public declarations } procedure EndPayPosTerm; end; var PayPosTermProcessForm : TPayPosTermProcessForm; function PayPosTerminal(PosTerm: IPos; ASalerCash : currency) : Boolean; implementation {$R *.dfm} {TPosTermThread} constructor TPosTermThread.Create; begin inherited Create(True); FPosTerm := Nil; FSalerCash := 0; FPeyResult := False; FMsgDescription := ''; end; destructor TPosTermThread.Destroy; begin inherited Destroy; end; procedure TPosTermThread.Execute; begin if Terminated then Exit; if not Assigned(FPosTerm) then Exit; if FSalerCash > 0 then FPosTerm.Payment(FSalerCash); if Assigned(FEndPayPosTerm) then FEndPayPosTerm; end; procedure TPosTermThread.MsgDescriptionProc(AMsgDescription : string); begin if FMsgDescription <> AMsgDescription then begin FMsgDescription := AMsgDescription; Synchronize(UpdateMsgDescription); end; end; procedure TPosTermThread.UpdateMsgDescription; begin PayPosTermProcessForm.edMsgDescription.Text := FMsgDescription; end; function TPosTermThread.GetLastPosError : string; begin if Assigned(FPosTerm) then Result := FPosTerm.LastPosError; end; {TPayPosTermProcessForm} procedure TPayPosTermProcessForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(FPosTermThread) and not FPosTermThread.Finished then begin Action := caNone; ModalResult := 0; if MessageDlg('Прервать оплату документа?',mtConfirmation,mbYesNo,0)<>mrYes then FPosTermThread.FPosTerm.Cancel; end else begin if Assigned(FPosTermThread) then begin if FPosTermThread.GetLastPosError <> '' then ShowMessage(FPosTermThread.GetLastPosError); FreeAndNil(FPosTermThread); end; Timer.Enabled := False; end; end; procedure TPayPosTermProcessForm.FormDestroy(Sender: TObject); begin if Assigned(FPosTermThread) then FPosTermThread.Free; end; procedure TPayPosTermProcessForm.FormShow(Sender: TObject); begin if Assigned(FPosTermThread) then FPosTermThread.Start; Timer.Enabled := True; end; procedure TPayPosTermProcessForm.TimerTimer(Sender: TObject); begin if Assigned(FPosTermThread) then begin if FPosTermThread.Finished then Close; end else Close; end; procedure TPayPosTermProcessForm.EndPayPosTerm; begin if Assigned(FPosTermThread) and FPosTermThread.FPeyResult then ModalResult := mrOk else ModalResult := mrCancel; end; function PayPosTerminal(PosTerm: IPos; ASalerCash : currency) : Boolean; Begin if NOT assigned(PayPosTermProcessForm) then PayPosTermProcessForm := TPayPosTermProcessForm.Create(Application); With PayPosTermProcessForm do try try FPosTermThread := TPosTermThread.Create; FPosTermThread.FPosTerm := PosTerm; FPosTermThread.FSalerCash := ASalerCash; FPosTermThread.FEndPayPosTerm := EndPayPosTerm; PosTerm.OnMsgDescriptionProc := FPosTermThread.MsgDescriptionProc; Result := ShowModal = mrOK; Except ON E: Exception DO MessageDlg(E.Message,mtError,[mbOk],0); end; finally PosTerm.OnMsgDescriptionProc := Nil; end; End; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIPopupMenu.pas // Creator : Shen Min // Date : 2002-09-01 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIPopupMenu; interface {$I SUIPack.inc} uses Windows, Messages, SysUtils, Classes, Menus, Graphics, Forms, Controls, SUIThemes, SUIMgr; type TsuiPopupMenu = class(TPopupMenu) private m_UIStyle : TsuiUIStyle; m_Height : Integer; m_SeparatorHeight : Integer; m_BarColor : TColor; m_BarWidth : Integer; m_Color : TColor; m_SeparatorColor : TColor; m_SelectedBorderColor : TColor; m_SelectedColor : TColor; m_SelectedFontColor : TColor; m_FontColor : TColor; m_BorderColor : TColor; m_FlatMenu : Boolean; m_FontName : TFontName; m_FontSize : Integer; m_FontCharset : TFontCharset; m_UseSystemFont : Boolean; m_FileTheme : TsuiFileTheme; function GetOwnerDraw() : Boolean; procedure SetOwnerDraw(const Value : Boolean); procedure DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure MeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetHeight(const Value: Integer); procedure SetSeparatorHeight(const Value: Integer); procedure SetFileTheme(const Value: TsuiFileTheme); protected procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; procedure MenuAdded(); published property OwnerDraw read GetOwnerDraw write SetOwnerDraw; property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property MenuItemHeight : Integer read m_Height write SetHeight; property SeparatorHeight : Integer read m_SeparatorHeight write SetSeparatorHeight; property BarWidth : Integer read m_BarWidth write m_BarWidth; property BarColor : TColor read m_BarColor write m_BarColor; property Color : TColor read m_Color write m_Color; property SeparatorColor : TColor read m_SeparatorColor write m_SeparatorColor; property SelectedBorderColor : TColor read m_SelectedBorderColor write m_SelectedBorderColor; property SelectedColor : TColor read m_SelectedColor write m_SelectedColor; property SelectedFontColor : TColor read m_SelectedFontColor write m_SelectedFontColor; property FontColor : TColor read m_FontColor write m_FontColor; property BorderColor : TColor read m_BorderColor write m_BorderColor; property FlatMenu : Boolean read m_FlatMenu write m_FlatMenu; property FontName : TFontName read m_FontName write m_FontName; property FontSize : Integer read m_FontSize write m_FontSize; property FontCharset : TFontCharset read m_FontCharset write m_FontCharset; property UseSystemFont : Boolean read m_UseSystemFont write m_UseSystemFont; end; implementation uses SUIPublic, SUIMenu; var l_ImageList : TImageList; { TsuiPopupMenu } constructor TsuiPopupMenu.Create(AOwner: TComponent); begin inherited; inherited OwnerDraw := true; m_Height := 21; m_SeparatorHeight := 21; m_BarColor := clBtnFace; m_BarWidth := 0; m_Color := clWhite; m_SeparatorColor := clGray; m_SelectedBorderColor := clHighlight; m_SelectedColor := clHighlight; m_SelectedFontColor := clWhite; m_FontColor := clWhite; m_BorderColor := clBlack; m_FlatMenu := false; m_FontName := 'MS Sans Serif'; m_FontSize := 8; m_FontCharset := DEFAULT_CHARSET; m_UseSystemFont := true; UIStyle := GetSUIFormStyle(AOwner); end; procedure TsuiPopupMenu.DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); var R : TRect; Cap : String; ShortKey : String; nCharLength : Integer; nCharStart : Integer; Item : TMenuItem; HandleOfMenuWindow : HWND; OutUIStyle : TsuiUIStyle; L2R : Boolean; Style : Integer; X : Integer; begin Item := Sender as TMenuItem; L2R := (BiDiMode = bdLeftToRight) or (not SysLocale.MiddleEast); if m_FlatMenu then begin HandleOfMenuWindow := WindowFromDC(ACanvas.Handle); if HandleOfMenuWindow <> 0 then begin if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then Menu_DrawWindowBorder( HandleOfMenuWindow, clBlack, m_FileTheme.GetColor(SUI_THEME_FORM_BACKGROUND_COLOR) ) else Menu_DrawWindowBorder( HandleOfMenuWindow, clBlack, GetInsideThemeColor(OutUIStyle, SUI_THEME_FORM_BACKGROUND_COLOR) ) end; end; // draw line if Item.Caption = '-' then begin {$IFDEF RES_MACOS} if m_UIStyle = MacOS then Menu_DrawMacOSLineItem(ACanvas, ARect) else {$ENDIF} begin // draw Left bar if L2R then begin if m_BarWidth > 0 then begin R := Rect(ARect.Left, ARect.Top, ARect.Left + m_BarWidth, ARect.Bottom); Menu_DrawBackGround(ACanvas, R, m_BarColor); end; // draw right non-bar R := Rect(ARect.Left + m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom); end else begin if m_BarWidth > 0 then begin R := Rect(ARect.Right - m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom); Menu_DrawBackGround(ACanvas, R, m_BarColor); end; // draw right non-bar R := Rect(ARect.Left, ARect.Top, ARect.Right - m_BarWidth, ARect.Bottom); end; Menu_DrawBackGround(ACanvas, R, m_Color); // draw line Menu_DrawLineItem(ACanvas, ARect, m_SeparatorColor, m_BarWidth, L2R); end; Exit; end; // draw line // draw background if Selected and Item.Enabled then begin {$IFDEF RES_MACOS} if m_UIStyle = MacOS then Menu_DrawMacOSSelectedItem(ACanvas, ARect) else {$ENDIF} begin Menu_DrawBackGround(ACanvas, ARect, m_SelectedColor); Menu_DrawBorder(ACanvas, ARect, m_SelectedBorderColor); end; end else begin {$IFDEF RES_MACOS} if m_UIStyle = MacOS then Menu_DrawMacOSNonSelectedItem(ACanvas, ARect) else {$ENDIF} begin // draw left bar if m_BarWidth > 0 then begin if L2R then R := Rect(ARect.Left, ARect.Top, ARect.Left + m_BarWidth, ARect.Bottom) else R := Rect(ARect.Right - m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom); Menu_DrawBackGround(ACanvas, R, m_BarColor); end; if L2R then R := Rect(ARect.Left + m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom) else R := Rect(ARect.Left, ARect.Top, ARect.Right - m_BarWidth, ARect.Bottom); Menu_DrawBackGround(ACanvas, R, m_Color); end end; // draw caption and shortkey Cap := Item.Caption; if m_UseSystemFont then Menu_GetSystemFont(ACanvas.Font) else begin ACanvas.Font.Name := m_FontName; ACanvas.Font.Size := m_FontSize; ACanvas.Font.Charset := m_FontCharset; end; ACanvas.Brush.Style := bsClear; if Item.Enabled then begin if Selected then ACanvas.Font.Color := m_SelectedFontColor else ACanvas.Font.Color := m_FontColor; end else ACanvas.Font.Color := clGray; if Item.Default then ACanvas.Font.Style := ACanvas.Font.Style + [fsBold]; if L2R then begin R := Rect(ARect.Left + m_BarWidth + 4, ARect.Top + 4, ARect.Right, ARect.Bottom); Style := DT_LEFT; end else begin R := Rect(ARect.Left, ARect.Top + 4, ARect.Right - m_BarWidth - 4, ARect.Bottom); Style := DT_RIGHT; end; DrawText(ACanvas.Handle, PChar(Cap), -1, R, Style or DT_TOP or DT_SINGLELINE); ShortKey := ShortCutToText(Item.ShortCut); if L2R then begin nCharLength := ACanvas.TextWidth(ShortKey); nCharStart := ARect.Right - nCharLength - 16; end else begin nCharStart := ARect.Left + 16; end; ACanvas.TextOut(nCharStart, ARect.Top + 4, ShortKey); if L2R then X := ARect.Left + 4 else X := ARect.Right - 20; // draw checked if Item.Checked then begin if ( (Item.ImageIndex = -1) or (Images = nil) or (Item.ImageIndex >= Images.Count) ) then l_ImageList.Draw(ACanvas, X, ARect.Top + 3, 0, Item.Enabled) else begin ACanvas.Brush.Color := clBlack; ACanvas.FrameRect(Rect(X - 2, ARect.Top + 1, X + 17, ARect.Top + 20)); ACanvas.Brush.Color := m_SelectedColor; ACanvas.FillRect(Rect(X - 1, ARect.Top + 2, X + 16, ARect.Top + 19)); end; end; // draw images if (Item.ImageIndex <> -1) and (Images <> nil) then if Item.ImageIndex < Images.Count then Images.Draw(ACanvas, X, ARect.Top + 3, Item.ImageIndex, Item.Enabled); end; function TsuiPopupMenu.GetOwnerDraw: Boolean; begin Result := true; end; procedure TsuiPopupMenu.Loaded; begin inherited; MenuAdded(); end; procedure TsuiPopupMenu.MeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); var Item : TMenuItem; begin Item := Sender as TMenuItem; if Item.Caption = '-' then Height := m_SeparatorHeight else Height := m_Height; Width := ACanvas.TextWidth(Item.Caption) + ACanvas.TextWidth(ShortCutToText(Item.ShortCut)) + m_BarWidth + 40; end; procedure TsuiPopupMenu.MenuAdded; var i : Integer; begin for i := 0 to Items.Count - 1 do Menu_SetItemEvent(Items[i], DrawItem, MeasureItem); end; procedure TsuiPopupMenu.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; if ( (Operation = opInsert) and (AComponent is TMenuItem) ) then begin Menu_SetItemEvent(AComponent as TMenuItem, DrawItem, MeasureItem); end; end; procedure TsuiPopupMenu.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiPopupMenu.SetHeight(const Value: Integer); begin if {$IFDEF RES_MACOS}m_UIStyle <> MacOS {$ELSE} True {$ENDIF} then m_Height := Value; end; procedure TsuiPopupMenu.SetOwnerDraw(const Value: Boolean); begin // Do nothing end; procedure TsuiPopupMenu.SetSeparatorHeight(const Value: Integer); begin if {$IFDEF RES_MACOS}m_UIStyle <> MacOS {$ELSE} True {$ENDIF} then m_SeparatorHeight := Value; end; procedure TsuiPopupMenu.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; begin m_UIStyle := Value; m_BarWidth := 26; {$IFDEF RES_MACOS} if m_UIStyle = MacOS then begin m_Height := 20; m_SeparatorHeight := 12; m_SeparatorColor := 0; end else {$ENDIF} begin m_Height := 21; m_SeparatorHeight := 5; m_SeparatorColor := $00848284; end; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then begin m_BarColor := m_FileTheme.GetColor(SUI_THEME_MENU_LEFTBAR_COLOR); m_Color := m_FileTheme.GetColor(SUI_THEME_MENU_BACKGROUND_COLOR); m_FontColor := m_FileTheme.GetColor(SUI_THEME_MENU_FONT_COLOR); m_SelectedBorderColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_BORDER_COLOR); m_SelectedColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR); m_SelectedFontColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_FONT_COLOR); end else begin m_BarColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_LEFTBAR_COLOR); m_Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_BACKGROUND_COLOR); m_FontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_FONT_COLOR); m_SelectedBorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_BORDER_COLOR); m_SelectedColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR); m_SelectedFontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_FONT_COLOR); end; end; procedure InitUnit(); var Bmp : TBitmap; begin l_ImageList := TImageList.Create(nil); Bmp := TBitmap.Create(); Bmp.LoadFromResourceName( hInstance, 'MENU_CHECKED' ); Bmp.Transparent := True; l_ImageList.AddMasked(Bmp, clWhite); Bmp.Free(); end; procedure UnInitUnit(); begin l_ImageList.Free(); l_ImageList := nil; end; initialization InitUnit(); finalization UnInitUnit(); end.
unit classe.disciplina; interface Uses TEntity, AttributeEntity, SysUtils; type [TableName('DISCIPLINA')] TDisciplina = class(TGenericEntity) private FIdDisciplina:integer; FDescricao:string; procedure setIdDisciplina(const Value: integer); procedure setDescricao(value:string); public [KeyField('IDDISCIPLINA')] [FieldName('IDDISCIPLINA')] property Codigo: integer read FIdDisciplina write setIdDisciplina; [FieldName('DESCRICAO')] property Descricao :string read FDescricao write setDescricao; function ToString:string; override; end; implementation procedure TDisciplina.setIdDisciplina(const Value: integer); begin FIdDisciplina := Value; end; procedure TDisciplina.setDescricao(value: string); begin FDescricao := Value; end; function TDisciplina.toString; begin result := ' Código : '+ IntToStr(Codigo) + ' Descrição: '+ Descricao; end; end.
unit URegraCRUDTodasVacinas; interface uses URegraCRUD , URepositorioDB , URepositorioTodasVacinas , UEntidade , UTodasVacinas ; type TRegraCRUDTodasVacinas = class(TRegraCRUD) protected procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; end; implementation { TRegraCRUDCidade } uses SysUtils , UUtilitarios , UMensagens , UConstantes ; constructor TRegraCRUDTodasVacinas.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioTodasVacinas.Create); end; procedure TRegraCRUDTodasVacinas.ValidaInsercao(const coENTIDADE: TENTIDADE); begin inherited; if Trim(TTODASVACINAS(coENTIDADE).NOME_VACINA) = EmptyStr Then raise EValidacaoNegocio.Create(STR_VACINA_NAO_INFORMADA); if (TTODASVACINAS(coENTIDADE).DESCRICAO) = EmptyStr then raise EValidacaoNegocio.Create (STR_DESCRICAO_VACINA_NAO_INFORMADA); end; end.
unit UTransform; {$mode objfpc}{$H+} interface uses Classes, UFloatPoint; type ArrayOfPoints = array of TPoint; function WorldToScreen(APoint: TFloatPoint): TPoint; function WorldToScreenX(AX: Single): Integer; function WorldToScreenY(AY: Single): Integer; function WorldToScreen(Points: array of TFloatPoint): ArrayOfPoints; function ScreenToWorld(APoint: TPoint): TFloatPoint; function ScreenToWorldX(AX: Integer): Single; function ScreenToWorldY(AY: Integer): Single; var Offset, MinBound, MaxBound: TFloatPoint; Scale: Single = 1; PaintBoxWidth, PaintBoxHeight: Integer; implementation function WorldToScreen(APoint: TFloatPoint): TPoint; begin Result := Point(round((APoint.x - Offset.x) / Scale), round((APoint.y - Offset.y) / Scale)); end; function WorldToScreen(Points: array of TFloatPoint): ArrayOfPoints; var i: Integer; begin SetLength(Result, Length(Points)); for i := 0 to Length(Points) - 1 do Result[i] := Point(round((Points[i].x - Offset.x) / Scale), round((Points[i].y - Offset.y) / Scale)); end; function WorldToScreenX(AX: Single): Integer; begin Result := round((AX - Offset.x) / Scale); end; function WorldToScreenY(AY: Single): Integer; begin Result := round((AY - Offset.y) / Scale); end; function ScreenToWorld(APoint: TPoint): TFloatPoint; begin Result := FloatPoint(APoint.x * Scale + Offset.x, APoint.y * Scale + Offset.y); end; function ScreenToWorldX(AX: Integer): Single; begin Result := AX * Scale + Offset.x; end; function ScreenToWorldY(AY: Integer): Single; begin Result := AY * Scale + Offset.Y; end; initialization Offset := FloatPoint(0, 0); end.
unit Win95pie; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Menus; type TWin95PieChart = class(TCustomPanel) private { Private declarations } FValue, FMaximum, FDepth: integer; FUsedColor, FUsedShadowColor, FFreeColor, FFreeShadowColor, FLineColor: TColor; FAbout: string; procedure DrawPie; procedure SetValue(Value: integer); procedure SetMaximum(Maximum: integer); procedure SetDepth(Depth: integer); Procedure SetUsedColor(Color: TColor); Procedure SetUsedShadowColor(Color: TColor); Procedure SetFreeColor(Color: TColor); Procedure SetFreeShadowColor(Color: TColor); Procedure SetLineColor(Color: TColor); protected { Protected declarations } {$IFDEF WIN32} procedure ValidateRename(AComponent: TComponent; const CurName, NewName: string); override; {$ENDIF} public { Public declarations } constructor Create(AOwner: TComponent); override; procedure Paint; override; published { Published declarations } property Value: integer read FValue write SetValue; property Maximum: integer read FMaximum write SetMaximum; property Depth: integer read FDepth write SetDepth; property UsedColor: TColor read FUsedColor write SetUsedColor; property UsedShadowColor: TColor read FUsedShadowColor write SetUsedShadowColor; property FreeColor: TColor read FFreeColor write SetFreeColor; property FreeShadowColor: TColor read FFreeShadowColor write SetFreeShadowColor; property LineColor: TColor read FLineColor write SetLineColor; property Align; property BorderStyle; property Color; property HelpContext; property Hint; property ParentColor; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property About: string read FAbout write FAbout; end; procedure Register; implementation procedure Register; begin RegisterComponents('BealeARTS', [TWin95PieChart]); end; {$IFDEF WIN32} procedure TWin95PieChart.ValidateRename(AComponent: TComponent; const CurName, NewName: string); begin if (AComponent <> nil) and (CompareText(CurName, NewName) <> 0) and (FindComponent(NewName) <> nil) then raise EComponentError.CreateFmt('A component named %s already exists.', [NewName]); end; {$ENDIF} constructor TWin95PieChart.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 125 + 10; Height := 65 + 10; BevelOuter := bvNone; FValue := 80; FMaximum := 100; FDepth := 10; FUsedColor := clBlue; FUsedShadowColor := clNavy; FFreeColor := clFuchsia; FFreeShadowColor := clPurple; FLineColor := clBlack; end; procedure TWin95PieChart.DrawPie; var X1, Y1, X2, Y2, Angle: integer; DegreeCount: Real; begin Angle := Round((FValue/FMaximum)*360); DegreeCount := (-Angle+270); X1 := Trunc( 0.5 * Width * SIN(((DegreeCount*PI) / 180)) ); Y1 := Trunc( 0.5 * (Height-FDepth) * COS(((DegreeCount*PI) / 180)) ); X1 := X1 + Trunc(Width/2); Y1 := Y1 + Trunc((Height-FDepth)/2); X2 := 0; Y2 := Trunc((Height-FDepth)/2); Canvas.Brush.color := Color; Canvas.FillRect(Rect(0,0,Width,Height)); Canvas.Pen.Color := FLineColor; Canvas.Brush.Color := FreeShadowColor; Canvas.Pie(0,FDepth+0,Width,Height,0,Trunc((Height+FDepth)/2),Width,Trunc((Height+FDepth)/2)); Canvas.Pen.Color := FreeShadowColor; Canvas.MoveTo(X2+1,Y2+FDepth); Canvas.LineTo(Width-2,Y2+FDepth); Canvas.Pen.Color := FLineColor; Canvas.MoveTo(X2,Y2); Canvas.LineTo(X2,Y2+FDepth); Canvas.MoveTo(Width-1,Y2); Canvas.LineTo(Width-1,Y2+FDepth); if Y1 > Trunc((Height-FDepth)/2) then begin Canvas.MoveTo(X1,Y1); Canvas.LineTo(X1,Y1+FDepth); end; Canvas.Brush.Color := FUsedColor; Canvas.Pie(0,0,Width,Height-FDepth,X1,Y1,X2,Y2); Canvas.Brush.Color := FreeColor; Canvas.Pie(0,0,Width,Height-FDepth,X2,Y2,X1,y1); if Y1 > Trunc((Height-FDepth)/2) then begin Canvas.Brush.Color := FreeShadowColor; Canvas.FloodFill(X1-1 ,Y1+Trunc(FDepth/2),FLineColor,fsBorder); Canvas.Brush.Color := UsedShadowColor; Canvas.FloodFill(X1+1 ,Y1+Trunc(FDepth/2),FLineColor,fsBorder); end else begin Canvas.Brush.Color := FreeShadowColor; Canvas.FloodFill(Trunc(Width/2),Height-Trunc(FDepth/2),FLineColor,fsBorder); end; end; procedure TWin95PieChart.Paint; begin Caption := ''; inherited Paint; DrawPie; end; procedure TWin95PieChart.SetValue(Value: integer); begin if Value < 0 then exit; FValue := Value; DrawPie; end; procedure TWin95PieChart.SetMaximum(Maximum: integer); begin if Maximum < 1 then exit; FMaximum := Maximum; DrawPie; end; procedure TWin95PieChart.SetDepth(Depth: integer); begin if Depth < 0 then exit; FDepth := Depth; DrawPie; end; Procedure TWin95PieChart.SetUsedColor(Color: TColor); begin FUsedColor := Color; DrawPie; end; Procedure TWin95PieChart.SetUsedShadowColor(Color: TColor); begin FUsedShadowColor := Color; DrawPie; end; Procedure TWin95PieChart.SetFreeColor(Color: TColor); begin FFreeColor := Color; DrawPie; end; Procedure TWin95PieChart.SetFreeShadowColor(Color: TColor); begin FFreeShadowColor := Color; DrawPie; end; Procedure TWin95PieChart.SetLineColor(Color: TColor); begin FLineColor := Color; DrawPie; end; end.
unit AnswerSQLUnit; interface uses JoanModule, TestClasses, SysUtils, Generics.Collections, Classes, Contnrs; procedure InsertAnswerData(AnswerData: TAnswer); procedure ModifyAnswerData(AnswerData: TAnswer); procedure DeleteAnswerData(AnswerData: TAnswer); function GetAnswerData(TestIndex: integer): TObjectList<TAnswer>; implementation function GetAnswerData(TestIndex: integer): TObjectList<TAnswer>; var answer: TAnswer; begin Result := TObjectList<TAnswer>.Create; Joan.JoanQuery.SQL.Clear; Joan.JoanQuery.SQL.Text := 'SELECT t1.*, t2.* FROM ' + '(SELECT * FROM listening ' + ' WHERE test_idx = :idx) t1 ' + 'LEFT JOIN quiz t2 ' + 'ON t1.quiz_idx = t2.idx;'; Joan.JoanQuery.ParamByName('idx').AsInteger := TestIndex; Joan.JoanQuery.Open; while not Joan.JoanQuery.Eof do begin begin answer := TAnswer.Create; answer.test_Idx := Joan.JoanQuery.FieldByName('test_idx').AsInteger; answer.Quiz_Idx := Joan.JoanQuery.FieldByName('quiz_idx').AsInteger; answer.Quiz_answer := Joan.JoanQuery.FieldByName('answer').AsInteger; answer.Quiz_number := Joan.JoanQuery.FieldByName('number').AsInteger; // answer.member_id := Joan.JoanQuery.FieldByName('member_id').Asstring; // answer.score := Joan.JoanQuery.FieldByName('score').Asinteger; // answer.Answer := Joan.JoanQuery.FieldByName('answer').Asstring; Result.Add(answer); Joan.JoanQuery.Next; end; end; end; procedure InsertAnswerData(AnswerData: TAnswer); begin with Joan.JoanQuery do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO answer (test_idx, quiz_idx, quiz_answer, answer, score, member_id, quiz_number) values ' + ' (:test_idx, :quiz_idx, :quiz_answer, :answer, :score, :member_id, :quiz_number)'; ParamByName('test_idx').AsInteger := AnswerData.test_idx; ParamByName('quiz_idx').AsInteger := answerdata.quiz_idx; ParamByName('quiz_answer').AsInteger := AnswerData.quiz_answer; ParamByName('answer').AsInteger := AnswerData.answer; ParamByName('score').AsInteger := AnswerData.score; ParamByName('member_id').Asstring := AnswerData.member_id; ParamByName('quiz_number').AsInteger := AnswerData.quiz_number; ExecSQL(); end; end; procedure ModifyAnswerData(AnswerData: TAnswer); begin with Joan.JoanQuery do begin Close; SQL.Clear; SQL.Text := 'UPDATE answer SET ' + 'test_idx =:test_idx, quiz_idx =:quiz_idx, quiz_answer =:quiz_answer ' + 'answer =:answer, score =:score, member_id =:member_id, quiz_number =:quiz_number ' + 'WHERE idx = :quizidx '; ParamByName('test_idx').AsInteger := AnswerData.test_idx; ParamByName('quiz_idx').AsInteger := answerdata.quiz_idx; ParamByName('quiz_answer').AsInteger := AnswerData.quiz_answer; ParamByName('answer').AsInteger := AnswerData.answer; ParamByName('score').AsInteger := AnswerData.score; ParamByName('member_id').Asstring := AnswerData.member_id; ParamByName('quiz_number').AsInteger := AnswerData.quiz_number; ExecSQL(); end; end; procedure DeleteAnswerData(AnswerData: TAnswer); begin with Joan.JoanQuery do begin Close; SQL.Clear; SQL.Text := ' DELETE FROM answer WHERE (test_idx = :test_idx) and (quiz_idx = :quiz_idx) '; ParamByName('test_idx').AsInteger := AnswerData.test_idx; ParamByName('quiz_idx').AsInteger := AnswerData.quiz_idx; ExecSQL(); end; end; end.
unit DImageCollections; interface uses System.SysUtils, System.Classes, IconFontsImageCollection, //Vcl.BaseImageCollection, //If you are compiling with a versione older than 10.3 remove this line SVGIconImageCollection; type TIconsType = (itIconFonts, itSVGIcons); TImageCollectionDataModule = class(TDataModule) SVGIconImageCollection: TSVGIconImageCollection; IconFontsImageCollection: TIconFontsImageCollection; IconFontsImageCollectionMono: TIconFontsImageCollection; private FIconsType: TIconsType; procedure SetIconsType(const Value: TIconsType); public property IconsType: TIconsType read FIconsType write SetIconsType; end; var ImageCollectionDataModule: TImageCollectionDataModule; implementation {$R *.dfm} { TImageCollectionDataModule } procedure TImageCollectionDataModule.SetIconsType(const Value: TIconsType); begin FIconsType := Value; end; end.
unit testschurunit; interface uses Math, Sysutils, Ap, hblas, reflections, creflections, sblas, ablasf, ablas, ortfac, blas, rotations, hsschur, schur; function TestSchur(Silent : Boolean):Boolean; function testschurunit_test_silent():Boolean; function testschurunit_test():Boolean; implementation procedure FillSparseA(var A : TReal2DArray; N : AlglibInteger; Sparcity : Double);forward; procedure TestSchurProblem(const A : TReal2DArray; N : AlglibInteger; var MatErr : Double; var OrtErr : Double; var ErrStruct : Boolean; var WFailed : Boolean);forward; (************************************************************************* Testing Schur decomposition subroutine *************************************************************************) function TestSchur(Silent : Boolean):Boolean; var A : TReal2DArray; N : AlglibInteger; MaxN : AlglibInteger; I : AlglibInteger; J : AlglibInteger; Pass : AlglibInteger; PassCount : AlglibInteger; WasErrors : Boolean; ErrStruct : Boolean; WFailed : Boolean; MatErr : Double; OrtErr : Double; Threshold : Double; begin MatErr := 0; OrtErr := 0; ErrStruct := False; WFailed := False; WasErrors := False; MaxN := 70; PassCount := 1; Threshold := 5*100*MachineEpsilon; SetLength(A, MaxN-1+1, MaxN-1+1); // // zero matrix, several cases // I:=0; while I<=MaxN-1 do begin J:=0; while J<=MaxN-1 do begin A[I,J] := 0; Inc(J); end; Inc(I); end; N:=1; while N<=MaxN do begin if (N>30) and (N mod 2=0) then begin Inc(N); Continue; end; TestSchurProblem(A, N, MatErr, OrtErr, ErrStruct, WFailed); Inc(N); end; // // Dense matrix // Pass:=1; while Pass<=PassCount do begin N:=1; while N<=MaxN do begin if (N>30) and (N mod 2=0) then begin Inc(N); Continue; end; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin A[I,J] := 2*RandomReal-1; Inc(J); end; Inc(I); end; TestSchurProblem(A, N, MatErr, OrtErr, ErrStruct, WFailed); Inc(N); end; Inc(Pass); end; // // Sparse matrices, very sparse matrices, incredible sparse matrices // Pass:=1; while Pass<=1 do begin N:=1; while N<=MaxN do begin if (N>30) and (N mod 3<>0) then begin Inc(N); Continue; end; FillSparseA(A, N, 0.8); TestSchurProblem(A, N, MatErr, OrtErr, ErrStruct, WFailed); FillSparseA(A, N, 0.9); TestSchurProblem(A, N, MatErr, OrtErr, ErrStruct, WFailed); FillSparseA(A, N, 0.95); TestSchurProblem(A, N, MatErr, OrtErr, ErrStruct, WFailed); FillSparseA(A, N, 0.997); TestSchurProblem(A, N, MatErr, OrtErr, ErrStruct, WFailed); Inc(N); end; Inc(Pass); end; // // report // WasErrors := AP_FP_Greater(MatErr,Threshold) or AP_FP_Greater(OrtErr,Threshold) or ErrStruct or WFailed; if not Silent then begin Write(Format('TESTING SCHUR DECOMPOSITION'#13#10'',[])); Write(Format('Schur decomposition error: %5.4e'#13#10'',[ MatErr])); Write(Format('Schur orthogonality error: %5.4e'#13#10'',[ OrtErr])); Write(Format('T matrix structure: ',[])); if not ErrStruct then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; Write(Format('Always converged: ',[])); if not WFailed then begin Write(Format('OK'#13#10'',[])); end else begin Write(Format('FAILED'#13#10'',[])); end; Write(Format('Threshold: %5.4e'#13#10'',[ Threshold])); if WasErrors then begin Write(Format('TEST FAILED'#13#10'',[])); end else begin Write(Format('TEST PASSED'#13#10'',[])); end; Write(Format(''#13#10''#13#10'',[])); end; Result := not WasErrors; end; procedure FillSparseA(var A : TReal2DArray; N : AlglibInteger; Sparcity : Double); var I : AlglibInteger; J : AlglibInteger; begin I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin if AP_FP_Greater_Eq(RandomReal,Sparcity) then begin A[I,J] := 2*RandomReal-1; end else begin A[I,J] := 0; end; Inc(J); end; Inc(I); end; end; procedure TestSchurProblem(const A : TReal2DArray; N : AlglibInteger; var MatErr : Double; var OrtErr : Double; var ErrStruct : Boolean; var WFailed : Boolean); var S : TReal2DArray; T : TReal2DArray; SR : TReal1DArray; ASTC : TReal1DArray; SASTC : TReal1DArray; I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; V : Double; LocErr : Double; i_ : AlglibInteger; begin SetLength(SR, N-1+1); SetLength(ASTC, N-1+1); SetLength(SASTC, N-1+1); // // Schur decomposition, convergence test // SetLength(T, N-1+1, N-1+1); I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin T[I,J] := A[I,J]; Inc(J); end; Inc(I); end; if not RMatrixSchur(T, N, S) then begin WFailed := True; Exit; end; // // decomposition error // LocErr := 0; J:=0; while J<=N-1 do begin APVMove(@SR[0], 0, N-1, @S[J][0], 0, N-1); K:=0; while K<=N-1 do begin V := APVDotProduct(@T[K][0], 0, N-1, @SR[0], 0, N-1); ASTC[K] := V; Inc(K); end; K:=0; while K<=N-1 do begin V := APVDotProduct(@S[K][0], 0, N-1, @ASTC[0], 0, N-1); SASTC[K] := V; Inc(K); end; K:=0; while K<=N-1 do begin LocErr := Max(LocErr, AbsReal(SASTC[K]-A[K,J])); Inc(K); end; Inc(J); end; MatErr := Max(MatErr, LocErr); // // orthogonality error // LocErr := 0; I:=0; while I<=N-1 do begin J:=0; while J<=N-1 do begin V := 0.0; for i_ := 0 to N-1 do begin V := V + S[i_,I]*S[i_,J]; end; if I<>J then begin LocErr := Max(LocErr, AbsReal(V)); end else begin LocErr := Max(LocErr, AbsReal(V-1)); end; Inc(J); end; Inc(I); end; OrtErr := Max(OrtErr, LocErr); // // T matrix structure // J:=0; while J<=N-1 do begin I:=J+2; while I<=N-1 do begin if AP_FP_Neq(T[I,J],0) then begin ErrStruct := True; end; Inc(I); end; Inc(J); end; end; (************************************************************************* Silent unit test *************************************************************************) function testschurunit_test_silent():Boolean; begin Result := TestSchur(True); end; (************************************************************************* Unit test *************************************************************************) function testschurunit_test():Boolean; begin Result := TestSchur(False); end; end.
unit ClassScoreBoard; interface uses Windows, Graphics, ExtCtrls, Controls; const CInterval = 3000; type TState = ( sTitle , sPl1 , sPl2 ); TPlyr = ( pComp1 , pComp2 , pComp3 , pPl1 , pPl2 ); TScoreBoard = class private FImage : TImage; FTitle : TBitmap; FState : TState; FScPl1 : integer; FScPl2 : integer; FPlayer1 : TPlyr; FPlayer2 : TPlyr; FTimer : TTimer; procedure OnTimer( Sender : TObject ); procedure OnClick( Sender : TObject ); procedure SetState( NewState : TState ); procedure SetScore1( NewScore : integer ); procedure SetScore2( NewScore : integer ); procedure PaintPlayer1; procedure PaintPlayer2; public constructor Create( Image : TImage ); destructor Destroy; override; procedure Reset; property Player1 : TPlyr write FPlayer1; property Player2 : TPlyr write FPlayer2; property Score1 : integer write SetScore1; property Score2 : integer write SetScore2; property State : TState write SetState; end; implementation uses SysUtils; //============================================================================== // Constructor / destructor //============================================================================== constructor TScoreBoard.Create( Image : TImage ); begin inherited Create; FImage := Image; FTitle := TBitmap.Create; FState := sTitle; FPlayer1 := pPl1; FPlayer2 := pPl2; FTimer := TTimer.Create( nil ); FTimer.Interval := CInterval; FTimer.OnTimer := OnTimer; FImage.OnClick := OnClick; FTitle.Assign( FImage.Picture.Bitmap ); end; destructor TScoreBoard.Destroy; begin FTimer.Free; FTitle.Free; inherited; end; //============================================================================== // P R I V A T E //============================================================================== procedure TScoreBoard.OnTimer( Sender : TObject ); begin State := sTitle; FTimer.Enabled := false; end; procedure TScoreBoard.OnClick( Sender : TObject ); begin if (FState <> sPl2) then State := Succ( FState ) else State := sTitle; end; procedure TScoreBoard.SetState( NewState : TState ); begin FState := NewState; case (FState) of sTitle : FImage.Canvas.Draw( 0 , 0 , FTitle ); sPl1 : PaintPlayer1; sPl2 : PaintPlayer2; end; end; procedure TScoreBoard.SetScore1( NewScore : integer ); begin FScPl1 := NewScore; State := sPl1; FTimer.Interval := CInterval; FTimer.Enabled := false; FTimer.Enabled := true; end; procedure TScoreBoard.SetScore2( NewScore : integer ); begin FScPl2 := NewScore; State := sPl2; FTimer.Interval := CInterval; FTimer.Enabled := false; FTimer.Enabled := true; end; procedure TScoreBoard.PaintPlayer1; var Bmp : TBitmap; S : string; begin Bmp := TBitmap.Create; try with FImage.Canvas do begin Brush.Color := RGB( 51 , 102 , 51 ); FillRect( FImage.ClientRect ); S := 'Player 1 : '+IntToStr( FScPl1 ); Font.Name := 'Arial'; Font.Size := 18; Font.Color := RGB( 255 , 204 , 0 ); TextOut( (FImage.Width - TextWidth( S )) div 2 , 10 , S ); end; finally Bmp.Free; end; end; procedure TScoreBoard.PaintPlayer2; var Bmp : TBitmap; S : string; begin Bmp := TBitmap.Create; try with FImage.Canvas do begin Brush.Color := RGB( 51 , 102 , 51 ); FillRect( FImage.ClientRect ); S := 'Player 2 : '+IntToStr( FScPl2 ); Font.Name := 'Arial'; Font.Size := 18; Font.Color := RGB( 255 , 204 , 0 ); TextOut( (FImage.Width - TextWidth( S )) div 2 , 10 , S ); end; finally Bmp.Free; end; end; //============================================================================== // P U B L I C //============================================================================== procedure TScoreBoard.Reset; begin FScPl1 := 0; FScPl2 := 0; State := sTitle; end; end.
unit generic_darrays_1; interface implementation type TDArray<T> = array of T; var A: TDArray<Int32>; G1, G2, G3: Int32; procedure Test; begin SetLength(A, 3); A[0] := 11; A[1] := 12; A[2] := 13; G1 := A[0]; G2 := A[1]; G3 := A[2]; end; initialization Test(); finalization Assert(G1 = 11); Assert(G2 = 12); Assert(G3 = 13); end.
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+} unit Config; interface uses Global; const maxItem = 56; cfgTop = 4; var numItem : Byte; cfgBot : Byte; cfgCol : Byte; cfgLn : Byte; cfgSel : Byte; cfgKey : Char; cfgDone : Boolean; cfgDraw : Boolean; cfgOver : Boolean; cfgRead : String; cfgStat : Byte; cfgSrt : Byte; cfgBarPos : Byte; procedure cfgAskCreate(Dir : String); procedure cfgBar; procedure cfgDrawAllItems; procedure cfgEditInfo(Def : String; Max : Byte; iFl : tInFlag; iCh : tInChar; Opt : String; Bl : Boolean); function cfgFlags(var F : tUserFlags) : String; procedure cfgInit(Ttl : String); procedure cfgInfo(Info : String); procedure cfgItem(Itm : String; Len : Byte; Res : String; Info : String); function cfgItemNumber(Ch : Char) : Byte; procedure cfgItemXY(X,Y,C : Byte; Itm : String; Len : Byte; Res : String; Info : String); function cfgOption(var Opt; Cur : Byte) : String; procedure cfgPrompt(var Opt; Num : Byte); procedure cfgPromptCommand; procedure cfgReadBoolean(var B : Boolean); procedure cfgReadColor(var Col : tColorRec); procedure cfgReadDate; procedure cfgReadFlags(var F : tUserFlags); procedure cfgReadInfo(Def : String; iFl : tInFlag; iCh : tInChar; Opt : String; Bl : Boolean); procedure cfgReadOption(var Opt; Num : Byte; var Pick : Byte); procedure cfgReadPhone; procedure cfgReadTime; procedure cfgSetItem(Res : String); function cfgYesNo(Def : Boolean) : Boolean; implementation uses Crt, Output, Strings, Input, Files, Misc; type tItem = record Key : Char; sX : Byte; pX : Byte; pY : Byte; Len : Byte; Res : String; Info : String[78]; end; var Item : array[1..maxItem] of tItem; procedure cfgInit(Ttl : String); begin if not cfgDraw then Exit; if not cfgOver then begin { oClrScr; oStrCtr(' |U3c|U1ommand|U2:'); oMoveRight(60); oStrCtr('|U3e|U1sc|U2/|U3q|U1uit'); Insert('- ',ttl,1); Ttl := Ttl+' -'; oGotoXY(CenterPos(Ttl),1); oStrCtr('|U4'+Ttl); oDnLn(1); oStrCtr('|U2'+sRepeat('Ä',79)); oDnLn(1); FillChar(Item,SizeOf(Item),#0);} oSetCol(colText); oClrScr; oStrCtr('|U5ŽÜ'); oMoveRight(75); oStrCtr('ÜŻ'); Insert('- ',ttl,1); Ttl := Ttl+' -'; oGotoXY(CenterPos(Ttl),1); oStrLn('|U4'+Ttl); oStrCtrLn('|U5 ß²ÜÜÜÜÜܲž[|U4command: |U5]žÜÜÜÜÜÜÜÜÜÜžÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜ'+ 'ÜÜž[|U4esc|U5/|U4quit|U5]ž²ÜÜÜÜÜܲß'); FillChar(Item,SizeOf(Item),#0); cfgBarPos := 1; end; numItem := 0; cfgCol := 30; cfgLn := cfgTop; cfgSel := 0; cfgKey := #0; cfgDone := False; cfgStat := 0; cfgSrt := 1; cfgBot := 0; end; procedure cfgBar; begin if (not cfgDraw) or (cfgOver) then Exit; oGotoXY(1,cfgTop+cfgBot); oDnLn(1); oStrCtr('|U5ßž|U4['); oMoveRight(73); oStrCtr(']|U5žß'); { oStrCtr('|U2'+sRepeat('Ä',79));} end; procedure cfgInfo(Info : String); var T : Byte; begin if Info = '' then begin if cfgStat = 0 then Exit; oGotoXY(4,cfgTop+1+cfgBot); oWrite(sRepeat(' ',cfgStat)); { oClrEol;} cfgStat := 0; end else begin T := cfgStat; cfgStat := Length(NoColor(Info)); while Length(NoColor(Info)) < T do Info := Info+' '; oSetCol(colInfoHi); oGotoXY(4,cfgTop+1+cfgBot); oStrCtr(Info); end; end; procedure cfgBarOff(i : Byte); begin with Item[i] do begin oGotoXY(sX,pY); oSetCol(colInfoLo); oWriteChar('['); oSetCol(colInfoHi); case Key of #8 : oWrite('Tab'); #32 : oWrite('Space'); else oWriteChar(Key); end; oSetCol(colInfoLo); oWriteChar(']'); end; end; procedure cfgBarOn(i : Byte); begin with Item[i] do begin oGotoXY(sX,pY); oSetCol(colItemSel); case Key of #8 : oWrite(' Tab '); #32 : oWrite(' Space '); else oWrite(' '+Key+' '); end; end; end; procedure cfgItemXY(X,Y,C : Byte; Itm : String; Len : Byte; Res : String; Info : String); begin if (numItem = maxItem) or (not cfgDraw) then Exit; Inc(numItem); if not cfgOver then begin if Itm[2] <> ' ' then Item[numItem].Key := #1 else Item[numItem].Key := Itm[1]; Item[numItem].Len := Len; Item[numItem].sX := X; Item[numItem].pX := C; Item[numItem].pY := cfgTop+Y-1; Item[numItem].Info := Info; end; Item[numItem].Res := Res; if (cfgOver) or (Length(CleanUp(Itm)) < 1) then Exit; if Itm[2] <> ' ' then begin if cfgBarPos = numItem then Inc(cfgBarPos); oGotoXY(X,Item[numItem].pY); oSetCol(colInfoLo); oWrite('---'); end else if cfgBarPos = numItem then cfgBarOn(numItem) else cfgBarOff(numItem); { begin oGotoXY(X,Item[numItem].pY); oSetCol(colInfoLo); oWriteChar('['); oSetCol(colInfoHi); case Itm[1] of #8 : oWrite('Tab'); #32 : oWrite('Space'); #13 : oWrite('Enter'); #27 : oWrite('Esc'); else oWriteChar(Itm[1]); end; oSetCol(colInfoLo); oWriteChar(']'); end;} oSetCol(colInfo); oWrite(' '+Copy(Itm,3,255)); end; procedure cfgItem(Itm : String; Len : Byte; Res : String; Info : String); begin if (numItem = maxItem) or (not cfgDraw) then Exit; cfgItemXY(cfgSrt,cfgLn-cfgTop+1,cfgCol,Itm,Len,Res,Info); Inc(cfgBot); Inc(cfgLn); end; procedure cfgDrawItem(Itm : Byte; Over : Boolean); begin if Item[Itm].Len = 0 then Exit; oGotoXY(Item[Itm].pX,Item[Itm].pY); oSetCol(colText); if Over then oCWrite(Resize(Item[Itm].Res,Item[Itm].Len)) else oCWrite(strSquish(Item[Itm].Res,Item[Itm].Len)); end; procedure cfgDrawAllItems; var N : Byte; begin if cfgDraw then for N := 1 to numItem do cfgDrawItem(N,cfgOver); cfgDraw := False; cfgOver := False; end; procedure cfgKeyDown; var x, dis, nearest : Integer; begin nearest := 0; dis := 255; for x := 1 to numItem do if (Item[x].pY > Item[cfgBarPos].pY) and (Item[x].pY-Item[cfgBarPos].pY < dis) and (Item[x].Key <> #1) and (Item[x].sX = Item[cfgBarPos].sX) then begin nearest := x; dis := Item[x].pY-Item[cfgBarPos].pY; end; if nearest = 0 then Exit; cfgBarOff(cfgBarPos); cfgBarPos := nearest; cfgBarOn(cfgBarPos); oGotoXY(22,2); oSetCol(colInfoHi); oWrite(' '#8); end; procedure cfgKeyRight; var x, dis, nearest : Integer; begin nearest := 0; dis := 255; for x := 1 to numItem do if (Item[x].sX > Item[cfgBarPos].sX) and (Item[x].sX-Item[cfgBarPos].sX < dis) and (Item[x].Key <> #1) and (Item[x].pY = Item[cfgBarPos].pY) then begin nearest := x; dis := Item[x].sX-Item[cfgBarPos].sX; end; if nearest = 0 then Exit; cfgBarOff(cfgBarPos); cfgBarPos := nearest; cfgBarOn(cfgBarPos); oGotoXY(22,2); oSetCol(colInfoHi); oWrite(' '#8); end; procedure cfgKeyUp; var x, dis, nearest : Integer; begin nearest := 0; dis := 255; for x := 1 to numItem do if (Item[x].pY < Item[cfgBarPos].pY) and (Item[cfgBarPos].pY-Item[x].pY < dis) and (Item[x].Key <> #1) and (Item[x].sX = Item[cfgBarPos].sX) then begin nearest := x; dis := Item[cfgBarPos].pY-Item[x].pY; end; if nearest = 0 then Exit; cfgBarOff(cfgBarPos); cfgBarPos := nearest; cfgBarOn(cfgBarPos); oGotoXY(22,2); oSetCol(colInfoHi); oWrite(' '#8); end; procedure cfgKeyLeft; var x, dis, nearest : Integer; begin nearest := 0; dis := 255; for x := 1 to numItem do if (Item[x].sX < Item[cfgBarPos].sX) and (Item[cfgBarPos].sX-Item[x].sX < dis) and (Item[x].Key <> #1) and (Item[x].pY = Item[cfgBarPos].pY) then begin nearest := x; dis := Item[cfgBarPos].sX-Item[x].sX; end; if nearest = 0 then Exit; cfgBarOff(cfgBarPos); cfgBarPos := nearest; cfgBarOn(cfgBarPos); oGotoXY(22,2); oSetCol(colInfoHi); oWrite(' '#8); end; procedure cfgPromptCommand; var Ch : Char; Pk, N : Byte; isQ : Boolean; begin oGotoXY(22,2); oSetCol(colInfoHi); oWrite(' '#8); Pk := 0; repeat Ch := UpCase(iReadKey); isQ := False; if extKey <> #0 then case extKey of UpArrow : cfgKeyUp; DnArrow : cfgKeyDown; LfArrow : cfgKeyLeft; RtArrow : cfgKeyRight; end else for N := 1 to numItem do begin if (Item[N].Key <> #1) and (Ch = Item[N].Key) then Pk := N; if (not isQ) and (Item[N].Key = 'Q') then isQ := True; end; cfgDone := (Ch in [#27,#13]) or ((not isQ) and (Ch = 'Q')); until (HangUp) or (cfgDone) or (Pk > 0); if HangUp then begin cfgDone := True; Ch := #27; end; if Ch = #13 then begin Ch := Item[cfgBarPos].Key; Pk := cfgBarPos; cfgDone := False; end; case Ch of #8 : oWrite('Tab'); #32 : oWrite('Space'); #27 : begin oWrite('Quit'); oGotoXY(1,24); end; else oWriteChar(Ch); end; if (ch <> #13) and (not cfgDone) then begin if Pk <> cfgBarPos then begin cfgBarOff(cfgBarPos); cfgBarPos := Pk; cfgBarOn(cfgBarPos); oSetCol(colInfoHi); end; end; cfgSel := Pk; cfgKey := Ch; end; function cfgItemNumber(Ch : Char) : Byte; var N : Byte; begin cfgItemNumber := 0; for N := 1 to numItem do if Item[N].Key = Ch then cfgItemNumber := N; end; procedure cfgEditInfo(Def : String; Max : Byte; iFl : tInFlag; iCh : tInChar; Opt : String; Bl : Boolean); var I, L : Byte; begin I := cfgItemNumber(cfgKey); if Item[I].Info <> '' then cfgInfo(Item[I].Info); oGotoXY(Item[I].pX,Item[I].pY); oSetCol(colTextHi); L := Item[I].Len; if max = 0 then begin max := Item[I].Len; Inc(L); end; cfgRead := iEditString(Def,iFl,iCh,rsAbort+rsNoCR+Opt,Max,L); if (Bl) and (cfgRead = '') then cfgRead := Def; cfgInfo(''); end; procedure cfgReadInfo(Def : String; iFl : tInFlag; iCh : tInChar; Opt : String; Bl : Boolean); begin cfgEditInfo(Def,0,iFl,iCh,rsNoCR+rsAbort+Opt,Bl); end; procedure cfgReadPhone; var I : Byte; begin I := cfgItemNumber(cfgKey); if Item[I].Info <> '' then cfgInfo(Item[I].Info); oGotoXY(Item[I].pX,Item[I].pY); oSetCol(colTextHi); cfgRead := iReadPhone(Item[I].Res); cfgInfo(''); end; procedure cfgReadTime; var I : Byte; begin I := cfgItemNumber(cfgKey); if Item[I].Info <> '' then cfgInfo(Item[I].Info); oGotoXY(Item[I].pX,Item[I].pY); oSetCol(colTextHi); cfgRead := iReadTime(Item[I].Res); cfgInfo(''); end; procedure cfgReadDate; var I : Byte; begin I := cfgItemNumber(cfgKey); if Item[I].Info <> '' then cfgInfo(Item[I].Info); oGotoXY(Item[I].pX,Item[I].pY); oSetCol(colTextHi); cfgRead := iReadDate(Item[I].Res); cfgInfo(''); end; { Add BLINK!!!!!!!!!! } procedure cfgReadColor(var Col : tColorRec); var I : Byte; Ch : Char; F,B : Integer; Bl : Boolean; X : tColorRec; begin I := cfgItemNumber(cfgKey); cfgInfo('[up/down: foreground; left/right: background; enter: done; esc: abort]'); oGotoXY(Item[I].pX,Item[I].pY); X := Col; F := Col.Fore; B := Col.Back; Bl := Col.Blink; repeat oCWrite(Resize(strColor(Col),40)); oGotoXY(Item[I].pX,Item[I].pY); Ch := UpCase(iReadKey); case extKey of #75 : begin Dec(B,1); if B < 0 then B := 7; Col.Back := B; end; #77 : begin Inc(B,1); if B > 7 then B := 0; Col.Back := B; end; #80 : begin Dec(F,1); if F < 0 then F := 15; Col.Fore := F; end; #72 : begin Inc(F,1); if F > 15 then F := 0; Col.Fore := F; end; end; until (HangUp) or (Ch in [#27,#13]); if (Ch = #27) or (HangUp) then Col := X; oCWrite(Resize(strColor(Col),40)); cfgRead := ''; cfgInfo(''); end; function cfgYesNo(Def : Boolean) : Boolean; var C : Char; Yes : Boolean; procedure WriteNo; begin oMoveLeft(9); oCWrite('|U4 Yes |U5[|U6No|U5]'); Yes := False; end; procedure WriteYes; begin oMoveLeft(9); oCWrite('|U5[|U6Yes|U5]|U4 No '); Yes := True; end; begin mCursor(False); if Def then oCWrite('|U5[|U6Yes|U5]|U4 No ') else oCWrite('|U4 Yes |U5[|U6No|U5]'); Yes := Def; repeat C := UpCase(iReadKey); if (Yes) and ((extKey in [#77,#75]) or (C in [' ','N'])) then WriteNo else if (not Yes) and ((extKey in [#77,#75]) or (C in [' ','Y'])) then WriteYes; until (HangUp) or (C in [#13,'Y','N']); oSetCol(colInfo); if C = 'Y' then Yes := True else if C = 'N' then Yes := False; mCursor(True); if HangUp then cfgYesNo := Def else cfgYesNo := Yes; end; procedure cfgReadBoolean(var B : Boolean); var I : Byte; begin I := cfgItemNumber(cfgKey); if Item[I].Info <> '' then cfgInfo(Item[I].Info); oGotoXY(Item[I].pX-1,Item[I].pY); B := cfgYesNo(B); oGotoXY(Item[I].pX-1,Item[I].pY); oWrite(sRepeat(' ',10)); cfgInfo(''); end; procedure cfgSetItem(Res : String); var I : Byte; begin I := cfgItemNumber(cfgKey); Item[I].Res := Res; oSetCol(colText); cfgDrawItem(I,True); end; procedure cfgAskCreate(Dir : String); begin if Dir[Length(Dir)] = '\' then Delete(Dir,Length(Dir),1); if fDirExists(Dir) then Exit; cfgInfo('Create Directory? '); if iYesNo(True) then fCreateDir(Dir,True); Inc(cfgStat,10); cfgInfo(''); end; function cfgOption(var Opt; Cur : Byte) : String; type tStrArray = array[1..20] of String; var Choice : ^tStrArray; begin Choice := @Opt; cfgOption := Choice^[Cur]; end; procedure cfgReadOption(var Opt; Num : Byte; var Pick : Byte); type tStrArray = array[1..20] of String; var Sel : ^tStrArray; I, Cur : Byte; Ch : Char; begin Sel := @Opt; I := cfgItemNumber(cfgKey); if Item[I].Info <> '' then cfgInfo('[space/arrows: select; enter: done] '+Item[I].Info); oGotoXY(Item[I].pX,Item[I].pY); oSetCol(colTextHi); if Pick < 1 then Pick := 1 else if Pick > num then Pick := num; Cur := Pick; repeat oWrite(Resize(Sel^[Cur],Item[I].Len)); {Resize(Sel^[Cur],30)); -- ?? } oGotoXY(Item[I].pX,Item[I].pY); Ch := UpCase(iReadKey); if extKey = #0 then case Ch of ' ' : begin Inc(Cur,1); if Cur > Num then Cur := 1; end; end else case extKey of #75,#80 : begin Dec(Cur,1); if Cur < 1 then Cur := Num; end; #77,#72 : begin Inc(Cur,1); if Cur > Num then Cur := 1; end; end; until (HangUp) or (Ch in [#27,#13]); cfgInfo(''); if Ch = #13 then Pick := Cur; end; procedure cfgPrompt(var Opt; Num : Byte); type tStrArray = array[1..20] of String; var Cmd : ^tStrArray; Z : Byte; begin Cmd := @Opt; oCWrite('|U2-- '); for Z := 1 to Num do oCWrite('|U2[|U3'+Copy(Cmd^[Z],1,Pos(' ',Cmd^[Z])-1)+'|U2]|U1'+Copy(Cmd^[Z],Pos(' ',Cmd^[Z])+1,255)+' '); oCWrite('|U2ł |U4Command|U5: |U6'); end; procedure cfgReadFlags(var F : tUserFlags); var I, cur : Byte; z, ch : Char; procedure rfDrawCur; begin oGotoXY(Item[I].pX+cur,Item[I].pY); oSetCol(3); if z in F then oWriteChar(z) else oWriteChar(LowCase(z)); oMoveLeft(1); end; procedure rfNoCur; begin oGotoXY(Item[I].pX+cur,Item[I].pY); oSetCol(1); if z in F then oWriteChar(z) else oWriteChar(LowCase(z)); end; begin I := cfgItemNumber(cfgKey); cfgInfo('[left/right: select; space/a-z: toggle; enter: done] '+Item[I].Info); oGotoXY(Item[I].pX,Item[I].pY); oSetCol(2); oWriteChar('['); oSetCol(1); for z := 'A' to 'Z' do if z in F then oWriteChar(z) else oWriteChar(LowCase(z)); oSetCol(2); oWriteChar(']'); cur := 1; z := 'A'; rfDrawCur; repeat Ch := UpCase(iReadKey); if extKey = #0 then case Ch of 'A'..'Z' : begin if z <> ch then rfNoCur; z := ch; cur := Ord(Ch)-64; if z in F then F := F-[z] else F := F+[z]; rfDrawCur; end; ' ' : begin if z in F then F := F-[z] else F := F+[z]; rfDrawCur; end; end else case extKey of #75 : begin rfNoCur; Dec(Cur); Dec(z); if Cur < 1 then begin cur := 26; z := 'Z'; end; rfDrawCur; end; #77 : begin rfNoCur; Inc(Cur); Inc(z); if Cur > 26 then begin cur := 1; z := 'A'; end; rfDrawCur; end; end; until (HangUp) or (Ch in [#27,#13]); cfgInfo(''); end; function cfgFlags(var F : tUserFlags) : String; var z : Char; s : String; begin s := '|U2[|U1'; for z := 'A' to 'Z' do if z in F then s := s+z else s := s+LowCase(z); s := s+'|U2]'; cfgFlags := s; end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_RecastHelper; interface uses RN_Helper, RN_Recast; procedure rcSwap(var a,b: Single); overload; procedure rcSwap(var a,b: Word); overload; procedure rcSwap(var a,b: Integer); overload; procedure rcSwap(var a,b: Pointer); overload; procedure rcSwap(var a,b: PSingle); overload; function rcMin(a,b: Single): Single; overload; function rcMin(a,b: Integer): Integer; overload; function rcMax(a,b: Single): Single; overload; function rcMax(a,b: Integer): Integer; overload; function rcMax(a,b: Cardinal): Cardinal; overload; function rcClamp(v, mn, mx: Single): Single; overload; function rcClamp(v, mn, mx: Integer): Integer; overload; procedure rcVcross(dest: PSingle; v1, v2: PSingle); function rcVdot(v1, v2: PSingle): Single; procedure rcVmad(dest: PSingle; v1, v2: PSingle; s: Single); procedure rcVadd(dest: PSingle; v1, v2: PSingle); procedure rcVsub(dest: PSingle; v1, v2: PSingle); procedure rcVmin(mn: PSingle; v: PSingle); procedure rcVmax(mx: PSingle; v: PSingle); procedure rcVcopy(dest: PSingle; v: PSingle); function rcVdist(v1, v2: PSingle): Single; function rcVdistSqr(v1, v2: PSingle): Single; procedure rcVnormalize(v: PSingle); procedure rcSetCon(s: PrcCompactSpan; dir, i: Integer); function rcGetCon(s: PrcCompactSpan; dir: Integer): Integer; function rcGetDirOffsetX(dir: Integer): Integer; function rcGetDirOffsetY(dir: Integer): Integer; implementation uses Math; /// Swaps the values of the two parameters. /// @param[in,out] a Value A /// @param[in,out] b Value B procedure rcSwap(var a,b: Single); var T: Single; begin T := a; a := b; b := T; end; procedure rcSwap(var a,b: Word); var T: Word; begin T := a; a := b; b := T; end; procedure rcSwap(var a,b: Integer); var T: Integer; begin T := a; a := b; b := T; end; procedure rcSwap(var a,b: Pointer); var T: Pointer; begin T := a; a := b; b := T; end; procedure rcSwap(var a,b: PSingle); var T: PSingle; begin T := a; a := b; b := T; end; /// Returns the minimum of two values. /// @param[in] a Value A /// @param[in] b Value B /// @return The minimum of the two values. //template<class T> inline T rcMin(T a, T b) { return a < b ? a : b; } function rcMin(a,b: Single): Single; begin Result := Min(a,b); end; function rcMin(a,b: Integer): Integer; begin Result := Min(a,b); end; /// Returns the maximum of two values. /// @param[in] a Value A /// @param[in] b Value B /// @return The maximum of the two values. //template<class T> inline T rcMax(T a, T b) { return a > b ? a : b; } function rcMax(a,b: Single): Single; begin Result := Max(a,b); end; function rcMax(a,b: Integer): Integer; begin Result := Max(a,b); end; function rcMax(a,b: Cardinal): Cardinal; begin Result := Max(a,b); end; /// Returns the absolute value. /// @param[in] a The value. /// @return The absolute value of the specified value. //template<class T> inline T rcAbs(T a) { return a < 0 ? -a : a; } /// Returns the square of the value. /// @param[in] a The value. /// @return The square of the value. //template<class T> inline T rcSqr(T a) { return a*a; } /// Clamps the value to the specified range. /// @param[in] v The value to clamp. /// @param[in] mn The minimum permitted return value. /// @param[in] mx The maximum permitted return value. /// @return The value, clamped to the specified range. //template<class T> inline T rcClamp(T v, T mn, T mx) { return v < mn ? mn : (v > mx ? mx : v); } function rcClamp(v, mn, mx: Single): Single; begin Result := EnsureRange(v, mn, mx); end; function rcClamp(v, mn, mx: Integer): Integer; begin Result := EnsureRange(v, mn, mx); end; /// Returns the square root of the value. /// @param[in] x The value. /// @return The square root of the vlaue. //float rcSqrt(float x); /// @} /// @name Vector helper functions. /// @{ /// Derives the cross product of two vectors. (@p v1 x @p v2) /// @param[out] dest The cross product. [(x, y, z)] /// @param[in] v1 A Vector [(x, y, z)] /// @param[in] v2 A vector [(x, y, z)] procedure rcVcross(dest: PSingle; v1, v2: PSingle); begin dest[0] := v1[1]*v2[2] - v1[2]*v2[1]; dest[1] := v1[2]*v2[0] - v1[0]*v2[2]; dest[2] := v1[0]*v2[1] - v1[1]*v2[0]; end; /// Derives the dot product of two vectors. (@p v1 . @p v2) /// @param[in] v1 A Vector [(x, y, z)] /// @param[in] v2 A vector [(x, y, z)] /// @return The dot product. function rcVdot(v1, v2: PSingle): Single; begin Result := v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; end; /// Performs a scaled vector addition. (@p v1 + (@p v2 * @p s)) /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] v1 The base vector. [(x, y, z)] /// @param[in] v2 The vector to scale and add to @p v1. [(x, y, z)] /// @param[in] s The amount to scale @p v2 by before adding to @p v1. procedure rcVmad(dest: PSingle; v1, v2: PSingle; s: Single); begin dest[0] := v1[0]+v2[0]*s; dest[1] := v1[1]+v2[1]*s; dest[2] := v1[2]+v2[2]*s; end; /// Performs a vector addition. (@p v1 + @p v2) /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] v1 The base vector. [(x, y, z)] /// @param[in] v2 The vector to add to @p v1. [(x, y, z)] procedure rcVadd(dest: PSingle; v1, v2: PSingle); begin dest[0] := v1[0]+v2[0]; dest[1] := v1[1]+v2[1]; dest[2] := v1[2]+v2[2]; end; /// Performs a vector subtraction. (@p v1 - @p v2) /// @param[out] dest The result vector. [(x, y, z)] /// @param[in] v1 The base vector. [(x, y, z)] /// @param[in] v2 The vector to subtract from @p v1. [(x, y, z)] procedure rcVsub(dest: PSingle; v1, v2: PSingle); begin dest[0] := v1[0]-v2[0]; dest[1] := v1[1]-v2[1]; dest[2] := v1[2]-v2[2]; end; /// Selects the minimum value of each element from the specified vectors. /// @param[in,out] mn A vector. (Will be updated with the result.) [(x, y, z)] /// @param[in] v A vector. [(x, y, z)] procedure rcVmin(mn: PSingle; v: PSingle); begin mn[0] := rcMin(mn[0], v[0]); mn[1] := rcMin(mn[1], v[1]); mn[2] := rcMin(mn[2], v[2]); end; /// Selects the maximum value of each element from the specified vectors. /// @param[in,out] mx A vector. (Will be updated with the result.) [(x, y, z)] /// @param[in] v A vector. [(x, y, z)] procedure rcVmax(mx: PSingle; v: PSingle); begin mx[0] := rcMax(mx[0], v[0]); mx[1] := rcMax(mx[1], v[1]); mx[2] := rcMax(mx[2], v[2]); end; /// Performs a vector copy. /// @param[out] dest The result. [(x, y, z)] /// @param[in] v The vector to copy. [(x, y, z)] procedure rcVcopy(dest: PSingle; v: PSingle); begin dest[0] := v[0]; dest[1] := v[1]; dest[2] := v[2]; end; /// Returns the distance between two points. /// @param[in] v1 A point. [(x, y, z)] /// @param[in] v2 A point. [(x, y, z)] /// @return The distance between the two points. function rcVdist(v1, v2: PSingle): Single; var dx,dy,dz: Single; begin dx := v2[0] - v1[0]; dy := v2[1] - v1[1]; dz := v2[2] - v1[2]; Result := Sqrt(dx*dx + dy*dy + dz*dz); end; /// Returns the square of the distance between two points. /// @param[in] v1 A point. [(x, y, z)] /// @param[in] v2 A point. [(x, y, z)] /// @return The square of the distance between the two points. function rcVdistSqr(v1, v2: PSingle): Single; var dx,dy,dz: Single; begin dx := v2[0] - v1[0]; dy := v2[1] - v1[1]; dz := v2[2] - v1[2]; Result := dx*dx + dy*dy + dz*dz; end; /// Normalizes the vector. /// @param[in,out] v The vector to normalize. [(x, y, z)] procedure rcVnormalize(v: PSingle); var d: Single; begin d := 1.0 / Sqrt(Sqr(v[0]) + Sqr(v[1]) + Sqr(v[2])); v[0] := v[0] * d; v[1] := v[1] * d; v[2] := v[2] * d; end; /// Sets the neighbor connection data for the specified direction. /// @param[in] s The span to update. /// @param[in] dir The direction to set. [Limits: 0 <= value < 4] /// @param[in] i The index of the neighbor span. procedure rcSetCon(s: PrcCompactSpan; dir, i: Integer); var shift: Cardinal; con: Integer; begin shift := Cardinal(dir)*6; con := s.con; s.con := (con and not ($3f shl shift)) or ((Cardinal(i) and $3f) shl shift); end; /// Gets neighbor connection data for the specified direction. /// @param[in] s The span to check. /// @param[in] dir The direction to check. [Limits: 0 <= value < 4] /// @return The neighbor connection data for the specified direction, /// or #RC_NOT_CONNECTED if there is no connection. function rcGetCon(s: PrcCompactSpan; dir: Integer): Integer; var shift: Cardinal; begin shift := Cardinal(dir)*6; Result := (s.con shr shift) and $3f; end; /// Gets the standard width (x-axis) offset for the specified direction. /// @param[in] dir The direction. [Limits: 0 <= value < 4] /// @return The width offset to apply to the current cell position to move /// in the direction. function rcGetDirOffsetX(dir: Integer): Integer; const offset: array [0..3] of Integer = (-1, 0, 1, 0); begin Result := offset[dir and $03]; end; /// Gets the standard height (z-axis) offset for the specified direction. /// @param[in] dir The direction. [Limits: 0 <= value < 4] /// @return The height offset to apply to the current cell position to move /// in the direction. function rcGetDirOffsetY(dir: Integer): Integer; const offset: array [0..3] of Integer = (0, 1, 0, -1); begin Result := offset[dir and $03]; end; end.
unit salsa20; {Salsa20 stream cipher routines} interface {$i STD.INC} {$ifdef BIT32} {.$define ChaChaBasm32} {Use EddyHawk's BASM version of chacha_wordtobyte} {$endif} (************************************************************************* DESCRIPTION : Salsa20 stream cipher routines REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : [1] Original version for ECRYPT Stream Cipher Project http://www.ecrypt.eu.org/stream/ciphers/salsa20/salsa20.zip http://www.ecrypt.eu.org/stream/ciphers/salsa20/salsa20source.zip [2] salsa20,12,8-ref.c version 20060209, D.J. Bernstein, public domain http://cr.yp.to/streamciphers/submissions.tar.gz [3] Snuffle 2005: the Salsa20 encryption function: http://cr.yp.to/snuffle.html [4] D.J. Bernstein: Extending the Salsa20 nonce, available via http://cr.yp.to/papers.html#xsalsa, version used is http://cr.yp.to/snuffle/xsalsa-20081128.pdf [5] D.J. Bernstein: Cryptography in NaCl, available via http://nacl.cr.yp.to/valid.html, version used is http://cr.yp.to/highspeed/naclcrypto-20090310.pdf [6] D.J. Bernstein: ChaCha, a variant of Salsa20 http://cr.yp.to/chacha/chacha-20080128.pdf Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 22.02.06 W.Ehrhardt Initial BP7 version, ABC layout, ref code 0.11 23.02.06 we improved wordtobyte, all compilers 0.12 23.02.06 we quarterround function with BASM 0.13 26.02.06 we 8/12 rounds versions 0.14 26.02.06 we BIT32/BASM16 with BASM 0.15 26.02.06 we separate code for salsa_keystream_bytes 0.16 26.02.06 we salsa_keystream_bytes writes to keystream if possible 0.17 26.02.06 we optimized salsa_keysetup, salsa_keysetup256 0.18 01.03.06 we BASM16: salsa20_wordtobyte completely with basm 0.19 04.03.06 we BASM16: Make x in salsa20_wordtobyte dword aligned 0.20 04.03.06 we BASM16: removed dopush variable 0.21 23.04.06 we xkeysetup with keybits and rounds 0.22 10.11.06 we Corrected typo about IV size 0.23 28.07.08 we Default 12 rounds for 128 bit keys, 20 for 256 0.24 23.11.08 we Uses BTypes 0.25 08.04.09 we salsa20_wordtobyte with finaladd parameter 0.26 09.04.09 we XSalsa20 functions 0.27 09.04.09 we Clear context in XSalsa20 packet functions 0.28 12.04.09 we BASM16: encryption speed more than doubled 0.29 13.04.09 we Increased encryption speed for other compilers 0.30 13.04.09 we Special case FPC 0.31 14.04.09 we BASM16: encryption speed increased with 32 bit access 0.32 15.04.09 we Second pass in xsalsa_selftest with length <> blocksize 0.33 12.03.10 EddyHawk EddyHawk contributed functions: chacha20_wordtobyte, chacha_ivsetup, chacha_ks, chacha_keystream_bytes 0.34 12.03.10 we ChaCha: Remove BASM16 push from chacha_keystream_bytes 0.35 12.03.10 we ChaCha: Allow even number of ChaCha rounds > 0 0.36 12.03.10 we ChaCha: 128 bit keys implemented 0.37 12.03.10 we ChaCha: Encrypt/Decrypt/Packets/Blocks 0.38 13.03.10 we new name: chacha_wordtobyte 0.39 13.03.10 we chacha_selftest, ChaCha URL 0.40 02.05.12 EddyHawk EddyHawk contributed BASM32 chacha_wordtobyte 0.41 17.06.12 we Added PurePascal 64-bit compatible salsa20_wordtobyte 0.42 08.09.13 Martok Martok contributed improved PurePascal chacha_wordtobyte 0.43 29.09.13 we BIT16: improved chacha_wordtobyte and chacha_encrypt_bytes 0.44 26.08.15 we Faster (reordered) PurePascal salsa20_wordtobyte **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2006-2015 Wolfgang Ehrhardt Portions of ChaCha code (C) Copyright 2010/2012 EddyHawk Portions of ChaCha code (C) Copyright 2013 Martok This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) (************************************************************************* Encryption/decryption of arbitrary length messages with Salsa20 For efficiency reasons, the API provides two types of encrypt/decrypt functions. The salsa_encrypt_bytes function encrypts byte strings of arbitrary length, while the salsa_encrypt_blocks function only accepts lengths which are multiples of salsa_blocklength. The user is allowed to make multiple calls to salsa_encrypt_blocks to incrementally encrypt a long message, but he is NOT allowed to make additional encryption calls once he has called salsa_encrypt_bytes (unless he starts a new message of course). For example, this sequence of calls is acceptable: salsa_keysetup(); salsa_ivsetup(); salsa_encrypt_blocks(); salsa_encrypt_blocks(); salsa_encrypt_bytes(); salsa_ivsetup(); salsa_encrypt_blocks(); salsa_encrypt_blocks(); salsa_ivsetup(); salsa_encrypt_bytes(); The following sequence is not: salsa_keysetup(); salsa_ivsetup(); salsa_encrypt_blocks(); salsa_encrypt_bytes(); salsa_encrypt_blocks(); XSalsa20 note: ------------- Since the 192 bit nonce/IV is used (together with the primary 266 bit key) to derive the secondary working key, there are no separate key/IV setup functions and packet processing can be done without a user supplied context. ChaCha note: ----------- ChaCha is a variant of Salsa with improved diffusion per round (and conjectured increased resistance to cryptanalysis). My implementation allows 128/256 bit keys and any even number of rounds > 0. **************************************************************************) uses BTypes; const salsa_blocklength = 64; {Block length in bytes} type TSalsaBlk = array[0..15] of longint; {Structure containing the context of salsa20} salsa_ctx = packed record input : TSalsaBlk; {internal state} rounds: word; {number of rounds} kbits : word; {number of key bits} end; procedure salsa_keysetup(var ctx: salsa_ctx; key: pointer); {-Key setup, 128 bits of key^ are used, default rounds=12. It is the user's} { responsibility to supply a pointer to at least 128 accessible key bits!} procedure salsa_keysetup256(var ctx: salsa_ctx; key: pointer); {-Key setup, 256 bits of key^ are used, default rounds=20 It is the user's} { responsibility to supply a pointer to at least 256 accessible key bits!} procedure salsa_xkeysetup(var ctx: salsa_ctx; key: pointer; keybits, rounds: word); {-Key setup, 128 bits of key^ are used if keybits<>256.. It is the user's } { responsibility to supply a pointer to at least 128 (resp 256) accessible} { key bits. If rounds not in [8,12,20], then rounds=20 will be used.} procedure salsa_ivsetup(var ctx: salsa_ctx; IV: pointer); {-IV setup, 64 bits of IV^ are used. It is the user's responsibility to } { supply least 64 accessible IV bits. After having called salsa_keysetup,} { the user is allowed to call salsa_ivsetup different times in order to } { encrypt/decrypt different messages with the same key but different IV's} procedure salsa_encrypt_bytes(var ctx: salsa_ctx; ptp, ctp: pointer; msglen: longint); {-Bytewise encryption, msglen: message length in bytes} procedure salsa_encrypt_blocks(var ctx: salsa_ctx; ptp, ctp: pointer; blocks: word); {-Blockwise encrypt plainttext to ciphertext, blocks: length in 64 byte blocks} procedure salsa_encrypt_packet(var ctx: salsa_ctx; IV, ptp, ctp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} procedure salsa_decrypt_bytes(var ctx: salsa_ctx; ctp, ptp: pointer; msglen: longint); {-Bytewise decryption, msglen: message length in bytes} procedure salsa_decrypt_blocks(var ctx: salsa_ctx; ctp, ptp: pointer; blocks: word); {-Blockwise decryption, blocks: length in 64 byte blocks} procedure salsa_decrypt_packet(var ctx: salsa_ctx; IV, ctp, ptp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} procedure salsa_keystream_bytes(var ctx: salsa_ctx; keystream: pointer; kslen: longint); {-Generate keystream, kslen: keystream length in bytes} procedure salsa_keystream_blocks(var ctx: salsa_ctx; keystream: pointer; blocks: word); {-Generate keystream, blocks: keystream length in 64 byte blocks} function salsa_selftest: boolean; {-Simple self-test of Salsa20, tests 128/256 key bits and 8/12/20 rounds} {---------------------------------------------------------------------------} {---------------------- XSalsa20 functions -------------------------------} {---------------------------------------------------------------------------} procedure xsalsa_setup(var ctx: salsa_ctx; key, IV: pointer); {-Key/IV setup, 256 bits of key^ and 192 bits of IV^ are used. It is the} { user's responsibility that the required bits are accessible! Rounds=20} procedure xsalsa_encrypt_bytes(var ctx: salsa_ctx; ptp, ctp: pointer; msglen: longint); {-Bytewise encryption, msglen: message length in bytes} procedure xsalsa_decrypt_bytes(var ctx: salsa_ctx; ctp, ptp: pointer; msglen: longint); {-Bytewise decryption, msglen: message length in bytes} procedure xsalsa_encrypt_packet(key, IV, ptp, ctp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 192 accessible IV bits.} procedure xsalsa_decrypt_packet(key, IV, ctp, ptp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 192 accessible IV bits.} function xsalsa_selftest: boolean; {-Simple self-test of XSalsa20} {---------------------------------------------------------------------------} {------------------------ ChaCha functions -------------------------------} {---------------------------------------------------------------------------} {$ifdef ChaChaBasm32} {$ifndef BIT32} {$undef ChaChaBasm32} {$endif} {$endif} {$ifdef ChaChaBasm32} const ChaChaBasm32 = true; {$else} const ChaChaBasm32 = false; {$endif} procedure chacha_xkeysetup(var ctx: salsa_ctx; key: pointer; keybits, rounds: word); {-Key setup, 128 bits of key^ are used if keybits<>256.. It is the user's } { responsibility to supply a pointer to at least 128 (resp 256) accessible} { key bits. Rounds should be even > 0 (will be forced)} procedure chacha_keysetup(var ctx: salsa_ctx; key: pointer); {-Key setup, 128 bits of key^ are used, default rounds=12. It is the user's} { responsibility to supply a pointer to at least 128 accessible key bits!} procedure chacha_keysetup256(var ctx: salsa_ctx; key: pointer); {-Key setup, 256 bits of key^ are used, default rounds=20. It is the user's} { responsibility to supply a pointer to at least 256 accessible key bits!} procedure chacha_ivsetup(var ctx: salsa_ctx; IV: pointer); {-IV setup, 64 bits of IV^ are used. It is the user's responsibility to } { supply least 64 accessible IV bits. After having called salsa_keysetup,} { the user is allowed to call salsa_ivsetup different times in order to } { encrypt/decrypt different messages with the same key but different IV's} procedure chacha_encrypt_bytes(var ctx: salsa_ctx; ptp, ctp: pointer; msglen: longint); {-Bytewise encryption, msglen: message length in bytes} procedure chacha_decrypt_bytes(var ctx: salsa_ctx; ctp, ptp: pointer; msglen: longint); {-Bytewise decryption, msglen: message length in bytes} procedure chacha_encrypt_blocks(var ctx: salsa_ctx; ptp, ctp: pointer; blocks: word); {-Blockwise encryption, blocks: length in 64 byte blocks} procedure chacha_decrypt_blocks(var ctx: salsa_ctx; ctp, ptp: pointer; blocks: word); {-Blockwise decryption, blocks: length in 64 byte blocks} procedure chacha_encrypt_packet(var ctx: salsa_ctx; IV, ptp, ctp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} procedure chacha_decrypt_packet(var ctx: salsa_ctx; IV, ctp, ptp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} procedure chacha_keystream_bytes(var ctx: salsa_ctx; keystream: pointer; kslen: longint); {-Generate keystream, kslen: keystream length in bytes} procedure chacha_keystream_blocks(var ctx: salsa_ctx; keystream: pointer; blocks: word); {-Generate keystream, blocks: keystream length in 64 byte blocks} function chacha_selftest: boolean; {-Simple self-test of ChaCha, tests 128/256 key bits and 8/12/20 rounds} implementation {$ifdef BIT16} {$F-} {$ifdef BASM16} (** TP6-7/D1 **) {---------------------------------------------------------------------------} function RotL(X: longint; c: word): longint; inline( $59/ {pop cx } $66/$58/ {pop eax } $66/$D3/$C0/ {rol eax,cl } $66/$8B/$D0/ {mov edx,eax} $66/$C1/$EA/$10); {shr edx,16 } {$else} {** T5/5.5 **} {---------------------------------------------------------------------------} function RotL(X: longint; c: word): longint; {-Rotate left} inline( $59/ { pop cx } $58/ { pop ax } $5A/ { pop dx } $83/$F9/$10/ { cmp cx,16 } $72/$06/ { jb S } $92/ { xchg dx,ax } $83/$E9/$10/ { sub cx,16 } $74/$09/ { je X } $2B/$DB/ {S:sub bx,bx } $D1/$D0/ {L:rcl ax,1 } $D1/$D2/ { rcl dx,1 } $13/$C3/ { adc ax,bx } $49/ { dec cx } $75/$F7); { jne L } {X: } {$endif} {$endif} {Helper types} type T4L = array[0..3] of longint; P4L = ^T4L; T8L = array[0..7] of longint; P8L = ^T8L; T32B = array[0..31] of byte; T64B = array[0..63] of byte; P64B = ^T64B; const tau : packed array[0..15] of char8 = 'expand 16-byte k'; sigma: packed array[0..15] of char8 = 'expand 32-byte k'; {---------------------------------------------------------------------------} procedure salsa_keysetup(var ctx: salsa_ctx; key: pointer); {-Key setup, 128 bits of key^ are used, default rounds=12. It is the user's} { responsibility to supply a pointer to at least 128 accessible key bits!} begin with ctx do begin input[1] := P8L(key)^[0]; input[2] := P8L(key)^[1]; input[3] := P8L(key)^[2]; input[4] := P8L(key)^[3]; input[11] := input[1]; input[12] := input[2]; input[13] := input[3]; input[14] := input[4]; input[0] := T4L(tau)[0]; input[5] := T4L(tau)[1]; input[10] := T4L(tau)[2]; input[15] := T4L(tau)[3]; rounds := 12; kbits := 128; end; end; {---------------------------------------------------------------------------} procedure salsa_keysetup256(var ctx: salsa_ctx; key: pointer); {-Key setup, 256 bits of key^ are used, default rounds=20 It is the user's} { responsibility to supply a pointer to at least 256 accessible key bits!} begin with ctx do begin input[1] := P8L(key)^[0]; input[2] := P8L(key)^[1]; input[3] := P8L(key)^[2]; input[4] := P8L(key)^[3]; input[11] := P8L(key)^[4]; input[12] := P8L(key)^[5]; input[13] := P8L(key)^[6]; input[14] := P8L(key)^[7]; input[0] := T4L(sigma)[0]; input[5] := T4L(sigma)[1]; input[10] := T4L(sigma)[2]; input[15] := T4L(sigma)[3]; rounds := 20; kbits := 256; end; end; {---------------------------------------------------------------------------} procedure salsa_xkeysetup(var ctx: salsa_ctx; key: pointer; keybits, rounds: word); {-Key setup, 128 bits of key^ are used if keybits<>256.. It is the user's } { responsibility to supply a pointer to at least 128 (resp 256) accessible} { key bits. If rounds not in [8,12,20], then rounds=20 will be used.} begin if keybits=256 then salsa_keysetup256(ctx,key) else salsa_keysetup(ctx,key); if (rounds<>8) and (rounds<>12) then rounds := 20; ctx.rounds := rounds; end; {---------------------------------------------------------------------------} procedure salsa_ivsetup(var ctx: salsa_ctx; IV: pointer); {-IV setup, 64 bits of IV^ are used. It is the user's responsibility to } { supply least 64 accessible IV bits. After having called salsa_keysetup,} { the user is allowed to call salsa_ivsetup different times in order to } { encrypt/decrypt different messages with the same key but different IV's} begin with ctx do begin input[6] := P4L(IV)^[0]; input[7] := P4L(IV)^[1]; input[8] := 0; input[9] := 0; end; end; {$ifdef BIT64} {$define PurePascal} {$endif} {$ifdef PurePascal} {---------------------------------------------------------------------------} procedure salsa20_wordtobyte(var output: T64B; const input: TSalsaBlk; rounds: word; finaladd: boolean); {-This is the Salsa20 "hash" function} var i: integer; y: longint; x: TSalsaBlk; begin x := input; {$ifdef OldOrder} for i:=1 to (rounds shr 1) do begin y := x[ 0] + x[12]; x[ 4] := x[ 4] xor ((y shl 07) or (y shr (32-07))); y := x[ 4] + x[ 0]; x[ 8] := x[ 8] xor ((y shl 09) or (y shr (32-09))); y := x[ 8] + x[ 4]; x[12] := x[12] xor ((y shl 13) or (y shr (32-13))); y := x[12] + x[ 8]; x[ 0] := x[ 0] xor ((y shl 18) or (y shr (32-18))); y := x[ 5] + x[ 1]; x[ 9] := x[ 9] xor ((y shl 07) or (y shr (32-07))); y := x[ 9] + x[ 5]; x[13] := x[13] xor ((y shl 09) or (y shr (32-09))); y := x[13] + x[ 9]; x[ 1] := x[ 1] xor ((y shl 13) or (y shr (32-13))); y := x[ 1] + x[13]; x[ 5] := x[ 5] xor ((y shl 18) or (y shr (32-18))); y := x[10] + x[ 6]; x[14] := x[14] xor ((y shl 07) or (y shr (32-07))); y := x[14] + x[10]; x[ 2] := x[ 2] xor ((y shl 09) or (y shr (32-09))); y := x[ 2] + x[14]; x[ 6] := x[ 6] xor ((y shl 13) or (y shr (32-13))); y := x[ 6] + x[ 2]; x[10] := x[10] xor ((y shl 18) or (y shr (32-18))); y := x[15] + x[11]; x[ 3] := x[ 3] xor ((y shl 07) or (y shr (32-07))); y := x[ 3] + x[15]; x[ 7] := x[ 7] xor ((y shl 09) or (y shr (32-09))); y := x[ 7] + x[ 3]; x[11] := x[11] xor ((y shl 13) or (y shr (32-13))); y := x[11] + x[ 7]; x[15] := x[15] xor ((y shl 18) or (y shr (32-18))); y := x[ 0] + x[ 3]; x[ 1] := x[ 1] xor ((y shl 07) or (y shr (32-07))); y := x[ 1] + x[ 0]; x[ 2] := x[ 2] xor ((y shl 09) or (y shr (32-09))); y := x[ 2] + x[ 1]; x[ 3] := x[ 3] xor ((y shl 13) or (y shr (32-13))); y := x[ 3] + x[ 2]; x[ 0] := x[ 0] xor ((y shl 18) or (y shr (32-18))); y := x[ 5] + x[ 4]; x[ 6] := x[ 6] xor ((y shl 07) or (y shr (32-07))); y := x[ 6] + x[ 5]; x[ 7] := x[ 7] xor ((y shl 09) or (y shr (32-09))); y := x[ 7] + x[ 6]; x[ 4] := x[ 4] xor ((y shl 13) or (y shr (32-13))); y := x[ 4] + x[ 7]; x[ 5] := x[ 5] xor ((y shl 18) or (y shr (32-18))); y := x[10] + x[ 9]; x[11] := x[11] xor ((y shl 07) or (y shr (32-07))); y := x[11] + x[10]; x[ 8] := x[ 8] xor ((y shl 09) or (y shr (32-09))); y := x[ 8] + x[11]; x[ 9] := x[ 9] xor ((y shl 13) or (y shr (32-13))); y := x[ 9] + x[ 8]; x[10] := x[10] xor ((y shl 18) or (y shr (32-18))); y := x[15] + x[14]; x[12] := x[12] xor ((y shl 07) or (y shr (32-07))); y := x[12] + x[15]; x[13] := x[13] xor ((y shl 09) or (y shr (32-09))); y := x[13] + x[12]; x[14] := x[14] xor ((y shl 13) or (y shr (32-13))); y := x[14] + x[13]; x[15] := x[15] xor ((y shl 18) or (y shr (32-18))); end; {$else} for i:=1 to (rounds shr 1) do begin y := x[ 0] + x[12]; x[ 4] := x[ 4] xor ((y shl 07) or (y shr (32-07))); y := x[ 5] + x[ 1]; x[ 9] := x[ 9] xor ((y shl 07) or (y shr (32-07))); y := x[10] + x[ 6]; x[14] := x[14] xor ((y shl 07) or (y shr (32-07))); y := x[15] + x[11]; x[ 3] := x[ 3] xor ((y shl 07) or (y shr (32-07))); y := x[ 4] + x[ 0]; x[ 8] := x[ 8] xor ((y shl 09) or (y shr (32-09))); y := x[ 9] + x[ 5]; x[13] := x[13] xor ((y shl 09) or (y shr (32-09))); y := x[14] + x[10]; x[ 2] := x[ 2] xor ((y shl 09) or (y shr (32-09))); y := x[ 3] + x[15]; x[ 7] := x[ 7] xor ((y shl 09) or (y shr (32-09))); y := x[ 8] + x[ 4]; x[12] := x[12] xor ((y shl 13) or (y shr (32-13))); y := x[13] + x[ 9]; x[ 1] := x[ 1] xor ((y shl 13) or (y shr (32-13))); y := x[ 2] + x[14]; x[ 6] := x[ 6] xor ((y shl 13) or (y shr (32-13))); y := x[ 7] + x[ 3]; x[11] := x[11] xor ((y shl 13) or (y shr (32-13))); y := x[12] + x[ 8]; x[ 0] := x[ 0] xor ((y shl 18) or (y shr (32-18))); y := x[ 1] + x[13]; x[ 5] := x[ 5] xor ((y shl 18) or (y shr (32-18))); y := x[ 6] + x[ 2]; x[10] := x[10] xor ((y shl 18) or (y shr (32-18))); y := x[11] + x[ 7]; x[15] := x[15] xor ((y shl 18) or (y shr (32-18))); y := x[ 0] + x[ 3]; x[ 1] := x[ 1] xor ((y shl 07) or (y shr (32-07))); y := x[ 5] + x[ 4]; x[ 6] := x[ 6] xor ((y shl 07) or (y shr (32-07))); y := x[10] + x[ 9]; x[11] := x[11] xor ((y shl 07) or (y shr (32-07))); y := x[15] + x[14]; x[12] := x[12] xor ((y shl 07) or (y shr (32-07))); y := x[ 1] + x[ 0]; x[ 2] := x[ 2] xor ((y shl 09) or (y shr (32-09))); y := x[ 6] + x[ 5]; x[ 7] := x[ 7] xor ((y shl 09) or (y shr (32-09))); y := x[11] + x[10]; x[ 8] := x[ 8] xor ((y shl 09) or (y shr (32-09))); y := x[12] + x[15]; x[13] := x[13] xor ((y shl 09) or (y shr (32-09))); y := x[ 2] + x[ 1]; x[ 3] := x[ 3] xor ((y shl 13) or (y shr (32-13))); y := x[ 7] + x[ 6]; x[ 4] := x[ 4] xor ((y shl 13) or (y shr (32-13))); y := x[ 8] + x[11]; x[ 9] := x[ 9] xor ((y shl 13) or (y shr (32-13))); y := x[13] + x[12]; x[14] := x[14] xor ((y shl 13) or (y shr (32-13))); y := x[ 3] + x[ 2]; x[ 0] := x[ 0] xor ((y shl 18) or (y shr (32-18))); y := x[ 4] + x[ 7]; x[ 5] := x[ 5] xor ((y shl 18) or (y shr (32-18))); y := x[ 9] + x[ 8]; x[10] := x[10] xor ((y shl 18) or (y shr (32-18))); y := x[14] + x[13]; x[15] := x[15] xor ((y shl 18) or (y shr (32-18))); end; {$endif} if finaladd then begin for i:=0 to 15 do TSalsaBlk(output)[i] := x[i] + input[i] end else TSalsaBlk(output) := x; end; {$else} {$ifdef BIT32} {---------------------------------------------------------------------------} procedure salsa20_wordtobyte(var output: T64B; const input: TSalsaBlk; rounds: word; finaladd: boolean); {-This is the Salsa20 "hash" function} var i: integer; x: TSalsaBlk; begin x := input; asm push ebx push esi push edi movzx edi,[rounds] shr edi,1 {round4(x[ 4], x[ 8], x[12], x[ 0]);} @@1: mov eax,dword ptr x[ 4*4] mov ebx,dword ptr x[ 8*4] mov ecx,dword ptr x[12*4] mov edx,dword ptr x[ 0*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[ 4*4],eax mov dword ptr x[ 8*4],ebx mov dword ptr x[12*4],ecx mov dword ptr x[ 0*4],edx {round4(x[ 9], x[13], x[ 1], x[ 5]);} mov eax,dword ptr x[ 9*4] mov ebx,dword ptr x[13*4] mov ecx,dword ptr x[ 1*4] mov edx,dword ptr x[ 5*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[ 9*4],eax mov dword ptr x[13*4],ebx mov dword ptr x[ 1*4],ecx mov dword ptr x[ 5*4],edx {round4(x[14], x[ 2], x[ 6], x[10]);} mov eax,dword ptr x[14*4] mov ebx,dword ptr x[ 2*4] mov ecx,dword ptr x[ 6*4] mov edx,dword ptr x[10*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[14*4],eax mov dword ptr x[ 2*4],ebx mov dword ptr x[ 6*4],ecx mov dword ptr x[10*4],edx {round4(x[ 3], x[ 7], x[11], x[15]);} mov eax,dword ptr x[ 3*4] mov ebx,dword ptr x[ 7*4] mov ecx,dword ptr x[11*4] mov edx,dword ptr x[15*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[ 3*4],eax mov dword ptr x[ 7*4],ebx mov dword ptr x[11*4],ecx mov dword ptr x[15*4],edx {round4(x[ 1], x[ 2], x[ 3], x[ 0]);} mov eax,dword ptr x[ 1*4] mov ebx,dword ptr x[ 2*4] mov ecx,dword ptr x[ 3*4] mov edx,dword ptr x[ 0*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[ 1*4],eax mov dword ptr x[ 2*4],ebx mov dword ptr x[ 3*4],ecx mov dword ptr x[ 0*4],edx {round4(x[ 6], x[ 7], x[ 4], x[ 5]);} mov eax,dword ptr x[ 6*4] mov ebx,dword ptr x[ 7*4] mov ecx,dword ptr x[ 4*4] mov edx,dword ptr x[ 5*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[ 6*4],eax mov dword ptr x[ 7*4],ebx mov dword ptr x[ 4*4],ecx mov dword ptr x[ 5*4],edx {round4(x[11], x[ 8], x[ 9], x[10]);} mov eax,dword ptr x[11*4] mov ebx,dword ptr x[ 8*4] mov ecx,dword ptr x[ 9*4] mov edx,dword ptr x[10*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[11*4],eax mov dword ptr x[ 8*4],ebx mov dword ptr x[ 9*4],ecx mov dword ptr x[10*4],edx {round4(x[12], x[13], x[14], x[15]);} mov eax,dword ptr x[12*4] mov ebx,dword ptr x[13*4] mov ecx,dword ptr x[14*4] mov edx,dword ptr x[15*4] mov esi,edx add esi,ecx rol esi,7 xor eax,esi mov esi,eax add esi,edx rol esi,9 xor ebx,esi mov esi,ebx add esi,eax rol esi,13 xor ecx,esi mov esi,ecx add esi,ebx rol esi,18 xor edx,esi mov dword ptr x[12*4],eax mov dword ptr x[13*4],ebx mov dword ptr x[14*4],ecx mov dword ptr x[15*4],edx dec edi jnz @@1 pop edi pop esi pop ebx end; if finaladd then begin for i:=0 to 15 do TSalsaBlk(output)[i] := x[i] + input[i] end else TSalsaBlk(output) := x; end; {$else} {$ifdef BASM16} {---------------------------------------------------------------------------} procedure salsa20_wordtobyte(var output: T64B; {$ifdef CONST} const {$else} var {$endif} input: TSalsaBlk; rounds: word; finaladd: boolean); {-This is the Salsa20 "hash" function} var x: TSalsaBlk; begin {Remark; x should be dword align for optimized 32 bit access} {$ifdef Debug} if ofs(x) and 3 <>0 then begin writeln('ofs(x) and 3 <>0'); halt; end; {$endif} asm push ds {x := input;} mov ax,ss mov es,ax cld lds si,[input] lea di,[x] mov cx,salsa_blocklength shr 1 rep movsw mov di,[rounds] shr di,1 @@1: db $66; mov ax,word ptr x[ 4*4] db $66; mov bx,word ptr x[ 8*4] db $66; mov cx,word ptr x[12*4] db $66; mov dx,word ptr x[ 0*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[ 4*4],ax db $66; mov word ptr x[ 8*4],bx db $66; mov word ptr x[12*4],cx db $66; mov word ptr x[ 0*4],dx {round4(x[ 9], x[13], x[ 1], x[ 5]);} db $66; mov ax,word ptr x[ 9*4] db $66; mov bx,word ptr x[13*4] db $66; mov cx,word ptr x[ 1*4] db $66; mov dx,word ptr x[ 5*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[ 9*4],ax db $66; mov word ptr x[13*4],bx db $66; mov word ptr x[ 1*4],cx db $66; mov word ptr x[ 5*4],dx {round4(x[14], x[ 2], x[ 6], x[10]);} db $66; mov ax,word ptr x[14*4] db $66; mov bx,word ptr x[ 2*4] db $66; mov cx,word ptr x[ 6*4] db $66; mov dx,word ptr x[10*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[14*4],ax db $66; mov word ptr x[ 2*4],bx db $66; mov word ptr x[ 6*4],cx db $66; mov word ptr x[10*4],dx {round4(x[ 3], x[ 7], x[11], x[15]);} db $66; mov ax,word ptr x[ 3*4] db $66; mov bx,word ptr x[ 7*4] db $66; mov cx,word ptr x[11*4] db $66; mov dx,word ptr x[15*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[ 3*4],ax db $66; mov word ptr x[ 7*4],bx db $66; mov word ptr x[11*4],cx db $66; mov word ptr x[15*4],dx {round4(x[ 1], x[ 2], x[ 3], x[ 0]);} db $66; mov ax,word ptr x[ 1*4] db $66; mov bx,word ptr x[ 2*4] db $66; mov cx,word ptr x[ 3*4] db $66; mov dx,word ptr x[ 0*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[ 1*4],ax db $66; mov word ptr x[ 2*4],bx db $66; mov word ptr x[ 3*4],cx db $66; mov word ptr x[ 0*4],dx {round4(x[ 6], x[ 7], x[ 4], x[ 5]);} db $66; mov ax,word ptr x[ 6*4] db $66; mov bx,word ptr x[ 7*4] db $66; mov cx,word ptr x[ 4*4] db $66; mov dx,word ptr x[ 5*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[ 6*4],ax db $66; mov word ptr x[ 7*4],bx db $66; mov word ptr x[ 4*4],cx db $66; mov word ptr x[ 5*4],dx {round4(x[11], x[ 8], x[ 9], x[10]);} db $66; mov ax,word ptr x[11*4] db $66; mov bx,word ptr x[ 8*4] db $66; mov cx,word ptr x[ 9*4] db $66; mov dx,word ptr x[10*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[11*4],ax db $66; mov word ptr x[ 8*4],bx db $66; mov word ptr x[ 9*4],cx db $66; mov word ptr x[10*4],dx {round4(x[12], x[13], x[14], x[15]);} db $66; mov ax,word ptr x[12*4] db $66; mov bx,word ptr x[13*4] db $66; mov cx,word ptr x[14*4] db $66; mov dx,word ptr x[15*4] db $66; mov si,dx db $66; add si,cx db $66; rol si,7 db $66; xor ax,si db $66; mov si,ax db $66; add si,dx db $66; rol si,9 db $66; xor bx,si db $66; mov si,bx db $66; add si,ax db $66; rol si,13 db $66; xor cx,si db $66; mov si,cx db $66; add si,bx db $66; rol si,18 db $66; xor dx,si db $66; mov word ptr x[12*4],ax db $66; mov word ptr x[13*4],bx db $66; mov word ptr x[14*4],cx db $66; mov word ptr x[15*4],dx dec di jnz @@1 les di,[output] mov al,[finaladd] or al,al jnz @@2 {No adding, move x to output} mov ax,ss mov ds,ax lea si,[x] cld mov cx,salsa_blocklength shr 1 rep movsw jmp @@3 @@2: lds si,[input] db $66; mov ax,[si] db $66; add ax,word ptr [x] db $66; mov es:[di],ax db $66; mov ax,[si+4] db $66; add ax,word ptr [x+4] db $66; mov es:[di+4],ax db $66; mov ax,[si+8] db $66; add ax,word ptr [x+8] db $66; mov es:[di+8],ax db $66; mov ax,[si+12] db $66; add ax,word ptr [x+12] db $66; mov es:[di+12],ax db $66; mov ax,[si+16] db $66; add ax,word ptr [x+16] db $66; mov es:[di+16],ax db $66; mov ax,[si+20] db $66; add ax,word ptr [x+20] db $66; mov es:[di+20],ax db $66; mov ax,[si+24] db $66; add ax,word ptr [x+24] db $66; mov es:[di+24],ax db $66; mov ax,[si+28] db $66; add ax,word ptr [x+28] db $66; mov es:[di+28],ax db $66; mov ax,[si+32] db $66; add ax,word ptr [x+32] db $66; mov es:[di+32],ax db $66; mov ax,[si+36] db $66; add ax,word ptr [x+36] db $66; mov es:[di+36],ax db $66; mov ax,[si+40] db $66; add ax,word ptr [x+40] db $66; mov es:[di+40],ax db $66; mov ax,[si+44] db $66; add ax,word ptr [x+44] db $66; mov es:[di+44],ax db $66; mov ax,[si+48] db $66; add ax,word ptr [x+48] db $66; mov es:[di+48],ax db $66; mov ax,[si+52] db $66; add ax,word ptr [x+52] db $66; mov es:[di+52],ax db $66; mov ax,[si+56] db $66; add ax,word ptr [x+56] db $66; mov es:[di+56],ax db $66; mov ax,[si+60] db $66; add ax,word ptr [x+60] db $66; mov es:[di+60],ax @@3: pop ds end; end; {$else} {---------------------------------------------------------------------------} procedure round4(var x1,x2,x3,x4: longint); {-quarter round function} begin x1 := x1 xor RotL(x4 + x3, 7); x2 := x2 xor RotL(x1 + x4, 9); x3 := x3 xor RotL(x2 + x1, 13); x4 := x4 xor RotL(x3 + x2, 18); end; {---------------------------------------------------------------------------} procedure salsa20_wordtobyte(var output: T64B; {$ifdef CONST} const {$else} var {$endif} input: TSalsaBlk; rounds: word; finaladd: boolean); var i: integer; x: TSalsaBlk; begin x := input; for i:=1 to (rounds shr 1) do begin round4(x[ 4], x[ 8], x[12], x[ 0]); round4(x[ 9], x[13], x[ 1], x[ 5]); round4(x[14], x[ 2], x[ 6], x[10]); round4(x[ 3], x[ 7], x[11], x[15]); round4(x[ 1], x[ 2], x[ 3], x[ 0]); round4(x[ 6], x[ 7], x[ 4], x[ 5]); round4(x[11], x[ 8], x[ 9], x[10]); round4(x[12], x[13], x[14], x[15]); end; if finaladd then begin for i:=0 to 15 do TSalsaBlk(output)[i] := x[i] + input[i] end else TSalsaBlk(output) := x; end; {$endif BASM16} {$endif BIT32} {$endif Purepascal} {---------------------------------------------------------------------------} procedure salsa_encrypt_bytes(var ctx: salsa_ctx; ptp, ctp: pointer; msglen: longint); {-Bytewise encryption, msglen: message length in bytes} var i: integer; output: T64B; im: integer; begin {$ifdef BASM16} {Make x in salsa20_wordtobyte dword aligned for optimized 32 bit access} if (sptr and 3)=2 then asm push ax end; {$endif} while msglen>0 do begin salsa20_wordtobyte(output,ctx.input,ctx.rounds,true); {stopping at 2^70 bytes per nonce is user's responsibility} inc(ctx.input[8]); if ctx.input[8]=0 then inc(ctx.input[9]); if msglen<64 then im := integer(msglen) else im:=64; {$ifdef BASM16} {This was bottleneck in former versions, using stack addressing} {via ss:[bx] the encryption speed more than doubled in V0.28+.} {Note that the 32 byte access may be unaligned and the latency } {will be increased, but AFAIK even then the code will be faster} {than a pure 8 bit access version. In the unlikely event that } {the unaligned 32 bit access is too slow, remove the lines of } {code from 'shr cx,2' ... 'jz @@4'.} asm push ds lds si,[ptp] les di,[ctp] lea bx,[output] mov cx,[im] shr cx,2 jz @@2 @@1: db $66; mov ax,ss:[bx] db $66; xor ax,[si] db $66; mov es:[di],ax add si,4 add di,4 add bx,4 dec cx jnz @@1 @@2: mov cx,[im] and cx,3 jz @@4 @@3: mov al,ss:[bx] xor al,[si] mov es:[di],al inc si inc di inc bx dec cx jnz @@3 @@4: mov word ptr [ptp],si mov word ptr [ctp],di pop ds end; {$else} {$ifdef FPC} for i:=0 to pred(im) do begin pByte(ctp)^ := byte(ptp^) xor output[i]; inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); end; {$else} for i:=0 to pred(im) do P64B(ctp)^[i] := P64B(ptp)^[i] xor output[i]; inc(Ptr2Inc(ptp),im); inc(Ptr2Inc(ctp),im); {$endif} {$endif} dec(msglen,64); end; end; {---------------------------------------------------------------------------} procedure salsa_decrypt_bytes(var ctx: salsa_ctx; ctp, ptp: pointer; msglen: longint); {-Bytewise decryption, msglen: message length in bytes} begin salsa_encrypt_bytes(ctx, ctp, ptp, msglen); end; {---------------------------------------------------------------------------} procedure salsa_encrypt_blocks(var ctx: salsa_ctx; ptp, ctp: pointer; blocks: word); {-Blockwise encryption, blocks: length in 64 byte blocks} begin salsa_encrypt_bytes(ctx, ptp, ctp, longint(Blocks)*salsa_blocklength); end; {---------------------------------------------------------------------------} procedure salsa_decrypt_blocks(var ctx: salsa_ctx; ctp, ptp: pointer; blocks: word); {-Blockwise decryption, blocks: length in 64 byte blocks} begin salsa_encrypt_bytes(ctx, ctp, ptp, longint(Blocks)*salsa_blocklength); end; {---------------------------------------------------------------------------} procedure salsa_encrypt_packet(var ctx: salsa_ctx; IV, ptp, ctp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} begin salsa_ivsetup(ctx, iv); salsa_encrypt_bytes(ctx, ptp, ctp, msglen); end; {---------------------------------------------------------------------------} procedure salsa_decrypt_packet(var ctx: salsa_ctx; IV, ctp, ptp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} begin salsa_ivsetup(ctx, iv); salsa_decrypt_bytes(ctx, ctp, ptp, msglen); end; {---------------------------------------------------------------------------} procedure salsa_keystream_bytes(var ctx: salsa_ctx; keystream: pointer; kslen: longint); {-Generate keystream, kslen: keystream length in bytes} var output: T64B; begin {$ifdef BASM16} {Make x in salsa20_wordtobyte dword aligned for optimized 32 bit access} if (sptr and 3)=2 then asm push ax end; {$endif} {directly put salsa hash into keystream buffer as long as length is > 63} while kslen>63 do begin salsa20_wordtobyte(P64B(keystream)^,ctx.input,ctx.rounds,true); {stopping at 2^70 bytes per nonce is user's responsibility} inc(ctx.input[8]); if ctx.input[8]=0 then inc(ctx.input[9]); inc(Ptr2Inc(keystream),64); dec(kslen,64); end; if kslen>0 then begin {here 0 < kslen < 64} salsa20_wordtobyte(output,ctx.input,ctx.rounds,true); {stopping at 2^70 bytes per nonce is user's responsibility} inc(ctx.input[8]); if ctx.input[8]=0 then inc(ctx.input[9]); move(output,keystream^,integer(kslen)); end; end; {---------------------------------------------------------------------------} procedure salsa_keystream_blocks(var ctx: salsa_ctx; keystream: pointer; blocks: word); {-Generate keystream, blocks: keystream length in 64 byte blocks} begin salsa_keystream_bytes(ctx, keystream, longint(Blocks)*salsa_blocklength); end; {---------------------------------------------------------------------------} function salsa_selftest: boolean; {-Simple self-test of Salsa20, tests 128/256 key bits and 8/12/20 rounds} var i,idx,n,b,r: integer; key, iv: array[0..31] of byte; dig: array[0..15] of longint; buf: array[0..127] of longint; ctx: salsa_ctx; const nround: array[0..2] of word = (8,12,20); kbits : array[0..1] of word = (128,256); {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9 errors!} {$endif} XDT: array[0..5] of TSalsaBlk = (($52974958,$7b5774d1,$574b3efd,$0a6e5762, {128_08} $14539c7d,$e2c520f3,$35c2cc5f,$482df540, $8ab98d4e,$1b4a74c2,$14578a78,$f7e8ba22, $a45978e5,$797443c4,$d988097f,$73dca011), ($2bfeb421,$1d24ef96,$ce8a0c54,$e84956b1, {128_12} $42f8141f,$f7e56da8,$4811db9e,$ade63f0f, $558e7f81,$f7cdbe9a,$1e17fe34,$7cd2a9ae, $551937bb,$5522f4bf,$4976e50a,$9e564bd4), ($d274a2f7,$90673168,$58c07ea6,$2a0f5cf4, {128_20} $fc997a06,$c03662de,$56e0f8ce,$4ce59f34, $74ac135f,$709553d2,$abfe34fd,$0572c506, $95b54939,$81217485,$2260a7a5,$d422fa3a), ($b6e5d149,$cb0a12af,$da7cdac4,$90dfa5f3, {256_08} $d660fc0f,$ae58af71,$eb139fef,$5527182c, $aa05c1c7,$f3bb8639,$704dbef9,$e5a090a1, $0cd420c2,$0875361a,$e93097f7,$628c4700), ($60891461,$2e4546b8,$69cdd8b2,$1fce0aa8, {256_12} $7f9673f3,$16a55bfe,$675b75f6,$b8089b66, $8dc136c0,$57a119a1,$05150d9c,$7210ccc4, $58b0119f,$8f0dd8af,$b1f46d26,$4ddf77f7), ($8524ec50,$9cb17d63,$9c5e796e,$80829373, {256_20} $20b36d6f,$44043dfe,$d70767d5,$7f4556b4, $d7e8b33d,$75f35a06,$09a725a2,$74abc851, $95d5c44e,$f02552e8,$3fc02b8e,$6725c4e1)); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} begin salsa_selftest := false; for b:=0 to 1 do begin {Loop over key bits (b=0: 128 bits, b=1: 256 bits)} for r := 0 to 2 do begin if b=1 then idx := r+3 else idx := r; {Use test data from Set 1, vector# 0} fillchar(key,sizeof(key),0); key[0]:=$80; fillchar(IV, sizeof(IV) ,0); {Do 3 passes with different procedures} for n:=1 to 3 do begin fillchar(buf,sizeof(buf),0); fillchar(dig, sizeof(dig), 0); salsa_xkeysetup(ctx, @key,kbits[b] , nround[r]); case n of 1: begin {test keystream blocks/bytes} salsa_ivsetup(ctx, @iv); salsa_keystream_blocks(ctx, @buf, 4); salsa_keystream_bytes (ctx, @buf[64], 256); end; 2: begin {test encrypt blocks/bytes} salsa_ivsetup(ctx, @iv); salsa_encrypt_blocks(ctx, @buf, @buf, 4); salsa_encrypt_bytes (ctx, @buf[64], @buf[64],256); end; 3: begin {test packet interface} salsa_encrypt_packet(ctx, @iv, @buf, @buf, 512); end; end; {calculate xor digest} for i:=0 to 127 do dig[i and 15] := dig[i and 15] xor buf[i]; {compare with known answer, exit with false if any differences} for i:=0 to 15 do begin if dig[i]<>XDT[idx][i] then exit; end; end; end; end; salsa_selftest := true; end; {---------------------------------------------------------------------------} {---------------------- XSalsa20 functions -------------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} procedure xsalsa_encrypt_bytes(var ctx: salsa_ctx; ptp, ctp: pointer; msglen: longint); {-Bytewise encryption, msglen: message length in bytes} begin salsa_encrypt_bytes(ctx, ptp, ctp, msglen); end; {---------------------------------------------------------------------------} procedure xsalsa_decrypt_bytes(var ctx: salsa_ctx; ctp, ptp: pointer; msglen: longint); {-Bytewise decryption, msglen: message length in bytes} begin salsa_encrypt_bytes(ctx, ctp, ptp, msglen); end; {---------------------------------------------------------------------------} function xsalsa_selftest: boolean; {-Simple self-test of xSalsa20} const {From [5] p.39, Section "Testing: secretbox vs. onetimeauth"} key: array[0..31] of byte = ($1b,$27,$55,$64,$73,$e9,$85,$d4, $62,$cd,$51,$19,$7a,$9a,$46,$c7, $60,$09,$54,$9e,$ac,$64,$74,$f2, $06,$c4,$ee,$08,$44,$f6,$83,$89); nonce: array[0..23] of byte = ($69,$69,$6e,$e9,$55,$b6,$2b,$73, $cd,$62,$bd,$a8,$75,$fc,$73,$d6, $82,$19,$e0,$03,$6b,$7a,$0b,$37); test: array[0..31] of byte = ($ee,$a6,$a7,$25,$1c,$1e,$72,$91, $6d,$11,$c2,$cb,$21,$4d,$3c,$25, $25,$39,$12,$1d,$8e,$23,$4e,$65, $2d,$65,$1f,$a4,$c8,$cf,$f8,$80); var tmp: array[0..31] of byte; i,j,len: integer; begin xsalsa_selftest := false; for j:=0 to 1 do begin len := sizeof(test); if j=1 then dec(len,5); fillchar(tmp,sizeof(tmp),0); xsalsa_encrypt_packet(@key, @nonce, @tmp, @tmp, len); for i:=0 to pred(len) do begin if tmp[i]<>test[i] then exit; end; for i:=len to pred(sizeof(tmp)) do begin if tmp[i]<>0 then exit; end; end; xsalsa_selftest := true; end; {---------------------------------------------------------------------------} procedure HSalsa(k256, n128: pointer; r: word; var res: T32B); {-Transform 256 key bits and 128 nonce bits into 256 res bits} { using r salsa rounds without final addition} var input: TSalsaBlk; begin input[1] := P8L(k256)^[0]; input[2] := P8L(k256)^[1]; input[3] := P8L(k256)^[2]; input[4] := P8L(k256)^[3]; input[11] := P8L(k256)^[4]; input[12] := P8L(k256)^[5]; input[13] := P8L(k256)^[6]; input[14] := P8L(k256)^[7]; input[0] := T4L(sigma)[0]; input[5] := T4L(sigma)[1]; input[10] := T4L(sigma)[2]; input[15] := T4L(sigma)[3]; input[6] := P4L(n128)^[0]; input[7] := P4L(n128)^[1]; input[8] := P4L(n128)^[2]; input[9] := P4L(n128)^[3]; {$ifdef BASM16} {Make x in salsa20_wordtobyte dword aligned for optimized 32 bit access} if (sptr and 3)=2 then asm push ax end; {$endif} salsa20_wordtobyte(T64b(input),input,r,false); T8L(res)[0] := input[ 0]; T8L(res)[1] := input[ 5]; T8L(res)[2] := input[10]; T8L(res)[3] := input[15]; T8L(res)[4] := input[ 6]; T8L(res)[5] := input[ 7]; T8L(res)[6] := input[ 8]; T8L(res)[7] := input[ 9]; end; {---------------------------------------------------------------------------} procedure xsalsa_setup(var ctx: salsa_ctx; key, IV: pointer); {-Key/IV setup, 256 bits of key^ and 192 bits of IV^ are used. It is the} { user's responsibility that the required bits are accessible! Rounds=20} var key2: T32B; begin {HSalsa transforms the key, the sigma constant, and the first 128 bits} {of the IV/nonce into a secondary key key2. Key2 and the last 64 bits} {of the IV are used for a standard salsa20 key/IV setup with 20 rounds} HSalsa(key, IV, 20, key2); salsa_xkeysetup(ctx,@key2,256,20); salsa_ivsetup(ctx,@P8L(IV)^[4]); end; {---------------------------------------------------------------------------} procedure xsalsa_encrypt_packet(key, IV, ptp, ctp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 192 accessible IV bits.} var ctx: salsa_ctx; begin xsalsa_setup(ctx, key, iv); salsa_encrypt_bytes(ctx, ptp, ctp, msglen); fillchar(ctx,sizeof(ctx),0); end; {---------------------------------------------------------------------------} procedure xsalsa_decrypt_packet(key, IV, ctp, ptp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 192 accessible IV bits.} var ctx: salsa_ctx; begin xsalsa_setup(ctx, key, iv); salsa_decrypt_bytes(ctx, ctp, ptp, msglen); fillchar(ctx,sizeof(ctx),0); end; {---------------------------------------------------------------------------} {------------------------ ChaCha functions -------------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} procedure chacha_xkeysetup(var ctx: salsa_ctx; key: pointer; keybits, rounds: word); {-Key setup, 128 bits of key^ are used if keybits<>256.. It is the user's } { responsibility to supply a pointer to at least 128 (resp 256) accessible} { key bits. Rounds should be even > 0 (will be forced)} begin if rounds=0 then rounds := 2 else if odd(rounds) then inc(rounds); ctx.rounds := rounds; with ctx do begin input[4] := P8L(key)^[0]; input[5] := P8L(key)^[1]; input[6] := P8L(key)^[2]; input[7] := P8L(key)^[3]; if keybits=256 then begin input[8] := P8L(key)^[4]; input[9] := P8L(key)^[5]; input[10] := P8L(key)^[6]; input[11] := P8L(key)^[7]; input[0] := T4L(sigma)[0]; input[1] := T4L(sigma)[1]; input[2] := T4L(sigma)[2]; input[3] := T4L(sigma)[3]; kbits := 256; end else begin input[8] := input[4]; input[9] := input[5]; input[10] := input[6]; input[11] := input[7]; input[0] := T4L(tau)[0]; input[1] := T4L(tau)[1]; input[2] := T4L(tau)[2]; input[3] := T4L(tau)[3]; kbits := 128; end; end; end; {---------------------------------------------------------------------------} procedure chacha_keysetup(var ctx: salsa_ctx; key: pointer); {-Key setup, 128 bits of key^ are used, default rounds=12. It is the user's} { responsibility to supply a pointer to at least 128 accessible key bits!} begin chacha_xkeysetup(ctx, key, 128, 12); end; {---------------------------------------------------------------------------} procedure chacha_keysetup256(var ctx: salsa_ctx; key: pointer); {-Key setup, 256 bits of key^ are used, default rounds=20 It is the user's} { responsibility to supply a pointer to at least 256 accessible key bits!} begin chacha_xkeysetup(ctx, key, 256, 20); end; {---------------------------------------------------------------------------} procedure chacha_ivsetup(var ctx: salsa_ctx; IV: pointer); {-IV setup, 64 bits of IV^ are used. It is the user's responsibility to } { supply least 64 accessible IV bits. After having called chacha_keysetup,} { the user is allowed to call chacha_ivsetup different times in order to } { encrypt/decrypt different messages with the same key but different IV's} begin with ctx do begin input[12] := 0; input[13] := 0; input[14] := P4L(IV)^[0]; input[15] := P4L(IV)^[1]; end; end; {$ifdef ChaChaBasm32} {---------------------------------------------------------------------------} procedure chacha_wordtobyte(var output: T64B; const input: TSalsaBlk; rounds: word; finaladd: boolean); var i: integer; x: TSalsaBlk; begin {Contributed by EddyHawk, Apr. 30, 2012} {WE June 2012: removed odd(rounds(} x := input; asm push ebx push edi movzx edi,[rounds] shr edi,1 {round4(x[ 0], x[ 4], x[ 8], x[12]);} @@1: mov eax,dword ptr x[ 0*4] mov ebx,dword ptr x[ 4*4] mov ecx,dword ptr x[ 8*4] mov edx,dword ptr x[12*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 0*4],eax mov dword ptr x[ 4*4],ebx mov dword ptr x[ 8*4],ecx mov dword ptr x[12*4],edx {round4(x[ 1], x[ 5], x[ 9], x[13]);} mov eax,dword ptr x[ 1*4] mov ebx,dword ptr x[ 5*4] mov ecx,dword ptr x[ 9*4] mov edx,dword ptr x[13*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 1*4],eax mov dword ptr x[ 5*4],ebx mov dword ptr x[ 9*4],ecx mov dword ptr x[13*4],edx {round4(x[ 2], x[ 6], x[10], x[14]);} mov eax,dword ptr x[ 2*4] mov ebx,dword ptr x[ 6*4] mov ecx,dword ptr x[10*4] mov edx,dword ptr x[14*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 2*4],eax mov dword ptr x[ 6*4],ebx mov dword ptr x[10*4],ecx mov dword ptr x[14*4],edx {round4(x[ 3], x[ 7], x[11], x[15]);} mov eax,dword ptr x[ 3*4] mov ebx,dword ptr x[ 7*4] mov ecx,dword ptr x[11*4] mov edx,dword ptr x[15*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 3*4],eax mov dword ptr x[ 7*4],ebx mov dword ptr x[11*4],ecx mov dword ptr x[15*4],edx {round4(x[ 0], x[ 5], x[10], x[15]);} mov eax,dword ptr x[ 0*4] mov ebx,dword ptr x[ 5*4] mov ecx,dword ptr x[10*4] mov edx,dword ptr x[15*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 0*4],eax mov dword ptr x[ 5*4],ebx mov dword ptr x[10*4],ecx mov dword ptr x[15*4],edx {round4(x[ 1], x[ 6], x[11], x[12]);} mov eax,dword ptr x[ 1*4] mov ebx,dword ptr x[ 6*4] mov ecx,dword ptr x[11*4] mov edx,dword ptr x[12*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 1*4],eax mov dword ptr x[ 6*4],ebx mov dword ptr x[11*4],ecx mov dword ptr x[12*4],edx {round4(x[ 2], x[ 7], x[ 8], x[13]);} mov eax,dword ptr x[ 2*4] mov ebx,dword ptr x[ 7*4] mov ecx,dword ptr x[ 8*4] mov edx,dword ptr x[13*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 2*4],eax mov dword ptr x[ 7*4],ebx mov dword ptr x[ 8*4],ecx mov dword ptr x[13*4],edx {round4(x[ 3], x[ 4], x[ 9], x[14]);} mov eax,dword ptr x[ 3*4] mov ebx,dword ptr x[ 4*4] mov ecx,dword ptr x[ 9*4] mov edx,dword ptr x[14*4] add eax,ebx xor edx,eax rol edx,16 add ecx,edx xor ebx,ecx rol ebx,12 add eax,ebx xor edx,eax rol edx,8 add ecx,edx xor ebx,ecx rol ebx,7 mov dword ptr x[ 3*4],eax mov dword ptr x[ 4*4],ebx mov dword ptr x[ 9*4],ecx mov dword ptr x[14*4],edx dec edi jnz @@1 pop edi pop ebx end; if finaladd then begin for i:=0 to 15 do TSalsaBlk(output)[i] := x[i] + input[i]; end else TSalsaBlk(output) := x; end; {$else} {$ifdef BIT16} {---------------------------------------------------------------------------} procedure chacha_wordtobyte(var output: T64B; {$ifdef CONST} const {$else} var {$endif} input: TSalsaBlk; rounds: word; finaladd: boolean); {-This is the ChaCha "hash" function} var i: integer; x: TSalsaBlk; begin x := input; for i:=1 to (rounds shr 1) do begin x[ 0] := x[ 0]+x[ 4]; x[12] := RotL(x[12] xor x[ 0], 16); x[ 8] := x[ 8]+x[12]; x[ 4] := RotL(x[ 4] xor x[ 8], 12); x[ 0] := x[ 0]+x[ 4]; x[12] := RotL(x[12] xor x[ 0], 8); x[ 8] := x[ 8]+x[12]; x[ 4] := RotL(x[ 4] xor x[ 8], 7); x[ 1] := x[ 1]+x[ 5]; x[13] := RotL(x[13] xor x[ 1], 16); x[ 9] := x[ 9]+x[13]; x[ 5] := RotL(x[ 5] xor x[ 9], 12); x[ 1] := x[ 1]+x[ 5]; x[13] := RotL(x[13] xor x[ 1], 8); x[ 9] := x[ 9]+x[13]; x[ 5] := RotL(x[ 5] xor x[ 9], 7); x[ 2] := x[ 2]+x[ 6]; x[14] := RotL(x[14] xor x[ 2], 16); x[10] := x[10]+x[14]; x[ 6] := RotL(x[ 6] xor x[10], 12); x[ 2] := x[ 2]+x[ 6]; x[14] := RotL(x[14] xor x[ 2], 8); x[10] := x[10]+x[14]; x[ 6] := RotL(x[ 6] xor x[10], 7); x[ 3] := x[ 3]+x[ 7]; x[15] := RotL(x[15] xor x[ 3], 16); x[11] := x[11]+x[15]; x[ 7] := RotL(x[ 7] xor x[11], 12); x[ 3] := x[ 3]+x[ 7]; x[15] := RotL(x[15] xor x[ 3], 8); x[11] := x[11]+x[15]; x[ 7] := RotL(x[ 7] xor x[11], 7); x[ 0] := x[ 0]+x[ 5]; x[15] := RotL(x[15] xor x[ 0], 16); x[10] := x[10]+x[15]; x[ 5] := RotL(x[ 5] xor x[10], 12); x[ 0] := x[ 0]+x[ 5]; x[15] := RotL(x[15] xor x[ 0], 8); x[10] := x[10]+x[15]; x[ 5] := RotL(x[ 5] xor x[10], 7); x[ 1] := x[ 1]+x[ 6]; x[12] := RotL(x[12] xor x[ 1], 16); x[11] := x[11]+x[12]; x[ 6] := RotL(x[ 6] xor x[11], 12); x[ 1] := x[ 1]+x[ 6]; x[12] := RotL(x[12] xor x[ 1], 8); x[11] := x[11]+x[12]; x[ 6] := RotL(x[ 6] xor x[11], 7); x[ 2] := x[ 2]+x[ 7]; x[13] := RotL(x[13] xor x[ 2], 16); x[ 8] := x[ 8]+x[13]; x[ 7] := RotL(x[ 7] xor x[ 8], 12); x[ 2] := x[ 2]+x[ 7]; x[13] := RotL(x[13] xor x[ 2], 8); x[ 8] := x[ 8]+x[13]; x[ 7] := RotL(x[ 7] xor x[ 8], 7); x[ 3] := x[ 3]+x[ 4]; x[14] := RotL(x[14] xor x[ 3], 16); x[ 9] := x[ 9]+x[14]; x[ 4] := RotL(x[ 4] xor x[ 9], 12); x[ 3] := x[ 3]+x[ 4]; x[14] := RotL(x[14] xor x[ 3], 8); x[ 9] := x[ 9]+x[14]; x[ 4] := RotL(x[ 4] xor x[ 9], 7); end; if finaladd then begin for i:=0 to 15 do TSalsaBlk(output)[i] := x[i] + input[i]; end else TSalsaBlk(output) := x; end; {$else} {Improved PurePascal version contributed by Martok} {---------------------------------------------------------------------------} procedure chacha_wordtobyte(var output: T64B; const input: TSalsaBlk; rounds: word; finaladd: boolean); {-This is the ChaCha "hash" function} var i: integer; x: TSalsaBlk; a,b,c,d: longint; begin x := input; for i:= (rounds shr 1)-1 downto 0 do begin a := x[0]; b := x[4]; c := x[8]; d:= x[12]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[0] := a; x[4] := b; x[8] := c; x[12] := d; a := x[1]; b := x[5]; c := x[9]; d := x[13]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[1] := a; x[5] := b; x[9] := c; x[13] := d; a := x[2]; b := x[6]; c := x[10]; d := x[14]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[2] := a; x[6] := b; x[10] := c; x[14] := d; a := x[3]; b := x[7]; c := x[11]; d := x[15]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[3] := a; x[7] := b; x[11] := c; x[15] := d; a := x[0]; b := x[5]; c := x[10]; d := x[15]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[0] := a; x[5] := b; x[10] := c; x[15] := d; a := x[1]; b := x[6]; c := x[11]; d := x[12]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[1] := a; x[6] := b; x[11] := c; x[12] := d; a := x[2]; b := x[7]; c := x[8]; d := x[13]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[2] := a; x[7] := b; x[8] := c; x[13] := d; a := x[3]; b := x[4]; c := x[9]; d := x[14]; inc(a, b); d := a xor d; d := (d shl 16) or (d shr (32-16)); inc(c, d); b := c xor b; b := (b shl 12) or (b shr (32-12)); inc(a, b); d := a xor d; d := (d shl 8) or (d shr (32- 8)); inc(c, d); b := c xor b; b := (b shl 7) or (b shr (32- 7)); x[3] := a; x[4] := b; x[9] := c; x[14] := d; end; if finaladd then begin for i:=0 to 15 do TSalsaBlk(output)[i] := x[i] + input[i]; end else TSalsaBlk(output) := x; end; {$endif} {$endif} {---------------------------------------------------------------------------} procedure chacha_keystream_bytes(var ctx: salsa_ctx; keystream: pointer; kslen: longint); {-Generate keystream, kslen: keystream length in bytes} var output: T64B; begin {directly put ChaCha hash into keystream buffer as long as length is > 63} while kslen>63 do begin chacha_wordtobyte(P64B(keystream)^,ctx.input,ctx.rounds,true); {stopping at 2^70 bytes per nonce is user's responsibility} inc(ctx.input[12]); if ctx.input[12]=0 then inc(ctx.input[13]); inc(Ptr2Inc(keystream),64); dec(kslen,64); end; if kslen>0 then begin {here 0 < kslen < 64} chacha_wordtobyte(output,ctx.input,ctx.rounds,true); {stopping at 2^70 bytes per nonce is user's responsibility} inc(ctx.input[12]); if ctx.input[12]=0 then inc(ctx.input[13]); move(output,keystream^,integer(kslen)); end; end; {---------------------------------------------------------------------------} procedure chacha_keystream_blocks(var ctx: salsa_ctx; keystream: pointer; blocks: word); {-Generate keystream, blocks: keystream length in 64 byte blocks} begin chacha_keystream_bytes(ctx, keystream, longint(Blocks)*salsa_blocklength); end; {---------------------------------------------------------------------------} procedure chacha_encrypt_bytes(var ctx: salsa_ctx; ptp, ctp: pointer; msglen: longint); {-Bytewise encryption, msglen: message length in bytes} var i: integer; output: T64B; im: integer; begin while msglen>0 do begin chacha_wordtobyte(output,ctx.input,ctx.rounds,true); {stopping at 2^70 bytes per nonce is user's responsibility} inc(ctx.input[12]); if ctx.input[12]=0 then inc(ctx.input[13]); if msglen<64 then im := integer(msglen) else im:=64; {Same code as for salsa_encrypt_bytes} {$ifdef BASM16} asm push ds lds si,[ptp] les di,[ctp] lea bx,[output] mov cx,[im] shr cx,2 jz @@2 @@1: db $66; mov ax,ss:[bx] db $66; xor ax,[si] db $66; mov es:[di],ax add si,4 add di,4 add bx,4 dec cx jnz @@1 @@2: mov cx,[im] and cx,3 jz @@4 @@3: mov al,ss:[bx] xor al,[si] mov es:[di],al inc si inc di inc bx dec cx jnz @@3 @@4: mov word ptr [ptp],si mov word ptr [ctp],di pop ds end; {$else} {$ifdef FPC} for i:=0 to pred(im) do begin pByte(ctp)^ := byte(ptp^) xor output[i]; inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); end; {$else} for i:=0 to pred(im) do P64B(ctp)^[i] := P64B(ptp)^[i] xor output[i]; inc(Ptr2Inc(ptp),im); inc(Ptr2Inc(ctp),im); {$endif} {$endif} dec(msglen,64); end; end; {---------------------------------------------------------------------------} procedure chacha_decrypt_bytes(var ctx: salsa_ctx; ctp, ptp: pointer; msglen: longint); {-Bytewise decryption, msglen: message length in bytes} begin chacha_encrypt_bytes(ctx, ctp, ptp, msglen); end; {---------------------------------------------------------------------------} procedure chacha_encrypt_blocks(var ctx: salsa_ctx; ptp, ctp: pointer; blocks: word); {-Blockwise encryption, blocks: length in 64 byte blocks} begin chacha_encrypt_bytes(ctx, ptp, ctp, longint(Blocks)*salsa_blocklength); end; {---------------------------------------------------------------------------} procedure chacha_decrypt_blocks(var ctx: salsa_ctx; ctp, ptp: pointer; blocks: word); {-Blockwise decryption, blocks: length in 64 byte blocks} begin chacha_encrypt_bytes(ctx, ctp, ptp, longint(Blocks)*salsa_blocklength); end; {---------------------------------------------------------------------------} procedure chacha_encrypt_packet(var ctx: salsa_ctx; IV, ptp, ctp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} begin chacha_ivsetup(ctx, iv); chacha_encrypt_bytes(ctx, ptp, ctp, msglen); end; {---------------------------------------------------------------------------} procedure chacha_decrypt_packet(var ctx: salsa_ctx; IV, ctp, ptp: pointer; msglen: longint); {-All-in-one encryption of (short) packets, msglen: message length in bytes} { It is the user's responsibility to supply least 64 accessible IV bits.} begin chacha_ivsetup(ctx, iv); chacha_decrypt_bytes(ctx, ctp, ptp, msglen); end; {---------------------------------------------------------------------------} function chacha_selftest: boolean; {-Simple self-test of ChaCha, tests 128/256 key bits and 8/12/20 rounds} var i,idx,n,b,r: integer; key, iv: array[0..31] of byte; dig: array[0..15] of longint; buf: array[0..127] of longint; ctx: salsa_ctx; const nround: array[0..2] of word = (8,12,20); kbits : array[0..1] of word = (128,256); {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9 errors!} {$endif} {values are the xor digests of test vectors calculated from} {D.J. Bernstein's code using Pelles C compiler V4.50.113} XDT: array[0..5] of TSalsaBlk = (($ab144dd2,$6096ceb8,$8e5e1a45,$46982857, {128-8 } $db0b7c50,$4bd4e9ba,$9037934b,$d3679395, $3776fecd,$704a28e2,$da576cc0,$1991c0aa, $49700f6e,$bc637132,$8c1909d0,$1c050c47), ($14d18a20,$814fb9ad,$57ed7482,$d94ec55f, {128-12} $08d815c7,$20622bad,$380ac73f,$0fad38b4, $229b3120,$a153a4ef,$7a4480c3,$699fa2b9, $e4258ea5,$8fb60398,$bf190487,$77c9107c), ($ada52ec6,$c396a0b1,$4c862266,$d817eb3c, {128-20} $9defd2a9,$518ad675,$00d61cc6,$d0e439db, $9e49e47a,$82c5a29b,$28e79f10,$9c8db69a, $ea7d50fc,$7ab0f832,$0c27d877,$7a347541), ($39595f2c,$ec6bf171,$53bd4e78,$7a8593ec, {256-8 } $157867e0,$1c31e951,$a52410d9,$0030d51b, $6f038346,$a1661f02,$e3ec6649,$1260100a, $033d4ba4,$0e81a71c,$c2d788fb,$648e42bd), ($8a8c7024,$fb2d1693,$4febc96d,$6ebfaa6d, {256-12} $d2a1dfae,$078f704a,$616e7552,$cb747659, $862c2f43,$a35c51b5,$528c8489,$8900e0e5, $ee39abda,$738cd3a5,$0336faa4,$c7d28d39), ($96175f52,$fe56d50e,$ccf73266,$b941451e, {256-20} $ad167609,$3271e81d,$47ff7821,$3940215d, $69b56bd5,$1f16e0d8,$0c228e23,$39aca058, $29740ec4,$c1ff6f62,$1366c412,$d8f9471e)); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} begin chacha_selftest := false; for b:=0 to 1 do begin {Loop over key bits (b=0: 128 bits, b=1: 256 bits)} for r := 0 to 2 do begin if b=1 then idx := r+3 else idx := r; {Use test data from Set 1, vector# 0} fillchar(key,sizeof(key),0); key[0]:=$80; fillchar(IV, sizeof(IV) ,0); {Do 3 passes with different procedures} for n:=1 to 3 do begin fillchar(buf,sizeof(buf),0); fillchar(dig, sizeof(dig), 0); chacha_xkeysetup(ctx, @key,kbits[b] , nround[r]); case n of 1: begin {test keystream blocks/bytes} chacha_ivsetup(ctx, @iv); chacha_keystream_blocks(ctx, @buf, 4); chacha_keystream_bytes (ctx, @buf[64], 256); end; 2: begin {test encrypt blocks/bytes} chacha_ivsetup(ctx, @iv); chacha_encrypt_blocks(ctx, @buf, @buf, 4); chacha_encrypt_bytes (ctx, @buf[64], @buf[64],256); end; 3: begin {test packet interface} chacha_encrypt_packet(ctx, @iv, @buf, @buf, 512); end; end; {calculate xor digest} for i:=0 to 127 do dig[i and 15] := dig[i and 15] xor buf[i]; {compare with known answer, exit with false if any differences} for i:=0 to 15 do begin if dig[i]<>XDT[idx][i] then exit; end; end; end; end; chacha_selftest := true; end; end.
unit Mods; interface uses System.Classes; type TMods = class(TObject) private const Default = 'elvion'; private FSL: TStringList; FCurrent: string; function GetCurValue(const Name: string; DefValue: string): string; overload; function GetCurValue(const Name: string; DefValue: Integer): Integer; overload; public constructor Create; destructor Destroy; override; function GetPath(const SubDir, FileName: string): string; procedure SetCurrent(const FileName, MapFileName: string); overload; property Current: string read FCurrent; end; var GMods: TMods; implementation uses System.SysUtils, Utils, WorldMap, Dialogs, Mobs; { TMods } constructor TMods.Create; begin FSL := TStringList.Create; FCurrent := Default; end; destructor TMods.Destroy; begin FreeAndNil(FSL); inherited; end; function TMods.GetCurValue(const Name: string; DefValue: Integer): Integer; var I: Integer; begin I := FSL.IndexOfName(Name); Result := StrToIntDef(FSL.ValueFromIndex[I], DefValue); end; function TMods.GetCurValue(const Name: string; DefValue: string): string; var I: Integer; begin I := FSL.IndexOfName(Name); Result := FSL.ValueFromIndex[I]; end; function TMods.GetPath(const SubDir, FileName: string): string; begin Result := Utils.GetPath('mods' + PathDelim + Current + PathDelim + SubDir) + FileName; if not FileExists(Result) then Result := Utils.GetPath('mods' + PathDelim + Default +PathDelim + SubDir) + FileName; end; procedure TMods.SetCurrent(const FileName, MapFileName: string); begin FCurrent := FileName; FSL.LoadFromFile(GetPath('', 'mod.cfg'), TEncoding.UTF8); Map.LoadFromFile(MapFileName); end; initialization GMods := TMods.Create; finalization FreeAndNil(GMods); end.
unit uRandom; interface function RandomChar: Char; function RandomString(l: byte): string; implementation function RandomChar: Char; begin Result:=Char(Random(256)) end; function RandomNChar: Char; type TCS = Set of Char; Const chars:TCS=['!'..'ÿ']-['\','|','/','*','<','>']; begin repeat Result:=Char(Random(Byte('ÿ')-Byte('!'))+Byte('!')) until Result in CHARS end; function RandomString(l: byte): string; var i:byte; begin Result:=''; for i:=1 to l do Result:=Result+RandomNChar end; end.
{*********************************************} { TeeBI Software Library } { TDataItem Export Dialog } { Copyright (c) 2016 by Steema Software } { All Rights Reserved } {*********************************************} unit VCLBI.Editor.ExportData; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, BI.DataItem, BI.DataSource, Vcl.ExtCtrls, VCLBI.Editor.ListItems; type TExportData = class(TForm) Panel1: TPanel; Label1: TLabel; Label2: TLabel; LSize: TLabel; LBFormat: TListBox; BCopy: TButton; BSave: TButton; CBSchema: TCheckBox; SaveDialog1: TSaveDialog; Panel2: TPanel; Label3: TLabel; Panel3: TPanel; Panel4: TPanel; BClose: TButton; procedure BSaveClick(Sender: TObject); procedure LBFormatClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BCopyClick(Sender: TObject); private { Private declarations } Data : TDataItem; IItems : TFormListItems; FExports : Array of TBIExport; function Current:TBIExport; function CurrentExtension:String; function DialogFilter:String; class function GetExportFormat(const AFile:String):TBIExport; static; function Prepare(const AExport:TBIExport; const AData:TDataItem):TBIExport; procedure ShowSize(const ASize:UInt64); public { Public declarations } class function HasAnyFormat:Boolean; static; class procedure SaveToFile(const AData:TDataItem; const AFile:String); overload; static; procedure SaveToFile(const AFile:String); overload; class procedure Show(const AOwner:TComponent; const AData:TDataItem); static; end; implementation
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit MainFrm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FGX.ProgressDialog, FGX.ProgressDialog.Types, FMX.StdCtrls, FMX.Layouts, FMX.Controls.Presentation; type TFormMain = class(TForm) btnProgressDialog: TButton; fgProgressDialog: TfgProgressDialog; fgActivityDialog: TfgActivityDialog; btnActivityDialog: TButton; LayoutButtons: TLayout; Layout1: TLayout; Label1: TLabel; SwitchCancellable: TSwitch; procedure btnProgressDialogClick(Sender: TObject); procedure btnActivityDialogClick(Sender: TObject); procedure fgProgressDialogHide(Sender: TObject); procedure fgProgressDialogShow(Sender: TObject); procedure SwitchCancellableSwitch(Sender: TObject); procedure fgProgressDialogCancel(Sender: TObject); procedure fgActivityDialogCancel(Sender: TObject); private FProgressDialogThread: TThread; FActivityDialogThread: TThread; end; var FormMain: TFormMain; implementation {$R *.fmx} procedure TFormMain.btnProgressDialogClick(Sender: TObject); begin if not fgProgressDialog.IsShown then begin FProgressDialogThread := TThread.CreateAnonymousThread(procedure begin try TThread.Synchronize(nil, procedure begin fgProgressDialog.ResetProgress; fgProgressDialog.Show; fgProgressDialog.Message := 'Preparing downloading content'; fgProgressDialog.Kind := TfgProgressDialogKind.Undeterminated; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgProgressDialog.Kind := TfgProgressDialogKind.Determinated; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgProgressDialog.Message := 'Union units...'; fgProgressDialog.Progress := 10; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgProgressDialog.Message := 'Sorting units in package...'; fgProgressDialog.Progress := 20; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgProgressDialog.Message := 'Removed comments...'; fgProgressDialog.Progress := 60; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgProgressDialog.Message := 'Finishig'; fgProgressDialog.Progress := 90; end); Sleep(500); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgProgressDialog.Progress := 100; end); Sleep(500); if TThread.CheckTerminated then Exit; finally if not TThread.CheckTerminated then TThread.Synchronize(nil, procedure begin fgProgressDialog.Hide; end); end; end); FProgressDialogThread.FreeOnTerminate := False; FProgressDialogThread.Start; end; end; procedure TFormMain.btnActivityDialogClick(Sender: TObject); begin if not fgActivityDialog.IsShown then begin FActivityDialogThread := TThread.CreateAnonymousThread(procedure begin try TThread.Synchronize(nil, procedure begin fgActivityDialog.Message := 'Please, Wait'; fgActivityDialog.Show; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgActivityDialog.Message := 'Downloading file info.txt'; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgActivityDialog.Message := 'Downloading file game.level'; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgActivityDialog.Message := 'Downloading file delphi.zip'; end); Sleep(1000); if TThread.CheckTerminated then Exit; TThread.Synchronize(nil, procedure begin fgActivityDialog.Message := 'Finishig'; end); Sleep(500); if TThread.CheckTerminated then Exit; finally if not TThread.CheckTerminated then TThread.Synchronize(nil, procedure begin fgActivityDialog.Hide; end); end; end); FActivityDialogThread.FreeOnTerminate := False; FActivityDialogThread.Start; end; end; procedure TFormMain.fgActivityDialogCancel(Sender: TObject); begin Log.d('OnCancel'); FActivityDialogThread.Terminate; end; procedure TFormMain.fgProgressDialogCancel(Sender: TObject); begin Log.d('OnCancel'); FProgressDialogThread.Terminate; end; procedure TFormMain.fgProgressDialogHide(Sender: TObject); begin Log.d('OnHide'); end; procedure TFormMain.fgProgressDialogShow(Sender: TObject); begin Log.d('OnShow'); end; procedure TFormMain.SwitchCancellableSwitch(Sender: TObject); begin fgActivityDialog.Cancellable := SwitchCancellable.IsChecked; fgProgressDialog.Cancellable := SwitchCancellable.IsChecked; end; end.
unit RProrataWorksheets; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids, Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas, RPrinter, RPDefine, RPBase, RPFiler, locatdir, Mask, CheckLst, PASTypes; type Tfm_ProrataWorksheets = class(TForm) Panel2: TPanel; ReportFiler: TReportFiler; dlg_Print: TPrintDialog; ReportPrinter: TReportPrinter; tb_ProrataHeader: TTable; tb_ProrataDetails: TTable; tb_ProrataExemptions: TTable; Panel1: TPanel; Label1: TLabel; gb_Options: TGroupBox; Label2: TLabel; Label6: TLabel; cmb_CollectionType: TComboBox; ed_ProrataYear: TEdit; Panel4: TPanel; btn_Print: TBitBtn; btn_Close: TBitBtn; cb_SeparateIntoCollectionTypes: TCheckBox; Label3: TLabel; Label4: TLabel; cb_PrintThisIsNotABill: TCheckBox; tb_SchoolCode: TTable; Label5: TLabel; cb_CombineSimilarLevies: TCheckBox; tb_ExemptionCode: TTable; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn_PrintClick(Sender: TObject); procedure ReportPrint(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } UnitName, ProrataYear, CollectionType : String; ReportCancelled, PrintAllCollections, CombineSimilarLevies, SeparateIntoCollectionTypes, PrintThisIsNotABill : Boolean; ExtractFile : TextFile; Procedure InitializeForm; {Open the tables and setup.} Procedure LoadProrataInformation(ProrataDetailsList : TList; ProrataExemptionsList : TList; Category : String); end; implementation uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils, Prog, Preview, Types, DataAccessUnit, UtilBill; {$R *.DFM} {========================================================} Procedure Tfm_ProrataWorksheets.FormActivate(Sender: TObject); begin SetFormStateMaximized(Self); end; {========================================================} Procedure Tfm_ProrataWorksheets.InitializeForm; begin UnitName := 'RProrataInformation'; {mmm} _OpenTablesForForm(Self, GlblProcessingType, []); If GlblAssessmentYearIsSameAsTaxYearForMunicipal then ed_ProrataYear.Text := IntToStr(GetYearFromDate(Date)) else ed_ProrataYear.Text := IncrementNumericString(IntToStr(GetYearFromDate(Date)), 1); end; {InitializeForm} {===================================================================} Function ProrataExemptionInList(ProrataExemptionsList : TList; _ExemptionCode : String; _AssessmentYear : String) : Boolean; var I : Integer; begin Result := False; For I := 0 to (ProrataExemptionsList.Count - 1) do with ProrataRemovedExemptionPointer(ProrataExemptionsList[I])^ do If (_Compare(_ExemptionCode, ExemptionCode, coEqual) and _Compare(_AssessmentYear, AssessmentYear, coEqual)) then Result := True; end; {ProrataExemptionInList} {===================================================================} Procedure AddOneProrataExemptionToList(tb_ProrataExemptions : TTable; ProrataExemptionsList : TList); var ProrataExemptionPtr : ProrataRemovedExemptionPointer; begin If not ProrataExemptionInList(ProrataExemptionsList, tb_ProrataExemptions.FieldByName('ExemptionCode').AsString, tb_ProrataExemptions.FieldByName('TaxRollYr').AsString) then begin New(ProrataExemptionPtr); with tb_ProrataExemptions, ProrataExemptionPtr^ do begin ExemptionCode := FieldByName('ExemptionCode').AsString; AssessmentYear := FieldByName('TaxRollYr').AsString; HomesteadCode := FieldByName('HomesteadCode').AsString; CountyAmount := FieldByName('CountyAmount').AsInteger; MunicipalAmount := FieldByName('TownAmount').AsInteger; SchoolAmount := FieldByName('SchoolAmount').AsInteger; end; {with tb_ProrataExemptions, ProrataExemptionPtr^ do} ProrataExemptionsList.Add(ProrataExemptionPtr); end; {If not ProrataExemptionInList...} end; {AddOneProrataExemptionToList} {===================================================================} Procedure AddOneProrataDetailToList(tb_ProrataDetails : TTable; ProrataDetailsList : TList); var ProrataDetailPtr : ProrataDetailPointer; begin New(ProrataDetailPtr); with tb_ProrataDetails, ProrataDetailPtr^ do begin ProrataYear := FieldByName('ProrataYear').AsString; AssessmentYear := FieldByName('TaxRollYr').AsString; GeneralTaxType := FieldByName('GeneralTaxType').AsString; HomesteadCode := FieldByName('HomesteadCode').AsString; LevyDescription := FieldByName('LevyDescription').AsString; CalculationDays := FieldByName('Days').AsInteger; TaxRate := FieldByName('TaxRate').AsFloat; ExemptionAmount := FieldByName('ExemptionAmount').AsInteger; TaxAmount := FieldByName('TaxAmount').AsFloat; end; {with tb_ProrataDetails, ProrataDetailPtr^ do} ProrataDetailsList.Add(ProrataDetailPtr); end; {AddOneProrataDetailToList} {===================================================================} Procedure CombineProrataDetails(ProrataDetailsList : TList); var I, J : Integer; begin For I := 0 to (ProrataDetailsList.Count - 1) do For J := (ProrataDetailsList.Count - 1) downto (I + 1) do If ((ProrataDetailsList[I] <> nil) and (ProrataDetailsList[J] <> nil)) then with ProrataDetailPointer(ProrataDetailsList[I])^ do If (_Compare(ProrataYear, ProrataDetailPointer(ProrataDetailsList[J])^.ProrataYear, coEqual) and _Compare(GeneralTaxType, ProrataDetailPointer(ProrataDetailsList[J])^.GeneralTaxType, coEqual) and _Compare(LevyDescription, ProrataDetailPointer(ProrataDetailsList[J])^.LevyDescription, coEqual) and _Compare(CalculationDays, ProrataDetailPointer(ProrataDetailsList[J])^.CalculationDays, coEqual) and _Compare(TaxRate, ProrataDetailPointer(ProrataDetailsList[J])^.TaxRate, coEqual)) then begin ExemptionAmount := ExemptionAmount + ProrataDetailPointer(ProrataDetailsList[J])^.ExemptionAmount; TaxAmount := TaxAmount + ProrataDetailPointer(ProrataDetailsList[J])^.TaxAmount; FreeMem(ProrataDetailsList[J], SizeOf(ProrataDetailRecord)); ProrataDetailsList[J] := nil; end; {If (_Compare(ProrataYear,} For I := (ProrataDetailsList.Count - 1) downto 0 do If (ProrataDetailsList[I] = nil) then ProrataDetailsList.Delete(I); end; {CombineProrataDetails} {===================================================================} Procedure Tfm_ProrataWorksheets.LoadProrataInformation(ProrataDetailsList : TList; ProrataExemptionsList : TList; Category : String); var Done, FirstTimeThrough : Boolean; StartCategory, EndCategory : String; begin ClearTList(ProrataExemptionsList, SizeOf(ProrataRemovedExemptionRecord)); ClearTList(ProrataDetailsList, SizeOf(ProrataDetailRecord)); If _Compare(Category, coBlank) then begin StartCategory := ''; EndCategory := 'zzz'; end else begin StartCategory := Category; EndCategory := Category; end; with tb_ProrataHeader do begin _SetRange(tb_ProrataDetails, [FieldByName('SwisSBLKey').AsString, FieldByName('ProrataYear').AsString, StartCategory], [FieldByName('SwisSBLKey').AsString, FieldByName('ProrataYear').AsString, EndCategory], '', []); _SetRange(tb_ProrataExemptions, [FieldByName('SwisSBLKey').AsString, FieldByName('ProrataYear').AsString, StartCategory], [FieldByName('SwisSBLKey').AsString, FieldByName('ProrataYear').AsString, EndCategory], '', []); FirstTimeThrough := True; tb_ProrataDetails.First; with tb_ProrataDetails do repeat If FirstTimeThrough then FirstTimeThrough := False else Next; Done := EOF; If not Done then AddOneProrataDetailToList(tb_ProrataDetails, ProrataDetailsList); until Done; FirstTimeThrough := True; tb_ProrataExemptions.First; with tb_ProrataExemptions do repeat If FirstTimeThrough then FirstTimeThrough := False else Next; Done := EOF; If not Done then AddOneProrataExemptionToList(tb_ProrataExemptions, ProrataExemptionsList); until Done; end; {with tb_ProrataHeader do} end; {LoadProrataInformation} {===================================================================} Procedure PrintExemptionsHeader(Sender : TObject); begin with Sender as TBaseReport do begin Println(''); ClearTabs; SetTab(1.0, pjCenter, 0.5, 0, BOXLINEBottom, 0); {Exemption Code} SetTab(1.6, pjCenter, 1.5, 0, BOXLINEBottom, 0); {Exemption Description} SetTab(3.2, pjCenter, 0.6, 0, BOXLINEBottom, 0); {Assessment Year} SetTab(3.9, pjCenter, 0.4, 0, BOXLINEBottom, 0); {Homestead code} SetTab(4.4, pjCenter, 1.0, 0, BOXLINEBottom, 0); {County Amount} SetTab(5.5, pjCenter, 1.0, 0, BOXLINEBottom, 0); {Municipal Amount} SetTab(6.6, pjCenter, 1.0, 0, BOXLINEBottom, 0); {School Amount} Bold := True; Print(#9 + 'EX Code' + #9 + 'EX Description' + #9 + 'Year' + #9 + 'Hstd'); If (rtdCounty in GlblRollTotalsToShow) then Print(#9 + 'County Amt') else Print(#9); If (rtdMunicipal in GlblRollTotalsToShow) then Print(#9 + GetMunicipalityTypeName(GlblMunicipalityType) + ' Amt') else Print(#9); If (rtdSchool in GlblRollTotalsToShow) then Println(#9 + 'School Amt') else Println(#9); Bold := False; ClearTabs; SetTab(1.0, pjLeft, 0.5, 0, BOXLINENone, 0); {Exemption Code} SetTab(1.6, pjLeft, 1.5, 0, BOXLINENone, 0); {Exemption Description} SetTab(3.2, pjLeft, 0.6, 0, BOXLINENone, 0); {Assessment Year} SetTab(3.9, pjLeft, 0.4, 0, BOXLINENone, 0); {Homestead code} SetTab(4.4, pjRight, 1.0, 0, BOXLINENone, 0); {County Amount} SetTab(5.5, pjRight, 1.0, 0, BOXLINENone, 0); {Municipal Amount} SetTab(6.6, pjRight, 1.0, 0, BOXLINENone, 0); {School Amount} end; {with Sender as TBaseReport do} end; {PrintExemptionsHeader} {===================================================================} Procedure PrintExemptions(Sender : TObject; ProrataExemptionsList : TList; tb_ExemptionCode : TTable); var I : Integer; ExemptionDescription : String; begin with Sender as TBaseReport do For I := 0 to (ProrataExemptionsList.Count - 1) do with ProrataRemovedExemptionPointer(ProrataExemptionsList[I])^ do begin If _Locate(tb_ExemptionCode, [ExemptionCode], '', []) then ExemptionDescription := tb_ExemptionCode.FieldByName('Description').AsString else ExemptionDescription := ''; Print(#9 + ExemptionCode + #9 + ExemptionDescription + #9 + AssessmentYear + #9 + HomesteadCode); If (rtdCounty in GlblRollTotalsToShow) then Print(#9 + FormatFloat(CurrencyDisplayNoDollarSign, CountyAmount)) else Print(#9); If (rtdMunicipal in GlblRollTotalsToShow) then Print(#9 + FormatFloat(CurrencyDisplayNoDollarSign, MunicipalAmount)) else Print(#9); If (rtdSchool in GlblRollTotalsToShow) then Println(#9 + FormatFloat(CurrencyDisplayNoDollarSign, SchoolAmount)) else Println(#9); end; {with ProrataRemovedExemptionPointer(ProrataExemptionsList[I])^ do} end; {PrintExemptions} {===================================================================} Procedure PrintDetailsHeader(Sender : TObject; CollectionType : String; tb_SchoolCode : TTable); begin with Sender as TBaseReport do begin Println(''); If _Compare(CollectionType, coNotBlank) then begin ClearTabs; SetTab(1.0, pjLeft, 2.0, 0, BOXLINENone, 0); {Header} Bold := True; Underline := True; If _Compare(CollectionType, SchoolTaxType, coEqual) then Println(#9 + 'School Collection (' + tb_SchoolCode.FieldByName('SchoolName').AsString + '):'); If _Compare(CollectionType, [MunicipalTaxType, TownTaxType, VillageTaxType], coEqual) then Println(#9 + 'Municipal Collection:'); Bold := False; Underline := False; Println(''); end; {If _Compare(CollectionType, coNotBlank)} ClearTabs; SetTab(1.0, pjCenter, 0.6, 0, BOXLINEBottom, 0); {Assessment Year} SetTab(1.7, pjCenter, 2.0, 0, BOXLINEBottom, 0); {Levy Description} SetTab(3.8, pjCenter, 0.4, 0, BOXLINEBottom, 0); {Homestead code} SetTab(4.3, pjCenter, 0.4, 0, BOXLINEBottom, 0); {Calculation Days} SetTab(4.8, pjCenter, 1.0, 0, BOXLINEBottom, 0); {Exemption Amt} SetTab(5.9, pjCenter, 1.0, 0, BOXLINEBottom, 0); {Tax Rate} SetTab(7.0, pjCenter, 1.0, 0, BOXLINEBottom, 0); {Tax Amount} Bold := True; Println(#9 + 'Year' + #9 + 'Levy Description' + #9 + 'Hstd' + #9 + 'Days' + #9 + 'Exempt Amt' + #9 + 'Tax Rate' + #9 + 'Tax Amount'); Bold := False; ClearTabs; SetTab(1.0, pjLeft, 0.6, 0, BOXLINENone, 0); {Assessment Year} SetTab(1.7, pjLeft, 2.0, 0, BOXLINENone, 0); {Levy Description} SetTab(3.8, pjLeft, 0.4, 0, BOXLINENone, 0); {Homestead code} SetTab(4.3, pjRight, 0.4, 0, BOXLINENone, 0); {Calculation Days} SetTab(4.8, pjRight, 1.0, 0, BOXLINENone, 0); {Exemption Amt} SetTab(5.9, pjRight, 1.0, 0, BOXLINENone, 0); {Tax Rate} SetTab(7.0, pjRight, 1.0, 0, BOXLINENone, 0); {Tax Amount} end; {with Sender as TBaseReport do} end; {PrintDetailsHeader} {===================================================================} Procedure PrintDetails(Sender : TObject; ProrataDetailsList : TList; CollectionType : String; tb_SchoolCode : TTable); var I : Integer; TotalProrata : Double; DetailPrinted : Boolean; begin TotalProrata := 0; DetailPrinted := False; with Sender as TBaseReport do begin For I := 0 to (ProrataDetailsList.Count - 1) do with ProrataDetailPointer(ProrataDetailsList[I])^ do If (_Compare(CollectionType, coBlank) or (_Compare(CollectionType, SchoolTaxType, coEqual) and _Compare(GeneralTaxType, SchoolTaxType, coEqual)) or (_Compare(CollectionType, [MunicipalTaxType, TownTaxType, VillageTaxType], coEqual) and _Compare(GeneralTaxType, [MunicipalTaxType, TownTaxType, VillageTaxType, CountyTaxType], coEqual))) then begin If not DetailPrinted then begin PrintDetailsHeader(Sender, CollectionType, tb_SchoolCode); DetailPrinted := True; end; Println(#9 + AssessmentYear + #9 + LevyDescription + #9 + HomesteadCode + #9 + IntToStr(CalculationDays) + #9 + FormatFloat(CurrencyDisplayNoDollarSign, ExemptionAmount) + #9 + FormatFloat(ExtendedDecimalDisplay, TaxRate) + #9 + FormatFloat(DecimalDisplay, TaxAmount)); TotalProrata := TotalProrata + TaxAmount; end; {If (_Compare(CollectionType, coBlank) or ...} If _Compare(TotalProrata, 0, coGreaterThan) then begin Bold := True; Println(#9 + #9 + #9 + #9 + #9 + #9 + 'Subtotal: ' + #9 + FormatFloat(DecimalDisplay, TotalProrata)); Bold := False; Println(''); end; {If (_Compare(CollectionType, coNotBlank)} end; {with Sender as TBaseReport do} end; {PrintDetails} {===================================================================} Procedure PrintOneWorksheet(Sender : TObject; tb_ProrataHeader : TTable; tb_SchoolCode : TTable; tb_ExemptionCode : TTable; ProrataDetailsList : TList; ProrataExemptionsList : TList; SeperateIntoCollectionTypes : Boolean; PrintThisIsNotABill : Boolean; CombineSimilarLevies : Boolean); var I : Integer; NAddrArray : NameAddrArray; TotalThisProrata : Double; begin with Sender as TBaseReport, tb_ProrataHeader do begin SectionTop := 0.25; SectionLeft := 0.5; SectionRight := PageWidth - 0.5; Println(''); SetFont('Times New Roman', 14); PrintCenter('Prorata Taxes Worksheet', (PageWidth / 2)); SetFont('Times New Roman', 10); ClearTabs; SetTab(0.3, pjLeft, 0.7, 0, BOXLINENone, 0); {Header} SetTab(1.0, pjLeft, 2.0, 0, BOXLINENone, 0); {Data} Println(''); Println(''); Println(''); _Locate(tb_SchoolCode, [FieldByName('SchoolCode').AsString], '', []); Println(#9 + 'Parcel ID:' + #9 + ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').AsString)); Println(#9 + 'Sale Date:' + #9 + FieldByName('SaleDate').AsString); Println(#9 + 'School:' + #9 + FieldByName('SchoolCode').AsString + #9 + '(' + tb_SchoolCode.FieldByName('SchoolName').AsString + ')'); Println(''); Println(''); ClearTabs; SetTab(0.7, pjLeft, 3.0, 0, BOXLINENone, 0); {Header} GetNameAddress(tb_ProrataHeader, NAddrArray); For I := 1 to 6 do Println(#9 + NAddrArray[I]); PrintExemptionsHeader(Sender); PrintExemptions(Sender, ProrataExemptionsList, tb_ExemptionCode); If CombineSimilarLevies then CombineProrataDetails(ProrataDetailsList); If SeperateIntoCollectionTypes then begin PrintDetails(Sender, ProrataDetailsList, 'SC', tb_SchoolCode); PrintDetails(Sender, ProrataDetailsList, 'MU', tb_SchoolCode); end else PrintDetails(Sender, ProrataDetailsList, '', tb_SchoolCode); TotalThisProrata := 0; For I := 0 to (ProrataDetailsList.Count - 1) do with ProrataDetailPointer(ProrataDetailsList[I])^ do TotalThisProrata := TotalThisProrata + TaxAmount; Println(''); Bold := True; Println(#9 + #9 + #9 + #9 + #9 + #9 + 'GRAND TOTAL: ' + #9 + FormatFloat(DecimalDisplay, TotalThisProrata)); Bold := False; If PrintThisIsNotABill then begin GotoXY(1, 10); Bold := True; SetFont('Times New Roman', 12); PrintCenter('T H I S I S N O T A B I L L', (PageWidth / 2)); Bold := False; end; {If PrintThisIsNotABill} NewPage; end; {with Sender as TBaseReport do} end; {PrintOneParcel} {===================================================================} Procedure Tfm_ProrataWorksheets.ReportPrint(Sender: TObject); var SwisSBLKey, LastSwisSBLKey, Category : String; ProrataDetailsList, ProrataExemptionsList : TList; ProratasFound : Integer; begin ProratasFound := 0; LastSwisSBLKey := ''; tb_ProrataHeader.First; ProrataDetailsList := TList.Create; ProrataExemptionsList := TList.Create; with tb_ProrataHeader do begin First; while (not (EOF or ReportCancelled)) do begin SwisSBLKey := FieldByName('SwisSBLKey').AsString; ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(SwisSBLKey)); ProgressDialog.UserLabelCaption := 'Proratas Found = ' + IntToStr(ProratasFound); Application.ProcessMessages; If (_Compare(FieldByName('ProrataYear').AsString, ProrataYear, coEqual) and _Compare(SwisSBLKey, LastSwisSBLKey, coNotEqual) and (PrintAllCollections or CategoryMeetsCollectionTypeRequirements(CollectionType, FieldByName('Category').AsString))) then begin Inc(ProratasFound); If PrintAllCollections then Category := '' else Category := FieldByName('Category').AsString; LoadProrataInformation(ProrataDetailsList, ProrataExemptionsList, Category); If _Compare(ProrataDetailsList.Count, 0, coGreaterThan) then PrintOneWorksheet(Sender, tb_ProrataHeader, tb_SchoolCode, tb_ExemptionCode, ProrataDetailsList, ProrataExemptionsList, SeparateIntoCollectionTypes, PrintThisIsNotABill, CombineSimilarLevies); end; {If (_Compare(FieldByName('ProrataYear') ...} ReportCancelled := ProgressDialog.Cancelled; LastSwisSBLKey := SwisSBLKey; Next; end; {while (not (EOF or ReportCancelled)) do} end; {with tb_ProrataHeader do} FreeTList(ProrataExemptionsList, SizeOf(ProrataRemovedExemptionRecord)); FreeTList(ProrataDetailsList, SizeOf(ProrataDetailRecord)); end; {ReportPrint} {===================================================================} Procedure Tfm_ProrataWorksheets.btn_PrintClick(Sender: TObject); var Quit, Continue : Boolean; NewFileName : String; TempFile : File; begin Continue := True; Quit := False; ReportCancelled := False; PrintAllCollections := False; PrintThisIsNotABill := cb_PrintThisIsNotABill.Checked; SeparateIntoCollectionTypes := cb_SeparateIntoCollectionTypes.Checked; CombineSimilarLevies := cb_CombineSimilarLevies.Checked; btn_Print.Enabled := False; Application.ProcessMessages; SetPrintToScreenDefault(dlg_Print); If _Compare(cmb_CollectionType.Text, coBlank) then begin MessageDlg('Please select a collection type.', mtError, [mbOK], 0); cmb_CollectionType.SetFocus; Continue := False; end; {If _Compare ...} ProrataYear := ed_ProrataYear.Text; If (Continue and dlg_Print.Execute) then begin case cmb_CollectionType.ItemIndex of 0 : CollectionType := MunicipalTaxType; 1 : CollectionType := CountyTaxType; 2 : CollectionType := SchoolTaxType; 3 : CollectionType := VillageTaxType; 4 : PrintAllCollections := True; end; {case cmb_CollectionType.ItemIndex of} AssignPrinterSettings(dlg_Print, ReportPrinter, ReportFiler, [ptLaser], False, Quit); ProgressDialog.Start(GetRecordCount(tb_ProrataHeader), True, True); {Now print the report.} If not (Quit or ReportCancelled) then begin If dlg_Print.PrintToFile then begin NewFileName := GetPrintFileName(Self.Caption, True); ReportFiler.FileName := NewFileName; try PreviewForm := TPreviewForm.Create(self); PreviewForm.FilePrinter.FileName := NewFileName; PreviewForm.FilePreview.FileName := NewFileName; ReportFiler.Execute; ProgressDialog.StartPrinting(dlg_Print.PrintToFile); PreviewForm.ShowModal; finally PreviewForm.Free; {Now delete the file.} try AssignFile(TempFile, NewFileName); OldDeleteFile(NewFileName); finally ChDir(GlblProgramDir); end; end; {try PreviewForm := ...} end {If PrintDialog.PrintToFile} else ReportPrinter.Execute; ProgressDialog.Finish; ResetPrinter(ReportPrinter); end; {If not Quit} DisplayPrintingFinishedMessage(dlg_Print.PrintToFile); end; {If PrintDialog.Execute} btn_Print.Enabled := True; end; {PrintButtonClick} {===================================================================} Procedure Tfm_ProrataWorksheets.FormClose( Sender: TObject; var Action: TCloseAction); begin CloseTablesForForm(Self); {Free up the child window and set the ClosingAForm Boolean to true so that we know to delete the tab.} Action := caFree; GlblClosingAForm := True; GlblClosingFormCaption := Caption; end; {FormClose} end.
namespace RemotingSample.Implementation; interface uses System, RemotingSample.Interfaces; type { RemoteService } RemoteService = public class(MarshalByRefObject, IRemoteService) private protected method Sum(A, B : Integer) : Integer; public end; implementation method RemoteService.Sum(A, B : integer) : integer; begin Console.WriteLine('Serving a remote request: Sum '+A.ToString+'+'+B.ToString+'...'); result := A+B; end; end.
{ Private include file for the GUI library. } %include 'sys.ins.pas'; %include 'util.ins.pas'; %include 'string.ins.pas'; %include 'file.ins.pas'; %include 'img.ins.pas'; %include 'math.ins.pas'; %include 'vect.ins.pas'; %include 'rend.ins.pas'; %include 'gui.ins.pas'; type gui_win_childpos_t = record {position into child window list} child_p: gui_win_p_t; {pointer to current child window, may be NIL} win_p: gui_win_p_t; {pointer to window object} block_p: gui_childblock_p_t; {pointer to current child list block} ind: sys_int_machine_t; {curr child list block index, 0 before first} n: sys_int_machine_t; {1-N child number, 0 before first} end; { * Routine declarations. } procedure gui_menu_ent_draw ( {draw one entry of a menu} in out menu: gui_menu_t; {menu containing entry} in ent: gui_menent_t); {descriptor of entry to draw} val_param; extern; procedure gui_win_childpos_first ( {init child position to first child in list} in out win: gui_win_t; {window object} out pos: gui_win_childpos_t); {returned child list position object} val_param; extern; procedure gui_win_childpos_last ( {init child position to last child in list} in out win: gui_win_t; {window object} out pos: gui_win_childpos_t); {returned child list position object} val_param; extern; procedure gui_win_childpos_next ( {move position to next child in list} in out pos: gui_win_childpos_t); {child list position object} val_param; extern; procedure gui_win_childpos_prev ( {move position to previous child in list} in out pos: gui_win_childpos_t); {child list position object} val_param; extern; procedure gui_win_childpos_wentry ( {write value to child list entry} in out pos: gui_win_childpos_t; {child list position object} in child_p: gui_win_p_t); {pointer to new child window} val_param; extern;
{----------------------------------------------------------------------------- Author: Roman Fadeyev Purpose: Соединение, использующее для источника данных историю котировок (IStockDataStorage) History: -----------------------------------------------------------------------------} unit FC.StockData.EHC.StockDataConnection; {$I Compiler.inc} interface uses SysUtils,Classes,DB, Controls, Serialization, FC.Definitions, FC.StockData.StockDataSource,StockChart.Definitions,FC.Singletons, FC.StockData.StockDataConnectionFile; type //--------------------------------------------------------------------------- //Соединение с History Center TStockDataSourceConnection_EHC = class (TStockDataSourceConnectionFile) private FStartLoadingFrom: TDateTime; public //from IStockDataSourceConnection function CreateDataSource(aUseCacheIfPossible: boolean=true): IStockDataSource; override; //TPersistentObject procedure OnDefineValues; override; constructor Create(const aSymbol: string; aInterval: TStockTimeInterval; const aStartLoadingFrom: TDateTime;const aConnectionString: string); destructor Destroy; override; end; implementation uses SystemService,FC.StockData.EHC.StockDataSource,FC.StockData.StockDataSourceRegistry, FC.HistoryCenter.DataStorage ; { TStockDataSourceConnection_EHC } constructor TStockDataSourceConnection_EHC.Create(const aSymbol: string; aInterval: TStockTimeInterval; const aStartLoadingFrom: TDateTime;const aConnectionString: string); begin inherited Create(aSymbol,aInterval,aConnectionString); FStartLoadingFrom:=aStartLoadingFrom; end; function TStockDataSourceConnection_EHC.CreateDataSource(aUseCacheIfPossible: boolean=true): IStockDataSource; var aObj: TObject; aStockDataStorage : IStockDataStorage; begin aObj:=StockLoadedDataSourceRegistry.FindDataSourceObject(self.ConnectionString,TStockDataSource_EHC,self.Symbol,self.Interval,FloatToStr(FStartLoadingFrom)); if aObj<>nil then result:=aObj as TStockDataSource_EHC else begin aStockDataStorage:=TStockDataStorageContainer.Create(Self.ConnectionString); aStockDataStorage.CheckConnected; result:=TStockDataSource_EHC.Create(self,self.Symbol,self.Interval,aStockDataStorage,FStartLoadingFrom); end; end; destructor TStockDataSourceConnection_EHC.Destroy; begin inherited; end; procedure TStockDataSourceConnection_EHC.OnDefineValues; begin inherited; DefValDateTime('StartLoadingFrom',FStartLoadingFrom); end; initialization Serialization.TClassFactory.RegisterClass(TStockDataSourceConnection_EHC); end.
unit Getter.PhysicalDrive.NCQAvailability; interface uses Windows, OSFile.Handle, OSFile.IoControl, OS.Handle; type TNCQAvailability = (Unknown, Disabled, Enabled); TNCQAvailabilityGetter = class sealed(TIoControlFile) public constructor Create(const FileToGetAccess: String); override; function GetNCQStatus: TNCQAvailability; protected function GetMinimumPrivilege: TCreateFileDesiredAccess; override; private type STORAGE_PROPERTY_QUERY = record PropertyId: DWORD; QueryType: DWORD; AdditionalParameters: array[0..3] of Byte; end; TBusType = (UnknownBus = 0, SCSI, ATAPI, ATA, IEEE1394, SSA, Fibre, USB, RAID, iSCSI, SAS, SATA, BusTypeMaxReserved = $7F); STORAGE_ADAPTOR_DESCRIPTOR = record Version: DWORD; Size: DWORD; MaximumTransferLength: DWORD; MaximumPhysicalPages: DWORD; AlignmentMask: DWORD; AdaptorUsesPio: Boolean; AdaptorScansDown: Boolean; CommandQueuing: Boolean; AccelatedTransfer: Boolean; BusType: TBusType; BusMajorVersion: WORD; BusMinorVersion: WORD; end; TStorageAdaptorDescriptorWithBuffer = record StorageAdaptorDescriptor: STORAGE_ADAPTOR_DESCRIPTOR; Buffer: Array[0..1023] of Byte; end; private InnerQueryBuffer: STORAGE_PROPERTY_QUERY; InnerOutputBuffer: STORAGE_ADAPTOR_DESCRIPTOR; procedure GetAdaptorDescriptorAndIfNotReturnedRaiseException( const IOBuffer: TIoControlIOBuffer); procedure SetAdaptorDescriptor; function GetIOBufferToGetAdaptorDescriptor: TIoControlIOBuffer; procedure SetQueryBuffer; function DetermineNCQStatus: TNCQAvailability; function IsSCSIwithCommandQueuing: Boolean; function IsATAwithCommandQueuing: Boolean; function IsSATA: Boolean; function IsNCQ: Boolean; function IsUnknown: Boolean; function IsRAIDwithCommandQueuing: Boolean; end; implementation { TNCQAvailabilityGetter } constructor TNCQAvailabilityGetter.Create(const FileToGetAccess: String); begin inherited; CreateHandle(FileToGetAccess, GetMinimumPrivilege); end; function TNCQAvailabilityGetter.GetIOBufferToGetAdaptorDescriptor: TIoControlIOBuffer; const NullInputBuffer = nil; NullInputBufferSize = 0; begin result.InputBuffer.Buffer := @InnerQueryBuffer; result.InputBuffer.Size := SizeOf(InnerQueryBuffer); result.OutputBuffer.Buffer := @InnerOutputBuffer; result.OutputBuffer.Size := SizeOf(InnerOutputBuffer); end; procedure TNCQAvailabilityGetter. GetAdaptorDescriptorAndIfNotReturnedRaiseException( const IOBuffer: TIoControlIOBuffer); var ReturnedBytes: Cardinal; begin ReturnedBytes := IoControl(TIoControlCode.StorageQueryProperty, IOBuffer); if ReturnedBytes = 0 then ENoDataReturnedFromIO.Create ('NoDataReturnedFromIO: No data returned from StorageQueryProperty'); end; procedure TNCQAvailabilityGetter.SetQueryBuffer; type STORAGE_QUERY_TYPE = (PropertyStandardQuery = 0, PropertyExistsQuery, PropertyMaskQuery, PropertyQueryMaxDefined); TStorageQueryType = STORAGE_QUERY_TYPE; STORAGE_PROPERTY_ID = (StorageDeviceProperty = 0, StorageAdapterProperty); TStoragePropertyID = STORAGE_PROPERTY_ID; begin InnerOutputBuffer.Size := SizeOf(InnerOutputBuffer); InnerQueryBuffer.PropertyId := Cardinal(StorageAdapterProperty); InnerQueryBuffer.QueryType := Cardinal(PropertyStandardQuery); end; procedure TNCQAvailabilityGetter.SetAdaptorDescriptor; var IOBuffer: TIoControlIOBuffer; begin SetQueryBuffer; IOBuffer := GetIOBufferToGetAdaptorDescriptor; GetAdaptorDescriptorAndIfNotReturnedRaiseException(IOBuffer); end; function TNCQAvailabilityGetter.IsSCSIwithCommandQueuing: Boolean; begin result := (InnerOutputBuffer.CommandQueuing) and (InnerOutputBuffer.BusType = TBusType.SCSI); end; function TNCQAvailabilityGetter.IsATAwithCommandQueuing: Boolean; begin result := (InnerOutputBuffer.CommandQueuing) and (InnerOutputBuffer.BusType = TBusType.ATA); end; function TNCQAvailabilityGetter.IsRAIDwithCommandQueuing: Boolean; begin result := (InnerOutputBuffer.CommandQueuing) and (InnerOutputBuffer.BusType = TBusType.RAID); end; function TNCQAvailabilityGetter.IsSATA: Boolean; begin result := InnerOutputBuffer.BusType = TBusType.SATA; end; function TNCQAvailabilityGetter.IsUnknown: Boolean; begin result := (InnerOutputBuffer.BusType <> TBusType.SATA) and (InnerOutputBuffer.BusType <> TBusType.RAID) and (InnerOutputBuffer.BusType <> TBusType.ATA) and (InnerOutputBuffer.BusType <> TBusType.SCSI); end; function TNCQAvailabilityGetter.IsNCQ: Boolean; begin result := IsSCSIwithCommandQueuing or IsATAwithCommandQueuing or IsRAIDwithCommandQueuing or IsSATA; end; function TNCQAvailabilityGetter.DetermineNCQStatus: TNCQAvailability; begin if IsUnknown then result := TNCQAvailability.Unknown else if IsNCQ then result := TNCQAvailability.Enabled else result := TNCQAvailability.Disabled; end; function TNCQAvailabilityGetter.GetNCQStatus: TNCQAvailability; begin SetAdaptorDescriptor; result := DetermineNCQStatus; end; function TNCQAvailabilityGetter.GetMinimumPrivilege: TCreateFileDesiredAccess; begin exit(DesiredReadOnly); end; end.
unit PortUnitTest; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, WiseHardware, WiseDaq, WisePort, WiseStatusLine, ExtCtrls, DateUtils, CheckLst, cbw, ComCtrls; type TForm1 = class(TForm) MainTimer: TTimer; PortGroupBox: TGroupBox; PortSelector: TComboBox; DirectionSelector: TRadioGroup; PortValueHex: TLabeledEdit; PortStatusTimer: TTimer; BoardSelector: TComboBox; ValueBox: TGroupBox; StatusBar: TLabel; BoardDescription: TLabel; PortValueBin: TLabel; procedure MainTimerTick(Sender: TObject); procedure OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure PortStatusTimerTick(Sender: TObject); procedure ChangeBoard(Sender: TObject); procedure RedefinePort(Sender: TObject); procedure ShowPortValue(); procedure OnCreate(Sender: TObject); private { Private declarations } public procedure SetPortStatus(s: string; millis: integer); overload; procedure SetPortStatus(s: string; millis: integer; color: TColor); overload; { Public declarations } end; var Form1: TForm1; PortStatusExpiration: TDateTime; PortStatusLine: TWiseStatusLine; Port: TWisePort; DirectionType: (Output = 0, Input = 1); i: integer; okboard, okport: integer; initResult: string; implementation {$R *.dfm} procedure TForm1.MainTimerTick(Sender: TObject); begin if DirectionSelector.ItemIndex = 1 then ShowPortValue; end; procedure TForm1.PortStatusTimerTick(Sender: TObject); begin if (Time > PortStatusExpiration) then begin StatusBar.Caption := ''; StatusBar.Font.Color := clWindowText; end; end; procedure TForm1.SetPortStatus(s: string; millis: integer); begin StatusBar.Caption := s; if (millis = 0) then PortStatusExpiration := IncYear(Time, 1) else PortStatusExpiration := IncMilliSecond(Time, millis) end; procedure TForm1.SetPortStatus(s: string; millis: integer; color: TColor); begin StatusBar.Font.Color := color; StatusBar.Caption := s; if (millis = 0) then PortStatusExpiration := IncYear(Time, 1) else PortStatusExpiration := IncMilliSecond(Time, millis) end; procedure TForm1.OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var val, maxval: integer; begin if (Key <> 13) then exit; maxval := $FF; case WiseBoards[BoardSelector.ItemIndex].bitsPerDaq[PortSelector.ItemIndex] of 8: maxval := $FF; 4: maxval := $F; end; val := -1; try val := StrToInt(PortValueHex.Text); except on EConvertError do begin SetPortStatus(Format('Bad HEX value: %s', [PortValueHex.Text]), 1500, clRed); PortValueHex.Text := ''; exit; end; end; if (val < 0) or (val > maxval) then begin SetPortStatus(Format('Only positive values upto $%X', [maxval]), 1500, clRed); exit; end; Port.Value := val; ShowPortValue; end; procedure SetBoardDescription(boardno: integer); begin Form1.BoardDescription.Caption := Format('Board #%d: %s (%d daqs)', [boardno, WiseBoards[boardno].model, WiseBoards[boardno].Ndaqs]); end; procedure TForm1.ChangeBoard(Sender: TObject); var boardno, daqno: integer; begin boardno := BoardSelector.ItemIndex; PortSelector.Items.Clear; for daqno := 0 to WiseBoards[boardno].ndaqs - 1 do PortSelector.Items.Add(Format('%s', [WiseDaqPortNames[daqno + FIRSTPORTA]])); SetBoardDescription(boardno); end; procedure TForm1.RedefinePort(Sender: TObject); var boardno, portno, dir: integer; newport: TWisePort; dId: TDaqId; begin boardno := BoardSelector.ItemIndex; portno := PortSelector.ItemIndex + FIRSTPORTA; case DirectionSelector.ItemIndex of 0: dir := DIGITALOUT; 1: dir := DIGITALIN; end; if ((Port <> nil) and (dir = DIGITALOUT)) then // when switching to an Out port, zero it out Port.Value := 0; dId := daqId(boardno, portno, dir); try newport := TWisePort.Create(WiseDaqPortNames[portno], dId); except begin SetPortStatus(Format('Board%d:%s NOT SUPPORTED!', [BoardSelector.ItemIndex, PortSelector.Items[PortSelector.ItemIndex]]), 2000, clRed); BoardSelector.ItemIndex := okboard; PortSelector.ItemIndex := okport - FIRSTPORTA; exit; end; end; okboard := boardno; okport := okport; { At this point the new port was successfully created, we can update the display. daq contains either the new values or the restored values } if (Port <> nil) then Port.Destroy(); Port := newport; if (DirectionSelector.ItemIndex = 0) then // output PortValueHex.Enabled := true else PortValueHex.Enabled := false; ShowPortValue; end; procedure TForm1.ShowPortValue(); var bit, nbits, val: integer; binVal: String; begin val := Port.Value; nbits := WiseBoards[BoardSelector.ItemIndex].bitsPerDaq[PortSelector.ItemIndex]; // make the binary display binVal := ''; for bit := 0 to nbits - 1 do if (val AND (1 SHL bit)) <> 0 then binVal := '1' + binVal else binVal := '0' + binVal; PortValueBin.Caption := binVal; // show the hex dislay if (nbits = 8) then PortValueHex.Text := Format('$%2.2x', [val]) else PortValueHex.Text := Format('$%1.1x', [val]); end; procedure TForm1.OnCreate(Sender: TObject); var boardno, first, daqno: integer; begin if initResult = '' then begin BoardSelector.Items.Clear; first := -1; for boardno := 0 to High(WiseBoards) do if (WiseBoards[boardno].model <> nil) then begin BoardSelector.Items.Add(Format('Board %d', [boardno])); if (first = -1) then first := boardno; end; BoardSelector.ItemIndex := 0; SetBoardDescription(first); PortSelector.Items.Clear; for daqno := 0 to WiseBoards[first].ndaqs - 1 do PortSelector.Items.Add(Format('%s', [WiseDaqPortNames[daqno + FIRSTPORTA]])); PortSelector.Text := Format('%s', [WiseDaqPortNames[FIRSTPORTA]]); PortSelector.ItemIndex := 0; RedefinePort(Form1); end else begin BoardSelector.Text := ''; PortSelector.Text := ''; SetPortStatus(initResult + ' STOPPED!', 1000000000, clRed); exit; end; end; initialization initResult := InitDaqsInfo(); finalization Port.Value := 0; 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvSpecialImage.PAS, released on 2001-02-28. The Initial Developer of the Original Code is Sébastien Buysse [sbuysse att buypin dott com] Portions created by Sébastien Buysse are Copyright (C) 2001 Sébastien Buysse. All Rights Reserved. Contributor(s): Michael Beck [mbeck att bigfoot dott com]. You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id$ unit JvSpecialImage; {$mode objfpc}{$H+} interface uses SysUtils, Classes, {Windows,} Graphics, Controls, ExtCtrls, Forms, JvTypes; type TJvBright = -100..100; TJvFadingEnd = (feBlack, feWhite); TJvSpecialImage = class(TImage) private FInverted: Boolean; FFadingEnd: TJvFadingEnd; FFadingSpeed: Integer; FFadingIn: Boolean; FFlipped: Boolean; FBrightness: TJvBright; FOriginal: TPicture; FMirrored: Boolean; FWorking: Boolean; FTimer: TTimer; FChangingLocalProperty: Boolean; FOnFadingComplete: TNotifyEvent; procedure SetBright(Value: TJvBright); procedure SetFadingSpeed(const Value: Integer); procedure SetFlipped(const Value: Boolean); procedure SetInverted(const Value: Boolean); procedure SetMirrored(const Value: Boolean); procedure ApplyChanges; procedure FadeTimerHandler(Sender: TObject); function GetPicture: TPicture; procedure SetPicture(const Value: TPicture); protected procedure Loaded; override; procedure PictureChanged(Sender: TObject); override; // wp: moved from "private" public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Brightness: TJvBright read FBrightness write SetBright default 0; property Inverted: Boolean read FInverted write SetInverted default False; property FadingEnd: TJvFadingEnd read FFadingEnd write FFadingEnd default feBlack; property FadingSpeed: Integer read FFadingSpeed write SetFadingSpeed default 2; property Flipped: Boolean read FFlipped write SetFlipped default False; property Mirrored: Boolean read FMirrored write SetMirrored default False; property Picture: TPicture read GetPicture write SetPicture; procedure FadeIn; procedure FadeOut; procedure Reset; property OnFadingComplete: TNotifyEvent read FOnFadingComplete write FOnFadingComplete; end; implementation uses FPImage, IntfGraphics; constructor TJvSpecialImage.Create(AOwner: TComponent); begin inherited Create(AOwner); FOriginal := TPicture.Create; FBrightness := 0; FInverted := False; FFlipped := False; FMirrored := False; FWorking := False; FChangingLocalProperty := False; Picture.OnChange := @PictureChanged; FTimer := TTimer.Create(self); FTimer.Enabled := false; FTimer.Interval := 1; FTimer.OnTimer := @FadeTimerHandler; FFadingSpeed := 2; end; destructor TJvSpecialImage.Destroy; begin Picture.Assign(FOriginal); FOriginal.Free; inherited Destroy; end; procedure TJvSpecialImage.Loaded; begin inherited Loaded; FOriginal.Assign(Picture); end; procedure TJvSpecialImage.ApplyChanges; var I, J: Integer; C, C2: TFPColor; Dest: TBitmap; Val: Integer; IntfImg: TLazIntfImage; begin if FWorking or (csLoading in ComponentState) or (csDestroying in ComponentState) then Exit; FWorking := True; IntfImg := TLazIntfImage.Create(FOriginal.Width, FOriginal.Height); try IntfImg.LoadFromBitmap(FOriginal.Bitmap.Handle, FOriginal.Bitmap.MaskHandle); Val := Integer(65535) * FBrightness div 100; if Val > 0 then begin for J := 0 to IntfImg.Height - 1 do for I := 0 to IntfImg.Width - 1 do begin C := IntfImg.Colors[I, J]; if C.Blue + Val > 65535 then C.Blue := 65535 else C.Blue := C.Blue + Val; if C.Green + Val > 65535 then C.Green := 65535 else C.Green := C.Green + Val; if C.Red + Val > 65535 then C.Red := 65535 else C.Red := C.Red + Val; IntfImg.Colors[I, J] := C; end; end else if Val < 0 then begin for J := 0 to IntfImg.Height - 1 do for I := 0 to IntfImg.Width - 1 do begin C := IntfImg.Colors[I, J]; if C.Blue + Val < 0 then C.Blue := 0 else C.Blue := C.Blue + Val; if C.Green + Val < 0 then C.Green := 0 else C.Green := C.Green + Val; if C.Red + Val < 0 then C.Red := 0 else C.Red := C.Red + Val; IntfImg.Colors[I, J] := C; end; end; //Set Flipped if FFlipped then for J := 0 to (IntfImg.Height - 1) div 2 do for I := 0 to IntfImg.Width - 1 do begin C := IntfImg.Colors[I, J]; C2 := IntfImg.Colors[I, IntfImg.Height - J - 1]; IntfImg.Colors[I, J] := C2; IntfImg.Colors[I, IntfImg.Height - J - 1] := C; end; //Set inverted if FInverted then for J := 0 to IntfImg.Height - 1 do for I := 0 to IntfImg.Width - 1 do begin C := IntfImg.Colors[I, J]; C.Red := 65535 - C.Red; C.Green := 65535 - C.Green; C.Blue := 65535 - C.Blue; IntfImg.Colors[I, J] := C; end; //Set mirrored if FMirrored then for J := 0 to IntfImg.Height - 1 do for I := 0 to (IntfImg.Width - 1) div 2 do begin C := IntfImg.Colors[I, J]; C2 := IntfImg.Colors[IntfImg.Width - I - 1, J]; IntfImg.Colors[I, J] := C2; IntfImg.Colors[IntfImg.Width - I - 1, J] := C; end; Dest := TBitmap.Create; try Dest.LoadFromIntfImage(IntfImg); if FChangingLocalProperty then inherited Picture.Assign(Dest); finally Dest.Free; end; finally IntfImg.Free; FWorking := false; end; end; procedure TJvSpecialImage.FadeIn; begin FFadingIn := true; FTimer.Enabled := true; end; procedure TJvSpecialImage.FadeOut; begin FFadingIn := false; FTimer.Enabled := true; end; procedure TJvSpecialImage.FadeTimerHandler(Sender: TObject); const FADE_END_BRIGHTNESS: Array[TJvFadingEnd, boolean] of Integer = ( { jeBlack } (-100, 0), // fading out/in } { jeWhite } ( 100, 0) // fading out/in ); SGN: array[TJvFadingEnd, boolean] of Integer = ( { jeBlack } (-1, +1), { jeWhite } (+1, -1) ); function AwayFromEndPoint(AFadingEnd: TJvFadingEnd): Boolean; begin case AFadingEnd of feBlack: if FFadingIn then Result := FBrightness < -FFadingSpeed else Result := FBrightness >= -100 + FFadingSpeed; feWhite: if FFadingIn then Result := FBrightness > FFadingSpeed else Result := FBrightness <= 100 - FFadingSpeed; end; end; procedure EndPointReached(AFadingEnd: TJvFadingEnd); begin Brightness := FADE_END_BRIGHTNESS[AFadingEnd, FFadingIn]; FTimer.Enabled := false; if Assigned(FOnFadingComplete) then FOnFadingComplete(Self); end; function NextFadingEnd: TJvFadingEnd; begin Result := TJvFadingEnd((ord(FFadingEnd) + 1) mod 2); end; var lFadingEnd: TJvFadingEnd; begin if FInverted then lFadingEnd := NextFadingEnd else lFadingEnd := FFadingEnd; if AwayFromEndPoint(lFadingEnd) then Brightness := FBrightness + SGN[lFadingEnd, FFadingIn] * FFadingSpeed else EndPointReached(lFadingEnd); end; function TJvSpecialImage.GetPicture: TPicture; begin Result := inherited Picture; end; procedure TJvSpecialImage.PictureChanged(Sender: TObject); begin if FWorking = False then begin FOriginal.Assign(inherited Picture); ApplyChanges; // SetBright(FBrightness); end; Invalidate; end; procedure TJvSpecialImage.Reset; begin FWorking := True; Brightness := 0; Inverted := False; Flipped := False; Mirrored := False; FWorking := False; Picture.Assign(FOriginal); end; procedure TJvSpecialImage.SetBright(Value: TJvBright); begin FChangingLocalProperty := True; try FBrightness := Value; ApplyChanges; finally FChangingLocalProperty := False; end; end; procedure TJvSpecialImage.SetFadingSpeed(const Value: Integer); begin if Value <> FFadingSpeed then begin FFadingSpeed := abs(Value); if FFadingSpeed = 0 then FFadingSpeed := 1; end; end; procedure TJvSpecialImage.SetFlipped(const Value: Boolean); begin if Value <> FFlipped then begin FChangingLocalProperty := True; try FFlipped := Value; ApplyChanges; finally FChangingLocalProperty := False; end; end; end; procedure TJvSpecialImage.SetInverted(const Value: Boolean); begin if Value <> FInverted then begin FChangingLocalProperty := True; try FInverted := Value; ApplyChanges; finally FChangingLocalProperty := False; end; end; end; procedure TJvSpecialImage.SetMirrored(const Value: Boolean); begin if Value <> FMirrored then begin FChangingLocalProperty := True; try FMirrored := Value; ApplyChanges; finally FChangingLocalProperty := False; end; end; end; procedure TJvSpecialImage.SetPicture(const Value: TPicture); begin FOriginal.Assign(Value); inherited Picture := Value; end; end.
unit BodyDataQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, System.Generics.Collections, DSWrap; type TBodyDataW = class(TDSWrap) private FBodyData: TFieldWrap; FID: TFieldWrap; FIDBody: TFieldWrap; FIDProducer: TFieldWrap; public constructor Create(AOwner: TComponent); override; property BodyData: TFieldWrap read FBodyData; property ID: TFieldWrap read FID; property IDBody: TFieldWrap read FIDBody; property IDProducer: TFieldWrap read FIDProducer; end; TQueryBodyData = class(TQueryBase) FDUpdateSQL: TFDUpdateSQL; private FW: TBodyDataW; { Private declarations } public constructor Create(AOwner: TComponent); override; procedure LocateOrAppend(const ABodyData: string; AIDProducer, AIDBody: Integer); property W: TBodyDataW read FW; { Public declarations } end; implementation {$R *.dfm} uses StrHelper; constructor TQueryBodyData.Create(AOwner: TComponent); begin inherited; FW := TBodyDataW.Create(FDQuery); end; procedure TQueryBodyData.LocateOrAppend(const ABodyData: string; AIDProducer, AIDBody: Integer); var AFieldNames: string; begin Assert(not ABodyData.IsEmpty); Assert(AIDProducer > 0); Assert(AIDBody > 0); AFieldNames := Format('%s;%s;%s', [W.IDBody.FieldName, W.BodyData.FieldName, W.IDProducer.FieldName]); if not FDQuery.LocateEx(AFieldNames, VarArrayOf([AIDBody, ABodyData, AIDProducer]), [lxoCaseInsensitive]) then begin W.TryAppend; W.BodyData.F.Value := ABodyData; W.IDBody.F.Value := AIDBody; W.IDProducer.F.Value := AIDProducer; W.TryPost; end; end; constructor TBodyDataW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FBodyData := TFieldWrap.Create(Self, 'BodyData'); FIDBody := TFieldWrap.Create(Self, 'IDBody'); FIDProducer := TFieldWrap.Create(Self, 'IDProducer'); end; end.
{$MODE DELPHI} Program Week9; Type Text = array Of String; Var T1: Text; Function isPalindrome(w: String) : boolean; Var i: Integer; Begin result := true; For i := 1 To length(w) Div 2 Do If w[i] <> w[length(w)-i+1] Then result := false; End; Procedure input(Var T1: Text); Var n, err: Integer; str_length : String; Begin Repeat writeln('How many strings do you need to process?'); readln(str_length); Val (str_length, n, err); Until (n>0) And (err=0); SetLength(T1,n+1); writeln('Enter ',length(T1)-1,' words one by one'); For n:=1 To length(T1)-1 Do readln(T1[n]); End; Procedure process(Var T1: Text); Var c: Integer; Begin For c:=1 To length(T1)-1 Do If isPalindrome(T1[c]) Then writeln(T1[c],' is a Palindrome') Else writeln(T1[c],' is not a Palindrome'); End; Begin input(T1); process(T1); End.
{**********************************************} { TCustomChart (or derived) Editor Dialog } { Copyright (c) 1996-2004 by David Berneda } {**********************************************} unit TeeEdiGene; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} Qt, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} Chart, TeCanvas, TeePenDlg, TeeProcs, TeeNavigator; type TFormTeeGeneral = class(TForm) BPrint: TButton; GBMargins: TGroupBox; SETopMa: TEdit; SELeftMa: TEdit; SEBotMa: TEdit; SERightMa: TEdit; UDTopMa: TUpDown; UDRightMa: TUpDown; UDLeftMa: TUpDown; UDBotMa: TUpDown; PageControl1: TPageControl; TabSheet1: TTabSheet; LSteps: TLabel; Label1: TLabel; CBAllowZoom: TCheckBox; CBAnimatedZoom: TCheckBox; SEAniZoomSteps: TEdit; UDAniZoomSteps: TUpDown; BZoomPen: TButtonPen; BZoomColor: TButton; EMinPix: TEdit; UDMinPix: TUpDown; TabSheet2: TTabSheet; RGPanning: TRadioGroup; Label2: TLabel; CBDir: TComboFlat; Label3: TLabel; CBZoomMouse: TComboFlat; Label4: TLabel; CBScrollMouse: TComboFlat; Label5: TLabel; CBMarUnits: TComboFlat; Label6: TLabel; CBCursor: TComboFlat; CBUpLeft: TCheckBox; procedure BPrintClick(Sender: TObject); procedure CBAllowZoomClick(Sender: TObject); procedure CBAnimatedZoomClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure RGPanningClick(Sender: TObject); procedure SEAniZoomStepsChange(Sender: TObject); procedure SERightMaChange(Sender: TObject); procedure SETopMaChange(Sender: TObject); procedure SEBotMaChange(Sender: TObject); procedure SELeftMaChange(Sender: TObject); procedure BZoomColorClick(Sender: TObject); procedure EMinPixChange(Sender: TObject); procedure CBDirChange(Sender: TObject); procedure CBZoomMouseChange(Sender: TObject); procedure CBScrollMouseChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CBMarUnitsChange(Sender: TObject); procedure CBCursorChange(Sender: TObject); procedure CBUpLeftClick(Sender: TObject); private { Private declarations } procedure AdjustMarginMinMax; Function ChangeMargin(UpDown:TUpDown; APos,OtherSide:Integer):Integer; Procedure EnableZoomControls; public { Public declarations } TheChart : TCustomChart; Constructor CreateChart(Owner:TComponent; AChart:TCustomChart); end; // 5.03 Moved here from TeeNavigator.pas unit. // Now TeeNavigator is an abstract class. TChartPageNavigator=class(TCustomTeeNavigator) private function GetChart: TCustomChart; procedure SetChart(const Value: TCustomChart); protected procedure BtnClick(Index: TTeeNavigateBtn); override; procedure DoTeeEvent(Event: TTeeEvent); override; procedure SetPanel(const Value: TCustomTeePanel); override; public procedure EnableButtons; override; Function PageCount:Integer; override; procedure Print; override; published property Chart:TCustomChart read GetChart write SetChart; property OnButtonClicked; end; Procedure ChartPreview(AOwner:TComponent; TeePanel:TCustomTeePanel); implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFDEF CLX} TeePreviewPanel, {$ENDIF} TeEngine, TeePrevi, TeExport, TeeStore, TeeBrushDlg; Procedure ChartPreview(AOwner:TComponent; TeePanel:TCustomTeePanel); Begin with TChartPreview.Create(AOwner) do try PageNavigatorClass:=TChartPageNavigator; TeePreviewPanel1.Panel:=TeePanel; ShowModal; finally Free; TeePanel.Repaint; end; End; { Chart General Editor } Constructor TFormTeeGeneral.CreateChart(Owner:TComponent; AChart:TCustomChart); begin inherited Create(Owner); TheChart:=AChart; end; procedure TFormTeeGeneral.BPrintClick(Sender: TObject); begin ChartPreview(nil,TheChart); { 5.01 } end; Procedure TFormTeeGeneral.EnableZoomControls; begin EnableControls(TheChart.Zoom.Allow,[ CBAnimatedZoom, UDAniZoomSteps, SEAniZoomSteps,EMinPix,UDMinPix, BZoomPen,BZoomColor,CBDir,CBZoomMouse, CBUpLeft]); end; procedure TFormTeeGeneral.CBAllowZoomClick(Sender: TObject); begin TheChart.Zoom.Allow:=CBAllowZoom.Checked; EnableZoomControls; end; procedure TFormTeeGeneral.CBAnimatedZoomClick(Sender: TObject); begin TheChart.Zoom.Animated:=CBAnimatedZoom.Checked; end; procedure TFormTeeGeneral.FormShow(Sender: TObject); begin if Assigned(TheChart) then With TheChart do begin RGPanning.ItemIndex :=Ord(AllowPanning); UDTopMa.Position :=MarginTop; UDLeftMa.Position :=MarginLeft; UDBotMa.Position :=MarginBottom; UDRightMa.Position :=MarginRight; CBMarUnits.ItemIndex :=Ord(MarginUnits); AdjustMarginMinMax; With Zoom do begin CBAllowZoom.Checked :=Allow; CBAnimatedZoom.Checked :=Animated; UDAniZoomSteps.Position:=AnimatedSteps; EnableZoomControls; UDMinPix.Position :=MinimumPixels; CBDir.ItemIndex :=Ord(Direction); CBZoomMouse.ItemIndex :=Ord(MouseButton); CBUpLeft.Checked :=UpLeftZooms; BZoomPen.LinkPen(Pen); end; CBScrollMouse.ItemIndex :=Ord(ScrollMouseButton); CBScrollMouse.Enabled :=AllowPanning<>pmNone; TeeFillCursors(CBCursor,Cursor); end; end; procedure TFormTeeGeneral.AdjustMarginMinMax; Procedure SetMinMax(Up:TUpDown); begin if TheChart.MarginUnits=muPixels then begin Up.Min:=-2000; Up.Max:=2000; end else begin Up.Min:=0; Up.Max:=100; end; end; begin SetMinMax(UDTopMa); SetMinMax(UDLeftMa); SetMinMax(UDRightMa); SetMinMax(UDBotMa); end; procedure TFormTeeGeneral.CBMarUnitsChange(Sender: TObject); begin TheChart.MarginUnits:=TTeeUnits(CBMarUnits.ItemIndex); AdjustMarginMinMax; end; procedure TFormTeeGeneral.RGPanningClick(Sender: TObject); begin TheChart.AllowPanning:=TPanningMode(RGPanning.ItemIndex); CBScrollMouse.Enabled:=TheChart.AllowPanning<>pmNone; end; procedure TFormTeeGeneral.SEAniZoomStepsChange(Sender: TObject); begin if Showing then TheChart.Zoom.AnimatedSteps:=UDAniZoomSteps.Position; end; Function TFormTeeGeneral.ChangeMargin(UpDown:TUpDown; APos,OtherSide:Integer):Integer; begin result:=APos; if Showing then With UpDown do if (TheChart.MarginUnits=muPixels) or (Position+OtherSide<100) then result:=Position else Position:=APos; end; procedure TFormTeeGeneral.SERightMaChange(Sender: TObject); begin if Showing then With TheChart do MarginRight:=ChangeMargin(UDRightMa,MarginRight,MarginLeft); end; procedure TFormTeeGeneral.SETopMaChange(Sender: TObject); begin if Showing then With TheChart do MarginTop:=ChangeMargin(UDTopMa,MarginTop,MarginBottom); end; procedure TFormTeeGeneral.SEBotMaChange(Sender: TObject); begin if Showing then With TheChart do MarginBottom:=ChangeMargin(UDBotMa,MarginBottom,MarginTop); end; procedure TFormTeeGeneral.SELeftMaChange(Sender: TObject); begin if Showing then With TheChart do MarginLeft:=ChangeMargin(UDLeftMa,MarginLeft,MarginRight); end; procedure TFormTeeGeneral.BZoomColorClick(Sender: TObject); begin EditChartBrush(Self,TheChart.Zoom.Brush); end; procedure TFormTeeGeneral.EMinPixChange(Sender: TObject); begin if Showing then TheChart.Zoom.MinimumPixels:=UDMinPix.Position end; procedure TFormTeeGeneral.CBDirChange(Sender: TObject); begin TheChart.Zoom.Direction:=TTeeZoomDirection(CBDir.ItemIndex); end; procedure TFormTeeGeneral.CBZoomMouseChange(Sender: TObject); begin TheChart.Zoom.MouseButton:=TMouseButton(CBZoomMouse.ItemIndex) end; procedure TFormTeeGeneral.CBScrollMouseChange(Sender: TObject); begin TheChart.ScrollMouseButton:=TMouseButton(CBScrollMouse.ItemIndex) end; procedure TFormTeeGeneral.FormCreate(Sender: TObject); begin Align:=alClient; PageControl1.ActivePage:=TabSheet1; end; { TChartPageNavigator } procedure TChartPageNavigator.BtnClick(Index: TTeeNavigateBtn); var tmp : TCustomChart; begin tmp:=Chart; if Assigned(tmp) then with tmp do case Index of nbPrior : if Page>1 then Page:=Page-1; nbNext : if Page<NumPages then Page:=Page+1; nbFirst : if Page>1 then Page:=1; nbLast : if Page<NumPages then Page:=NumPages; end; EnableButtons; inherited; end; procedure TChartPageNavigator.SetPanel(const Value: TCustomTeePanel); begin if Value is TCustomAxisPanel then inherited else inherited SetPanel(nil); end; procedure TChartPageNavigator.EnableButtons; var tmp : TCustomChart; begin inherited; tmp:=Chart; if Assigned(tmp) then begin Buttons[nbFirst].Enabled:=tmp.Page>1; Buttons[nbPrior].Enabled:=Buttons[nbFirst].Enabled; Buttons[nbNext].Enabled:=tmp.Page<tmp.NumPages; Buttons[nbLast].Enabled:=Buttons[nbNext].Enabled; end; end; procedure TChartPageNavigator.DoTeeEvent(Event: TTeeEvent); begin if (Event is TChartChangePage) or ( (Event is TTeeSeriesEvent) and (TTeeSeriesEvent(Event).Event=seDataChanged) ) then EnableButtons; end; function TChartPageNavigator.GetChart: TCustomChart; begin result:=TCustomChart(Panel); end; procedure TChartPageNavigator.SetChart(const Value: TCustomChart); begin Panel:=Value; end; Function TChartPageNavigator.PageCount:Integer; begin result:=Chart.NumPages; end; procedure TChartPageNavigator.Print; begin if PageCount>1 then With TPrintDialog.Create(Self) do try {$IFNDEF CLX} Options:=[poPageNums]; PrintRange:=prPageNums; {$ENDIF} FromPage:=1; MinPage:=FromPage; ToPage:=Chart.NumPages; MaxPage:=ToPage; if Execute then Chart.PrintPages(FromPage,ToPage); finally Free; end else Chart.PrintPages(1,1); end; procedure TFormTeeGeneral.CBCursorChange(Sender: TObject); begin with TheChart do begin Cursor:=TeeSetCursor(Cursor,CBCursor.Items[CBCursor.ItemIndex]); OriginalCursor:=Cursor; end; end; procedure TFormTeeGeneral.CBUpLeftClick(Sender: TObject); begin TheChart.Zoom.UpLeftZooms:=CBUpLeft.Checked; end; end.
unit fpeMakerNoteEpson; {$IFDEF FPC} {$MODE DELPHI} //{$mode objfpc}{$H+} {$ENDIF} interface uses Classes, SysUtils, fpeTags, fpeExifReadWrite; type TEpsonMakerNoteReader = class(TMakerNoteReader) protected procedure GetTagDefs({%H-}AStream: TStream); override; end; implementation procedure BuildEpsonTagDefs(AList: TTagDefList); const // M = DWord(TAGPARENT_MAKERNOTE); M = LongWord(TAGPARENT_MAKERNOTE); begin Assert(AList <> nil); with AList do begin AddUShortTag(M+$0200, 'SpecialMode'); AddUShortTag(M+$0201, 'JpegQuality'); AddUShortTag(M+$0202, 'Macro'); AddUShortTag(M+$0204, 'DigitalZoom'); AddUShortTag(M+$0209, 'CameraID'); AddStringTag(M+$020A, 'Comments'); AddUShortTag(M+$020B, 'Width'); AddUShortTag(M+$020C, 'Height'); AddUShortTag(M+$020D, 'SoftRelease'); end; end; //============================================================================== // TEpsonMakerNoteReader //============================================================================== procedure TEpsonMakerNoteReader.GetTagDefs(AStream: TStream); begin BuildEpsonTagDefs(FTagDefs); end; initialization RegisterMakerNoteReader(TEpsonMakerNoteReader, 'Epson', ''); end.
{ Initial map viewer library: Copyright (C) 2011 Maciej Kaczkowski / keit.co Extensions: (C) 2014 ti_dic@hotmail.com (C) 2019 Werner Pamler (user wp at Lazarus forum https://forum.lazarus.freepascal.org License: modified LGPL with linking exception (like RTL, FCL and LCL) See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution, for details about the license. See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL } unit mvMapViewer; {$MODE objfpc}{$H+} interface uses Classes, SysUtils, Controls, Graphics, IntfGraphics, Forms, MvTypes, MvGPSObj, MvEngine, MvMapProvider, MvDownloadEngine, MvDrawingEngine; Type TDrawGpsPointEvent = procedure (Sender: TObject; ADrawer: TMvCustomDrawingEngine; APoint: TGpsPoint) of object; { TMapView } TMapView = class(TCustomControl) private FDownloadEngine: TMvCustomDownloadEngine; FBuiltinDownloadEngine: TMvCustomDownloadEngine; FEngine: TMapViewerEngine; FBuiltinDrawingEngine: TMvCustomDrawingEngine; FDrawingEngine: TMvCustomDrawingEngine; FActive: boolean; FGPSItems: TGPSObjectList; FInactiveColor: TColor; FPOIImage: TBitmap; FPOITextBgColor: TColor; FOnDrawGpsPoint: TDrawGpsPointEvent; FDebugTiles: Boolean; FDefaultTrackColor: TColor; FDefaultTrackWidth: Integer; FFont: TFont; procedure CallAsyncInvalidate; procedure DoAsyncInvalidate({%H-}Data: PtrInt); procedure DrawObjects(const {%H-}TileId: TTileId; aLeft, aTop, aRight,aBottom: integer); procedure DrawPt(const {%H-}Area: TRealArea; aPOI: TGPSPoint); procedure DrawTrack(const Area: TRealArea; trk: TGPSTrack); function GetCacheOnDisk: boolean; function GetCachePath: String; function GetCenter: TRealPoint; function GetDownloadEngine: TMvCustomDownloadEngine; function GetDrawingEngine: TMvCustoMDrawingEngine; function GetMapProvider: String; function GetOnCenterMove: TNotifyEvent; function GetOnChange: TNotifyEvent; function GetOnZoomChange: TNotifyEvent; function GetUseThreads: boolean; function GetZoom: integer; function IsCachePathStored: Boolean; function IsFontStored: Boolean; procedure SetActive(AValue: boolean); procedure SetCacheOnDisk(AValue: boolean); procedure SetCachePath(AValue: String); procedure SetCenter(AValue: TRealPoint); procedure SetDebugTiles(AValue: Boolean); procedure SetDefaultTrackColor(AValue: TColor); procedure SetDefaultTrackWidth(AValue: Integer); procedure SetDownloadEngine(AValue: TMvCustomDownloadEngine); procedure SetDrawingEngine(AValue: TMvCustomDrawingEngine); procedure SetFont(AValue: TFont); procedure SetInactiveColor(AValue: TColor); procedure SetMapProvider(AValue: String); procedure SetOnCenterMove(AValue: TNotifyEvent); procedure SetOnChange(AValue: TNotifyEvent); procedure SetOnZoomChange(AValue: TNotifyEvent); procedure SetPOIImage(AValue: TBitmap); procedure SetPOITextBgColor(AValue: TColor); procedure SetUseThreads(AValue: boolean); procedure SetZoom(AValue: integer); procedure UpdateFont(Sender: TObject); procedure UpdateImage(Sender: TObject); protected AsyncInvalidate : boolean; procedure ActivateEngine; procedure DblClick; override; procedure DoDrawTile(const TileId: TTileId; X,Y: integer; TileImg: TLazIntfImage); procedure DoDrawTileInfo(const {%H-}TileID: TTileID; X,Y: Integer); function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; procedure DoOnResize; override; function IsActive: Boolean; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X,Y: Integer); override; procedure Paint; override; procedure OnGPSItemsModified(Sender: TObject; objs: TGPSObjList; Adding: boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ClearBuffer; procedure GetMapProviders(lstProviders: TStrings); function GetVisibleArea: TRealArea; function LonLatToScreen(aPt: TRealPoint): TPoint; procedure SaveToFile(AClass: TRasterImageClass; const AFileName: String); function SaveToImage(AClass: TRasterImageClass): TRasterImage; procedure SaveToStream(AClass: TRasterImageClass; AStream: TStream); function ScreenToLonLat(aPt: TPoint): TRealPoint; procedure CenterOnObj(obj: TGPSObj); procedure ZoomOnArea(const aArea: TRealArea); procedure ZoomOnObj(obj: TGPSObj); procedure WaitEndOfRendering; property Center: TRealPoint read GetCenter write SetCenter; property Engine: TMapViewerEngine read FEngine; property GPSItems: TGPSObjectList read FGPSItems; published property Active: boolean read FActive write SetActive default false; property Align; property CacheOnDisk: boolean read GetCacheOnDisk write SetCacheOnDisk default true; property CachePath: String read GetCachePath write SetCachePath stored IsCachePathStored; property DebugTiles: Boolean read FDebugTiles write SetDebugTiles default false; property DefaultTrackColor: TColor read FDefaultTrackColor write SetDefaultTrackColor default clRed; property DefaultTrackWidth: Integer read FDefaultTrackWidth write SetDefaultTrackWidth default 1; property DownloadEngine: TMvCustomDownloadEngine read GetDownloadEngine write SetDownloadEngine; property DrawingEngine: TMvCustomDrawingEngine read GetDrawingEngine write SetDrawingEngine; property Font: TFont read FFont write SetFont stored IsFontStored; property Height default 150; property InactiveColor: TColor read FInactiveColor write SetInactiveColor default clWhite; property MapProvider: String read GetMapProvider write SetMapProvider; property POIImage: TBitmap read FPOIImage write SetPOIImage; property POITextBgColor: TColor read FPOITextBgColor write SetPOITextBgColor default clNone; property PopupMenu; property UseThreads: boolean read GetUseThreads write SetUseThreads default false; property Width default 150; property Zoom: integer read GetZoom write SetZoom; property OnCenterMove: TNotifyEvent read GetOnCenterMove write SetOnCenterMove; property OnZoomChange: TNotifyEvent read GetOnZoomChange write SetOnZoomChange; property OnChange: TNotifyEvent read GetOnChange write SetOnChange; property OnDrawGpsPoint: TDrawGpsPointEvent read FOnDrawGpsPoint write FOnDrawGpsPoint; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; end; implementation uses GraphType, Types, mvJobQueue, mvExtraData, mvDLEFpc, mvDE_IntfGraphics; type { TDrawObjJob } TDrawObjJob = class(TJob) private AllRun: boolean; Viewer: TMapView; FRunning: boolean; FLst: TGPSObjList; FStates: Array of integer; FArea: TRealArea; protected function pGetTask: integer; override; procedure pTaskStarted(aTask: integer); override; procedure pTaskEnded(aTask: integer; aExcept: Exception); override; public procedure ExecuteTask(aTask: integer; FromWaiting: boolean); override; function Running: boolean;override; public constructor Create(aViewer: TMapView; aLst: TGPSObjList; const aArea: TRealArea); destructor Destroy; override; end; { TDrawObjJob } function TDrawObjJob.pGetTask: integer; var i: integer; begin if not(AllRun) and not(Cancelled) then begin for i := Low(FStates) to High(FStates) do if FStates[i]=0 then begin result := i+1; Exit; end; AllRun:=True; end; Result := ALL_TASK_COMPLETED; for i := Low(FStates) to High(FStates) do if FStates[i]=1 then begin Result := NO_MORE_TASK; Exit; end; end; procedure TDrawObjJob.pTaskStarted(aTask: integer); begin FRunning := True; FStates[aTask-1] := 1; end; procedure TDrawObjJob.pTaskEnded(aTask: integer; aExcept: Exception); begin if Assigned(aExcept) then FStates[aTask-1] := 3 else FStates[aTask-1] := 2; end; procedure TDrawObjJob.ExecuteTask(aTask: integer; FromWaiting: boolean); var iObj: integer; Obj: TGpsObj; begin iObj := aTask-1; Obj := FLst[iObj]; if Obj.InheritsFrom(TGPSTrack) then Viewer.DrawTrack(FArea, TGPSTrack(Obj)); if Obj.InheritsFrom(TGPSPoint) then Viewer.DrawPt(FArea, TGPSPoint(Obj)); end; function TDrawObjJob.Running: boolean; begin Result := FRunning; end; constructor TDrawObjJob.Create(aViewer: TMapView; aLst: TGPSObjList; const aArea: TRealArea); begin FArea := aArea; FLst := aLst; SetLEngth(FStates,FLst.Count); Viewer := aViewer; AllRun := false; Name := 'DrawObj'; end; destructor TDrawObjJob.Destroy; begin inherited Destroy; FreeAndNil(FLst); if not(Cancelled) then Viewer.CallAsyncInvalidate; end; { TMapView } procedure TMapView.SetActive(AValue: boolean); begin if FActive = AValue then Exit; FActive := AValue; if FActive then ActivateEngine else Engine.Active := false; end; function TMapView.GetCacheOnDisk: boolean; begin Result := Engine.CacheOnDisk; end; function TMapView.GetCachePath: String; begin Result := Engine.CachePath; end; function TMapView.GetCenter: TRealPoint; begin Result := Engine.Center; end; function TMapView.GetDownloadEngine: TMvCustomDownloadEngine; begin if FDownloadEngine = nil then Result := FBuiltinDownloadEngine else Result := FDownloadEngine; end; function TMapView.GetDrawingEngine: TMvCustomDrawingEngine; begin if FDrawingEngine = nil then Result := FBuiltinDrawingEngine else Result := FDrawingEngine; end; function TMapView.GetMapProvider: String; begin result := Engine.MapProvider; end; function TMapView.GetOnCenterMove: TNotifyEvent; begin result := Engine.OnCenterMove; end; function TMapView.GetOnChange: TNotifyEvent; begin Result := Engine.OnChange; end; function TMapView.GetOnZoomChange: TNotifyEvent; begin Result := Engine.OnZoomChange; end; function TMapView.GetUseThreads: boolean; begin Result := Engine.UseThreads; end; function TMapView.GetZoom: integer; begin result := Engine.Zoom; end; function TMapView.IsCachePathStored: Boolean; begin Result := not SameText(CachePath, 'cache/'); end; function TMapView.IsFontStored: Boolean; begin Result := SameText(FFont.Name, 'default') and (FFont.Size = 0) and (FFont.Style = []) and (FFont.Color = clBlack); end; procedure TMapView.SetCacheOnDisk(AValue: boolean); begin Engine.CacheOnDisk := AValue; end; procedure TMapView.SetCachePath(AValue: String); begin Engine.CachePath := AValue; //CachePath; end; procedure TMapView.SetCenter(AValue: TRealPoint); begin Engine.Center := AValue; end; procedure TMapView.SetDebugTiles(AValue: Boolean); begin if FDebugTiles = AValue then exit; FDebugTiles := AValue; Engine.Redraw; end; procedure TMapView.SetDefaultTrackColor(AValue: TColor); begin if FDefaultTrackColor = AValue then exit; FDefaultTrackColor := AValue; Engine.Redraw; end; procedure TMapView.SetDefaultTrackWidth(AValue: Integer); begin if FDefaultTrackWidth = AValue then exit; FDefaultTrackWidth := AValue; Engine.Redraw; end; procedure TMapView.SetDownloadEngine(AValue: TMvCustomDownloadEngine); begin FDownloadEngine := AValue; FEngine.DownloadEngine := GetDownloadEngine; end; procedure TMapView.SetDrawingEngine(AValue: TMvCustomDrawingEngine); begin FDrawingEngine := AValue; if AValue = nil then FBuiltinDrawingEngine.CreateBuffer(ClientWidth, ClientHeight) else begin FBuiltinDrawingEngine.CreateBuffer(0, 0); FDrawingEngine.CreateBuffer(ClientWidth, ClientHeight); end; UpdateFont(nil); end; procedure TMapView.SetFont(AValue: TFont); begin FFont.Assign(AValue); UpdateFont(nil); end; procedure TMapView.SetInactiveColor(AValue: TColor); begin if FInactiveColor = AValue then exit; FInactiveColor := AValue; if not IsActive then Invalidate; end; procedure TMapView.ActivateEngine; begin Engine.SetSize(ClientWidth,ClientHeight); Engine.Active := IsActive; end; procedure TMapView.SetMapProvider(AValue: String); begin Engine.MapProvider := AValue; end; procedure TMapView.SetOnCenterMove(AValue: TNotifyEvent); begin Engine.OnCenterMove := AValue; end; procedure TMapView.SetOnChange(AValue: TNotifyEvent); begin Engine.OnChange := AValue; end; procedure TMapView.SetOnZoomChange(AValue: TNotifyEvent); begin Engine.OnZoomChange := AValue; end; procedure TMapView.SetPOIImage(AValue: TBitmap); begin if FPOIImage = AValue then exit; FPOIImage := AValue; Engine.Redraw; end; procedure TMapView.SetPOITextBgColor(AValue: TColor); begin if FPOITextBgColor = AValue then exit; FPOITextBgColor := AValue; Engine.Redraw; end; procedure TMapView.SetUseThreads(AValue: boolean); begin Engine.UseThreads := aValue; end; procedure TMapView.SetZoom(AValue: integer); begin Engine.Zoom := AValue; end; function TMapView.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin Result:=inherited DoMouseWheel(Shift, WheelDelta, MousePos); if IsActive then Engine.MouseWheel(self,Shift,WheelDelta,MousePos,Result); end; procedure TMapView.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if IsActive then Engine.MouseDown(self,Button,Shift,X,Y); end; procedure TMapView.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); if IsActive then Engine.MouseUp(self,Button,Shift,X,Y); end; procedure TMapView.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited MouseMove(Shift, X, Y); if IsActive then Engine.MouseMove(self,Shift,X,Y); end; procedure TMapView.DblClick; begin inherited DblClick; if IsActive then Engine.DblClick(self); end; procedure TMapView.DoOnResize; begin inherited DoOnResize; //cancel all rendering threads Engine.CancelCurrentDrawing; DrawingEngine.CreateBuffer(ClientWidth, ClientHeight); if IsActive then Engine.SetSize(ClientWidth, ClientHeight); end; procedure TMapView.Paint; begin inherited Paint; if IsActive then DrawingEngine.PaintToCanvas(Canvas) else begin Canvas.Brush.Color := InactiveColor; Canvas.Brush.Style := bsSolid; Canvas.FillRect(0, 0, ClientWidth, ClientHeight); end; end; procedure TMapView.OnGPSItemsModified(Sender: TObject; objs: TGPSObjList; Adding: boolean); var Area,ObjArea,vArea: TRealArea; begin if Adding and Assigned(Objs) then begin ObjArea := GetAreaOf(Objs); vArea := GetVisibleArea; if hasIntersectArea(ObjArea,vArea) then begin Area := IntersectArea(ObjArea, vArea); Engine.Jobqueue.AddJob(TDrawObjJob.Create(self, Objs, Area), Engine); end else objs.Free; end else begin Engine.Redraw; Objs.free; end; end; procedure TMapView.DrawTrack(const Area: TRealArea; trk: TGPSTrack); var Old,New: TPoint; i: integer; aPt: TRealPoint; LastInside, IsInside: boolean; trkColor: TColor; trkWidth: Integer; begin if trk.Points.Count > 0 then begin trkColor := FDefaultTrackColor; trkWidth := FDefaultTrackWidth; if trk.ExtraData <> nil then begin if trk.ExtraData.InheritsFrom(TDrawingExtraData) then trkColor := TDrawingExtraData(trk.ExtraData).Color; if trk.ExtraData.InheritsFrom(TTrackExtraData) then trkWidth := round(ScreenInfo.PixelsPerInchX * TTrackExtraData(trk.ExtraData).Width / 25.4); end; if trkWidth < 1 then trkWidth := 1; LastInside := false; DrawingEngine.PenColor := trkColor; DrawingEngine.PenWidth := trkWidth; for i:=0 to pred(trk.Points.Count) do begin aPt := trk.Points[i].RealPoint; IsInside := PtInsideArea(aPt,Area); if IsInside or LastInside then begin New := Engine.LonLatToScreen(aPt); if i > 0 then begin if not LastInside then Old := Engine.LonLatToScreen(trk.Points[pred(i)].RealPoint); DrawingEngine.Line(Old.X, Old.Y, New.X, New.Y); end; Old := New; LastInside := IsInside; end; end; end; end; procedure TMapView.DrawPt(const Area: TRealArea; aPOI: TGPSPoint); var Pt: TPoint; PtColor: TColor; extent: TSize; s: String; begin if Assigned(FOnDrawGpsPoint) then begin FOnDrawGpsPoint(Self, DrawingEngine, aPOI); exit; end; Pt := Engine.LonLatToScreen(aPOI.RealPoint); PtColor := clRed; if aPOI.ExtraData <> nil then begin if aPOI.ExtraData.inheritsFrom(TDrawingExtraData) then PtColor := TDrawingExtraData(aPOI.ExtraData).Color; end; // Draw point marker if Assigned(FPOIImage) and not (FPOIImage.Empty) then DrawingEngine.DrawBitmap(Pt.X - FPOIImage.Width div 2, Pt.Y - FPOIImage.Height, FPOIImage, true) else begin DrawingEngine.PenColor := ptColor; DrawingEngine.Line(Pt.X, Pt.Y - 5, Pt.X, Pt.Y + 5); DrawingEngine.Line(Pt.X - 5, Pt.Y, Pt.X + 5, Pt.Y); Pt.Y := Pt.Y + 5; end; // Draw point text s := aPOI.Name; if FPOITextBgColor = clNone then DrawingEngine.BrushStyle := bsClear else begin DrawingEngine.BrushStyle := bsSolid; DrawingEngine.BrushColor := FPOITextBgColor; s := ' ' + s + ' '; end; extent := DrawingEngine.TextExtent(s); DrawingEngine.Textout(Pt.X - extent.CX div 2, Pt.Y + 5, s); end; procedure TMapView.CallAsyncInvalidate; Begin if not(AsyncInvalidate) then begin AsyncInvalidate := true; Engine.Jobqueue.QueueAsyncCall(@DoAsyncInvalidate, 0); end; end; procedure TMapView.DrawObjects(const TileId: TTileId; aLeft, aTop,aRight,aBottom: integer); var aPt: TPoint; Area: TRealArea; lst: TGPSObjList; begin aPt.X := aLeft; aPt.Y := aTop; Area.TopLeft := Engine.ScreenToLonLat(aPt); aPt.X := aRight; aPt.Y := aBottom; Area.BottomRight := Engine.ScreenToLonLat(aPt); if GPSItems.Count > 0 then begin lst := GPSItems.GetObjectsInArea(Area); if lst.Count > 0 then Engine.Jobqueue.AddJob(TDrawObjJob.Create(self, lst, Area), Engine) else begin FreeAndNil(Lst); CallAsyncInvalidate; end; end else CallAsyncInvalidate; end; procedure TMapView.DoAsyncInvalidate(Data: PtrInt); Begin Invalidate; AsyncInvalidate := false; end; procedure TMapView.DoDrawTile(const TileId: TTileId; X, Y: integer; TileImg: TLazIntfImage); begin if Assigned(TileImg) then begin DrawingEngine.DrawLazIntfImage(X, Y, TileImg); end else begin DrawingEngine.BrushColor := clWhite; DrawingEngine.BrushStyle := bsSolid; DrawingEngine.FillRect(X, Y, X + TILE_SIZE, Y + TILE_SIZE); end; if FDebugTiles then DoDrawTileInfo(TileID, X, Y); DrawObjects(TileId, X, Y, X + TILE_SIZE, Y + TILE_SIZE); end; procedure TMapView.DoDrawTileInfo(const TileID: TTileID; X, Y: Integer); begin DrawingEngine.PenColor := clGray; DrawingEngine.PenWidth := 1; DrawingEngine.Line(X, Y, X, Y + TILE_SIZE); DrawingEngine.Line(X, Y, X + TILE_SIZE, Y); DrawingEngine.Line(X + TILE_SIZE, Y, X + TILE_SIZE, Y + TILE_SIZE); DrawingEngine.Line(X, Y + TILE_SIZE, X + TILE_SIZE, Y + TILE_SIZE); end; function TMapView.IsActive: Boolean; begin if not(csDesigning in ComponentState) then Result := FActive else Result := false; end; constructor TMapView.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 150; Height := 150; FActive := false; FDefaultTrackColor := clRed; FDefaultTrackWidth := 1; FInactiveColor := clWhite; FGPSItems := TGPSObjectList.Create; FGPSItems.OnModified := @OnGPSItemsModified; FBuiltinDownloadEngine := TMvDEFpc.Create(self); FBuiltinDownloadEngine.Name := 'BuiltInDLE'; FEngine := TMapViewerEngine.Create(self); FEngine.CachePath := 'cache/'; FEngine.CacheOnDisk := true; FEngine.OnDrawTile := @DoDrawTile; FEngine.DrawTitleInGuiThread := false; FEngine.DownloadEngine := FBuiltinDownloadEngine; FBuiltinDrawingEngine := TMvIntfGraphicsDrawingEngine.Create(self); FBuiltinDrawingEngine.Name := 'BuiltInDE'; FBuiltinDrawingEngine.CreateBuffer(Width, Height); FFont := TFont.Create; FFont.Name := 'default'; FFont.Size := 0; FFont.Style := []; FFont.Color := clBlack; FFont.OnChange := @UpdateFont; FPOIImage := TBitmap.Create; FPOIImage.OnChange := @UpdateImage; FPOITextBgColor := clNone; end; destructor TMapView.Destroy; begin FFont.Free; FreeAndNil(FPOIImage); FreeAndNil(FGPSItems); inherited Destroy; end; procedure TMapView.SaveToFile(AClass: TRasterImageClass; const AFileName: String); var stream: TFileStream; begin stream := TFileStream.Create(AFileName, fmCreate + fmShareDenyNone); try SaveToStream(AClass, stream); finally stream.Free; end; end; function TMapView.SaveToImage(AClass: TRasterImageClass): TRasterImage; begin Result := DrawingEngine.SaveToImage(AClass); end; procedure TMapView.SaveToStream(AClass: TRasterImageClass; AStream: TStream); var img: TRasterImage; begin img := SaveToImage(AClass); try img.SaveToStream(AStream); finally img.Free; end; end; function TMapView.ScreenToLonLat(aPt: TPoint): TRealPoint; begin Result:=Engine.ScreenToLonLat(aPt); end; function TMapView.LonLatToScreen(aPt: TRealPoint): TPoint; begin Result:=Engine.LonLatToScreen(aPt); end; procedure TMapView.GetMapProviders(lstProviders: TStrings); begin Engine.GetMapProviders(lstProviders); end; procedure TMapView.WaitEndOfRendering; begin Engine.Jobqueue.WaitAllJobTerminated(Engine); end; procedure TMapView.CenterOnObj(obj: TGPSObj); var Area: TRealArea; Pt: TRealPoint; begin obj.GetArea(Area); Pt.Lon := (Area.TopLeft.Lon + Area.BottomRight.Lon) /2; Pt.Lat := (Area.TopLeft.Lat + Area.BottomRight.Lat) /2; Center := Pt; end; procedure TMapView.ZoomOnObj(obj: TGPSObj); var Area: TRealArea; begin obj.GetArea(Area); Engine.ZoomOnArea(Area); end; procedure TMapView.ZoomOnArea(const aArea: TRealArea); begin Engine.ZoomOnArea(aArea); end; function TMapView.GetVisibleArea: TRealArea; var aPt: TPoint; begin aPt.X := 0; aPt.Y := 0; Result.TopLeft := Engine.ScreenToLonLat(aPt); aPt.X := Width; aPt.Y := Height; Result.BottomRight := Engine.ScreenToLonLat(aPt);; end; procedure TMapView.ClearBuffer; begin DrawingEngine.CreateBuffer(ClientWidth, ClientHeight); // ??? end; procedure TMapView.UpdateFont(Sender: TObject); begin if SameText(FFont.Name, 'default') then DrawingEngine.FontName := Screen.SystemFont.Name else DrawingEngine.FontName := FFont.Name; if FFont.Size = 0 then DrawingEngine.FontSize := Screen.SystemFont.Size else DrawingEngine.FontSize := FFont.Size; DrawingEngine.FontStyle := FFont.Style; DrawingEngine.FontColor := ColorToRGB(FFont.Color); Engine.Redraw; end; procedure TMapView.UpdateImage(Sender: TObject); begin Engine.Redraw; end; end.
unit Ths.Erp.Database.Table.SysGridColWidth; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TSysGridColWidth = class(TTable) private FTableName: TFieldDB; FColumnName: TFieldDB; FColumnWidth: TFieldDB; FSequenceNo: TFieldDB; //veri tabanı alanı değil FSequenceStatus: TSequenceStatus; FOldValue: Integer; protected procedure BusinessUpdate(pPermissionControl: Boolean); override; procedure BusinessDelete(pPermissionControl: Boolean); override; procedure BusinessInsert(out pID: Integer; var pPermissionControl: Boolean); override; published constructor Create(OwnerDatabase:TDatabase);override; function GetMaxSequenceNo(pTableName: string): Integer; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; procedure Clear();override; function Clone():TTable;override; Property TableName1: TFieldDB read FTableName write FTableName; Property ColumnName: TFieldDB read FColumnName write FColumnName; property ColumnWidth: TFieldDB read FColumnWidth write FColumnWidth; property SequenceNo: TFieldDB read FSequenceNo write FSequenceNo; //veri tabanı alanı değil property SequenceStatus: TSequenceStatus read FSequenceStatus write FSequenceStatus; property OldValue: Integer read FOldValue write FOldValue; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TSysGridColWidth.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'sys_grid_col_width'; SourceCode := '1'; FTableName := TFieldDB.Create('table_name', ftString, ''); FColumnName := TFieldDB.Create('column_name', ftString, ''); FColumnWidth := TFieldDB.Create('column_width', ftInteger, 0); FSequenceNo := TFieldDB.Create('sequence_no', ftInteger, 0); FSequenceStatus := ssNone; FOldValue := 0; end; function TSysGridColWidth.GetMaxSequenceNo(pTableName: string): Integer; var vGridColWidth: TSysGridColWidth; begin Result := 0; vGridColWidth := TSysGridColWidth.Create(Database); try vGridColWidth.SelectToList(' AND ' + TableName + '.' + TableName1.FieldName + '=' + QuotedStr(pTableName) + ' ORDER BY sequence_no DESC ', False, False); if vGridColWidth.List.Count > 0 then Result := TSysGridColWidth(vGridColWidth.List[0]).FSequenceNo.Value; finally vGridColWidth.Free; end; end; procedure TSysGridColWidth.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FTableName.FieldName, TableName + '.' + FColumnName.FieldName, TableName + '.' + FColumnWidth.FieldName, TableName + '.' + FSequenceNo.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FTableName.FieldName).DisplayLabel := 'TABLE NAME'; Self.DataSource.DataSet.FindField(FColumnName.FieldName).DisplayLabel := 'COLUMN NAME'; Self.DataSource.DataSet.FindField(FColumnWidth.FieldName).DisplayLabel := 'COLUMN WIDTH'; Self.DataSource.DataSet.FindField(FSequenceNo.FieldName).DisplayLabel := 'SEQUENCE NO'; end; end; end; procedure TSysGridColWidth.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Self.Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, TableName + '.' + FTableName.FieldName, TableName + '.' + FColumnName.FieldName, TableName + '.' + FColumnWidth.FieldName, TableName + '.' + FSequenceNo.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FTableName.Value := FormatedVariantVal(FieldByName(FTableName.FieldName).DataType, FieldByName(FTableName.FieldName).Value); FColumnName.Value := FormatedVariantVal(FieldByName(FColumnName.FieldName).DataType, FieldByName(FColumnName.FieldName).Value); FColumnWidth.Value := FormatedVariantVal(FieldByName(FColumnWidth.FieldName).DataType, FieldByName(FColumnWidth.FieldName).Value); FSequenceNo.Value := FormatedVariantVal(FieldByName(FSequenceNo.FieldName).DataType, FieldByName(FSequenceNo.FieldName).Value); List.Add(Self.Clone()); Next; end; EmptyDataSet; Close; end; end; end; procedure TSysGridColWidth.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FTableName.FieldName, FColumnName.FieldName, FColumnWidth.FieldName, FSequenceNo.FieldName ]); NewParamForQuery(QueryOfInsert, FTableName); NewParamForQuery(QueryOfInsert, FColumnName); NewParamForQuery(QueryOfInsert, FColumnWidth); NewParamForQuery(QueryOfInsert, FSequenceNo); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.notify; end; end; procedure TSysGridColWidth.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FTableName.FieldName, FColumnName.FieldName, FColumnWidth.FieldName, FSequenceNo.FieldName ]); NewParamForQuery(QueryOfUpdate, FTableName); NewParamForQuery(QueryOfUpdate, FColumnName); NewParamForQuery(QueryOfUpdate, FColumnWidth); NewParamForQuery(QueryOfUpdate, FSequenceNo); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.notify; end; end; procedure TSysGridColWidth.BusinessDelete(pPermissionControl: Boolean); var vGridColWidth: TSysGridColWidth; n1: Integer; begin Self.Delete(pPermissionControl); vGridColWidth := TSysGridColWidth.Create(Database); try vGridColWidth.SelectToList( ' and ' + TableName + '.' + FTableName.FieldName + '=' + QuotedStr(FTableName.Value) + ' ORDER BY ' + FSequenceNo.FieldName + ' ASC ', False, False); for n1 := 0 to vGridColWidth.List.Count-1 do begin TSysGridColWidth(vGridColWidth.List[n1]).SequenceNo.Value := n1+1; TSysGridColWidth(vGridColWidth.List[n1]).Update(pPermissionControl); end; finally vGridColWidth.Free; end; end; procedure TSysGridColWidth.BusinessInsert(out pID: Integer; var pPermissionControl: Boolean); var vGridColWidth: TSysGridColWidth; n1: Integer; begin vGridColWidth := TSysGridColWidth.Create(Database); try vGridColWidth.SelectToList( ' and ' + TableName + '.' + FTableName.FieldName + '=' + QuotedStr(FTableName.Value) + ' and ' + TableName + '.' + FSequenceNo.FieldName + ' >= ' + FSequenceNo.Value + ' ORDER BY ' + FSequenceNo.FieldName + ' DESC ', False, pPermissionControl); for n1 := 0 to vGridColWidth.List.Count-1 do begin TSysGridColWidth(vGridColWidth.List[n1]).FSequenceNo.Value := TSysGridColWidth(vGridColWidth.List[n1]).FSequenceNo.Value + 1; TSysGridColWidth(vGridColWidth.List[n1]).Update(pPermissionControl); end; Self.Insert(pID, pPermissionControl); finally vGridColWidth.Free; end; end; procedure TSysGridColWidth.BusinessUpdate(pPermissionControl: Boolean); var vGridColWidth: TSysGridColWidth; n1: Integer; begin vGridColWidth := TSysGridColWidth.Create(Database); try if FSequenceStatus = ssArtis then begin vGridColWidth.SelectToList( ' and ' + TableName + '.' + FTableName.FieldName + '=' + QuotedStr(FTableName.Value) + ' and ' + TableName + '.' + FSequenceNo.FieldName + ' between ' + IntToStr(FOldValue) + ' AND ' + FSequenceNo.Value + ' and ' + TableName + '.' + Self.Id.FieldName + '<>' + IntToStr(Self.Id.Value) + ' ORDER BY ' + FSequenceNo.FieldName + ' ASC ', False, pPermissionControl); FSequenceNo.Value := FSequenceNo.Value + 1000; Self.Update(); for n1 := 0 to vGridColWidth.List.Count-1 do begin if (FSequenceNo.Value - 1000) <> (OldValue+n1) then begin TSysGridColWidth(vGridColWidth.List[n1]).SequenceNo.Value := OldValue+n1; TSysGridColWidth(vGridColWidth.List[n1]).Update(); end; end; FSequenceNo.Value := FSequenceNo.Value - 1000; end else if FSequenceStatus = ssAzalma then begin vGridColWidth.SelectToList( ' and ' + TableName + '.' + FTableName.FieldName + '=' + QuotedStr(FTableName.Value) + ' and ' + TableName + '.' + FSequenceNo.FieldName + ' between ' + FSequenceNo.Value + ' AND ' + IntToStr(FOldValue) + ' and ' + TableName + '.' + Self.Id.FieldName + '<>' + IntToStr(Self.Id.Value) + ' ORDER BY ' + FSequenceNo.FieldName + ' ASC ', False, False); FSequenceNo.Value := FSequenceNo.Value + 1000; Self.Update(); for n1 := 0 to vGridColWidth.List.Count-1 do begin if (FSequenceNo.Value - 1000) <> (OldValue+n1) then begin TSysGridColWidth(vGridColWidth.List[n1]).SequenceNo.Value := (FSequenceNo.Value - 1000) + 1 + n1+100; TSysGridColWidth(vGridColWidth.List[n1]).Update(); end; end; for n1 := 0 to vGridColWidth.List.Count-1 do begin if (FSequenceNo.Value - 1000) <> (FSequenceNo.Value - 1000) + 1 + n1 then begin TSysGridColWidth(vGridColWidth.List[n1]).SequenceNo.Value := (FSequenceNo.Value - 1000) + 1 + n1; TSysGridColWidth(vGridColWidth.List[n1]).Update(); end; end; FSequenceNo.Value := FSequenceNo.Value - 1000; end; Self.Update(); finally vGridColWidth.Free; end; end; procedure TSysGridColWidth.Clear(); begin inherited; FSequenceStatus := ssNone; end; function TSysGridColWidth.Clone():TTable; begin Result := TSysGridColWidth.Create(Database); Self.Id.Clone(TSysGridColWidth(Result).Id); FTableName.Clone(TSysGridColWidth(Result).FTableName); FColumnName.Clone(TSysGridColWidth(Result).FColumnName); FColumnWidth.Clone(TSysGridColWidth(Result).FColumnWidth); FSequenceNo.Clone(TSysGridColWidth(Result).FSequenceNo); TSysGridColWidth(Result).FSequenceStatus := FSequenceStatus; TSysGridColWidth(Result).FOldValue := FOldValue; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DesignConst; interface resourcestring srNone = '(None)'; srLine = 'line'; srLines = 'lines'; SInvalidFormat = 'Invalid graphic format'; SUnableToFindComponent = 'Unable to locate form/component, ''%s'''; SCantFindProperty = 'Unable to locate property ''%s'' on component ''%s'''; SStringsPropertyInvalid = 'Property ''%s'' has not been initialized on component ''%s'''; SLoadPictureTitle = 'Load Picture'; SSavePictureTitle = 'Save Picture As'; SQueryApply = 'Do You want to apply the changes before closing?'; SAboutVerb = 'About...'; SNoPropertyPageAvailable = 'No property pages are available for this control'; SNoAboutBoxAvailable = 'An About Box is not available for this control'; SNull = '(Null)'; SUnassigned = '(Unassigned)'; SUnknown = '(Unknown)'; SDispatch = '(Dispatch)'; SError = '(Error)'; SString = 'String'; SUnknownType = 'Unknown Type'; SCannotCreateName = 'Cannot create a method for an unnamed component'; SColEditCaption = 'Editing %s%s%s'; SCantDeleteAncestor = 'Selection contains a component introduced in an ancestor form which cannot be deleted'; SCantAddToFrame = 'New components cannot be added to frame instances.'; SAllFiles = 'All Files (*.*)|*.*'; SLoadingDesktopFailed = 'Loading the desktop from "%s" for dock host window "%s" failed with message: ' + SLineBreak + SLineBreak + '"%s: %s"'; sAllConfigurations = 'All configurations'; sAllPlatforms = 'All platforms'; sPlatform = ' platform'; sConfiguration = ' configuration'; sClassNotApplicable = 'Class %s is not applicable to this module'; sNotAvailable = '(Not available)'; sEditSubmenu = 'Edit'; sUndoComponent = 'Undo'; sCutComponent = 'Cut'; sCopyComponent = 'Copy'; sPasteComponent = 'Paste'; sDeleteComponent = 'Delete'; sSelectAllComponent = 'Select All'; sControlSubmenu = 'Control'; sUnsupportedChildType = '%s doesn''t support %s children'; StrEditMultiResBitmap = 'Edit Bitmap Collection'; StrNoParentFound = 'No parent control found'; StrYouSureYouWantTo = 'Are you sure you want to delete the item "%s"?'; StrNewSourceItemName = 'New source item name: '; sDesktopFormFactor = 'Desktop'; sFullScreenFormFactor = 'Full Screen'; sPhoneFormFactor = 'Phone'; sTabletFormFactor = 'Tablet'; sMasterViewName = 'Master'; sCreatedViews = 'Created'; sAvailableViews = 'Available'; const SIniEditorsName = 'Property Editors'; implementation end.
unit ErrorMsgFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, AppEvnts; type TErrorMsgForm = class(TForm) memoErrorText: TMemo; btnAppQuit: TBitBtn; btnCancel: TBitBtn; ApplicationEvents1: TApplicationEvents; procedure ApplicationEvents1Exception(Sender: TObject; E: Exception); procedure memoErrorTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var ErrorMsgForm: TErrorMsgForm; implementation {$R *.dfm} procedure TErrorMsgForm.ApplicationEvents1Exception(Sender: TObject; E: Exception); begin with ErrorMsgForm do try memoErrorText.Lines.Text := 'Произошла ошибка времени выполнения с текстом'#13#10 + '<' + E.Message + '>'#13#10 + 'Хотите завершить работу программы немедленно?'; ActiveControl := btnCancel; Position := poScreenCenter; MessageBeep(MB_ICONERROR); if ShowModal = mrOK then Application.MainForm.Close; except end; end; procedure TErrorMsgForm.memoErrorTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: btnAppQuit.Click; VK_ESCAPE: btnCancel.Click; end; end; end.
{DELPHI IMPLEMENTATION OF TWAIN INTERFACE} {december 2003®, initially created by Gustavo Daud} {This is my newest contribution for Delphi comunity, a powerfull} {implementation of latest Twain features. As you know, twain is } {the most common library to acquire images from most acquisition} {devices such as Scanners and Web-Cameras.} {Twain library is a bit different from other libraries, because} {most of the hard work can be done by a a single method. Also it} {automatically changes in the application message loop, which is} {not a simple task, at least in delphi VCL.} {It is not 100% sure to to Twain not to be installed in Windows,} {as it ships with Windows and later and with most of the } {acquisition device drivers (automatically with their installation)} {This library dynamically calls the library, avoiding the application} {hand when it is not present.} {Also, as in most of my other components, I included a trigger} {to allow the component to work without the heavy delphi VCL} {for small final executables. To enable, edit DelphiTwain.inc} {20/01/2004 - Some updates and bug fixes by Nemeth Peter} {$INCLUDE DelphiTwain.inc} unit DelphiTwain; interface {Used units} uses Twain, Windows {$IFNDEF DONTUSEVCL}, Classes, SysUtils, Graphics{$ENDIF}, DelphiTwainUtils; const {Name of the Twain library for 32 bits enviroment} TWAINLIBRARY = 'TWAIN_32.DLL'; VIRTUALWIN_CLASSNAME = 'DELPHITWAIN_VIRTUALWINDOW'; const {Error codes} ERROR_BASE = 300; ERROR_INT16: TW_INT16 = HIGH(TW_INT16); type {From twain} TW_STR255 = Twain.TW_STR255; {Forward declaration} TDelphiTwain = class; {Component kinds} {$IFDEF DONTUSEVCL} TTwainComponent = TObject; {$ELSE} TTwainComponent = TComponent; {$ENDIF} {File formats} TTwainFormat = (tfTIFF, tfPict, tfBMP, tfXBM, tfJPEG, tfFPX, tfTIFFMulti, tfPNG, tfSPIFF, tfEXIF, tfUnknown); {Twain units} TTwainUnit = (tuInches, tuCentimeters, tuPicas, tuPoints, tuTwips, tuPixels, tuUnknown); TTwainUnitSet = set of TTwainUnit; {Twain pixel flavor} TTwainPixelFlavor = (tpfChocolate, tpfVanilla, tpfUnknown); TTwainPixelFlavorSet = set of TTwainPixelFlavor; {Twain pixel type} TTwainPixelType = (tbdBw, tbdGray, tbdRgb, tbdPalette, tbdCmy, tbdCmyk, tbdYuv, tbdYuvk, tbdCieXYZ, tbdUnknown); TTwainPixelTypeSet = set of TTwainPixelType; {Twain bit depth} TTwainBitDepth = array of TW_UINT16; {Twain resolutions} TTwainResolution = array of Extended; {Events} TOnTwainError = procedure(Sender: TObject; const Index: Integer; ErrorCode, Additional: Integer) of object; TOnTwainAcquire = procedure(Sender: TObject; const Index: Integer; Image: {$IFNDEF DONTUSEVCL}TBitmap{$ELSE}HBitmap{$ENDIF}; var Cancel: Boolean) of object; TOnAcquireProgress = procedure(Sender: TObject; const Index: Integer; const Image: HBitmap; const Current, Total: Integer) of object; TOnSourceNotify = procedure(Sender: TObject; const Index: Integer) of object; TOnSourceFileTransfer = procedure(Sender: TObject; const Index: Integer; Filename: TW_STR255; Format: TTwainFormat; var Cancel: Boolean) of object; {Avaliable twain languages} TTwainLanguage = ({-1}tlUserLocale, tlDanish, tlDutch, tlInternationalEnglish, tlFrenchCanadian, tlFinnish, tlFrench, tlGerman, tlIcelandic, tlItalian, tlNorwegian, tlPortuguese, tlSpanish, tlSwedish, tlUsEnglish, tlAfrikaans, tlAlbania, tlArabic, tlArabicAlgeria, tlArabicBahrain, {18} tlArabicEgypt, tlArabicIraq, tlArabJordan, tlArabicKuwait, tlArabicLebanon, tlArabicLibya, tlArabicMorocco, tlArabicOman, tlArabicQatar, tlArabicSaudiarabia, tlArabicSyria, tlArabicTunisia, tlArabicUae, tlArabicYemen, tlBasque, tlByelorussian, tlBulgarian, {35} tlCatalan, tlChinese, tlChineseHongkong, tlChinesePeoplesRepublic, tlChineseSingapore, tlChineseSimplified, tlChineseTwain, {42} tlChineseTraditional, tlCroatia, tlCzech, tlDutchBelgian, {46} tlEnglishAustralian, tlEnglishCanadian, tlEnglishIreland, tlEnglishNewZealand, tlEnglishSouthAfrica, tlEnglishUk, {52} tlEstonian, tlFaeroese, tlFarsi, tlFrenchBelgian, tlFrenchLuxembourg, {57} tlFrenchSwiss, tlGermanAustrian, tlGermanLuxembourg, tlGermanLiechtenstein, tlGermanSwiss, tlGreek, tlHebrew, tlHungarian, tlIndonesian, {66} tlItalianSwiss, tlJapanese, tlKorean, tlKoreanJohab, tlLatvian, {71} tlLithuanian, tlNorewgianBokmal, tlNorwegianNynorsk, tlPolish, {75} tlPortugueseBrazil, tlRomanian, tlRussian, tlSerbianLatin, tlSlovak, tlSlovenian, tlSpanishMexican, tlSpanishModern, tlThai, tlTurkish, tlUkranian, tlAssamese, tlBengali, tlBihari, tlBodo, tlDogri, tlGujarati {92}, tlHarayanvi, tlHindi, tlKannada, tlKashmiri, tlMalayalam, tlMarathi, tlMarwari, tlMeghalayan, tlMizo, tlNaga {102}, tlOrissi, tlPunjabi, tlPushtu, tlSerbianCyrillic, tlSikkimi, tlSwidishFinland, tlTamil, tlTelugu, tlTripuri, tlUrdu, tlVietnamese); {Twain supported groups} TTwainGroups = set of (tgControl, tgImage, tgAudio); {Transfer mode for twain} TTwainTransferMode = (ttmFile, ttmNative, ttmMemory); {rect for LAYOUT; npeter 2004.01.12.} TTwainRect = record Left: double; Top: double; Right: double; Bottom: double; end; {Object to handle TW_IDENTITY} TTwainIdentity = class{$IFNDEF DONTUSEVCL}(TPersistent){$ENDIF} private {Structure which should be filled} Structure: TW_IDENTITY; {Owner} fOwner: {$IFNDEF DONTUSEVCL}TComponent{$ELSE}TObject{$ENDIF}; {Returns/sets application language property} function GetLanguage(): TTwainLanguage; procedure SetLanguage(const Value: TTwainLanguage); {Returns/sets text values} function GetString(const Index: integer): String; procedure SetString(const Index: Integer; const Value: String); {Returns/sets avaliable groups} function GetGroups(): TTwainGroups; procedure SetGroups(const Value: TTwainGroups); protected {$IFNDEF DONTUSEVCL}function GetOwner(): TPersistent; override;{$ENDIF} public {Object being created} {$IFNDEF DONTUSEVCL} constructor Create(AOwner: TComponent); {$ELSE} constructor Create(AOwner: TObject); {$ENDIF} {Copy properties from another TTwainIdentity} {$IFDEF DONTUSEVCL} procedure Assign(Source: TObject); {$ELSE} procedure Assign(Source: TPersistent); override; {$ENDIF} published {Application major version} property MajorVersion: TW_UINT16 read Structure.Version.MajorNum write Structure.Version.MajorNum; {Application minor version} property MinorVersion: TW_UINT16 read Structure.Version.MinorNum write Structure.Version.MinorNum; {Language} property Language: TTwainLanguage read GetLanguage write SetLanguage; {Country code} property CountryCode: word read Structure.Version.Country write Structure.Version.Country; {Supported groups} property Groups: TTwainGroups read GetGroups write SetGroups; {Text values} property VersionInfo: String index 0 read GetString write SetString; property Manufacturer: String index 1 read GetString write SetString; property ProductFamily: String index 2 read GetString write SetString; property ProductName: String index 3 read GetString write SetString; end; {Return set for capability retrieving/setting} TCapabilityRet = (crSuccess, crUnsupported, crBadOperation, crDependencyError, crLowMemory, crInvalidState, crInvalidContainer); {Kinds of capability retrieving} TRetrieveCap = (rcGet, rcGetCurrent, rcGetDefault, rcReset); {Capability list type} TGetCapabilityList = array of string; TSetCapabilityList = array of pointer; {Source object} TTwainSource = class(TTwainIdentity) private {Holds the item index} fIndex: Integer; {Transfer mode for the images} fTransferMode: TTwainTransferMode; {Stores if user interface should be shown} fShowUI: Boolean; {Stores if the source window is modal} fModal: Boolean; {Stores if the source is enabled} fEnabled: Boolean; {Stores if the source is loaded} fLoaded: Boolean; {Stores the owner} fOwner: TDelphiTwain; {Used with property SourceManagerLoaded to test if the source manager} {is loaded or not.} function GetSourceManagerLoaded(): Boolean; {Returns a pointer to the application} function GetAppInfo(): pTW_IDENTITY; {Sets if the source is loaded} procedure SetLoaded(const Value: Boolean); {Sets if the source is enabled} procedure SetEnabled(const Value: Boolean); {Returns a pointer to the source pTW_IDENTITY} function GetStructure: pTW_IDENTITY; {Returns a resolution} function GetResolution(Capability: TW_UINT16; var Return: Extended; var Values: TTwainResolution; Mode: TRetrieveCap): TCapabilityRet; protected {Reads a native image} procedure ReadNative(Handle: TW_UINT32; var Cancel: Boolean); {Reads the file image} procedure ReadFile(Name: TW_STR255; Format: TW_UINT16; var Cancel: Boolean); {Call event for memory image} procedure ReadMemory(Image: HBitmap; var Cancel: Boolean); protected {Prepare image memory transference} function PrepareMemXfer(var BitmapHandle: HBitmap; var PixelType: TW_INT16): TW_UINT16; {Transfer image memory} function TransferImageMemory(var ImageHandle: HBitmap; PixelType: TW_INT16): TW_UINT16; {Returns a pointer to the TW_IDENTITY for the application} property AppInfo: pTW_IDENTITY read GetAppInfo; {Method to transfer the images} procedure TransferImages(); {Message received in the event loop} function ProcessMessage(const Msg: TMsg): Boolean; {Returns if the source manager is loaded} property SourceManagerLoaded: Boolean read GetSourceManagerLoaded; {Source configuration methods} {************************} protected {Gets an item and returns it in a string} procedure GetItem(var Return: String; ItemType: TW_UINT16; Data: Pointer); {Converts from a result to a TCapabilityRec} function ResultToCapabilityRec(const Value: TW_UINT16): TCapabilityRet; {Sets a capability} function SetCapabilityRec(const Capability, ConType: TW_UINT16; Data: HGLOBAL): TCapabilityRet; public {Returns a capability strucutre} function GetCapabilityRec(const Capability: TW_UINT16; var Handle: HGLOBAL; Mode: TRetrieveCap; var Container: TW_UINT16): TCapabilityRet; {************************} {Returns an one value capability} function GetOneValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var Value: string; Mode: TRetrieveCap{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}; MemHandle: HGLOBAL{$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet; {Returns an range capability} function GetRangeValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var Min, Max, Step, Default, Current: String; MemHandle: HGLOBAL{$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet; {Returns an enumeration capability} function GetEnumerationValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var List: TGetCapabilityList; var Current, Default: Integer; Mode: TRetrieveCap{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}; MemHandle: HGLOBAL{$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet; {Returns an array capability} function GetArrayValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var List: TGetCapabilityList; MemHandle: HGLOBAL {$IFDEF DEFAULTPARAM}=0{$ENDIF}): TCapabilityRet; {************************} {Sets an one value capability} function SetOneValue(Capability: TW_UINT16; ItemType: TW_UINT16; Value: Pointer): TCapabilityRet; {Sets a range capability} function SetRangeValue(Capability, ItemType: TW_UINT16; Min, Max, Step, Current: TW_UINT32): TCapabilityRet; {Sets an enumeration capability} function SetEnumerationValue(Capability, ItemType: TW_UINT16; CurrentIndex: TW_UINT32; List: TSetCapabilityList): TCapabilityRet; {Sets an array capability} function SetArrayValue(Capability, ItemType: TW_UINT16; List: TSetCapabilityList): TCapabilityRet; public {Setup file transfer} function SetupFileTransfer(Filename: String; Format: TTwainFormat): Boolean; function SetupFileTransferTWFF(Filename: String; Format: TW_UINT16): Boolean; protected {Used with property PendingXfers} function GetPendingXfers(): TW_INT16; public {Set source transfer mode} function ChangeTransferMode(NewMode: TTwainTransferMode): TCapabilityRet; {Returns return status information} function GetReturnStatus(): TW_UINT16; {Capability setting} {Set the number of images that the application wants to receive} function SetCapXferCount(Value: SmallInt): TCapabilityRet; {Returns the number of images that the source will return} function GetCapXferCount(var Return: SmallInt; Mode: TRetrieveCap{$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; {Retrieve the unit measure for all quantities} function GetICapUnits(var Return: TTwainUnit; var Supported: TTwainUnitSet; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; {Set the unit measure} function SetICapUnits(Value: TTwainUnit): TCapabilityRet; {npeter 2004.01.12 begin} function SetImagelayoutFrame(const fLeft,fTop,fRight, fBottom: double): TCapabilityRet; function SetIndicators(Value: boolean): TCapabilityRet; {npeter 2004.01.12 end} {Retrieve the pixel flavor values} function GetIPixelFlavor(var Return: TTwainPixelFlavor; var Supported: TTwainPixelFlavorSet; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; {Set the pixel flavor values} function SetIPixelFlavor(Value: TTwainPixelFlavor): TCapabilityRet; {Returns bitdepth values} function GetIBitDepth(var Return: Word; var Supported: TTwainBitDepth; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; {Set current bitdepth value} function SetIBitDepth(Value: Word): TCapabilityRet; {Returns pixel type values} function GetIPixelType(var Return: TTwainPixelType; var Supported: TTwainPixelTypeSet; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; {Set the pixel type value} function SetIPixelType(Value: TTwainPixelType): TCapabilityRet; {Returns X and Y resolutions} function GetIXResolution(var Return: Extended; var Values: TTwainResolution; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; function GetIYResolution(var Return: Extended; var Values: TTwainResolution; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; {Sets X and X resolutions} function SetIXResolution(Value: Extended): TCapabilityRet; function SetIYResolution(Value: Extended): TCapabilityRet; {Returns physical width and height} function GetIPhysicalWidth(var Return: Extended; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; function GetIPhysicalHeight(var Return: Extended; Mode: TRetrieveCap {$IFDEF DEFAULTPARAM}=rcGet{$ENDIF}): TCapabilityRet; {Returns if user interface is controllable} function GetUIControllable(var Return: Boolean): TCapabilityRet; {Returns feeder is loaded or not} function GetFeederLoaded(var Return: Boolean): TCapabilityRet; {Returns/sets if feeder is enabled} function GetFeederEnabled(var Return: Boolean): TCapabilityRet; function SetFeederEnabled(Value: WordBool): TCapabilityRet; {Returns/sets if auto feed is enabled} function GetAutofeed(var Return: Boolean): TCapabilityRet; function SetAutoFeed(Value: WordBool): TCapabilityRet; {Returns number of pending transfer} property PendingXfers: TW_INT16 read GetPendingXfers; public {Enables the source} function EnableSource(ShowUI, Modal: Boolean): Boolean; {Disables the source} function DisableSource: Boolean; {Loads the source} function LoadSource(): Boolean; {Unloads the source} function UnloadSource(): Boolean; {Returns a pointer to the source identity} property SourceIdentity: pTW_IDENTITY read GetStructure; {Returns/sets if the source is enabled} property Enabled: Boolean read fEnabled write SetEnabled; {Returns/sets if this source is loaded} property Loaded: Boolean read fLoaded write SetLoaded; {Object being created/destroyed} constructor Create(AOwner: TDelphiTwain); destructor Destroy; override; {Returns owner} property Owner: TDelphiTwain read fOwner; {Source window is modal} property Modal: Boolean read fModal write fModal; {Sets if user interface should be shown} property ShowUI: Boolean read fShowUI write fShowUI; {Transfer mode for transfering images from the source to} {the component and finally to the application} property TransferMode: TTwainTransferMode read fTransferMode write fTransferMode; {Returns the item index} property Index: Integer read fIndex; {Convert properties from write/read to read only} {(read description on TTwainIdentity source)} property MajorVersion: TW_UINT16 read Structure.Version.MajorNum; property MinorVersion: TW_UINT16 read Structure.Version.MinorNum; property Language: TTwainLanguage read GetLanguage; property CountryCode: word read Structure.Version.Country; property Groups: TTwainGroups read GetGroups; property VersionInfo: String index 0 read GetString; property Manufacturer: String index 1 read GetString; property ProductFamily: String index 2 read GetString; property ProductName: String index 3 read GetString; end; {Component part} TDelphiTwain = class(TTwainComponent) private {Should contain the number of Twain sources loaded} fSourcesLoaded: Integer; {Contains if the select source dialog is being displayed} SelectDialogDisplayed: Boolean; private {Event pointer holders} fOnSourceDisable: TOnSourceNotify; fOnAcquireCancel: TOnSourceNotify; fOnTwainAcquire: TOnTwainAcquire; fOnSourceSetupFileXfer: TOnSourceNotify; fOnSourceFileTransfer: TOnSourceFileTransfer; fOnAcquireError: TOnTwainError; fOnAcquireProgress: TOnAcquireProgress; private {Temp variable to allow SourceCount to be displayed in delphi} {property editor} fDummySourceCount: integer; {Contains list of source devices} DeviceList: TPointerList; {Contains a pointer to the structure with the application} {information} AppInfo: pTW_IDENTITY; {Holds the object to allow the user to set the application information} fInfo: TTwainIdentity; {Holds the handle for the virtual window which will receive} {twain message notifications} VirtualWindow: THandle; {Will hold Twain library handle} fHandle: HInst; {Holds if the component has enumerated the devices} fHasEnumerated: Boolean; {Holds twain dll procedure handle} fTwainProc: TDSMEntryProc; {Holds the transfer mode to be used} fTransferMode: TTwainTransferMode; {Contains if the library is loaded} fLibraryLoaded: Boolean; {Contains if the source manager was loaded} fSourceManagerLoaded: Boolean; {Procedure to load and unload twain library and update property} procedure SetLibraryLoaded(const Value: Boolean); {Procedure to load or unloaded the twain source manager} procedure SetSourceManagerLoaded(const Value: Boolean); {Updates the application information object} procedure SetInfo(const Value: TTwainIdentity); {Returns the number of sources} function GetSourceCount(): Integer; {Returns a source from the list} function GetSource(Index: Integer): TTwainSource; {Finds a matching source index} function FindSource(Value: pTW_IDENTITY): Integer; protected {Returns the default source} function GetDefaultSource: Integer; {Creates the virtual window} procedure CreateVirtualWindow(); {Clears the list of sources} procedure ClearDeviceList(); public {Allows Twain to display a dialog to let the user choose any source} {and returns the source index in the list} function SelectSource(): Integer; {Returns the number of loaded sources} property SourcesLoaded: Integer read fSourcesLoaded; {Enumerate the avaliable devices after Source Manager is loaded} function EnumerateDevices(): Boolean; {Object being created} {$IFNDEF DONTUSEVCL} constructor Create(AOwner: TComponent);override; {$ELSE} constructor Create; {$ENDIF} {Object being destroyed} destructor Destroy(); override; {Loads twain library and returns if it loaded sucessfully} function LoadLibrary(): Boolean; {Unloads twain and returns if it unloaded sucessfully} function UnloadLibrary(): Boolean; {Loads twain source manager} function LoadSourceManager(): Boolean; {Unloads the source manager} function UnloadSourceManager(forced: boolean): Boolean; {Returns the application TW_IDENTITY} property AppIdentity: pTW_IDENTITY read AppInfo; {Returns Twain library handle} property Handle: HInst read fHandle; {Returns a pointer to Twain only procedure} property TwainProc: TDSMEntryProc read fTwainProc; {Holds if the component has enumerated the devices} property HasEnumerated: Boolean read fHasEnumerated; {Returns a source} property Source[Index: Integer]: TTwainSource read GetSource; published {Events} {Source being disabled} property OnSourceDisable: TOnSourceNotify read fOnSourceDisable write fOnSourceDisable; {Acquire cancelled} property OnAcquireCancel: TOnSourceNotify read fOnAcquireCancel write fOnAcquireCancel; {Image acquired} property OnTwainAcquire: TOnTwainAcquire read fOnTwainAcquire write fOnTwainAcquire; {User should set information to prepare for the file transfer} property OnSourceSetupFileXfer: TOnSourceNotify read fOnSourceSetupFileXfer write fOnSourceSetupFileXfer; {File transfered} property OnSourceFileTransfer: TOnSourceFileTransfer read fOnSourceFileTransfer write fOnSourceFileTransfer; {Acquire error} property OnAcquireError: TOnTwainError read fOnAcquireError write fOnAcquireError; {Acquire progress, for memory transfers} property OnAcquireProgress: TOnAcquireProgress read fOnAcquireProgress write fOnAcquireProgress; published {Default transfer mode to be used with sources} property TransferMode: TTwainTransferMode read fTransferMode write fTransferMode; {Returns the number of sources, after Library and Source Manager} {has being loaded} property SourceCount: Integer read GetSourceCount write fDummySourceCount; {User should fill the application information} property Info: TTwainIdentity read fInfo write SetInfo; {Loads or unload Twain library} property LibraryLoaded: Boolean read fLibraryLoaded write SetLibraryLoaded; {Loads or unloads the source manager} property SourceManagerLoaded: Boolean read fSourceManagerLoaded write SetSourceManagerLoaded; end; {Puts a string inside a TW_STR255} function StrToStr255(Value: String): TW_STR255; {This method returns if Twain is installed in the current machine} function IsTwainInstalled(): Boolean; {Called by Delphi to register the component} procedure Register(); {Returns the size of a twain type} function TWTypeSize(TypeName: TW_UINT16): Integer; implementation {Units used bellow} uses Messages; {Called by Delphi to register the component} procedure Register(); begin {$IFNDEF DONTUSEVCL} RegisterComponents('NP', [TDelphiTwain]); {$ENDIF} end; {Returns the size of a twain type} function TWTypeSize(TypeName: TW_UINT16): Integer; begin {Test the type to return the size} case TypeName of TWTY_INT8 : Result := sizeof(TW_INT8); TWTY_UINT8 : Result := sizeof(TW_UINT8); TWTY_INT16 : Result := sizeof(TW_INT16); TWTY_UINT16: Result := sizeof(TW_UINT16); TWTY_INT32 : Result := sizeof(TW_INT32); TWTY_UINT32: Result := sizeof(TW_UINT32); TWTY_FIX32 : Result := sizeof(TW_FIX32); TWTY_FRAME : Result := sizeof(TW_FRAME); TWTY_STR32 : Result := sizeof(TW_STR32); TWTY_STR64 : Result := sizeof(TW_STR64); TWTY_STR128: Result := sizeof(TW_STR128); TWTY_STR255: Result := sizeof(TW_STR255); //npeter: the following types were not implemented //especially the bool caused problems TWTY_BOOL: Result := sizeof(TW_BOOL); TWTY_UNI512: Result := sizeof(TW_UNI512); TWTY_STR1024: Result := sizeof(TW_STR1024); else Result := 0; end {case} end; {Puts a string inside a TW_STR255} function StrToStr255(Value: String): TW_STR255; begin {Clean result} Fillchar(Result, sizeof(TW_STR255), #0); {If value fits inside the TW_STR255, copy memory} if Length(Value) <= sizeof(TW_STR255) then CopyMemory(@Result[0], @Value[1], Length(Value)) else CopyMemory(@Result[0], @Value[1], sizeof(TW_STR255)); end; {Returns full Twain directory (usually in Windows directory)} function GetTwainDirectory(): String; var i: TDirectoryKind; Dir: String; begin {Searches in all the directories} FOR i := LOW(TDirectoryKind) TO HIGH(TDirectoryKind) DO begin {Directory to search} Dir := GetCustomDirectory(i); {Tests if the file exists in this directory} if FileExists(Dir + TWAINLIBRARY) then begin {In case it exists, returns this directory and exit} {the for loop} Result := Dir; Break; end {if FileExists} end {FOR i} end; {This method returns if Twain is installed in the current machine} function IsTwainInstalled(): Boolean; begin {If GetTwainDirectory function returns an empty string, it means} {that Twain was not found} Result := (GetTwainDirectory() <> ''); end; { TTwainIdentity object implementation } {Object being created} {$IFNDEF DONTUSEVCL} constructor TTwainIdentity.Create(AOwner: TComponent); {$ELSE} constructor TTwainIdentity.Create(AOwner: TObject); {$ENDIF} begin {Allows ancestor to work} inherited Create; {Set initial properties} FillChar(Structure, sizeof(Structure), #0); Language := tlUserLocale; CountryCode := 1; MajorVersion := 1; VersionInfo := 'Application name'; Structure.ProtocolMajor := TWON_PROTOCOLMAJOR; Structure.ProtocolMinor := TWON_PROTOCOLMINOR; Groups := [tgImage, tgControl]; Manufacturer := 'Application manufacturer'; ProductFamily := 'App product family'; ProductName := 'App product name'; fOwner := AOwner; {Copy owner pointer} end; {$IFNDEF DONTUSEVCL} function TTwainIdentity.GetOwner(): TPersistent; begin Result := fOwner; end; {$ENDIF} {Sets a text value} procedure TTwainIdentity.SetString(const Index: Integer; const Value: String); var PropStr: PChar; begin {Select and copy pointer} case Index of 0: PropStr := @Structure.Version.Info[0]; 1: PropStr := @Structure.Manufacturer[0]; 2: PropStr := @Structure.ProductFamily[0]; else PropStr := @Structure.ProductName[0]; end {case}; {Set value} Fillchar(PropStr^, sizeof(TW_STR32), #0); if Length(Value) > sizeof(TW_STR32) then CopyMemory(PropStr, @Value[1], sizeof(TW_STR32)) else CopyMemory(PropStr, @Value[1], Length(Value)); end; {Returns a text value} function TTwainIdentity.GetString(const Index: Integer): String; begin {Test for the required property} case Index of 0: Result := Structure.Version.Info; 1: Result := Structure.Manufacturer; 2: Result := Structure.ProductFamily; else Result := Structure.ProductName; end {case} end; {Returns application language property} function TTwainIdentity.GetLanguage(): TTwainLanguage; begin Result := TTwainLanguage(Structure.Version.Language + 1); end; {Sets application language property} procedure TTwainIdentity.SetLanguage(const Value: TTwainLanguage); begin Structure.Version.Language := Word(Value) - 1; end; {Copy properties from another TTwainIdentity} {$IFDEF DONTUSEVCL} procedure TTwainIdentity.Assign(Source: TObject); {$ELSE} procedure TTwainIdentity.Assign(Source: TPersistent); {$ENDIF} begin {The source should also be a TTwainIdentity} if Source is TTwainIdentity then {Copy properties} Structure := TTwainIdentity(Source).Structure else {$IFNDEF DONTUSEVCL}inherited; {$ENDIF} end; {Returns avaliable groups} function TTwainIdentity.GetGroups(): TTwainGroups; begin {Convert from Structure.SupportedGroups to TTwainGroups} Include(Result, tgControl); if DG_IMAGE AND Structure.SupportedGroups <> 0 then Include(Result, tgImage); if DG_AUDIO AND Structure.SupportedGroups <> 0 then Include(Result, tgAudio); end; {Sets avaliable groups} procedure TTwainIdentity.SetGroups(const Value: TTwainGroups); begin {Convert from TTwainGroups to Structure.SupportedGroups} Structure.SupportedGroups := DG_CONTROL; if tgImage in Value then Structure.SupportedGroups := Structure.SupportedGroups or DG_IMAGE; if tgAudio in Value then Structure.SupportedGroups := Structure.SupportedGroups or DG_AUDIO; end; { TDelphiTwain component implementation } {Loads twain library and returns if it loaded sucessfully} function TDelphiTwain.LoadLibrary(): Boolean; var TwainDirectory: String; begin {The library must not be already loaded} if (not LibraryLoaded) then begin Result := FALSE; {Initially returns FALSE} {Searches for Twain directory} TwainDirectory := GetTwainDirectory(); {Continue only if twain is installed in an known directory} if TwainDirectory <> '' then begin fHandle := Windows.LoadLibrary(PChar(TwainDirectory + TWAINLIBRARY)); {If the library was sucessfully loaded} if (fHandle <> INVALID_HANDLE_VALUE) then begin {Obtains method handle} @fTwainProc := GetProcAddress(fHandle, MAKEINTRESOURCE(1)); {Returns TRUE/FALSE if the method was obtained} Result := (@fTwainProc <> nil); {If the method was not obtained, also free the library} if not Result then begin {Free the handle and clears the variable} Windows.FreeLibrary(fHandle); fHandle := 0; end {if not Result} end else {If it was not loaded, clears handle value} fHandle := 0; end {if TwainDirectory <> ''}; end else {If it was already loaded, returns true, since that is} {what was supposed to happen} Result := TRUE; {In case the method was sucessful, updates property} if Result then fLibraryLoaded := TRUE; end; {Unloads twain and returns if it unloaded sucessfully} function TDelphiTwain.UnloadLibrary(): Boolean; begin {The library must not be already unloaded} if (LibraryLoaded) then begin {Unloads the source manager} SourceManagerLoaded := FALSE; {Just call windows method to unload} Result := Windows.FreeLibrary(Handle); {If it was sucessfull, also clears handle value} if Result then fHandle := 0; {Updates property} fLibraryLoaded := not Result; end else {If it was already unloaded, returns true, since that is} {what was supposed to happen} Result := TRUE; {In case the method was sucessful, updates property} if Result then fLibraryLoaded := FALSE; end; {Enumerate the avaliable devices after Source Manager is loaded} function TDelphiTwain.EnumerateDevices(): Boolean; var NewSource: TTwainSource; CallRes : TW_UINT16; begin {Booth library and source manager must be loaded} if (LibraryLoaded and SourceManagerLoaded) then begin {Clears the preview list of sources} ClearDeviceList(); {Allocate new identity and tries to enumerate} NewSource := TTwainSource.Create(Self); CallRes := TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY, MSG_GETFIRST, @NewSource.Structure); if CallRes = TWRC_SUCCESS then repeat {Add this item to the list} DeviceList.Add(NewSource); {Allocate memory for the next} NewSource := TTwainSource.Create(Self); NewSource.TransferMode := Self.TransferMode; NewSource.fIndex := DeviceList.Count; {Try to get the next item} until TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY, MSG_GETNEXT, @NewSource.Structure) <> TWRC_SUCCESS; {Set that the component has enumerated the devices} {if everything went correctly} Result := TRUE; fHasEnumerated := Result; {Dispose un-needed source object} NewSource.Free; end else Result := FALSE; {If library and source manager aren't loaded} end; {Procedure to load and unload twain library and update property} procedure TDelphiTwain.SetLibraryLoaded(const Value: Boolean); begin {The value must be changing to activate} if (Value <> fLibraryLoaded) then begin {Depending on the parameter load/unload the library and updates} {property whenever it loaded or unloaded sucessfully} if Value then LoadLibrary() else {if not Value then} UnloadLibrary(); end {if (Value <> fLibraryLoaded)} end; {Loads twain source manager} function TDelphiTwain.LoadSourceManager(): Boolean; begin {The library must be loaded} if LibraryLoaded and not SourceManagerLoaded then {Loads source manager} Result := (fTwainProc(AppInfo, nil, DG_CONTROL, DAT_PARENT, MSG_OPENDSM, @VirtualWindow) = TWRC_SUCCESS) else {The library is not loaded, thus the source manager could} {not be loaded} Result := FALSE or SourceManagerLoaded; {In case the method was sucessful, updates property} if Result then fSourceManagerLoaded := TRUE; end; {UnLoads twain source manager} function TDelphiTwain.UnloadSourceManager(forced: boolean): Boolean; begin {The library must be loaded} if LibraryLoaded and SourceManagerLoaded then begin {Clears the list of sources} ClearDeviceList(); {Unload source manager} if not forced then Result := (TwainProc(AppInfo, nil, DG_CONTROL, DAT_PARENT, MSG_CLOSEDSM, @VirtualWindow) = TWRC_SUCCESS) else result:=true; end else {The library is not loaded, meaning that the Source Manager isn't either} Result := TRUE; {In case the method was sucessful, updates property} if Result then fSourceManagerLoaded := FALSE; end; {Procedure to load or unloaded the twain source manager} procedure TDelphiTwain.SetSourceManagerLoaded(const Value: Boolean); begin {The library must be loaded to have access to the method} if LibraryLoaded and (Value <> fSourceManagerLoaded) then begin {Load/unload the source manager} if Value then LoadSourceManager() else {if not Value then} UnloadSourceManager(false); end {if LibraryLoaded} end; {Clears the list of sources} procedure TDelphiTwain.ClearDeviceList(); var i: Integer; begin {Deallocate pTW_IDENTITY} FOR i := 0 TO DeviceList.Count - 1 DO TTwainSource(DeviceList.Item[i]).Free; {Clears the list} DeviceList.Clear; {Set trigger to tell that it has not enumerated again yet} fHasEnumerated := FALSE; end; {Finds a matching source index} function TDelphiTwain.FindSource(Value: pTW_IDENTITY): Integer; var i : Integer; begin Result := -1; {Default result} {Search for this source in the list} for i := 0 TO SourceCount - 1 DO if CompareMem(@Source[i].Structure, pChar(Value), SizeOf(TW_IDENTITY)) then begin {Return index and exit} Result := i; break; end; {if CompareMem, for i} end; {Allows Twain to display a dialog to let the user choose any source} {and returns the source index in the list} function TDelphiTwain.SelectSource: Integer; var Identity: TW_IDENTITY; begin Result := -1; {Default result} {Booth library and source manager must be loaded} if (LibraryLoaded and SourceManagerLoaded and not SelectDialogDisplayed) then begin {Don't allow this dialog to be displayed twice} SelectDialogDisplayed := TRUE; {Call twain to display the dialog} if TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY, MSG_USERSELECT, @Identity) = TWRC_SUCCESS then Result := FindSource(@Identity); {Ended using} SelectDialogDisplayed := FALSE end {(LibraryLoaded and SourceManagerLoaded)} end; {Returns the number of sources} function TDelphiTwain.GetSourceCount(): Integer; begin {Library and source manager must be loaded} if (LibraryLoaded and SourceManagerLoaded) then begin {Enumerate devices, if needed} if not HasEnumerated then EnumerateDevices(); {Returns} Result := DeviceList.Count; end {In case library and source manager aren't loaded, returns 0} else Result := 0 end; {Returns the default source} function TDelphiTwain.GetDefaultSource: Integer; var Identity: TW_IDENTITY; begin {Call twain to display the dialog} if SourceManagerLoaded and (TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY, MSG_GETDEFAULT, @Identity) = TWRC_SUCCESS) then Result := FindSource(@Identity) else Result := 0 {Returns} end; {Returns a source from the list} function TDelphiTwain.GetSource(Index: Integer): TTwainSource; begin {Booth library and source manager must be loaded} if (LibraryLoaded and SourceManagerLoaded) then begin {If index is in range, returns} {(Call to SourceCount property enumerates the devices, if needed)} if Index in [0..SourceCount - 1] then Result := DeviceList.Item[Index] else if (Index = -1) and (SourceCount > 0) then Result := DeviceList.Item[GetDefaultSource] {Unknown object, returns nil} else Result := nil; end {In case either the library or the source manager aren't} {loaded, it returns nil} else Result := nil end; {Object being created} constructor TDelphiTwain.Create{$IFNDEF DONTUSEVCL}(AOwner: TComponent){$ENDIF}; begin {Let the ancestor class also handle the call} inherited; {Create source list} DeviceList := TPointerList.Create; {Clear variables} fSourcesLoaded := 0; fHandle := 0; @fTwainProc := nil; SelectDialogDisplayed := FALSE; fSourceManagerLoaded := FALSE; fHasEnumerated := FALSE; fTransferMode := ttmMemory; {Creates the virtual window which will intercept messages} {from Twain} CreateVirtualWindow(); {Creates the object to allow the user to set the application} {information to inform twain source manager and sources} fInfo := TTwainIdentity.Create(Self); AppInfo := @fInfo.Structure; end; {Object being destroyed} destructor TDelphiTwain.Destroy; begin {Full unload the library} LibraryLoaded := FALSE; {Free the virtual window handle} DestroyWindow(VirtualWindow); {Free the object} fInfo.Free; {Clears and free source list} ClearDeviceList(); DeviceList.Free(); {Let ancestor class handle} inherited Destroy; end; {Creates the virtual window} procedure TDelphiTwain.CreateVirtualWindow; begin {Creates the window and passes a pointer to the class object} VirtualWindow := CreateWindow(VIRTUALWIN_CLASSNAME, 'Delphi Twain virtual ' + 'window', 0, 10, 10, 100, 100, 0, 0, hInstance, Self); end; {Updates the application information object} procedure TDelphiTwain.SetInfo(const Value: TTwainIdentity); begin {Assign one object to another} fInfo.Assign(Value); end; { TTwainSource object implementation } {Used with property SourceManagerLoaded to test if the source manager} {is loaded or not.} function TTwainSource.GetSourceManagerLoaded: Boolean; begin {Obtain information from owner TDelphiTwain} Result := Owner.SourceManagerLoaded; end; {Sets if the source is loaded} procedure TTwainSource.SetLoaded(const Value: Boolean); begin {Value should be changing} if (Value <> fLoaded) then begin {Loads or unloads the source} if Value then LoadSource() else {if not Value then} UnloadSource(); end {if (Value <> fLoaded)} end; {Sets if the source is enabled} procedure TTwainSource.SetEnabled(const Value: Boolean); begin {Source must be already enabled and value changing} if (Loaded) and (Value <> fEnabled) then begin {Enables/disables} if Value then EnableSource(ShowUI, Modal) else {if not Value then} DisableSource(); end {if (Loaded) and (Value <> fEnabled)} end; {Enables the source} function TTwainSource.EnableSource(ShowUI, Modal: Boolean): Boolean; var twUserInterface: TW_USERINTERFACE; begin {Source must be loaded and the value changing} if (Loaded) and (not Enabled) then begin {Builds UserInterface structure} twUserInterface.ShowUI := ShowUI; twUserInterface.ModalUI := Modal; twUserInterface.hParent := owner.VirtualWindow; //npeter may be it is better to send messages to VirtualWindow //I am not sure, but it seems more stable with a HP TWAIN driver //it was: := GetActiveWindow; fEnabled := TRUE; {Call method} Result := (Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_USERINTERFACE, MSG_ENABLEDS, @twUserInterface) in [TWRC_SUCCESS, TWRC_CHECKSTATUS]); end else {If it's either not loaded or already enabled} {If it is not loaded} Result := FALSE or Enabled; {Updates property} if (Result = TRUE) then fEnabled := TRUE; end; {Disables the source} function TTwainSource.DisableSource(): Boolean; var twUserInterface: TW_USERINTERFACE; begin {Source must be loaded and the value changing} if (Loaded) and (Enabled) then begin {Call method} Result := (Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_USERINTERFACE, MSG_DISABLEDS, @twUserInterface) = TWRC_SUCCESS); {Call notification event if being used} if (Result) and (Assigned(Owner.OnSourceDisable)) then Owner.OnSourceDisable(Owner, Index); end else {If it's either not loaded or already disabled} {If it is not loaded} Result := TRUE; {Updates property} if (Result = TRUE) then fEnabled := FALSE; end; {Loads the source} function TTwainSource.LoadSource: Boolean; begin {Only loads if it is not already loaded} if Not Loaded then begin Result := (Owner.TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY, MSG_OPENDS, @Structure) = TWRC_SUCCESS); {Increase the loaded sources count variable} if Result then inc(Owner.fSourcesLoaded); end else {If it was already loaded, returns true} Result := TRUE; {In case the method was sucessful, updates property} if Result then fLoaded := TRUE; end; {Unloads the source} function TTwainSource.UnloadSource: Boolean; begin {Only unloads if it is loaded} if Loaded then begin {If the source was enabled, disable it} DisableSource(); {Call method to load} Result := (Owner.TwainProc(AppInfo, nil, DG_CONTROL, DAT_IDENTITY, MSG_CLOSEDS, @Structure) = TWRC_SUCCESS); {Decrease the loaded sources count variable} if Result then dec(Owner.fSourcesLoaded); end else {If it was already unloaded, returns true} Result := TRUE; {In case the method was sucessful, updates property} fLoaded := FALSE; end; {Object being destroyed} destructor TTwainSource.Destroy; begin {If loaded, unloads source} UnloadSource(); {Let ancestor class process} inherited Destroy; end; {Returns a pointer to the application} function TTwainSource.GetAppInfo: pTW_IDENTITY; begin Result := Owner.AppInfo; end; {Returns a pointer to the source identity} function TTwainSource.GetStructure: pTW_IDENTITY; begin Result := @Structure; end; {Object being created} constructor TTwainSource.Create(AOwner: TDelphiTwain); begin {Allows ancestor class to process} inherited Create(AOwner); {Initial values} fTransferMode := ttmNative; fLoaded := FALSE; fShowUI := TRUE; fEnabled := FALSE; fModal := TRUE; {Stores owner} fOwner := AOwner; end; {Set source transfer mode} function TTwainSource.ChangeTransferMode( NewMode: TTwainTransferMode): TCapabilityRet; const TransferModeToTwain: Array[TTwainTransferMode] of TW_UINT16 = (TWSX_FILE, TWSX_NATIVE, TWSX_MEMORY); var Value: TW_UINT16; begin {Set transfer mode method} Value := TransferModeToTwain[NewMode]; Result := SetOneValue(ICAP_XFERMECH, TWTY_UINT16, @Value); TransferMode := NewMode; end; {Message received in the event loop} function TTwainSource.ProcessMessage(const Msg: TMsg): Boolean; var twEvent: TW_EVENT; begin {Make twEvent structure} twEvent.TWMessage := MSG_NULL; twEvent.pEvent := TW_MEMREF(@Msg); {Call Twain procedure to handle message} Result := (Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_EVENT, MSG_PROCESSEVENT, @twEvent) = TWRC_DSEVENT); {If it is a message from the source, process} if Result then case twEvent.TWMessage of {No message from the source} MSG_NULL: exit; {Requested to close the source} MSG_CLOSEDSREQ: begin {Call notification event} if (Assigned(Owner.OnAcquireCancel)) then Owner.OnAcquireCancel(Owner, Index); {Disable the source} DisableSource(); end; {Ready to transfer the images} MSG_XFERREADY: {Call method to transfer} TransferImages(); MSG_CLOSEDSOK: result:=true; MSG_DEVICEEVENT: result:=true; end {case twEvent.TWMessage} end; {Returns return status information} function TTwainSource.GetReturnStatus: TW_UINT16; var StatusInfo: TW_STATUS; begin {The source must be loaded in order to get the status} if Loaded then begin {Call method to get the information} Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_STATUS, MSG_GET, @StatusInfo); Result := StatusInfo.ConditionCode; end else Result := 0 {In case it was called while the source was not loaded} end; {Converts from a result to a TCapabilityRec} function TTwainSource.ResultToCapabilityRec( const Value: TW_UINT16): TCapabilityRet; begin {Test result code to return} case Value of {Successull, copy handle and return a success value} TWRC_SUCCESS: Result := crSuccess; {Error, get more on the error, and return result} {case} else case GetReturnStatus() of TWCC_CAPUNSUPPORTED: Result := crUnsupported; TWCC_CAPBADOPERATION: Result := crBadOperation; TWCC_CAPSEQERROR: Result := crDependencyError; TWCC_LOWMEMORY: Result := crLowMemory; TWCC_SEQERROR: Result := crInvalidState; else Result := crBadOperation; end {case GetReturnStatus of} end {case}; end; {Sets a capability} function TTwainSource.SetCapabilityRec(const Capability, ConType: TW_UINT16; Data: HGlobal): TCapabilityRet; var CapabilityInfo: TW_CAPABILITY; begin {Source must be loaded to set} if Loaded then begin {Fill structure} CapabilityInfo.Cap := Capability; CapabilityInfo.ConType := ConType; CapabilityInfo.hContainer := Data; {Call method and store return} Result := ResultToCapabilityRec(Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_CAPABILITY, MSG_SET, @CapabilityInfo)); end else Result := crInvalidState {In case the source is not loaded} end; {Returns a capability strucutre} function TTwainSource.GetCapabilityRec( const Capability: TW_UINT16; var Handle: HGLOBAL; Mode: TRetrieveCap; var Container: TW_UINT16): TCapabilityRet; const ModeToTwain: Array[TRetrieveCap] of TW_UINT16 = (MSG_GET, MSG_GETCURRENT, MSG_GETDEFAULT, MSG_RESET); var CapabilityInfo: TW_CAPABILITY; begin {Source must be loaded} if Loaded then begin {Fill structure} CapabilityInfo.Cap := Capability; CapabilityInfo.ConType := TWON_DONTCARE16; CapabilityInfo.hContainer := 0; {Call method and store return} Result := ResultToCapabilityRec(Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_CAPABILITY, ModeToTwain[Mode], @CapabilityInfo)); if Result = crSuccess then begin Handle := CapabilityInfo.hContainer; Container := CapabilityInfo.ConType; end end {if not Loaded} else Result := crInvalidState {In case the source is not loaded} end; {Gets an item and returns it in a string} procedure TTwainSource.GetItem(var Return: String; ItemType: TW_UINT16; Data: Pointer); begin {Test the item type} case ItemType of TWTY_INT8 : Return := IntToStr(pTW_INT8(Data)^); TWTY_UINT8 : Return := IntToStr(pTW_UINT8(Data)^); TWTY_INT16, 44 {TWTY_HANDLE} : Return := IntToStr(pTW_INT16(Data)^); TWTY_UINT16, TWTY_BOOL : Return := IntToStr(pTW_UINT16(Data)^); TWTY_INT32 : Return := IntToStr(pTW_INT32(Data)^); TWTY_UINT32, 43 {TWTY_MEMREF} : Return := IntToStr(pTW_UINT32(Data)^); {Floating integer type} TWTY_FIX32: with pTW_FIX32(Data)^ do //npeter bugfix: //it is better to use the actual decimal separator //and not a wired in value! //If not, you may get error on strtofloat //original: Return := IntToStr(Whole) + ',' + IntToStr(Frac); Return := IntToStr(Whole) + decimalseparator + IntToStr(Frac); {String types, which are all ended by a null char (#0)} TWTY_STR32, TWTY_STR64, TWTY_STR128, TWTY_STR255 : Return := PChar(Data); end {case ItemType} end; {Returns an array capability} function TTwainSource.GetArrayValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var List: TGetCapabilityList; MemHandle: HGLOBAL): TCapabilityRet; var ArrayV : pTW_ARRAY; ItemSize : Integer; Data : PChar; CurItem : Integer; Value : String; Container: TW_UINT16; begin {Call method to get the memory to the return} if MemHandle = 0 then Result := GetCapabilityRec(Capability, MemHandle, rcGet, Container) else begin Result := crSuccess; Container := TWON_ARRAY; end; if (Result = crSuccess) and (Container <> TWON_ARRAY) then begin Result := crInvalidContainer; GlobalFree(MemHandle); Exit; end; {If result was sucessfull and memory was allocated} if (Result = crSuccess) then begin {Obtain structure pointer} ArrayV := GlobalLock(MemHandle); {Fill return properties} ItemType := ArrayV^.ItemType; {Prepare to list items} ItemSize := TWTypeSize(ItemType); Data := @ArrayV^.ItemList[0]; SetLength(List, ArrayV^.NumItems); {Copy items} for CurItem := 0 TO ArrayV^.NumItems - 1 do begin {Obtain this item} GetItem(Value, ItemType, Data); List[CurItem] := Value; {Move memory to the next} inc(Data, ItemSize); end; {Unlock memory and unallocate} GlobalUnlock(MemHandle); GlobalFree(MemHandle); end {if (Result = crSuccess)} end; {Returns an enumeration capability} function TTwainSource.GetEnumerationValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var List: TGetCapabilityList; var Current, Default: Integer; Mode: TRetrieveCap; MemHandle: HGLOBAL): TCapabilityRet; var EnumV : pTW_ENUMERATION; ItemSize : Integer; Data : PChar; CurItem : Integer; Value : String; Container: TW_UINT16; begin {Call method to get the memory to the return} if MemHandle = 0 then Result := GetCapabilityRec(Capability, MemHandle, Mode, Container) else begin Result := crSuccess; Container := TWON_ENUMERATION; end; if (Result = crSuccess) and (Container <> TWON_ENUMERATION) then begin Result := crInvalidContainer; GlobalFree(MemHandle); Exit; end; {If result was sucessfull and memory was allocated} if (Result = crSuccess) then begin {Obtain structure pointer} EnumV := GlobalLock(MemHandle); {Fill return properties} Current := EnumV^.CurrentIndex; Default := EnumV^.DefaultIndex; ItemType := EnumV^.ItemType; {Prepare to list items} ItemSize := TWTypeSize(ItemType); Data := @EnumV^.ItemList[0]; SetLength(List, EnumV^.NumItems); {Copy items} for CurItem := 0 TO EnumV^.NumItems - 1 do begin {Obtain this item} GetItem(Value, ItemType, Data); List[CurItem] := Value; {Move memory to the next} inc(Data, ItemSize); end; {Unlock memory and unallocate} GlobalUnlock(MemHandle); GlobalFree(MemHandle); end {if (Result = crSuccess)} end; {Returns a range capability} function TTwainSource.GetRangeValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var Min, Max, Step, Default, Current: String; MemHandle: HGLOBAL): TCapabilityRet; var RangeV : pTW_RANGE; Container: TW_UINT16; begin {Call method to get the memory to the return} if MemHandle = 0 then Result := GetCapabilityRec(Capability, MemHandle, rcGet, Container) else begin Result := crSuccess; Container := TWON_RANGE; end; if (Result = crSuccess) and (Container <> TWON_RANGE) then begin Result := crInvalidContainer; GlobalFree(MemHandle); Exit; end; {If result was sucessfull and memory was allocated} if (Result = crSuccess) then begin {Obtain structure pointer} RangeV := GlobalLock(MemHandle); {Fill return} ItemType := RangeV^.ItemType; GetItem(Min, ItemType, @RangeV^.MinValue); GetItem(Max, ItemType, @RangeV^.MaxValue); GetItem(Step, ItemType, @RangeV^.StepSize); GetItem(Default, ItemType, @RangeV^.DefaultValue); GetItem(Current, ItemType, @RangeV^.CurrentValue); {Unlock memory and unallocate} GlobalUnlock(MemHandle); GlobalFree(MemHandle); end {if (Result = crSuccess)} end; {Returns an one value capability} function TTwainSource.GetOneValue(Capability: TW_UINT16; var ItemType: TW_UINT16; var Value: String; Mode: TRetrieveCap; MemHandle: HGLOBAL): TCapabilityRet; var OneV : pTW_ONEVALUE; Container: TW_UINT16; begin {Call method to get the memory to the return} if MemHandle = 0 then Result := GetCapabilityRec(Capability, MemHandle, Mode, Container) else begin Result := crSuccess; Container := TWON_ONEVALUE; end; if (Result = crSuccess) and (Container <> TWON_ONEVALUE) then begin Result := crInvalidContainer; GlobalFree(MemHandle); Exit; end; {If result was sucessfull and memory was allocated} if (Result = crSuccess) then begin {Obtain structure pointer} OneV := GlobalLock(MemHandle); {Fill return} ItemType := OneV^.ItemType; GetItem(Value, OneV^.ItemType, @OneV^.Item); {Unlock memory and unallocate} GlobalUnlock(MemHandle); GlobalFree(MemHandle); end {if (Result = crSuccess)} end; {Sets an one value capability} function TTwainSource.SetOneValue(Capability: TW_UINT16; ItemType: TW_UINT16; Value: Pointer): TCapabilityRet; var Data: HGLOBAL; OneV: pTW_ONEVALUE; ItemSize,ItemSize2: Integer; begin {Allocate enough memory for the TW_ONEVALUE and obtain pointer} ItemSize := TWTypeSize(ItemType); //npeter: TW_ONEVALUE minimal size !!! //I think to meet the specifications the //Item's size must be at least sizeof(TW_UINT32)! //when I did it, some mistic errors on some drivers went gone if ItemSize<TWTypeSize(TWTY_UINT32) then ItemSize2:=TWTypeSize(TWTY_UINT32) else ItemSize2:=ItemSize; Data := GlobalAlloc(GHND, sizeof(OneV^.ItemType) + ItemSize2); OneV := GlobalLock(Data); {Fill value} OneV^.ItemType := ItemType; CopyMemory(@OneV^.Item, Value, ItemSize); GlobalUnlock(Data); {Call method to set} Result := SetCapabilityRec(Capability, TWON_ONEVALUE, Data); {Unload memory} GlobalFree(Data); end; {Sets a range capability} function TTwainSource.SetRangeValue(Capability: TW_UINT16; ItemType: TW_UINT16; Min, Max, Step, Current: TW_UINT32): TCapabilityRet; var Data: HGLOBAL; RangeV: pTW_RANGE; begin {Allocate enough memory for the TW_RANGE and obtain pointer} Data := GlobalAlloc(GHND, sizeof(TW_RANGE)); RangeV := GlobalLock(Data); {Fill value} RangeV^.ItemType := ItemType; RangeV^.MinValue := Min; RangeV^.MaxValue := Max; RangeV^.StepSize := Step; RangeV^.CurrentValue := Current; GlobalUnlock(Data); {Call method to set} Result := SetCapabilityRec(Capability, TWON_RANGE, Data); {Unload memory} GlobalFree(Data); end; {Sets an array capability} function TTwainSource.SetArrayValue(Capability: TW_UINT16; ItemType: TW_UINT16; List: TSetCapabilityList): TCapabilityRet; var Data: HGLOBAL; EnumV: pTW_ENUMERATION; i, ItemSize: Integer; DataPt: PChar; begin {Allocate enough memory for the TW_ARRAY and obtain pointer} ItemSize := TWTypeSize(ItemType); Data := GlobalAlloc(GHND, sizeof(TW_ARRAY) + ItemSize * Length(List)); EnumV := GlobalLock(Data); {Fill values} EnumV^.ItemType := ItemType; EnumV^.NumItems := Length(List); {Copy item values} DataPt := @EnumV^.ItemList[0]; for i := Low(List) TO High(List) do begin {Copy item} CopyMemory(DataPt, List[i], ItemSize); {Move to next item} inc(DataPt, ItemSize); end; GlobalUnlock(Data); {Call method to set} Result := SetCapabilityRec(Capability, TWON_ARRAY, Data); {Unload memory} GlobalFree(Data); end; {Sets an enumeration capability} function TTwainSource.SetEnumerationValue(Capability: TW_UINT16; ItemType: TW_UINT16; CurrentIndex: TW_UINT32; List: TSetCapabilityList): TCapabilityRet; var Data: HGLOBAL; EnumV: pTW_ENUMERATION; i, ItemSize: Integer; DataPt: PChar; begin {Allocate enough memory for the TW_ENUMERATION and obtain pointer} ItemSize := TWTypeSize(ItemType); Data := GlobalAlloc(GHND, sizeof(TW_ENUMERATION) + ItemSize * Length(List)); EnumV := GlobalLock(Data); {Fill values} EnumV^.ItemType := ItemType; EnumV^.NumItems := Length(List); EnumV^.CurrentIndex := CurrentIndex; {Copy item values} DataPt := @EnumV^.ItemList[0]; for i := Low(List) TO High(List) do begin {Copy item} CopyMemory(DataPt, List[i], ItemSize); {Move to next item} inc(DataPt, ItemSize); end; GlobalUnlock(Data); {Call method to set} Result := SetCapabilityRec(Capability, TWON_ENUMERATION, Data); {Unload memory} GlobalFree(Data); end; {Transfer image memory} function TTwainSource.TransferImageMemory(var ImageHandle: HBitmap; PixelType: TW_INT16): TW_UINT16; var {Memory buffer information from the source} Setup : TW_SETUPMEMXFER; {Memory information from the image} Xfer : TW_IMAGEMEMXFER; {Image processing variables} ImageInfo : Windows.TBitmap; Ptr : pChar; LineLength, CurLine: Cardinal; LinePtr, AllocPtr : pointer; DataSize, Readed, Index : Cardinal; ItemPtr : pRGBTriple; Temp : Byte; begin {Obtain information on the transference buffers} Result := Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_SETUPMEMXFER, MSG_GET, @Setup); {Get information on the bitmap} GetObject(ImageHandle, sizeof(Windows.TBitmap), @ImageInfo); LineLength := (((ImageInfo.bmWidth * ImageInfo.bmBitsPixel + 31) div 32) * 4); {Get pointer for the last line} CurLine := ImageInfo.bmHeight - 1; Cardinal(LinePtr) := Cardinal(ImageInfo.bmBits) + LineLength * CurLine; Ptr := LinePtr; DataSize := 0; {Prepare buffer record to transfer} Fillchar(Xfer, SizeOf(TW_IMAGEMEMXFER), $FF); Xfer.Memory.Flags := TWMF_APPOWNS or TWMF_POINTER; Xfer.Memory.Length := Setup.Preferred; GetMem(AllocPtr, Setup.Preferred); Xfer.Memory.TheMem := AllocPtr; {Transfer data until done or cancelled} if Result = TWRC_SUCCESS then repeat {Retrieve another piece of memory to the pointer} Xfer.BytesWritten := 0; Result := Owner.TwainProc(AppInfo, @Structure, DG_IMAGE, DAT_IMAGEMEMXFER, MSG_GET, @Xfer); {Test the result} {Piece sucessfully transfer, move to next} if (Result = TWRC_SUCCESS) or (Result = TWRC_XFERDONE) then begin {While we have data} while Xfer.BytesWritten > 0 do begin {In case the total bytes received now have more than we} {need to complete the line} if Xfer.BytesWritten + DataSize > LineLength then begin Readed := LineLength - DataSize; CopyMemory(Ptr, Xfer.Memory.TheMem, LineLength - DataSize); end else {Otherwise, continue completing the line} begin Readed := Xfer.BytesWritten; CopyMemory(Ptr, Xfer.Memory.TheMem, Readed); end; {Adjust} inc(DataSize, Readed); inc(Ptr, Readed); dec(Xfer.BytesWritten, Readed); Cardinal(Xfer.Memory.TheMem) := Cardinal(Xfer.Memory.TheMem) + Readed; {Reached end of line} if DataSize >= LineLength then begin {Fix RGB to BGR} if PixelType = TWPT_RGB then begin ItemPtr := LinePtr; FOR Index := 1 TO ImageInfo.bmWidth DO begin Temp := ItemPtr^.rgbtRed; ItemPtr^.rgbtRed := ItemPtr^.rgbtBlue; ItemPtr^.rgbtBlue := Temp; inc(ItemPtr); end {FOR Index}; end {if PixelType = TWPT_RGB}; {Adjust pointers} Cardinal(LinePtr) := Cardinal(LinePtr) - LineLength; Ptr := LinePtr; dec(CurLine); DataSize := 0; {Call event} if Assigned(Owner.OnAcquireProgress) then Owner.OnAcquireProgress(Self, Self.Index, ImageHandle, Cardinal(ImageInfo.bmHeight) - CurLine - 1, ImageInfo.bmHeight - 1); end {if DataSize >= LineLength} end {while Xfer.BytesWritten > 0}; {Set again pointer to write to} Xfer.Memory.TheMem := AllocPtr; end {TWRC_SUCCESS}; until Result <> TWRC_SUCCESS; {Free allocated memory} FreeMem(AllocPtr, Setup.Preferred); {Some error ocurred, free memory and returns} if Result <> TWRC_XFERDONE then DeleteObject(ImageHandle); end; {Prepare image memory transference} function TTwainSource.PrepareMemXfer(var BitmapHandle: HBitmap; var PixelType: TW_INT16): TW_UINT16; const PixelColor: Array[TTwainPixelFlavor] of Array[0..1] of Byte = ((0, $FF), ($FF, 00), (0, $FF)); var Handle: HGlobal; Info: TW_IMAGEINFO; Setup: TW_SETUPMEMXFER; structsize, index, Size, Blocks: Integer; XRes, YRes: Extended; Pal : TW_PALETTE8; vUnit : TTwainUnit; vUnits: TTwainUnitSet; Dib : pBitmapInfo; PixelFlavor: TTwainPixelFlavor; PixelFlavors: TTwainPixelFlavorSet; DC: HDC; Data : Pointer; begin {First of all, get information on the image being acquired} Result := Owner.TwainProc(AppInfo, @Structure, DG_IMAGE, DAT_IMAGEINFO, MSG_GET, @Info); if Result <> TWRC_SUCCESS then exit; {Calculate image size} with Info do size := ((((ImageWidth * BitsPerPixel + 31) div 32)*4) * info.ImageLength); {Obtain image buffer transference sizes} Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_SETUPMEMXFER, MSG_GET, @Setup); blocks := (size div Integer(setup.Preferred)); size := (blocks + 1) * Integer(setup.Preferred); {Prepare new bitmap} structsize := size + sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD); Handle := GlobalAlloc(GHND, StructSize); Dib := GlobalLock(Handle); Fillchar(Dib^, structsize, #0); {Fill image information} Dib^.bmiHeader.biSize := sizeof(BITMAPINFOHEADER); Dib^.bmiHeader.biWidth := info.ImageWidth; Dib^.bmiHeader.biHeight := info.ImageLength; {Only 1 plane supported} Dib^.bmiHeader.biPlanes := 1; Dib^.bmiHeader.biBitCount := info.BitsPerPixel; {No compression} Dib^.bmiHeader.biCompression := BI_RGB; Dib^.bmiHeader.biSizeImage := Size; {Adjust units} XRes := Fix32ToFloat(Info.XResolution); YRes := Fix32ToFloat(Info.YResolution); GetICapUnits(vUnit, vUnits); case vUnit of tuInches: begin Dib^.bmiHeader.biXPelsPerMeter := Trunc((XRes*2.54)*100); Dib^.bmiHeader.biYPelsPerMeter := Trunc((YRes*2.54)*100); end; tuCentimeters: begin Dib^.bmiHeader.biXPelsPerMeter := Trunc(XRes*100); Dib^.bmiHeader.biYPelsPerMeter := Trunc(YRes*100); end else begin Dib^.bmiHeader.biXPelsPerMeter := 0; Dib^.bmiHeader.biYPelsPerMeter := 0; end end {case vUnits of}; {Now it should setup the palette to be used by the image} {by either building a definied palette or retrieving the} {image's one} case (Info.PixelType) of TWPT_BW: begin {Only two colors are used} Dib^.bmiHeader.biClrUsed := 2; Dib^.bmiHeader.biClrImportant := 0; {Try obtaining the pixel flavor} if GetIPixelFlavor(PixelFlavor, PixelFlavors) <> crSuccess then PixelFlavor := tpfChocolate; {Set palette colors} for Index := 0 to 1 do begin Dib^.bmiColors[Index].rgbRed := PixelColor[PixelFlavor][Index]; Dib^.bmiColors[Index].rgbGreen := PixelColor[PixelFlavor][Index]; Dib^.bmiColors[Index].rgbBlue := PixelColor[PixelFlavor][Index]; Dib^.bmiColors[Index].rgbReserved := 0; end; end; TWPT_GRAY: begin {Creates a 256 shades of gray palette} Dib^.bmiHeader.biClrUsed := 256; for index := 0 to 255 do begin Dib^.bmiColors[index].rgbRed := index; Dib^.bmiColors[index].rgbGreen := index; Dib^.bmiColors[index].rgbBlue := index; Dib^.bmiColors[index].rgbReserved := 0; end {for i} end; TWPT_RGB: Dib^.bmiHeader.biClrUsed := 0; else begin {Try obtaining the palette} if Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_PALETTE8, MSG_GET, @Pal) <> TWRC_SUCCESS then begin {If the source did not provide a palette, uses shades of gray here} Dib^.bmiHeader.biClrUsed := 256; for index := 0 to 255 do begin Dib^.bmiColors[index].rgbRed := index; Dib^.bmiColors[index].rgbGreen := index; Dib^.bmiColors[index].rgbBlue := index; Dib^.bmiColors[index].rgbReserved := 0; end {for i} end else begin {Uses source palette here} Dib^.bmiHeader.biClrUsed := Pal.NumColors; for Index := 0 TO Pal.NumColors - 1 do begin Dib^.bmiColors[index].rgbRed := pal.Colors[index].Channel1; Dib^.bmiColors[index].rgbGreen := pal.Colors[index].Channel2; Dib^.bmiColors[index].rgbBlue := pal.Colors[index].Channel3; Dib^.bmiColors[index].rgbReserved := 0; end {for Index} end {if Owner.TwainProc(AppInfo...} end {case else}; end {case Info.PixelType}; {Creates the bitmap} DC := GetDC(Owner.VirtualWindow); Cardinal(Data) := Cardinal(Dib) + Dib^.bmiHeader.biSize + (Dib^.bmiHeader.biClrUsed * sizeof(RGBQUAD)); BitmapHandle := CreateDIBSection(DC, Dib^, DIB_RGB_COLORS, Data, 0, 0); ReleaseDC(Owner.VirtualWindow, DC); PixelType := Info.PixelType; {Unlock and free data} GlobalUnlock(Handle); GlobalFree(Handle); end; {Method to transfer the images} procedure TTwainSource.TransferImages(); var {To test if the image transfer is done} Cancel, Done : Boolean; {Return code from Twain method} rc : TW_UINT16; {Handle to the native Device independent Image (DIB)} hNative: TW_UINT32; {Pending transfers structure} PendingXfers: TW_PENDINGXFERS; {File transfer info} Info: TW_SETUPFILEXFER; {Image handle and pointer} ImageHandle: HBitmap; PixelType : TW_INT16; begin {Set the transfer mode} //npeter: //on a HP driver I got error events //when it was set above state 5; //commented out // ChangeTransferMode(TransferMode); Cancel := FALSE; {Testing if it was cancelled} Done := FALSE; {Initialize done variable} {Obtain all the images from the source} repeat {Transfer depending on the transfer mode} case TransferMode of {Native transfer, the source creates the image thru a device} {dependent image} ttmNative: begin {Call method to obtain the image} hNative := 0; rc := Owner.TwainProc(AppInfo, @Structure, DG_IMAGE, DAT_IMAGENATIVEXFER, MSG_GET, @hNative); end {case ttmNative}; {File transfering, the source should create a file with} {the acquired image} ttmFile: begin {Event to allow user to set the file transfer information} if Assigned(Owner.OnSourceSetupFileXfer) then Owner.OnSourceSetupFileXfer(Owner, Index); Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_SETUPFILEXFER, MSG_GET, @Info); {Call method to make source acquire and create file} rc := Owner.TwainProc(AppInfo, @Structure, DG_IMAGE, DAT_IMAGEFILEXFER, MSG_GET, nil); end {case ttmFile}; {Memory buffer transfers} ttmMemory: begin {Prepare for memory transference} rc := PrepareMemXfer(ImageHandle, PixelType); {If the image was sucessfully prepared to be transfered, it's} {now time to transfer it} if rc = TWRC_SUCCESS then rc := TransferImageMemory(ImageHandle, PixelType); end {Unknown transfer mode ?} else Rc := 0; end; {Twain call to transfer image return} case rc of {Transfer sucessfully done} TWRC_XFERDONE: case TransferMode of {Native transfer sucessfull} ttmNative: ReadNative(hNative, Cancel); {File transfer sucessfull} ttmFile: ReadFile(Info.FileName, Info.Format, Cancel); {Memory transfer sucessfull} ttmMemory: ReadMemory(ImageHandle, Cancel); end {case TransferMode, TWRC_XFERDONE}; {User cancelled the transfers} TWRC_CANCEL: begin {Acknowledge end of transfer} Done := TRUE; {Call event, if avaliable} if Assigned(Owner.OnAcquireCancel) then Owner.OnAcquireCancel(Owner, Index) end else {Unknown return or error} if Assigned(Owner.OnAcquireError) then Owner.OnAcquireError(Owner, Index, Rc, GetReturnStatus()) end; {Check if there are pending transfers} if not Done then Done := (Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_PENDINGXFERS, MSG_ENDXFER, @PendingXfers) <> TWRC_SUCCESS) or (PendingXfers.Count = 0); {If user has cancelled} if not Done and Cancel then Done := (Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_PENDINGXFERS, MSG_RESET, @PendingXfers) = TWRC_SUCCESS); until Done; {Disable source} Enabled := False; end; {Returns the number of colors in the DIB} function DibNumColors (pv: Pointer): Word; var Bits: Integer; lpbi: PBITMAPINFOHEADER absolute pv; lpbc: PBITMAPCOREHEADER absolute pv; begin //With the BITMAPINFO format headers, the size of the palette //is in biClrUsed, whereas in the BITMAPCORE - style headers, it //is dependent on the bits per pixel ( = 2 raised to the power of //bits/pixel). if (lpbi^.biSize <> sizeof(BITMAPCOREHEADER)) then begin if (lpbi^.biClrUsed <> 0) then begin result := lpbi^.biClrUsed; exit; end; Bits := lpbi^.biBitCount; end else Bits := lpbc^.bcBitCount; {Test bits to return} case (Bits) of 1: Result := 2; 4: Result := 16; 8: Result := 256; else Result := 0; end {case}; end; {Converts from TWain TW_UINT16 to TTwainFormat} function TwainToTTwainFormat(Value: TW_UINT16): TTwainFormat; begin Case Value of TWFF_TIFF : Result := tfTIFF; TWFF_PICT : Result := tfPict; TWFF_BMP : Result := tfBMP; TWFF_XBM : Result := tfXBM; TWFF_JFIF : Result := tfJPEG; TWFF_FPX : Result := tfFPX; TWFF_TIFFMULTI: Result := tfTIFFMulti; TWFF_PNG : Result := tfPNG; TWFF_SPIFF : Result := tfSPIFF; TWFF_EXIF : Result := tfEXIF; else Result := tfUnknown; end {case Value of} end; {Reads the file image} procedure TTwainSource.ReadFile(Name: TW_STR255; Format: TW_UINT16; var Cancel: Boolean); begin {Call event, if set} if Assigned(Owner.OnSourceFileTransfer) then Owner.OnSourceFileTransfer(Self, Index, Name, TwainToTTwainFormat(Format), Cancel); end; {Call event for memory image} procedure TTwainSource.ReadMemory(Image: HBitmap; var Cancel: Boolean); {$IFNDEF DONTUSEVCL} var BitmapObj: TBitmap;{$ENDIF} begin if Assigned(Owner.OnTwainAcquire) then {$IFDEF DONTUSEVCL} Owner.OnTwainAcquire(Owner, Index, Image, Cancel); {$ELSE} begin BitmapObj := TBitmap.Create; BitmapObj.Handle := Image; Owner.OnTwainAcquire(Owner, Index, BitmapObj, Cancel); BitmapObj.Free; end; {$ENDIF} end; {Reads a native image} procedure TTwainSource.ReadNative(Handle: TW_UINT32; var Cancel: Boolean); var DibInfo: ^TBITMAPINFO; ColorTableSize: Integer; lpBits: PChar; DC: HDC; BitmapHandle: HBitmap; {$IFNDEF DONTUSEVCL}BitmapObj: TBitmap;{$ENDIF} begin {Get image information pointer and size} DibInfo := GlobalLock(Handle); ColorTableSize := (DibNumColors(DibInfo) * SizeOf(RGBQUAD)); {Get data memory position} lpBits := PChar(DibInfo); Inc(lpBits, DibInfo.bmiHeader.biSize); Inc(lpBits, ColorTableSize); {Creates the bitmap} DC := GetDC(Owner.VirtualWindow); BitmapHandle := CreateDIBitmap(DC, DibInfo.bmiHeader, CBM_INIT, lpBits, DibInfo^, DIB_RGB_COLORS); ReleaseDC(Owner.VirtualWindow, DC); if Assigned(Owner.OnTwainAcquire) then {$IFDEF DONTUSEVCL} Owner.OnTwainAcquire(Owner, Index, BitmapHandle, Cancel); {$ELSE} begin BitmapObj := TBitmap.Create; BitmapObj.Handle := BitmapHandle; Owner.OnTwainAcquire(Owner, Index, BitmapObj, Cancel); BitmapObj.Free; end; {$ENDIF} {Free bitmap} GlobalUnlock(Handle); GlobalFree(Handle); end; {Setup file transfer} function TTwainSource.SetupFileTransfer(Filename: String; Format: TTwainFormat): Boolean; const FormatToTwain: Array[TTwainFormat] of TW_UINT16 = (TWFF_TIFF, TWFF_PICT, TWFF_BMP, TWFF_XBM, TWFF_JFIF, TWFF_FPX, TWFF_TIFFMULTI, TWFF_PNG, TWFF_SPIFF, TWFF_EXIF, 0); var FileTransferInfo: TW_SETUPFILEXFER; begin {Source must be loaded to set things} if (Loaded) then begin {Prepare structure} FileTransferInfo.FileName := StrToStr255(FileName); FileTransferInfo.Format := FormatToTwain[Format]; {Call method} Result := (Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_SETUPFILEXFER, MSG_SET, @FileTransferInfo) = TWRC_SUCCESS); end else Result := FALSE; {Could not set file transfer with source unloaded} end; {Setup file transfer} function TTwainSource.SetupFileTransferTWFF(Filename: String; Format: TW_UINT16): Boolean; var FileTransferInfo: TW_SETUPFILEXFER; begin {Source must be loaded to set things} if (Loaded) then begin {Prepare structure} FileTransferInfo.FileName := StrToStr255(FileName); FileTransferInfo.Format := Format; {Call method} Result := (Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_SETUPFILEXFER, MSG_SET, @FileTransferInfo) = TWRC_SUCCESS); end else Result := FALSE; {Could not set file transfer with source unloaded} end; {Set the number of images that the application wants to receive} function TTwainSource.SetCapXferCount(Value: SmallInt): TCapabilityRet; begin {Call method to set the value} Result := SetOneValue(CAP_XFERCOUNT, TWTY_UINT16, @Value); end; {Returns the number of images that the source will return} function TTwainSource.GetCapXferCount(var Return: SmallInt; Mode: TRetrieveCap): TCapabilityRet; var {Will hold the capability information} ItemType: TW_UINT16; Value : String; begin {Call method to return information} Result := GetOneValue(CAP_XFERCOUNT, ItemType, Value, Mode); {Item type must be of TW_UINT16} if (Result = crSuccess) and (ItemType <> TWTY_INT16) then Result := crUnsupported; {If everything gone ok, fill result} if Result = crSuccess then Return := StrToIntDef(Value, -1); end; {Set the unit measure} function TTwainSource.SetICapUnits(Value: TTwainUnit): TCapabilityRet; //npeter //the TTwainUnit is byte!!! //so we have to convert it to TW_UINT16 //before this fix I was not able to set this capability //on a HP driver const Transfer: Array[TTwainUnit] of TW_UINT16 = (TWUN_INCHES, TWUN_CENTIMETERS, TWUN_PICAS, TWUN_POINTS, TWUN_TWIPS, TWUN_PIXELS, TWUN_INCHES); var iValue: TW_UINT16; begin ivalue:=Transfer[Value]; Result := SetOneValue(ICAP_UNITS, TWTY_UINT16, @iValue); end; {Convert from Twain to TTwainPixelFlavor} function TwainToTTwainPixelFlavor(Value: TW_UINT16): TTwainPixelFlavor; begin {Test the value to make the convertion} case Value of TWPF_CHOCOLATE: Result := tpfChocolate; TWPF_VANILLA : Result := tpfVanilla; else Result := tpfUnknown; end {case Value} end; {Convert from Twain to TTwainUnit} function TwainToTTwainUnit(Value: TW_UINT16): TTwainUnit; begin {Test the value to make the convertion} case Value of TWUN_INCHES : Result := tuInches; TWUN_CENTIMETERS: Result := tuCentimeters; TWUN_PICAS : Result := tuPicas; TWUN_POINTS : Result := tuPoints; TWUN_TWIPS : Result := tuTwips; TWUN_PIXELS : Result := tuPixels; else Result := tuUnknown; end {case Value} end; {Retrieve the unit measure for all quantities} function TTwainSource.GetICapUnits(var Return: TTwainUnit; var Supported: TTwainUnitSet; Mode: TRetrieveCap): TCapabilityRet; var ItemType: TW_UINT16; List : TGetCapabilityList; Current, i, Default : Integer; begin {Call method to get result} Result := GetEnumerationValue(ICAP_UNITS, ItemType, List, Current, Default, Mode); if ItemType <> TWTY_UINT16 then Result := crUnsupported; {If it was sucessfull, return values} if Result = crSuccess then begin {Make list} for i := Low(List) to High(List) do Include(Supported, TwainToTTwainUnit(StrToIntDef(List[i], -1))); {Return values depending on the mode} if Mode = rcGetDefault then Return := TwainToTTwainUnit(StrToIntDef(List[Default], -1)) else Return := TwainToTTwainUnit(StrToIntDef(List[Current], -1)); end {if Result = crSuccess} end; {Retrieve the pixel flavor values} function TTwainSource.GetIPixelFlavor(var Return: TTwainPixelFlavor; var Supported: TTwainPixelFlavorSet; Mode: TRetrieveCap): TCapabilityRet; var ItemType: TW_UINT16; List : TGetCapabilityList; Current, i, Default : Integer; begin {Call method to get result} Result := GetEnumerationValue(ICAP_PIXELFLAVOR, ItemType, List, Current, Default, Mode); if ItemType <> TWTY_UINT16 then Result := crUnsupported; {If it was sucessfull, return values} if Result = crSuccess then begin {Make list} for i := Low(List) to High(List) do Include(Supported, TwainToTTwainPixelFlavor(StrToIntDef(List[i], -1))); {Return values depending on the mode} if Mode = rcGetDefault then Return := TwainToTTwainPixelFlavor(StrToIntDef(List[Default], -1)) else Return := TwainToTTwainPixelFlavor(StrToIntDef(List[Current], -1)); end {if Result = crSuccess} end; function TTwainSource.SetIPixelFlavor(Value: TTwainPixelFlavor): TCapabilityRet; //npeter //the TTwainPixelFlavor is byte!!! //so we have to convert it to TW_UINT16 //before this fix I was not able to set this capability //on a HP driver const Transfer: array [TTwainPixelFlavor] of TW_UINT16 = (TWPF_CHOCOLATE,TWPF_VANILLA,TWPF_CHOCOLATE); var iValue: TW_UINT16; begin iValue:=Transfer[value]; Result := SetOneValue(ICAP_PIXELFLAVOR, TWTY_UINT16, @iValue); end; {Convert from Twain to TTwainPixelType} function TwainToTTwainPixelType(Value: TW_UINT16): TTwainPixelType; begin {Test the value to make the convertion} case Value of TWPT_BW : Result := tbdBw; TWPT_GRAY : Result := tbdGray; TWPT_RGB : Result := tbdRgb; TWPT_PALETTE : Result := tbdPalette; TWPT_CMY : Result := tbdCmy; TWPT_CMYK : Result := tbdCmyk; TWPT_YUV : Result := tbdYuv; TWPT_YUVK : Result := tbdYuvk; TWPT_CIEXYZ : Result := tbdCieXYZ; else Result := tbdUnknown; end {case Value} end; {Returns pixel type values} function TTwainSource.GetIPixelType(var Return: TTwainPixelType; var Supported: TTwainPixelTypeSet; Mode: TRetrieveCap): TCapabilityRet; var ItemType: TW_UINT16; List : TGetCapabilityList; Current, i, Default : Integer; begin {Call method to get result} Result := GetEnumerationValue(ICAP_PIXELTYPE, ItemType, List, Current, Default, Mode); if ItemType <> TWTY_UINT16 then Result := crUnsupported; {If it was sucessfull, return values} if Result = crSuccess then begin {Make list} for i := Low(List) to High(List) do Include(Supported, TwainToTTwainPixelType(StrToIntDef(List[i], -1))); {Return values depending on the mode} if Mode = rcGetDefault then Return := TwainToTTwainPixelType(StrToIntDef(List[Default], -1)) else Return := TwainToTTwainPixelType(StrToIntDef(List[Current], -1)); end {if Result = crSuccess} end; {Set the pixel type value} function TTwainSource.SetIPixelType(Value: TTwainPixelType): TCapabilityRet; //npeter //the TTwainPixelType is byte!!! //so we have to convert it to TW_UINT16 //before this fix occasionally I was not able to set this capability //on a HP driver var ivalue: smallint; begin ivalue:=ord(value); Result := SetOneValue(ICAP_PIXELTYPE, TWTY_UINT16, @iValue); end; {Returns bitdepth values} function TTwainSource.GetIBitDepth(var Return: Word; var Supported: TTwainBitDepth; Mode: TRetrieveCap): TCapabilityRet; var ItemType: TW_UINT16; List : TGetCapabilityList; Current, i, Default : Integer; begin {Call GetOneValue to obtain this property} Result := GetEnumerationValue(ICAP_BITDEPTH, ItemType, List, Current, Default, Mode); if ItemType <> TWTY_UINT16 then Result := crUnsupported; {In case everything went ok, fill parameters} if Result = crSuccess then begin {Build bit depth list} SetLength(Supported, Length(List)); FOR i := LOW(List) TO HIGH(List) DO Supported[i] := StrToIntDef(List[i], -1); {Return values depending on the mode} if Mode = rcGetDefault then Return := StrToIntDef(List[Default], -1) else Return := StrToIntDef(List[Current], -1); end {if Result = crSuccess} end; {Set current bitdepth value} function TTwainSource.SetIBitDepth(Value: Word): TCapabilityRet; begin Result := SetOneValue(ICAP_BITDEPTH, TWTY_UINT16, @Value); end; {Returns physical width} function TTwainSource.GetIPhysicalWidth(var Return: Extended; Mode: TRetrieveCap): TCapabilityRet; var Handle: HGlobal; OneV : pTW_ONEVALUE; Container: TW_UINT16; begin {Obtain handle to data from this capability} Result := GetCapabilityRec(ICAP_PHYSICALWIDTH, Handle, Mode, Container); if Result = crSuccess then begin {Obtain data} OneV := GlobalLock(Handle); if OneV^.ItemType <> TWTY_FIX32 then Result := crUnsupported else Return := Fix32ToFloat(pTW_FIX32(@OneV^.Item)^); {Free data} GlobalUnlock(Handle); GlobalFree(Handle); end; end; {Returns physical height} function TTwainSource.GetIPhysicalHeight(var Return: Extended; Mode: TRetrieveCap): TCapabilityRet; var Handle: HGlobal; OneV : pTW_ONEVALUE; Container: TW_UINT16; begin {Obtain handle to data from this capability} Result := GetCapabilityRec(ICAP_PHYSICALHEIGHT, Handle, Mode, Container); if Result = crSuccess then begin {Obtain data} OneV := GlobalLock(Handle); if OneV^.ItemType <> TWTY_FIX32 then Result := crUnsupported else Return := Fix32ToFloat(pTW_FIX32(@OneV^.Item)^); {Free data} GlobalUnlock(Handle); GlobalFree(Handle); end; end; {Returns a resolution} function TTwainSource.GetResolution(Capability: TW_UINT16; var Return: Extended; var Values: TTwainResolution; Mode: TRetrieveCap): TCapabilityRet; var Handle: HGlobal; EnumV: pTW_ENUMERATION; Container: TW_UINT16; Item: pTW_FIX32; i : Integer; begin {Obtain handle to data from this capability} Result := GetCapabilityRec(Capability, Handle, Mode, Container); if Result = crSuccess then begin {Obtain data} //npeter //the "if" is just for sure! if (Container<>TWON_ENUMERATION) and (Container<>TWON_ARRAY) then begin result:=crUnsupported; exit; end; EnumV := GlobalLock(Handle); if EnumV^.ItemType <> TWTY_FIX32 then Result := crUnsupported else begin {Set array size and pointer to the first item} Item := @EnumV^.ItemList[0]; SetLength(Values, EnumV^.NumItems); {Fill array} FOR i := 1 TO EnumV^.NumItems DO begin {Fill array with the item} Values[i - 1] := Fix32ToFloat(Item^); {Move to next item} inc(Item); end {FOR i}; {Fill return} //npeter //DefaultIndex and CurrentIndex valid for enum only! //I got nice AV with an old Mustek scanner which uses TWON_ARRAY //i return 0 in this case (may be not the best solution, but not AV at least :-) if (Container<>TWON_ARRAY) then begin if Mode = rcGetDefault then Return := Values[EnumV^.DefaultIndex] else Return := Values[EnumV^.CurrentIndex]; end else return:=0; end; {Free data} GlobalUnlock(Handle); GlobalFree(Handle); end; end; {Sets X resolution} function TTwainSource.SetIXResolution(Value: Extended): TCapabilityRet; var Fix32: TW_FIX32; begin Fix32 := FloatToFix32(Value); Result := SetOneValue(ICAP_XRESOLUTION, TWTY_FIX32, @Fix32); end; {Sets Y resolution} function TTwainSource.SetIYResolution(Value: Extended): TCapabilityRet; var Fix32: TW_FIX32; begin Fix32 := FloatToFix32(Value); Result := SetOneValue(ICAP_YRESOLUTION, TWTY_FIX32, @Fix32); end; {Returns X resolution} function TTwainSource.GetIXResolution(var Return: Extended; var Values: TTwainResolution; Mode: TRetrieveCap): TCapabilityRet; begin Result := GetResolution(ICAP_XRESOLUTION, Return, Values, Mode); end; {Returns Y resolution} function TTwainSource.GetIYResolution(var Return: Extended; var Values: TTwainResolution; Mode: TRetrieveCap): TCapabilityRet; begin Result := GetResolution(ICAP_YRESOLUTION, Return, Values, Mode); end; {Returns if user interface is controllable} function TTwainSource.GetUIControllable(var Return: Boolean): TCapabilityRet; var ItemType: TW_UINT16; Value : String; begin {Try to obtain value and make sure it is of type TW_BOOL} Result := GetOneValue(CAP_UICONTROLLABLE, ItemType, Value, rcGet); if (Result = crSuccess) and (ItemType <> TWTY_BOOL) then Result := crUnsupported; {Return value, by checked the return value from GetOneValue} if Result = crSuccess then Return := (Value = '1'); end; {Returns if feeder is loaded} function TTwainSource.GetFeederLoaded(var Return: Boolean): TCapabilityRet; var ItemType: TW_UINT16; Value : String; begin {Try to obtain value and make sure it is of type TW_BOOL} Result := GetOneValue(CAP_FEEDERLOADED, ItemType, Value, rcGet); if (Result = crSuccess) and (ItemType <> TWTY_BOOL) then Result := crUnsupported; {Return value, by checked the return value from GetOneValue} if Result = crSuccess then Return := (Value = '1'); end; {Returns if feeder is enabled} function TTwainSource.GetFeederEnabled(var Return: Boolean): TCapabilityRet; var ItemType: TW_UINT16; Value : String; begin {Try to obtain value and make sure it is of type TW_BOOL} Result := GetOneValue(CAP_FEEDERENABLED, ItemType, Value, rcGet); if (Result = crSuccess) and (ItemType <> TWTY_BOOL) then Result := crUnsupported; {Return value, by checked the return value from GetOneValue} if Result = crSuccess then Return := (Value = '1'); end; {Set if feeder is enabled} function TTwainSource.SetFeederEnabled(Value: WordBool): TCapabilityRet; begin {Call SetOneValue to set value} Result := SetOneValue(CAP_FEEDERENABLED, TWTY_BOOL, @Value); end; {Returns if autofeed is enabled} function TTwainSource.GetAutofeed(var Return: Boolean): TCapabilityRet; var ItemType: TW_UINT16; Value : String; begin {Try to obtain value and make sure it is of type TW_BOOL} Result := GetOneValue(CAP_AUTOFEED, ItemType, Value, rcGet); if (Result = crSuccess) and (ItemType <> TWTY_BOOL) then Result := crUnsupported; {Return value, by checked the return value from GetOneValue} if Result = crSuccess then Return := (Value = '1'); end; {Set if autofeed is enabled} function TTwainSource.SetAutoFeed(Value: WordBool): TCapabilityRet; begin {Call SetOneValue to set value} Result := SetOneValue(CAP_AUTOFEED, TWTY_BOOL, @Value); end; {Used with property PendingXfers} function TTwainSource.GetPendingXfers: TW_INT16; var PendingXfers: TW_PENDINGXFERS; begin if Loaded and Enabled then begin {Call method to retrieve} if Owner.TwainProc(AppInfo, @Structure, DG_CONTROL, DAT_PENDINGXFERS, MSG_GET, @PendingXfers) = TWRC_SUCCESS then Result := PendingXfers.Count else Result := ERROR_INT16; {Some error ocurred while calling message} end else Result := ERROR_INT16; {Source not loaded/enabled} end; {Returns a TMsg structure} function MakeMsg(const Handle: THandle; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): TMsg; begin {Fill structure with the parameters} Result.hwnd := Handle; Result.message := uMsg; Result.wParam := wParam; Result.lParam := lParam; GetCursorPos(Result.pt); end; {Virtual window procedure handler} function VirtualWinProc(Handle: THandle; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LResult; stdcall; {Returns the TDelphiTwain object} function Obj: TDelphiTwain; begin Longint(Result) := GetWindowLong(Handle, GWL_USERDATA); end {function}; var Twain: TDelphiTwain; i : Integer; Msg : TMsg; begin {Tests for the message} case uMsg of {Creation of the window} WM_CREATE: {Stores the TDelphiTwain object handle} with pCreateStruct(lParam)^ do SetWindowLong(Handle, GWL_USERDATA, Longint(lpCreateParams)); {case} else begin {Try to obtain the current object pointer} Twain := Obj; if Assigned(Twain) then {If there are sources loaded, we need to verify} {this message} if (Twain.SourcesLoaded > 0) then begin {Convert parameters to a TMsg} Msg := MakeMsg(Handle, uMsg, wParam, lParam); {Tell about this message} FOR i := 0 TO Twain.SourceCount - 1 DO if ((Twain.Source[i].Loaded) and (Twain.Source[i].Enabled)) then if Twain.Source[i].ProcessMessage(Msg) then begin {Case this was a message from the source, there is} {no need for the default procedure to process} Result := 0; Exit; end; end {if (Twain.SourcesLoaded > 0)} end {case Else} end {case uMsg of}; {Calls method to handle} Result := DefWindowProc(Handle, uMsg, wParam, lParam); end; //npeter: 2004.01.12 //sets the acquired area function TTwainSource.SetImagelayoutFrame(const fLeft, fTop, fRight, fBottom: double): TCapabilityRet; var ImageLayout: TW_IMAGELAYOUT; begin if not Loaded then begin Result := crInvalidState; {In case the source is not loaded} exit; end; fillchar(ImageLayout,sizeof(TW_IMAGELAYOUT),0); with ImageLayout.Frame do begin Left:=FloatToFIX32(fLeft); Top:=FloatToFIX32(fTop); Right:=FloatToFIX32(fRight); Bottom:=FloatToFIX32(fBottom); end; {Call method and store return} Result := ResultToCapabilityRec(Owner.TwainProc(AppInfo, @Structure, DG_IMAGE, DAT_IMAGELAYOUT, MSG_SET, @ImageLayout)); end; //npeter: 2004.01.12 //enable/disable progress indicators function TTwainSource.SetIndicators(Value: boolean): TCapabilityRet; begin {Call SetOneValue to set value} Result := SetOneValue(CAP_INDICATORS, TWTY_BOOL, @Value); end; {Information for the virtual window class} var VirtualWinClass: TWNDClass; initialization {Registers the virtual window class} VirtualWinClass.hInstance := hInstance; VirtualWinClass.style := 0; VirtualWinClass.lpfnWndProc := @VirtualWinProc; VirtualWinClass.cbClsExtra := 0; VirtualWinClass.cbWndExtra := 0; VirtualWinClass.hIcon := 0; VirtualWinClass.hCursor := 0; VirtualWinClass.hbrBackground := COLOR_WINDOW + 1; VirtualWinClass.lpszMenuName := ''; VirtualWinClass.lpszClassName := VIRTUALWIN_CLASSNAME; Windows.RegisterClass(VirtualWinClass); finalization {Unregisters the virtual window class} Windows.UnregisterClass(VIRTUALWIN_CLASSNAME, hInstance); end.
{(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is frClarify.pas, released April 2000. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} unit frClarifyReturns; {$I JcfGlobal.inc} interface uses { delphi } Classes, Controls, Forms, StdCtrls, ExtCtrls, { local} JvEdit, frmBaseSettingsFrame, JvExStdCtrls, JvValidateEdit; type TfClarifyReturns = class(TfrSettingsFrame) rgReturnChars: TRadioGroup; gbRemoveReturns: TGroupBox; cbRemoveProcDefReturns: TCheckBox; cbRemoveVarReturns: TCheckBox; cbRemoveExprReturns: TCheckBox; cbRemovePropertyReturns: TCheckBox; cbRemoveReturns: TCheckBox; gbInsert: TGroupBox; cbUsesClauseOnePerLine: TCheckBox; cbInsertReturns: TCheckBox; cbBreakAfterUses: TCheckBox; private public constructor Create(AOwner: TComponent); override; procedure Read; override; procedure Write; override; end; implementation {$ifdef FPC} {$R *.lfm} {$else} {$R *.dfm} {$endif} uses SettingsTypes, JcfSettings, SetReturns, JcfHelp; constructor TfClarifyReturns.Create(AOwner: TComponent); begin inherited; fiHelpContext := HELP_CLARIFY_RETURNS; end; {------------------------------------------------------------------------------- worker procs } procedure TfClarifyReturns.Read; begin with JcfFormatSettings.Returns do begin cbRemoveReturns.Checked := RemoveBadReturns; cbRemovePropertyReturns.Checked := RemovePropertyReturns; cbRemoveProcDefReturns.Checked := RemoveProcedureDefReturns; cbRemoveVarReturns.Checked := RemoveVarReturns; cbRemoveExprReturns.Checked := RemoveExpressionReturns; cbInsertReturns.Checked := AddGoodReturns; cbUsesClauseOnePerLine.Checked := UsesClauseOnePerLine; cbBreakAfterUses.Checked := BreakAfterUses; rgReturnChars.ItemIndex := Ord(ReturnChars); end; end; procedure TfClarifyReturns.Write; begin with JcfFormatSettings.Returns do begin RemoveBadReturns := cbRemoveReturns.Checked; RemovePropertyReturns := cbRemovePropertyReturns.Checked; RemoveProcedureDefReturns := cbRemoveProcDefReturns.Checked; RemoveVarReturns := cbRemoveVarReturns.Checked; RemoveExpressionReturns := cbRemoveExprReturns.Checked; AddGoodReturns := cbInsertReturns.Checked; UsesClauseOnePerLine := cbUsesClauseOnePerLine.Checked; BreakAfterUses := cbBreakAfterUses.Checked; ReturnChars := TReturnChars(rgReturnChars.ItemIndex); end; end; end.
unit xSimpleInfoControl; interface uses SysUtils, Classes, xDBActionBase, FireDAC.Stan.Param, xFunction ; type /// <summary> /// 信息 /// </summary> TSimpleInfo = class private FSIRemark1: string; FSIID: Integer; FSIName: string; FSIRemark2: string; public constructor Create; destructor Destroy; override; procedure Assign(Source: TSimpleInfo); virtual; /// <summary> /// 编号 /// </summary> property SIID : Integer read FSIID write FSIID; /// <summary> /// 名称 /// </summary> property SIName : string read FSIName write FSIName; /// <summary> /// 备注1 /// </summary> property SIRemark1 : string read FSIRemark1 write FSIRemark1; /// <summary> /// 备注2 /// </summary> property SIRemark2 : string read FSIRemark2 write FSIRemark2; public /// <summary> /// 清除信息 /// </summary> procedure Clear; end; type TSimpleInfoAction = class(TDBActionBase) private FDBTableName : string; public constructor Create; overload; destructor Destroy; override; /// <summary> /// 数据库表名称 /// </summary> property DBTableName : string read FDBTableName write FDBTableName; /// <summary> /// 添加 /// </summary> procedure AddInfo(AInfo : TSimpleInfo); /// <summary> /// 删除 /// </summary> procedure DelInfo(AInfoID : Integer); /// <summary> /// 编辑 /// </summary> procedure EditInfo(AInfo : TSimpleInfo); /// <summary> /// 清空 /// </summary> procedure ClearInfo; /// <summary> /// 加载信息 /// </summary> procedure LoadInfo(slList : TStringList); end; type TSimpleInfoControl = class private FAction : TSimpleInfoAction; FSimpleInfoList: TStringList; FSimpleInfoName: string; function GetSimpleInfo(nIndex: Integer): TSimpleInfo; /// <summary> /// 获取最大编号 /// </summary> function GetMaxID : Integer; public constructor Create; destructor Destroy; override; public /// <summary> /// 信息列表 /// </summary> property SimpleInfoList : TStringList read FSimpleInfoList write FSimpleInfoList; property SimpleInfo[nIndex:Integer] : TSimpleInfo read GetSimpleInfo; /// <summary> /// 根据名称获取信息 /// </summary> /// <param name="sInfoName">信息名称</param> /// <param name="aNotInfo">排除的信息</param> /// <returns>获取的信息,不等于排除信息</returns> function GetInfoByName(sInfoName : string; aNotInfo : TSimpleInfo = nil) : TSimpleInfo; /// <summary> /// 根据编号获取信息 /// </summary> function GetInfoByID(nID : Integer): TSimpleInfo; /// <summary> /// 添加 /// </summary> procedure AddInfo(AInfo : TSimpleInfo); /// <summary> /// 删除 /// </summary> procedure DelInfo(nInfoID : Integer); /// <summary> /// 编辑 /// </summary> procedure EditInfo(AInfo : TSimpleInfo); /// <summary> /// 清空 /// </summary> procedure ClearInfo; /// <summary> /// 加载列表 /// </summary> procedure LoadList(sDBTableName : string); /// <summary> /// 简单信息名称 /// </summary> property SimpleInfoName : string read FSimpleInfoName write FSimpleInfoName; end; //var // ASimpleInfoControl : TSimpleInfoControl; implementation { TSimpleInfo } procedure TSimpleInfo.Assign(Source: TSimpleInfo); begin if Assigned(Source) then begin FSIID := Source.SIID ; FSIName := Source.SIName ; FSIRemark1 := Source.SIRemark1; FSIRemark2 := Source.SIRemark2; end; end; procedure TSimpleInfo.Clear; begin FSIID := -1; FSIName := ''; FSIRemark1 := ''; FSIRemark2 := ''; end; constructor TSimpleInfo.Create; begin Clear; end; destructor TSimpleInfo.Destroy; begin inherited; end; { TSimpleInfoAction } procedure TSimpleInfoAction.AddInfo(AInfo: TSimpleInfo); var sSQL : string; begin if not Assigned(AInfo) then Exit; sSQL := 'insert into ' + FDBTableName + ' (SIID, SIName, SIRemark1, SIRemark2)' + ' values (:SIID, :SIName, :SIRemark1, :SIRemark2)'; FQuery.SQL.Text := sSQL; with FQuery.Params, AInfo do begin ParamByName( 'SIID' ).Value := FSIID ; ParamByName( 'SIName' ).Value := FSIName ; ParamByName( 'SIRemark1' ).Value := FSIRemark1; ParamByName( 'SIRemark2' ).Value := FSIRemark2; end; ExecSQL; end; procedure TSimpleInfoAction.ClearInfo; begin FQuery.SQL.Text := 'delete from ' + FDBTableName; ExecSQL; end; constructor TSimpleInfoAction.Create; begin inherited Create; // FDBTableName := sDBTableName; end; procedure TSimpleInfoAction.DelInfo(AInfoID: Integer); var sSQL : string; begin sSQL := 'delete from ' + FDBTableName +' where SIID = %d'; FQuery.SQL.Text := Format(sSQL, [AInfoID]); ExecSQL; end; destructor TSimpleInfoAction.Destroy; begin inherited; end; procedure TSimpleInfoAction.EditInfo(AInfo: TSimpleInfo); var sSQL : string; begin if not Assigned(AInfo) then Exit; sSQL := 'update ' + FDBTableName + ' set SIName = :SIName, ' + 'SIRemark1 = :SIRemark1, SIRemark2 = :SIRemark2 where SIID = :SIID'; FQuery.SQL.Text := sSQL; with FQuery.Params, AInfo do begin ParamByName( 'SIID' ).Value := FSIID ; ParamByName( 'SIName' ).Value := FSIName ; ParamByName( 'SIRemark1' ).Value := FSIRemark1; ParamByName( 'SIRemark2' ).Value := FSIRemark2; end; ExecSQL; end; procedure TSimpleInfoAction.LoadInfo(slList: TStringList); var sSQL : string; AInfo : TSimpleInfo; begin if not Assigned(slList) then Exit; sSQL := 'select * from ' + FDBTableName; FQuery.SQL.Text := sSQL; FQuery.Open; while not FQuery.Eof do begin AInfo := TSimpleInfo.Create; AInfo.SIID := FQuery.FieldByName('SIID').AsInteger; AInfo.SIName := FQuery.FieldByName('SIName').AsString; AInfo.SIRemark1 := FQuery.FieldByName('SIRemark1').AsString; AInfo.SIRemark2 := FQuery.FieldByName('SIRemark2').AsString; slList.AddObject('', AInfo); FQuery.Next; end; FQuery.Close; end; { TSimpleInfoControl } procedure TSimpleInfoControl.AddInfo(AInfo : TSimpleInfo); begin if Assigned(AInfo) then begin AInfo.SIID := GetMaxID + 1; FAction.AddInfo(AInfo); FSimpleInfoList.AddObject('', AInfo); end; end; procedure TSimpleInfoControl.ClearInfo; begin FAction.ClearInfo; ClearStringList(FSimpleInfoList); end; constructor TSimpleInfoControl.Create; begin FAction := TSimpleInfoAction.Create; FSimpleInfoList:= TStringList.Create; FSimpleInfoName := '基本信息'; end; procedure TSimpleInfoControl.DelInfo(nInfoID: Integer); var i : Integer; begin for i := FSimpleInfoList.Count - 1 downto 0 do begin with TSimpleInfo(FSimpleInfoList.Objects[i]) do begin if SIID = nInfoID then begin TSimpleInfo(FSimpleInfoList.Objects[i]).Free; FSimpleInfoList.Delete(i); Break; end; end; end; FAction.DelInfo(nInfoID); end; destructor TSimpleInfoControl.Destroy; begin ClearStringList(FSimpleInfoList); FSimpleInfoList.Free; FAction.Free; inherited; end; procedure TSimpleInfoControl.EditInfo(AInfo: TSimpleInfo); begin FAction.EditInfo(AInfo); end; function TSimpleInfoControl.GetInfoByID(nID: Integer): TSimpleInfo; var i : Integer; AInfo : TSimpleInfo; begin Result := nil; for i := 0 to FSimpleInfoList.Count - 1 do begin AInfo := TSimpleInfo(FSimpleInfoList.Objects[i]); if (AInfo.SIID = nID) then begin Result := AInfo; Break; end; end; end; function TSimpleInfoControl.GetInfoByName(sInfoName: string; aNotInfo : TSimpleInfo): TSimpleInfo; var i : Integer; AInfo : TSimpleInfo; begin Result := nil; for i := 0 to FSimpleInfoList.Count - 1 do begin AInfo := TSimpleInfo(FSimpleInfoList.Objects[i]); if (Trim(AInfo.SIName) = Trim(sInfoName)) and (AInfo <> aNotInfo) then begin Result := AInfo; Break; end; end; end; function TSimpleInfoControl.GetMaxID: Integer; var i : Integer; begin Result := 0; for i := 0 to FSimpleInfoList.Count - 1 do begin with TSimpleInfo(FSimpleInfoList.Objects[i]) do begin if SIID > Result then begin Result := SIID; end; end; end; end; function TSimpleInfoControl.GetSimpleInfo(nIndex: Integer): TSimpleInfo; begin if (nIndex >= 0) and (FSimpleInfoList.Count > nIndex) then begin Result := TSimpleInfo(FSimpleInfoList.Objects[nIndex]); end else begin Result := nil; end; end; procedure TSimpleInfoControl.LoadList(sDBTableName : string); begin FAction.DBTableName := sDBTableName; FAction.LoadInfo(FSimpleInfoList); end; end.
unit ctrU1; interface uses Math, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ElAES; type TForm1 = class(TForm) edtKey: TLabeledEdit; memCipher: TMemo; lblCipherText: TLabel; memPlainText: TMemo; lblPlainText: TLabel; btnDecrypt: TButton; memCheck: TMemo; lblCheck: TLabel; procedure btnDecryptClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} function StringToHex(S: string): string; var i: integer; begin Result := ''; // Go throught every single characters, and convert them // to hexadecimal... for i := 1 to Length( S ) do Result := Result + IntToHex( Ord( S[i] ), 2 ); end; function HexToString(S: string): string; var i: integer; begin Result := ''; // Go throught every single hexadecimal characters, and convert // them to ASCII characters... for i := 1 to Length( S ) - 1 do begin // Only process chunk of 2 digit Hexadecimal... if ((i mod 2) = 1) then Result := Result + Chr( StrToInt( '0x' + Copy( S, i, 2 ))); end; end; procedure HexToVector8(S: string; out Vec: TAESBuffer); var i: integer; x: byte; begin for I := 0 to 15 do Vec[i] := 0; // Go throught every single hexadecimal characters, and convert // them to ASCII characters... for i := 1 to Length( S ) do begin // Only process chunk of 2 digit Hexadecimal... if ((i mod 2) = 1) then begin x := StrToInt( '0x' + Copy( S, i, 2 )); //Vec[i shr 1 - 1] := StrToInt( '0x' + Copy( S, i, 2 )); Vec[i shr 1] := x; end; end; end; procedure HexToVector(S: string; out Vec: TAESBuffer); var i: integer; x: byte; begin // Go throught every single hexadecimal characters, and convert // them to ASCII characters... for i := 1 to Length( S ) do begin // Only process chunk of 2 digit Hexadecimal... if ((i mod 2) = 1) then begin x := StrToInt( '0x' + Copy( S, i, 2 )); //Vec[i shr 1 - 1] := StrToInt( '0x' + Copy( S, i, 2 )); Vec[i shr 1] := x; end; end; end; function VectorToHex(Vec: TAESBuffer): string; var i: integer; begin Result := ''; for i := 0 to 15 do Result := Result + IntToHex(Vec[i], 2) {SetLength(Result, 32); for i := 0 to 15 do begin Result[i shl 1] := IntToHex(Hi(Vec[i]), 1)[1]; Result[i shl 1+1] := IntToHex(Lo(Vec[i]), 1)[1]; end;} end; procedure TForm1.btnDecryptClick(Sender: TObject); var Dest: TStringStream; Start, Stop: cardinal; //Size: integer; Key: TAESKey128; IV: TAESBuffer; EncryptedText: TStrings; T, S: string; m:array[0..3] of TAESBuffer; i, len: byte; ExpandedKey: TAESExpandedKey128; TempIn, TempOut: TAESBuffer; //Vector1, Vector2: TAESBuffer; begin s := StringReplace(memCipher.Text, #13#10, '', [rfReplaceAll]); len := Length(s) div 2; //ShowMessage('Length of message is: ' + IntToStr(Length(s))); // Convert hexadecimal to a strings before decrypting... //Source := TStringStream.Create( HexToString( StringReplace(memCipher.Text, #13#10, '', [rfReplaceAll]))); HexToVector(edtKey.Text, Key); {HexToVector8(Copy(S, 1, 16), IV); HexToVector(Copy(S, 17, 32), m[0]); HexToVector(Copy(S, 49, 32), m[1]); HexToVector(Copy(S, 81, 32), m[2]); HexToVector(Copy(S, 113, 32), m[3]); } HexToVector(Copy(S, 1, 32), IV); HexToVector(Copy(S, 33, 32), m[0]); HexToVector(Copy(S, 65, 32), m[1]); HexToVector(Copy(S, 97, 32), m[2]); HexToVector(Copy(S, 129, 32), m[3]); //KeySource := TStringStream.Create(HexToString(edtKey.Text)); //Source.ReadBuffer(IV, 16); //KeySource.ReadBuffer(Key, 16); Dest := TStringStream.Create( '' ); //for i := 0 to 2 do // Source.ReadBuffer(m[i], 16); memCheck.Text := 'Key: ' + VectorToHex(Key) + #13#10'IV: ' + VectorToHex(IV) + #13#10'm[0]: ' + VectorToHex(m[0]) + #13#10'm[1]: ' + VectorToHex(m[1]) + #13#10'm[2]: ' + VectorToHex(m[2]) + #13#10'm[3]: ' + VectorToHex(m[3]) + #13#10'Key: ' + UpperCase(edtKey.Text) + #13#10'IV: ' + UpperCase(Copy(S, 1, 32)) + #13#10'm[0]: ' + UpperCase(Copy(S, 33, 32)) + #13#10'm[1]: ' + UpperCase(Copy(S, 65, 32)) + #13#10'm[2]: ' + UpperCase(Copy(S, 97, 32)) + #13#10'm[3]: ' + UpperCase(Copy(S, 129, 32)); ExpandAESKeyForEncryption(Key, ExpandedKey); //Vector1 := IV; T := ''; for i := 0 to 3 do begin TempIn := m[i]; //Vector2 := TempIn; EncryptAES(IV, ExpandedKey, TempOut); PLongWord(@TempOut[0])^ := PLongWord(@TempOut[0])^ xor PLongWord(@TempIn[0])^; PLongWord(@TempOut[4])^ := PLongWord(@TempOut[4])^ xor PLongWord(@TempIn[4])^; PLongWord(@TempOut[8])^ := PLongWord(@TempOut[8])^ xor PLongWord(@TempIn[8])^; PLongWord(@TempOut[12])^ := PLongWord(@TempOut[12])^ xor PLongWord(@TempIn[12])^; T := T + VectorToHex(TempOut); Dest.Write(TempOut, SizeOf(TempOut)); Inc(IV[15]); //Vector1 := Vector2; end; try // Start decryption... //Size := Source.Size; //Start := GetTickCount; // Prepare key... //KeyStr := HexToString(edtKey.Text); //FillChar(Key, SizeOf(Key), 0); //Move(PChar(KeyStr)^, Key, Min(SizeOf(Key), Length(KeyStr))); // Decrypt now... //DecryptAESStreamCBC(Source, Source.Size - Source.Position, Key, IV, Dest); //Stop := GetTickCount; //Label8.Caption := IntToStr(Stop - Start) + ' ms'; //Refresh; // Display unencrypted text... //setLength(T, 2 * len); memPlainText.Text := T + #13#10 + HexToString(T);//Dest.DataString; finally //Source.Free; Dest.Free; end; end; {var Source: TStringStream; Dest: TStringStream; Start, Stop: cardinal; Size: integer; Key: TAESKey128; IV: TAESBuffer; begin // Encryption //Label_Status.Caption := 'Encrypting...'; //Refresh; Source := TStringStream.Create( memCipher.Text ); Dest := TStringStream.Create( '' ); try // Save data to memory stream... Size := Source.Size; Dest.WriteBuffer( Size, SizeOf(Size) ); // Prepare key... FillChar( Key, SizeOf(Key), 0 ); Move( PChar(edtKey.Text)^, Key, Min( SizeOf( Key ), Length( edtKey.Text ))); // Start encryption... //Start := GetTickCount; EncryptAESStreamCBC( Source, 0, Key, Dest ); //Stop := GetTickCount; //Label_Time.Caption := IntToStr(Stop - Start) + ' ms'; Refresh; // Display encrypted text using hexadecimals... Memo_CyperText.Lines.BeginUpdate; Memo_CyperText.Text := StringToHex( Dest.DataString ); Memo_CyperText.Lines.EndUpdate; finally Source.Free; Dest.Free; end; end; } end.
unit FormMain; {$mode objfpc}{$H+} {$Codepage utf8} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Menus, PythonEngine, PythonGUIInputOutput; type { TfmMain } TfmMain = class(TForm) mnuHelpAbout: TMenuItem; Panel1: TPanel; PythonEngine: TPythonEngine; PythonInputOutput1: TPythonInputOutput; PythonModule1: TPythonModule; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure PythonEngineAfterInit(Sender: TObject); procedure PythonInputOutput1SendData(Sender: TObject; const Data: AnsiString); procedure PythonInputOutput1SendUniData(Sender: TObject; const Data: UnicodeString); procedure PythonModule1Initialization(Sender: TObject); private { private declarations } procedure InitFonts; procedure DoPy_InitEngine; public { public declarations } end; var fmMain: TfmMain; implementation uses LclType, FormConsole, proc_py; {$R *.lfm} const cPyLibraryWindows: string = 'python37.dll'; cPyLibraryLinux: string = 'libpython3.8.so.1.0'; //default in Ubuntu 20.x cPyLibraryMac: string = '/Library/Frameworks/Python.framework/Versions/3.7/lib/libpython3.7.dylib'; cPyZipWindows: string = 'python37.zip'; function Py_s0(Self, Args : PPyObject): PPyObject; cdecl; begin with GetPythonEngine do Result:= PyUnicode_FromString('1.0.0'); end; function Py_s1(Self, Args : PPyObject): PPyObject; cdecl; const S0: string = 'begin.Привет.end'; begin with GetPythonEngine do Result:= PyUnicode_FromString(PChar(S0)); end; function Py_n1(Self, Args : PPyObject): PPyObject; cdecl; begin with GetPythonEngine do Result:= PyLong_FromLong(-100000); end; { TfmMain } procedure TfmMain.PythonInputOutput1SendData(Sender: TObject; const Data: AnsiString); begin if Assigned(fmConsole) then fmConsole.DoLogConsoleLine(Data); end; procedure TfmMain.PythonInputOutput1SendUniData(Sender: TObject; const Data: UnicodeString); begin if Assigned(fmConsole) then fmConsole.DoLogConsoleLine(Data); end; procedure TfmMain.PythonModule1Initialization(Sender: TObject); begin with Sender as TPythonModule do begin AddMethod('s0', @Py_s0, ''); AddMethod('s1', @Py_s1, ''); AddMethod('n1', @Py_n1, ''); end; end; procedure TfmMain.FormCreate(Sender: TObject); begin fmConsole:= TfmConsole.Create(Self); fmConsole.Parent:= Self; fmConsole.Align:= alClient; end; procedure TfmMain.FormShow(Sender: TObject); begin fmConsole.Show; fmConsole.edConsole.SetFocus; InitFonts; DoPy_InitEngine; end; procedure TfmMain.InitFonts; begin fmConsole.Font.Name:= cDefFixedFontName; fmConsole.Font.Size:= cDefFixedFontSize; fmConsole.edConsole.Font:= fmConsole.Font; end; procedure TfmMain.PythonEngineAfterInit(Sender: TObject); const NTest: Longint = 1 shl 30; var dir: string; begin dir:= ExtractFilePath(Application.ExeName); {$ifdef windows} Py_SetSysPath([dir+'DLLs', dir+cPyZipWindows], false); {$endif} Py_SetSysPath([dir+'Py'], true); //test for LongInt //Caption:= BoolToStr(PythonEngine.PyInt_AsLong(PythonEngine.PyInt_FromLong(NTest)) = NTest, true); end; procedure TfmMain.DoPy_InitEngine; var S: string; begin S:= {$ifdef windows} cPyLibraryWindows {$endif} {$ifdef linux} cPyLibraryLinux {$endif} {$ifdef darwin} cPyLibraryMac {$endif} ; PythonEngine.DllPath:= ExtractFileDir(S); PythonEngine.DllName:= ExtractFileName(S); PythonEngine.LoadDll; end; {$ifdef darwin} procedure InitMacLibPath; var N: integer; S: string; begin for N:= 11 downto 5 do begin S:= Format('/Library/Frameworks/Python.framework/Versions/3.%d/lib/libpython3.%d.dylib', [N, N]); if FileExists(S) then begin cPyLibraryMac:= S; exit; end; end; end; {$endif} initialization {$ifdef darwin} InitMacLibPath; {$endif} end.
{ Copyright (C) 2014, 2020 Matthias Bolte <matthias@tinkerforge.com> Redistribution and use in source and binary forms of this file, with or without modification, are permitted. See the Creative Commons Zero (CC0 1.0) License for more details. } unit BrickDaemon; {$ifdef FPC}{$mode OBJFPC}{$H+}{$endif} interface uses Device, LEConverter; const BRICK_DAEMON_FUNCTION_GET_AUTHENTICATION_NONCE = 1; BRICK_DAEMON_FUNCTION_AUTHENTICATE = 2; type TArray0To3OfUInt8 = array [0..3] of byte; TArray0To19OfUInt8 = array [0..19] of byte; TBrickDaemon = class(TDevice) public constructor Create(const uid: string; ipcon_: TObject); function GetAuthenticationNonce: TArray0To3OfUInt8; virtual; procedure Authenticate(const clientNonce: TArray0To3OfUInt8; const digest: TArray0To19OfUInt8); virtual; procedure GetIdentity(out uid: string; out connectedUid: string; out position: char; out hardwareVersion: TVersionNumber; out firmwareVersion: TVersionNumber; out deviceIdentifier: word); override; end; implementation uses IPConnection; constructor TBrickDaemon.Create(const uid: string; ipcon_: TObject); begin inherited Create(uid, ipcon_, 0, 'Brick Daemon'); apiVersion[0] := 2; apiVersion[1] := 0; apiVersion[2] := 0; responseExpected[BRICK_DAEMON_FUNCTION_GET_AUTHENTICATION_NONCE] := DEVICE_RESPONSE_EXPECTED_ALWAYS_TRUE; responseExpected[BRICK_DAEMON_FUNCTION_AUTHENTICATE] := DEVICE_RESPONSE_EXPECTED_TRUE; (ipcon_ as TIPConnection).AddDevice(self); end; function TBrickDaemon.GetAuthenticationNonce: TArray0To3OfUInt8; var request, response: TByteArray; i: longint; begin request := (ipcon as TIPConnection).CreateRequestPacket(self, BRICK_DAEMON_FUNCTION_GET_AUTHENTICATION_NONCE, 8); response := SendRequest(request, 12); for i := 0 to 3 do result[i] := LEConvertUInt8From(8 + i, response); end; procedure TBrickDaemon.Authenticate(const clientNonce: TArray0To3OfUInt8; const digest: TArray0To19OfUInt8); var request: TByteArray; i: longint; begin request := (ipcon as TIPConnection).CreateRequestPacket(self, BRICK_DAEMON_FUNCTION_AUTHENTICATE, 32); for i := 0 to Length(clientNonce) - 1 do LEConvertUInt8To(clientNonce[i], 8 + i, request); for i := 0 to Length(digest) - 1 do LEConvertUInt8To(digest[i], 12 + i, request); SendRequest(request, 0); end; procedure TBrickDaemon.GetIdentity(out uid: string; out connectedUid: string; out position: char; out hardwareVersion: TVersionNumber; out firmwareVersion: TVersionNumber; out deviceIdentifier: word); var i: longint; begin uid := ''; connectedUid := ''; position := char(0); for i := 0 to 2 do hardwareVersion[i] := 0; for i := 0 to 2 do firmwareVersion[i] := 0; deviceIdentifier := 0; end; end.
unit classesGeraeteAusgabe; interface uses System.SysUtils, System.StrUtils, Vcl.Dialogs, System.UITypes, classesPersonen, classesTelefonie, classesArbeitsmittel, 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, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TGeraeteAusgabe = class private AusgabeQuery : TFDQuery; FId : integer; FMitarbeiter : TMitarbeiter; FArbeitsmittel : TArbeitsmittel; FDatumAusgabe : TDateTime; FDatumRueckgabe: variant; FAusgabeDurch : TBenutzer; public property Id : integer read FId write FId; property Mitarbeiter : TMitarbeiter read FMitarbeiter write FMitarbeiter; property Arbeitsmittel : TArbeitsmittel read FArbeitsmittel write FArbeitsmittel; property DatumAusgabe : TDateTime read FDatumAusgabe write FDatumAusgabe; property DatumRueckgabe: variant read FDatumRueckgabe write FDatumRueckgabe; property AusgabeDurch : TBenutzer read FAusgabeDurch write FAusgabeDurch; constructor Create(Mitarbeiter: TMitarbeiter; Arbeitsmittel: TArbeitsmittel; DatumAusgabe: TDateTime; DatumRueckgabe: variant; AusgabeDurch: TBenutzer; Connection: TFDConnection); constructor CreateFromId(Id: integer; Connection: TFDConnection); end; implementation { TGeraetAusgaben } constructor TGeraeteAusgabe.Create(Mitarbeiter: TMitarbeiter; Arbeitsmittel: TArbeitsmittel; DatumAusgabe: TDateTime; DatumRueckgabe: variant; AusgabeDurch: TBenutzer; Connection: TFDConnection); begin self.Id := 0; self.Mitarbeiter := Mitarbeiter; self.Arbeitsmittel := Arbeitsmittel; self.DatumAusgabe := DatumAusgabe; self.DatumRueckgabe := DatumRueckgabe; self.AusgabeDurch := AusgabeDurch; self.AusgabeQuery := TFDQuery.Create(nil); self.AusgabeQuery.Connection := Connection; end; constructor TGeraeteAusgabe.CreateFromId(Id: integer; Connection: TFDConnection); var Geraete_Id : integer; Mitarbeiter_Id: integer; Benutzer_Id : integer; begin self.AusgabeQuery := TFDQuery.Create(nil); self.AusgabeQuery.Connection := Connection; with self.AusgabeQuery, SQL do begin Clear; Add('SELECT * FROM Mitarbeiter_Arbeitsmittel WHERE Id = :id'); ParamByName('id').Value := Id; Open; end; if self.AusgabeQuery.RecordCount = 1 then begin Geraete_Id := self.AusgabeQuery.FieldByName('Arbeitsmittel_Id').AsInteger; Mitarbeiter_Id := self.AusgabeQuery.FieldByName('Mitarbeiter_Id').AsInteger; Benutzer_Id := self.AusgabeQuery.FieldByName('UebergabeDurchBenutzer_Id').AsInteger; self.Id := self.AusgabeQuery.FieldByName('Id').AsInteger; self.Mitarbeiter := TMitarbeiter.CreateFromId(Mitarbeiter_Id, Connection); self.Arbeitsmittel := TArbeitsmittel.CreateFromId(Geraete_Id, Connection); self.DatumAusgabe := self.AusgabeQuery.FieldByName('DatumAusgabe').AsDateTime; self.DatumRueckgabe := self.AusgabeQuery.FieldByName('DatumRueckgabe').AsVariant; self.AusgabeDurch := TBenutzer.CreateFromId(Benutzer_Id, Connection); end; self.AusgabeQuery.Close; end; end.
unit BrickCamp.Model.TUser; interface uses Spring, Spring.Persistence.Mapping.Attributes, BrickCamp.Model.IProduct; type [Entity] [Table('CUSER')] TUser = class private [Column('ID', [cpRequired, cpPrimaryKey, cpNotNull, cpDontInsert], 0, 0, 0, 'primary key')] [AutoGenerated] FId: Integer; private FName: string; function GetId: Integer; function GetName: string; procedure SetName(const Value: string); public constructor Create(const Id: integer); reintroduce; property ID: Integer read GetId; [Column('NAME', [cpNotNull])] property Name: string read GetName write SetName; end; implementation { TEmployee } constructor TUser.Create(const Id: integer); begin FId := Id; end; function TUser.GetId: Integer; begin Result := FId; end; function TUser.GetName: string; begin Result := FName; end; procedure TUser.SetName(const Value: string); begin FName := Value; end; end.
{----------------------------------------------------------------------------- Author: Roman Fadeyev Purpose: Реализация IStockDataSource для файлов формата CSV History: -----------------------------------------------------------------------------} unit FC.StockData.CSV.StockDataSource; {$I Compiler.inc} interface uses SysUtils,Classes,DB, FC.Definitions,FC.StockData.StockDataSource, FC.StockData.StockDataConnectionFile; type TStockDataSource_CSV = class(TStockDataSource_StreamToMemory) public constructor Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval; aStream: TStream; aDate,aTime,aOpen,aHigh,aLow,aClose,aVolume: integer;const aFilter_StartFrom: TDateTime=0; const aFilter_GoTo: TDateTime=0); end; implementation uses DateUtils,BaseUtils; constructor TStockDataSource_CSV.Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval; aStream: TStream; aDate,aTime, aOpen, aHigh, aLow, aClose, aVolume: integer;const aFilter_StartFrom: TDateTime=0; const aFilter_GoTo: TDateTime=0); var aValues: array [0..6] of string; aFS : TFormatSettings; procedure CreateRecord; var aDateTime : TDateTime; aDataOpen : TStockRealNumber; aDataHigh : TStockRealNumber; aDataLow : TStockRealNumber; aDataClose : TStockRealNumber; aDataVolume : integer; begin try try aDateTime :=StrToDate(aValues[aDate],aFS)+StrToTime(aValues[aTime],aFS); except if aFS.ShortDateFormat='yyyy.mm.dd' then aFS.ShortDateFormat:='dd.mm.yyyy' else aFS.ShortDateFormat:='yyyy.mm.dd'; aDateTime :=StrToDate(aValues[aDate],aFS)+StrToTime(aValues[aTime],aFS); end; //Значение меньше стартового порога if (aFilter_StartFrom>0) and (CompareDateTime(aDateTime,aFilter_StartFrom)<0) then exit; //Значение больше конечного порога if (aFilter_GoTo>0) and (CompareDateTime(aDateTime,aFilter_GoTo)>0) then exit; aDataOpen :=StrToMoney(aValues[aOpen]); aDataHigh :=StrToMoney(aValues[aHigh]); aDataLow :=StrToMoney(aValues[aLow]); aDataClose :=StrToMoney(aValues[aClose]); aDataVolume:=StrToInt(aValues[aVolume]); except on E:EConvertError do raise Exception.CreateFmt('Cannot understand expression "%s": %s', [aValues[0]+aValues[1]+aValues[2]+aValues[3]+ aValues[4]+aValues[5],e.Message]); end; FRecordList.Add(TStockDataRecord.Create( aDateTime, aDataOpen, aDataHigh, aDataLow, aDataClose, aDataVolume)); end; var aString: string; aTemp : AnsiString; i,j : integer; b,b2 : boolean; begin inherited Create(aConnection, aSymbol,aInterval) ; aFS.DateSeparator:='.'; aFS.ShortTimeFormat:='hh:mm'; aFS.TimeSeparator:=':'; aFS.ShortDateFormat:='yyyy.mm.dd'; b:=true; //Алгоритм: вычитываем порционном из файла текст и складываем его в //aString. Тут же его разбираем на части и складываем в массив aValues //как только массив заполняется - формирует запись, очищаем массив и продолжаем далше aString:=''; i:=0; SetLength(aTemp,255); while b do begin j:=aStream.Read(PAnsiString(aTemp)^,255); b:=j=255; SetLength(aTemp,j); aString:=aString+aTemp; b2:=true; while b2 do begin while i<Length(aValues) do begin if not SplitString(aString,aValues[i],aString,[';',',',#13]) then begin aString:=aValues[i]; b2:=false; break; end; aValues[i]:=Trim(aValues[i]); inc(i); end; //массив полный, пора создать запись if (i=Length(aValues)) then begin CreateRecord; i:=0; end; end; end; if (aString<>'') and (i=High(aValues)) then begin aValues[i]:=aString; CreateRecord; end; end; end.
unit Unit2; interface uses UI.SizeForm, UI.Ani, UI.Frame, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, UI.Base, UI.Standard, FMX.Effects, FMX.Controls.Presentation, FMX.StdCtrls; type TForm2 = class(TSizeForm) layTitle: TLinearLayout; tvTitle: TTextView; btnMin: TTextView; btnClose: TTextView; layBackground: TLinearLayout; layBody: TRelativeLayout; btnOk: TButtonView; btnCancel: TButtonView; txvMsg: TTextView; procedure FormCreate(Sender: TObject); procedure btnCloseMouseEnter(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnMinClick(Sender: TObject); procedure btnMinMouseLeave(Sender: TObject); private { Private declarations } protected function GetShadowBackgroundColor: TAlphaColor; override; function GetShadowColor: TAlphaColor; override; public { Public declarations } procedure AniTextViewBackgroundColor(Sender: TObject; IsIn: Boolean); end; function TextDialog(AText: string): TModalResult; implementation {$R *.fmx} function TextDialog(AText: string): TModalResult; var Form2: TForm2; LScale: Single; begin Application.CreateForm(TForm2, Form2); LScale := Form2.GetSceneScale; Form2.txvMsg.Text := AText; Form2.Left := Application.MainForm.Left + (Round(Application.MainForm.Width * LScale) - Form2.Width) div 2; Form2.Top := Application.MainForm.Top + (Round(Application.MainForm.Height * LScale) - Form2.Height) div 2; Form2.btnOk.SetFocus; Result := Form2.ShowModal; Form2.Free; end; procedure TForm2.AniTextViewBackgroundColor(Sender: TObject; IsIn: Boolean); var SrcColor, DsetColor: TAlphaColor; begin SrcColor := TTextView(Sender).Background.ItemHovered.Color; DsetColor := SrcColor; if IsIn then begin TAlphaColorRec(DsetColor).A := $FF; end else begin TAlphaColorRec(DsetColor).A := $0; end; TFrameAnimator.AnimateColor(TTextView(Sender), 'Background.ItemHovered.Color', DsetColor); end; procedure TForm2.btnCloseClick(Sender: TObject); begin ModalResult := mrClose; end; procedure TForm2.btnCloseMouseEnter(Sender: TObject); begin AniTextViewBackgroundColor(Sender, True); end; procedure TForm2.btnMinClick(Sender: TObject); begin ShowMin(); end; procedure TForm2.btnMinMouseLeave(Sender: TObject); begin AniTextViewBackgroundColor(Sender, False); end; procedure TForm2.FormCreate(Sender: TObject); begin tvTitle.Text := Self.Caption; Resizable := False; ShowShadow := True; // ´ò¿ªÒõÓ° end; function TForm2.GetShadowBackgroundColor: TAlphaColor; begin Result := Fill.Color; end; function TForm2.GetShadowColor: TAlphaColor; begin Result := $7f101010; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit HCtlEdit; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type THeaderControlEditor = class(TForm) GroupBox1: TGroupBox; SectionList: TListBox; NewButton: TButton; DeleteButton: TButton; GroupBox2: TGroupBox; SectionText: TEdit; SectionWidth: TEdit; SectionMinWidth: TEdit; SectionMaxWidth: TEdit; SectionStyle: TComboBox; SectionAlignment: TComboBox; SectionAllowClick: TCheckBox; OkButton: TButton; CancelButton: TButton; ApplyButton: TButton; HelpButton: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; procedure FormCreate(Sender: TObject); procedure SectionListClick(Sender: TObject); procedure NewButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure SectionListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SectionListDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure SectionListDragDrop(Sender, Source: TObject; X, Y: Integer); procedure SectionControlExit(Sender: TObject); procedure SectionEditChange(Sender: TObject); procedure SectionComboChange(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure ApplyButtonClick(Sender: TObject); procedure HelpButtonClick(Sender: TObject); private HeaderControl: THeaderControl; TargetSections: THeaderSections; FocusIndex: Integer; UpdatingControls: Boolean; Modified: Boolean; procedure UpdateControls; procedure UpdateSection; procedure UpdateSectionList; end; function EditHeaderSections(HeaderSections: THeaderSections): Boolean; implementation uses DsnConst; {$R *.dfm} function EditHeaderSections(HeaderSections: THeaderSections): Boolean; begin with THeaderControlEditor.Create(Application) do try TargetSections := HeaderSections; HeaderControl.Sections.Assign(TargetSections); UpdateSectionList; if SectionList.Items.Count > 0 then SectionList.ItemIndex := 0; UpdateControls; ShowModal; Result := Modified; finally Free; end; end; function GetIntValue(Edit: TEdit): Integer; begin try Result := StrToInt(Edit.Text); except Edit.SelectAll; Edit.SetFocus; raise; end; end; procedure THeaderControlEditor.FormCreate(Sender: TObject); begin HeaderControl := THeaderControl.Create(Self); end; procedure THeaderControlEditor.UpdateControls; var Index: Integer; Section: THeaderSection; SectionSelected: Boolean; begin Index := SectionList.ItemIndex; SectionSelected := Index >= 0; UpdatingControls := True; if SectionSelected then begin Section := TargetSections[Index]; SectionText.Text := Section.Text; SectionWidth.Text := IntToStr(Section.Width); SectionMinWidth.Text := IntToStr(Section.MinWidth); SectionMaxWidth.Text := IntToStr(Section.MaxWidth); SectionStyle.ItemIndex := Ord(Section.Style); SectionAlignment.ItemIndex := Ord(Section.Alignment); SectionAllowClick.Checked := Section.AllowClick; end else begin SectionText.Text := ''; SectionWidth.Text := ''; SectionMinWidth.Text := ''; SectionMaxWidth.Text := ''; SectionStyle.ItemIndex := -1; SectionAlignment.ItemIndex := -1; SectionAllowClick.Checked := False; end; UpdatingControls := False; SectionText.Enabled := SectionSelected; SectionWidth.Enabled := SectionSelected; SectionMinWidth.Enabled := SectionSelected; SectionMaxWidth.Enabled := SectionSelected; SectionStyle.Enabled := SectionSelected; SectionAlignment.Enabled := SectionSelected; SectionAllowClick.Enabled := SectionSelected; end; procedure THeaderControlEditor.UpdateSection; var I: Integer; Section: THeaderSection; begin I := SectionList.ItemIndex; if I >= 0 then begin Section := TargetSections[SectionList.ItemIndex]; if Section.Text <> SectionText.Text then begin Section.Text := SectionText.Text; UpdateSectionList; SectionList.ItemIndex := I; end; Section.Width := GetIntValue(SectionWidth); Section.MinWidth := GetIntValue(SectionMinWidth); Section.MaxWidth := GetIntValue(SectionMaxWidth); Section.Style := THeaderSectionStyle(SectionStyle.ItemIndex); Section.Alignment := TAlignment(SectionAlignment.ItemIndex); Section.AllowClick := SectionAllowClick.Checked; UpdateControls; ApplyButton.Enabled := False; ApplyButton.Default := False; OkButton.Default := True; end; end; procedure THeaderControlEditor.UpdateSectionList; var I: Integer; S: string; begin SectionList.Items.BeginUpdate; try SectionList.Items.Clear; for I := 0 to TargetSections.Count - 1 do begin S := TargetSections[I].Text; if S = '' then S := SUntitled; SectionList.Items.Add(Format('%d - %s', [I, S])); end; finally SectionList.Items.EndUpdate; end; DeleteButton.Enabled := SectionList.Items.Count > 0; end; procedure THeaderControlEditor.SectionListClick(Sender: TObject); begin UpdateControls; end; procedure THeaderControlEditor.NewButtonClick(Sender: TObject); begin UpdateSection; TargetSections.Add; UpdateSectionList; SectionList.ItemIndex := TargetSections.Count - 1; UpdateControls; SectionText.SetFocus; Modified := True; end; procedure THeaderControlEditor.DeleteButtonClick(Sender: TObject); var I: Integer; begin I := SectionList.ItemIndex; if I >= 0 then begin TargetSections[I].Free; UpdateSectionList; if I >= SectionList.Items.Count then Dec(I); SectionList.ItemIndex := I; UpdateControls; SectionList.SetFocus; Modified := True; end; end; procedure THeaderControlEditor.SectionListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin with SectionList do if ItemIndex >= 0 then BeginDrag(False); end; procedure THeaderControlEditor.SectionListDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var NewIndex: Integer; begin if Source = SectionList then with SectionList do begin NewIndex := ItemAtPos(Point(X, Y), True); Accept := (NewIndex >= 0) and (NewIndex <> ItemIndex); if NewIndex = ItemIndex then NewIndex := -1; if State = dsDragEnter then FocusIndex := -1; if State = dsDragLeave then NewIndex := -1; if FocusIndex <> NewIndex then begin Canvas.DrawFocusRect(ItemRect(FocusIndex)); Canvas.DrawFocusRect(ItemRect(NewIndex)); end; FocusIndex := NewIndex; end else Accept := False; end; procedure THeaderControlEditor.SectionListDragDrop(Sender, Source: TObject; X, Y: Integer); var Index: Integer; begin if Sender = SectionList then with SectionList do begin Index := ItemAtPos(Point(X, Y), True); if Index >= 0 then begin TargetSections[ItemIndex].Index := Index; UpdateSectionList; ItemIndex := Index; Modified := True; end; end; end; procedure THeaderControlEditor.SectionControlExit(Sender: TObject); begin UpdateSection; end; procedure THeaderControlEditor.SectionEditChange(Sender: TObject); begin if not UpdatingControls then begin OkButton.Default := False; ApplyButton.Default := True; ApplyButton.Enabled := True; Modified := True; end; end; procedure THeaderControlEditor.SectionComboChange(Sender: TObject); begin if not UpdatingControls then begin UpdateSection; Modified := True; end; end; procedure THeaderControlEditor.OkButtonClick(Sender: TObject); begin UpdateSection; ModalResult := mrOk; end; procedure THeaderControlEditor.CancelButtonClick(Sender: TObject); begin TargetSections.Assign(HeaderControl.Sections); Modified := False; ModalResult := mrCancel; end; procedure THeaderControlEditor.ApplyButtonClick(Sender: TObject); begin UpdateSection; if ActiveControl is TEdit then TEdit(ActiveControl).SelectAll; end; procedure THeaderControlEditor.HelpButtonClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; end.
(* **************************************************************** *) (* Copyright (C) 1999-2010, Jon Gentle, All right reserved. *) (* **************************************************************** *) (* This program is free software; you can redistribute it under the *) (* terms of the Artistic License, as specified in the LICENSE file. *) (* **************************************************************** *) unit filedrv; interface uses Sysutils, classes, regexp; type PFile = ^TFile; TFile = class private inF: TFileStream; Feof: boolean; FlineCount: cardinal; Feol: TRegExp; public property lineCount: cardinal read FlineCount; property eof: boolean read Feof; public constructor init(f: string); function getLine: string; destructor Destroy; override; end; implementation constructor TFile.init(f: string); begin inF := TFileStream.Create(f, fmOpenRead); Feol := TRegExp.create('\R+', [MultiLine, SingleLine, Extended]); end; { We need to be more effective and use a buffer to get the data} function TFile.getLine: string; var c: char; status: cardinal; begin if eof then exit; c := #0; result := ''; while Feol.match(result) = false do begin status := inF.Read(c, 1); if status = 0 then begin Feof := true; exit; end; result := result + c; end; result := Feol.substitute(result, ''); inc(FlineCount); end; destructor TFile.Destroy; begin end; end.
unit caBaseDataset; {$INCLUDE ca.inc} interface uses // Standard Delphi units Classes, SysUtils, Windows, Forms, DB, caLog; type //---------------------------------------------------------------------------- // TcaRecordInfo   //---------------------------------------------------------------------------- PcaRecordInfo = ^TcaRecordInfo; TcaRecordInfo = record RecordID: Pointer; Bookmark: Pointer; BookMarkFlag: TBookmarkFlag; end; //---------------------------------------------------------------------------- // TcaBaseDataset   //---------------------------------------------------------------------------- TcaBaseDataset = class(TDataset) private FFieldsCreated: Boolean; FIsOpen: Boolean; FStartCalculated: Integer; FBufferMap: TStringList; // Property fields FReadOnly: Boolean; // Private methods function GetCalculatedFieldData(Field: TField; Buffer: Pointer; RecBuffer: PChar): Boolean; procedure GetPhysicalFieldData(Field: TField; Buffer: Pointer; RecBuffer: PChar); procedure FillBufferMap; // Property methods function GetReadOnly: Boolean; procedure SetReadOnly(const Value: Boolean); protected //--------------------------------------------------------------------------- // These virtual abstract methods must all be overridden by descendents   //--------------------------------------------------------------------------- // Basic DB methods  function CanOpen: Boolean; virtual; abstract; function GetFieldValue(Field: TField): Variant; virtual; abstract; procedure DoClose; virtual; abstract; procedure DoCreateFieldDefs; virtual; abstract; procedure DoDeleteRecord; virtual; abstract; procedure GetBlobField(Field: TField; Stream: TStream); virtual; abstract; procedure SetBlobField(Field: TField; Stream: TStream); virtual; abstract; procedure SetFieldValue(Field: TField; Value: Variant); virtual; abstract; // Buffer ID methods  function AllocateRecordID: Pointer; virtual; abstract; procedure DisposeRecordID(Value: Pointer); virtual; abstract; procedure GotoRecordID(Value: Pointer); virtual; abstract; // BookMark functions  procedure AllocateBookMark(RecordID: Pointer; Bookmark: Pointer); virtual; abstract; procedure DoGotoBookmark(Bookmark: Pointer); virtual; abstract; // Navigation methods  function Navigate(GetMode: TGetMode): TGetResult; virtual; abstract; procedure DoFirst; virtual; abstract; procedure DoLast; virtual; abstract; //--------------------------------------------------------------------------- // These virtual methods can be optionally overridden   //--------------------------------------------------------------------------- // Resource allocation  procedure AllocateBlobPointers(Buffer: PChar); virtual; procedure FreeBlobPointers(Buffer: PChar); virtual; procedure FreeRecordPointers(Buffer: PChar); virtual; // Record and field info  function GetDataSize: Integer; virtual; function GetFieldOffset(Field: TField): Integer; virtual; // Buffer / record conversion  procedure BufferToRecord(Buffer: PChar); virtual; procedure RecordToBuffer(Buffer: PChar); virtual; // Called before and after getting a set of field values  procedure DoBeforeGetFieldValue; virtual; procedure DoAfterGetFieldValue; virtual; procedure DoBeforeSetFieldValue(Inserting: Boolean); virtual; procedure DoAfterSetFieldValue(Inserting: Boolean); virtual; // BookMark functions  function GetBookMarkSize: Integer; virtual; // Internal properties  property IsOpen: Boolean read FIsOpen; //--------------------------------------------------------------------------- // These are the virtual methods from TDataset that have all been overridden  //--------------------------------------------------------------------------- function AllocRecordBuffer: PChar; override; function GetActiveRecordBuffer: PChar; virtual; function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override; function GetCanModify: Boolean; override; function GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override; function GetRecordSize: Word; override; function IsCursorOpen: Boolean; override; procedure ClearCalcFields(Buffer: PChar); override; procedure FreeRecordBuffer(var Buffer: PChar); override; procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override; procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override; procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override; procedure InternalClose; override; procedure InternalDelete; override; procedure InternalEdit; override; procedure InternalFirst; override; procedure InternalGotoBookmark(Bookmark: Pointer); override; procedure InternalHandleException; override; procedure InternalInsert; override; procedure InternalInitFieldDefs; override; procedure InternalInitRecord(Buffer: PChar); override; procedure InternalLast; override; procedure InternalOpen; override; procedure InternalPost; override; procedure InternalSetToRecord(Buffer: PChar); override; procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override; procedure SetFieldData(Field: TField; Buffer: Pointer); override; property ReadOnly: Boolean read GetReadOnly write SetReadOnly; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // Public virtual methods overridden from TDataset  function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override; function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override; end; //---------------------------------------------------------------------------- // TcaBlobStream   //---------------------------------------------------------------------------- TcaBlobStream = class(TMemoryStream) private // Private fields  FField: TBlobField; FDataSet: TcaBaseDataSet; FMode: TBlobStreamMode; FModified: Boolean; FOpened: Boolean; // Private methods  procedure LoadBlobData; procedure SaveBlobData; public constructor Create(Field: TBlobField; Mode: TBlobStreamMode); destructor Destroy; override; // Publc methods  function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; end; implementation //---------------------------------------------------------------------------- // TcaBaseDataset   //---------------------------------------------------------------------------- constructor TcaBaseDataset.Create(AOwner: TComponent); begin inherited; FBufferMap := TStringList.Create; end; destructor TcaBaseDataset.Destroy; begin if Active then Close; FBufferMap.Free; inherited; end; // Public virtual methods overridden from TDataset  function TcaBaseDataset.GetFieldData(Field: TField; Buffer: Pointer): Boolean; var RecBuffer: PChar; begin Result := False; if FIsOpen then begin RecBuffer := GetActiveRecordBuffer; if RecBuffer <> nil then begin Result := True; if Buffer <> nil then begin if (Field.FieldKind = fkCalculated) or (Field.FieldKind = fkLookup) then Result := GetCalculatedFieldData(Field, Buffer, RecBuffer) else begin GetPhysicalFieldData(Field, Buffer, RecBuffer); Result := True; end; end; end; end; end; function TcaBaseDataset.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; begin Result := TcaBlobStream.Create(Field as TBlobField, Mode); end; //---------------------------------------------------------------------------- // TcaBaseDataset   //---------------------------------------------------------------------------- // Resource allocation  procedure TcaBaseDataset.AllocateBlobPointers(Buffer: PChar); var Index: Integer; Offset: Integer; Stream: TMemoryStream; begin for Index := 0 to FieldCount - 1 do if Fields[Index].DataType in [ftBlob, ftMemo, ftGraphic] then begin Offset := GetFieldOffset(Fields[Index]); Stream := TMemoryStream.Create; Move(Pointer(Stream), (Buffer + Offset)^, SizeOf(Pointer)); end; end; procedure TcaBaseDataset.FreeBlobPointers(Buffer: PChar); var Index: Integer; Offset: Integer; FreeObject: TObject; begin for Index := 0 to FieldCount - 1 do if Fields[Index].DataType in [ftBlob, ftMemo, ftGraphic] then begin Offset := GetFieldOffset(Fields[Index]); Move((Buffer + Offset)^, Pointer(FreeObject), SizeOf(Pointer)); if FreeObject <> nil then FreeObject.Free; FreeObject := nil; Move(Pointer(FreeObject), (Buffer + Offset)^, SizeOf(Pointer)); end; end; procedure TcaBaseDataset.FreeRecordPointers(Buffer: PChar); begin FreeBlobPointers(Buffer); DisposeRecordID(PcaRecordInfo(Buffer + GetDataSize).RecordID); if PcaRecordInfo(Buffer + GetDataSize)^.BookMark <> nil then begin FreeMem(PcaRecordInfo(Buffer + GetDataSize)^.BookMark); PcaRecordInfo(Buffer + GetDataSize)^.BookMark := nil; end; end; // Record and field info  function TcaBaseDataset.GetDataSize: Integer; var Index: Integer; begin Result := 0; for Index := 0 to FieldCount - 1 do case Fields[Index].DataType of ftString: Result := Result + Fields[Index].Size + 1; ftInteger, ftSmallInt, ftDate, ftTime: Result := Result + SizeOf(Integer); ftFloat, ftCurrency, ftBCD, ftDateTime: Result := Result + SizeOf(Double); ftBoolean: Result := Result + SizeOf(WordBool); ftBlob, ftMemo, ftGraphic: Result := Result + SizeOf(Pointer); end; end; function TcaBaseDataset.GetFieldOffset(Field: TField): Integer; var FieldPos: Integer; Index: Integer; begin Result := 0; FieldPos := FBufferMap.Indexof(Field.FieldName); for Index := 0 to FieldPos - 1 do begin case FieldbyName(FBufferMap[Index]).DataType of ftString: Inc(Result, FieldbyName(FBufferMap[Index]).Size + 1); ftInteger, ftSmallInt, ftDate, ftTime: Inc(Result, SizeOf(Integer)); ftDateTime, ftFloat, ftBCD, ftCurrency: Inc(Result, SizeOf(Double)); ftBoolean: Inc(Result, SizeOf(WordBool)); ftBlob, ftGraphic, ftMemo: Inc(Result, SizeOf(Pointer)); end; end; end; // Buffer / record conversion  procedure TcaBaseDataset.BufferToRecord(Buffer: PChar); var Index: Integer; Offset: Integer; Stream: TStream; TempBool: WordBool; TempDouble: Double; TempInt: Integer; TempStr: string; begin for Index := 0 to FieldCount - 1 do begin Offset := GetFieldOffset(Fields[Index]); case Fields[Index].DataType of ftString: begin TempStr := PChar(Buffer + Offset); SetFieldValue(Fields[Index], TempStr); end; ftInteger, ftSmallInt, ftDate, ftTime: begin Move((Buffer + Offset)^, TempInt, SizeOf(Integer)); SetFieldValue(Fields[Index], TempInt); end; ftFloat, ftBCD, ftCurrency, ftDateTime: begin Move((Buffer + Offset)^, TempDouble, SizeOf(Double)); SetFieldValue(Fields[Index], TempDouble); end; ftBoolean: begin Move((Buffer + Offset)^, TempBool, SizeOf(WordBool)); SetFieldValue(Fields[Index], TempBool); end; ftBlob, ftGraphic, ftMemo: begin Move((Buffer + Offset)^, Pointer(Stream), SizeOf(Pointer)); Stream.Position := 0; SetBlobField(Fields[Index], Stream); end; end; end; end; procedure TcaBaseDataset.RecordToBuffer(Buffer: PChar); var Index: Integer; Offset: Integer; Stream: TStream; TempBool: WordBool; TempDouble: Double; TempInt: Integer; TempStr: string; Value: Variant; begin with PcaRecordInfo(Buffer + GetDataSize)^ do begin BookmarkFlag := bfCurrent; RecordID := AllocateRecordID; if GetBookMarkSize > 0 then begin if BookMark = nil then GetMem(BookMark, GetBookMarkSize); AllocateBookMark(RecordID, BookMark); end else BookMark := nil; end; DoBeforeGetFieldValue; for Index := 0 to FieldCount - 1 do begin if not (Fields[Index].DataType in [ftBlob, ftMemo, ftGraphic]) then Value := GetFieldValue(Fields[Index]); Offset := GetFieldOffset(Fields[Index]); case Fields[Index].DataType of ftString: begin TempStr := Value; if length(TempStr) > Fields[Index].Size then System.Delete(TempStr, Fields[Index].Size, length(TempStr) - Fields[Index].Size); StrLCopy(PChar(Buffer + Offset), PChar(TempStr), length(TempStr)); end; ftInteger, ftSmallInt, ftDate, ftTime: begin TempInt := Value; Move(TempInt, (Buffer + Offset)^, SizeOf(TempInt)); end; ftFloat, ftBCD, ftCurrency, ftDateTime: begin TempDouble := Value; Move(TempDouble, (Buffer + Offset)^, SizeOf(TempDouble)); end; ftBoolean: begin TempBool := Value; Move(TempBool, (Buffer + Offset)^, SizeOf(TempBool)); end; ftBlob, ftMemo, ftGraphic: begin Move((Buffer + Offset)^, Pointer(Stream), SizeOf(Pointer)); Stream.Size := 0; Stream.Position := 0; GetBlobField(Fields[Index], Stream); end; end; end; DoAfterGetFieldValue; end; // Called before and after getting a set of field values  procedure TcaBaseDataset.DoBeforeGetFieldValue; begin // Virtual  end; procedure TcaBaseDataset.DoAfterGetFieldValue; begin // Virtual  end; procedure TcaBaseDataset.DoBeforeSetFieldValue(Inserting: Boolean); begin // Virtual  end; procedure TcaBaseDataset.DoAfterSetFieldValue(Inserting: Boolean); begin // Virtual  end; // BookMark functions  function TcaBaseDataset.GetBookMarkSize: Integer; begin Result := 0; end; //---------------------------------------------------------------------------- // These are the virtual methods from TDataset that have all been overridden   //---------------------------------------------------------------------------- function TcaBaseDataset.AllocRecordBuffer: PChar; begin GetMem(Result, GetRecordSize); FillChar(Result^, GetRecordSize, 0); AllocateBlobPointers(Result); end; function TcaBaseDataset.GetActiveRecordBuffer: PChar; begin case State of dsBrowse: if IsEmpty then Result := nil else Result := ActiveBuffer; dsCalcFields: Result := CalcBuffer; dsFilter: Result := nil; dsEdit, dsInsert: Result := ActiveBuffer; else Result := nil; end; end; function TcaBaseDataset.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; begin Result := PcaRecordInfo(Buffer + GetDataSize).BookMarkFlag; end; function TcaBaseDataset.GetCanModify: Boolean; begin Result := not FReadOnly; end; function TcaBaseDataset.GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; begin Result := Navigate(GetMode); if (Result = grOk) then begin RecordToBuffer(Buffer); ClearCalcFields(Buffer); GetCalcFields(Buffer); end else if (Result = grError) and DoCheck then DatabaseError('No Records'); end; function TcaBaseDataset.GetRecordSize: Word; begin Result := GetDataSize + SizeOf(TcaRecordInfo) + CalcFieldsSize; FStartCalculated := GetDataSize + SizeOf(TcaRecordInfo); end; function TcaBaseDataset.IsCursorOpen: Boolean; begin Result := FIsOpen; end; procedure TcaBaseDataset.ClearCalcFields(Buffer: PChar); begin FillChar(Buffer[FStartCalculated], CalcFieldsSize, 0); end; procedure TcaBaseDataset.FreeRecordBuffer(var Buffer: PChar); begin FreeRecordPointers(Buffer); FreeMem(Buffer, GetRecordSize); end; procedure TcaBaseDataset.GetBookmarkData(Buffer: PChar; Data: Pointer); begin if BookMarkSize > 0 then AllocateBookMark(PcaRecordInfo(Buffer + GetDataSize).RecordID, Data); end; procedure TcaBaseDataset.SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); begin PcaRecordInfo(Buffer + GetDataSize).BookMarkFlag := Value; end; procedure TcaBaseDataset.InternalAddRecord(Buffer: Pointer; Append: Boolean); begin if Append then InternalLast; DoBeforeSetFieldValue(True); BufferToRecord(Buffer); DoAfterSetFieldValue(True); end; procedure TcaBaseDataset.InternalClose; begin BindFields(False); if DefaultFields then DestroyFields; DoClose; FIsOpen := False; end; procedure TcaBaseDataset.InternalDelete; begin DoDeleteRecord; end; procedure TcaBaseDataset.InternalEdit; begin if GetActiveRecordBuffer <> nil then InternalSetToRecord(GetActiveRecordBuffer); end; procedure TcaBaseDataset.InternalFirst; begin DoFirst; end; procedure TcaBaseDataset.InternalGotoBookmark(Bookmark: Pointer); begin DoGotoBookMark(BookMark); end; procedure TcaBaseDataset.InternalHandleException; begin Application.HandleException(Self); end; procedure TcaBaseDataset.InternalInsert; begin //  end; procedure TcaBaseDataset.InternalInitFieldDefs; begin FieldDefs.Clear; DoCreateFieldDefs; end; procedure TcaBaseDataset.InternalInitRecord(Buffer: PChar); begin FreeRecordPointers(Buffer); FillChar(Buffer^, GetRecordSize, 0); AllocateBlobPointers(Buffer); end; procedure TcaBaseDataset.InternalLast; begin DoLast; end; procedure TcaBaseDataset.InternalOpen; begin if CanOpen then begin // Bookmarks not supported  BookmarkSize := GetBookMarkSize; InternalInitFieldDefs; if DefaultFields and (not FFieldsCreated) then begin CreateFields; FFieldsCreated := True; end; BindFields(True); FIsOpen := True; FillBufferMap; end; end; procedure TcaBaseDataset.InternalPost; begin if FIsOpen then begin if State = dsInsert then InternalLast; DoBeforeSetFieldValue(State = dsInsert); BufferToRecord(GetActiveRecordBuffer); DoAfterSetFieldValue(State = dsInsert); end; end; procedure TcaBaseDataset.InternalSetToRecord(Buffer: PChar); begin GotoRecordID(PcaRecordInfo(Buffer + GetDataSize).RecordID); end; procedure TcaBaseDataset.SetBookmarkData(Buffer: PChar; Data: Pointer); begin if PcaRecordInfo(Buffer + GetDataSize)^.BookMark = nil then GetMem(PcaRecordInfo(Buffer + GetDataSize)^.BookMark, GetBookMarkSize); Move(PcaRecordInfo(Buffer + GetDataSize).BookMark^, Data, GetBookMarkSize); end; procedure TcaBaseDataset.SetFieldData(Field: TField; Buffer: Pointer); var Data: TDateTimeRec; Offset: Integer; RecBuffer: Pchar; TempBool: WordBool; TempDouble: Double; TimeStamp: TTimeStamp; begin if Active then begin RecBuffer := GetActiveRecordBuffer; if (RecBuffer <> nil) and (Buffer <> nil) then begin if (Field.FieldKind = fkCalculated) or (Field.FieldKind = fkLookup) then begin Inc(RecBuffer, FStartCalculated + Field.Offset); Boolean(RecBuffer[0]) := (Buffer <> nil); if Boolean(RecBuffer[0]) then CopyMemory(@RecBuffer[1], Buffer, Field.DataSize); end else begin Offset := GetFieldOffset(Field); case Field.DataType of ftInteger, ftDate, ftTime: begin Move(Integer(Buffer^), (RecBuffer + Offset)^, SizeOf(Integer)); end; ftSmallInt: begin Move(SmallInt(Buffer^), (RecBuffer + Offset)^, SizeOf(SmallInt)); end; ftBoolean: begin Move(WordBool(Buffer^), TempBool, SizeOf(WordBool)); Move(TempBool, (RecBuffer + Offset)^, SizeOf(WordBool)); end; ftString: begin StrLCopy(PChar(RecBuffer + Offset), Buffer, StrLen(PChar(Buffer))); end; ftDateTime: begin Data := TDateTimeRec(Buffer^); TimeStamp := MSecsToTimeStamp(Data.DateTime); TempDouble := TimeStampToDateTime(TimeStamp); Move(TempDouble, (RecBuffer + Offset)^, SizeOf(TempDouble)); end; ftFloat, ftCurrency: begin Move(Double(Buffer^), (RecBuffer + Offset)^, SizeOf(Double)); end; end; end; if not (State in [dsCalcFields, dsFilter, dsNewValue]) then DataEvent(deFieldChange, Longint(Field)); end; end; end; // Private methods  function TcaBaseDataset.GetCalculatedFieldData(Field: TField; Buffer: Pointer; RecBuffer: PChar): Boolean; begin Result := False; Inc(RecBuffer, FStartCalculated + Field.Offset); if (RecBuffer[0] <> #0) and (Buffer <> nil) then begin Result := True; CopyMemory(Buffer, @RecBuffer[1], Field.DataSize) end; end; procedure TcaBaseDataset.GetPhysicalFieldData(Field: TField; Buffer: Pointer; RecBuffer: PChar); var Data: TDateTimeRec; Offset: Integer; TempBool: WordBool; TempDouble: Double; TimeStamp: TTimeStamp; begin Offset := GetFieldOffset(Field); case Field.DataType of ftInteger, ftTime, ftDate: begin Move((RecBuffer + Offset)^, Integer(Buffer^), SizeOf(Integer)); end; ftSmallInt: begin Move((RecBuffer + Offset)^, SmallInt(Buffer^), SizeOf(SmallInt)); end; ftBoolean: begin Move((RecBuffer + Offset)^, TempBool, SizeOf(WordBool)); Move(TempBool, WordBool(Buffer^), SizeOf(WordBool)); end; ftString: begin StrLCopy(Buffer, PChar(RecBuffer + Offset), StrLen(PChar(RecBuffer + Offset))); end; ftCurrency, ftFloat: begin Move((RecBuffer + Offset)^, Double(Buffer^), SizeOf(Double)); end; ftDateTime: begin Move((RecBuffer + Offset)^, TempDouble, SizeOf(Double)); TimeStamp := DateTimeToTimeStamp(TempDouble); Data.DateTime := TimeStampToMSecs(TimeStamp); Move(Data, Buffer^, SizeOf(TDateTimeRec)); end; end; end; procedure TcaBaseDataset.FillBufferMap; var Index: Integer; begin FBufferMap.Clear; for Index := 0 to FieldCount - 1 do FBufferMap.Add(Fields[Index].FieldName); end; // Property methods  function TcaBaseDataset.GetReadOnly: Boolean; begin Result := FReadOnly; end; procedure TcaBaseDataset.SetReadOnly(const Value: Boolean); begin if Value <> FReadOnly then begin if Active then DatabaseError('Cannot change readonly property when dataset is active'); FReadOnly := Value; end; end; //---------------------------------------------------------------------------- // TcaBlobStream   //---------------------------------------------------------------------------- constructor TcaBlobStream.Create(Field: TBlobField; Mode: TBlobStreamMode); begin inherited Create; FField := Field; FMode := Mode; FDataSet := FField.DataSet as TcaBaseDataset; if Mode <> bmWrite then LoadBlobData; end; destructor TcaBlobStream.Destroy; begin if FModified then SaveBlobData; inherited; end; // Public methods  function TcaBlobStream.Read(var Buffer; Count: Integer): Longint; begin Result := inherited Read(Buffer, Count); FOpened := True; end; function TcaBlobStream.Write(const Buffer; Count: Integer): Longint; begin Result := inherited Write(Buffer, Count); FModified := True; end; // Private methods  procedure TcaBlobStream.LoadBlobData; var Offset: Integer; RecBuffer: PChar; Stream: TMemoryStream; begin Self.Size := 0; RecBuffer := FDataset.GetActiveRecordBuffer; if RecBuffer <> nil then begin Offset := FDataset.GetFieldOffset(FField); Move((RecBuffer + Offset)^, Pointer(Stream), SizeOf(Pointer)); Self.CopyFrom(Stream, 0); end; Position := 0; end; procedure TcaBlobStream.SaveBlobData; var Offset: Integer; RecBuffer: PChar; Stream: TMemoryStream; begin RecBuffer := FDataset.GetActiveRecordBuffer; if RecBuffer <> nil then begin Offset := FDataset.GetFieldOffset(FField); Move((RecBuffer + Offset)^, Pointer(Stream), SizeOf(Pointer)); Stream.Size := 0; Stream.CopyFrom(Self, 0); Stream.Position := 0; end; FModified := False; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1996,99 Inprise Corporation } { } {*******************************************************} unit DBInpReq; {$R-} interface uses Windows, Classes, SysUtils, Forms, Controls, StdCtrls, ExtCtrls, BDE, Dialogs; type TInputReqDialog = class(TForm) OKButton: TButton; CancelButton: TButton; InputOptions: TPanel; NoPromptAgain: TCheckBox; ErrorHelp: TLabel; InputMessage: TLabel; ErrorGroupBox: TPanel; ErrorGoupBoxSpacer: TPanel; DescriptionGroupBox: TPanel; DescriptionGroupBoxSpacer: TPanel; procedure InputOptionsClick(Sender: TObject); private FCBInfo: PCBInputDesc; FSelection: Integer; procedure SetCBInfo(var CBInfo: CBInputDesc); procedure GetCBInfo(var CBInfo: CBInputDesc); end; function InputRequest(var InputReqInfo: CBInputDesc): CBRType; implementation uses DB, DBTables; {$R *.DFM} function InputRequest(var InputReqInfo: CBInputDesc): CBRType; begin Result := cbrUSEDEF; with TInputReqDialog.Create(Application) do try SetCBInfo(InputReqInfo); begin ShowModal; if ModalResult = mrOK then begin GetCBInfo(InputReqInfo); Result := cbrCHKINPUT; end; end; finally Free; end; end; procedure TInputReqDialog.SetCBInfo(var CBInfo: CBInputDesc); procedure CreateRadioButton(Index: Integer; const Cap: string); begin with TRadioButton.Create(Self) do begin Top := Index * (Height + 2) + 7; Left := 5; Width := InputOptions.Width - 10; Caption := Cap; Tag := Index; OnClick := InputOptionsClick; Parent := InputOptions; end; end; var I: Integer; Sel: Integer; begin FCBInfo := @CBInfo; with CBInfo do begin InputMessage.Caption := szMsg; for I := 0 to iCount - 1 do CreateRadioButton(I, acbEntry[I].szKeyWord); NoPromptAgain.Checked := bSave; Sel := iSelection; if (Sel < 1) or (Sel > iCount) then Sel := 1; ActiveControl := InputOptions.Controls[Sel - 1] as TWinControl; end; end; procedure TInputReqDialog.GetCBInfo(var CBInfo: CBInputDesc); begin with CBInfo do begin iSelection := FSelection + 1; bSave := NoPromptAgain.Checked; end; end; procedure TInputReqDialog.InputOptionsClick(Sender: TObject); begin FSelection := (Sender as TComponent).Tag; if (FSelection >= 0) and (FSelection < FCBInfo.iCount) then ErrorHelp.Caption := FCBInfo.acbEntry[FSelection].szHelp; end; type TInputReqClass = class FCBInputReq: CBInputDesc; FCallBack: TBDECallback; public destructor Destroy; override; function InputReqCallBack(CBInfo: Pointer): CBRType; procedure RegisterCallback(Session: TSession); end; destructor TInputReqClass.Destroy; begin if Assigned(Session) and (Session.Active) then FCallBack.Free; end; procedure TInputReqClass.RegisterCallback(Session: TSession); begin FCallBack := TBDECallback.Create(Self, nil, cbINPUTREQ, @FCBInputReq, SizeOf(FCBInputReq), InputReqCallBack, False); end; function TInputReqClass.InputReqCallBack(CBInfo: Pointer): CBRType; begin try Result := InputRequest(PCBInputDesc(CBInfo)^); except Result := cbrUseDef; end; end; var InputReqClass: TInputReqClass; procedure InitProc(Session: TSession); begin InputReqClass.RegisterCallback(Session); end; initialization InputReqClass := TInputReqClass.Create; RegisterBDEInitProc(InitProc); finalization InputReqClass.Free; end.
{**********************************************} { TCustomChart (or derived) Editor Dialog } { Copyright (c) 1996-2004 by David Berneda } {**********************************************} unit TeeEdiPage; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QExtCtrls, TeePenDlg, TeCanvas, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, {$ENDIF} TeeProcs, TeEngine, Chart, TeeEdiGene, TeeNavigator; type TFormTeePage = class(TForm) L17: TLabel; SEPointsPerPage: TEdit; CBScaleLast: TCheckBox; LabelPages: TLabel; UDPointsPerPage: TUpDown; CBPageLegend: TCheckBox; ChartPageNavigator1: TChartPageNavigator; CBPageNum: TCheckBox; procedure SEPointsPerPageChange(Sender: TObject); procedure CBScaleLastClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure CBPageLegendClick(Sender: TObject); procedure CBPageNumClick(Sender: TObject); procedure ChartPageNavigator1ButtonClicked(Index: TTeeNavigateBtn); private { Private declarations } Function Chart:TCustomChart; Function PageNumTool(CreateTool:Boolean):TTeeCustomTool; public { Public declarations } Constructor CreateChart(Owner:TComponent; AChart:TCustomChart); end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeConst; { TFormTeePage } Constructor TFormTeePage.CreateChart(Owner:TComponent; AChart:TCustomChart); begin inherited Create(Owner); ChartPageNavigator1.Chart:=AChart; end; procedure TFormTeePage.SEPointsPerPageChange(Sender: TObject); begin if Showing then begin With Chart do if SEPointsPerPage.Text='' then MaxPointsPerPage:=0 else MaxPointsPerPage:=UDPointsPerPage.Position; ChartPageNavigator1ButtonClicked(nbCancel); end; end; procedure TFormTeePage.CBScaleLastClick(Sender: TObject); begin Chart.ScaleLastPage:=CBScaleLast.Checked; end; procedure TFormTeePage.FormShow(Sender: TObject); var tmp : TTeeCustomTool; begin if Chart<>nil then With Chart do begin UDPointsPerPage.Position :=MaxPointsPerPage; CBScaleLast.Checked :=ScaleLastPage; CBPageLegend.Checked :=Legend.CurrentPage; ChartPageNavigator1ButtonClicked(nbCancel); end; CBPageNum.Visible:=Assigned(TeePageNumToolClass); tmp:=PageNumTool(False); CBPageNum.Checked:=Assigned(tmp) and tmp.Active; end; { try to find a PageNumber tool in Chart. If not found, create it } Function TFormTeePage.PageNumTool(CreateTool:Boolean):TTeeCustomTool; var t : Integer; tmp : TComponent; begin if Chart<>nil then with Chart.Tools do for t:=0 to Count-1 do if Items[t] is TeePageNumToolClass then begin result:=Items[t]; exit; end; { not found } if CreateTool then { do create } begin tmp:=Chart; if Assigned(tmp) and Assigned(tmp.Owner) then tmp:=tmp.Owner; result:=TeePageNumToolClass.Create(tmp); result.Name:=TeeGetUniqueName(tmp,TeeMsg_DefaultToolName); if Chart<>nil then Chart.Tools.Add(result); end else result:=nil; end; procedure TFormTeePage.CBPageLegendClick(Sender: TObject); begin Chart.Legend.CurrentPage:=CBPageLegend.Checked; end; procedure TFormTeePage.ChartPageNavigator1ButtonClicked( Index: TTeeNavigateBtn); begin With Chart do LabelPages.Caption:=Format(TeeMsg_PageOfPages,[Page,NumPages]); end; procedure TFormTeePage.CBPageNumClick(Sender: TObject); begin { show / hide the Page Number tool } PageNumTool(True).Active:=(Sender as TCheckBox).Checked; { 5.02 } end; function TFormTeePage.Chart: TCustomChart; begin result:=ChartPageNavigator1.Chart; end; end.
unit TestCase1; {$mode objfpc}{$H+} interface uses chocolatey, Classes, SysUtils, fpcunit, testutils, testregistry; type { TTestCase1 } TTestCase1= class(TTestCase) private FChoco: TChocolatey; protected procedure SetUp; override; procedure TearDown; override; published procedure Search; procedure DivideLines; procedure PackageInfo; end; implementation procedure TTestCase1.SetUp; begin FChoco:= TChocolatey.Create; end; procedure TTestCase1.TearDown; begin FChoco.Free; end; procedure TTestCase1.Search; var PackageString: String; IsChocoRun: Boolean; begin PackageString:= FChoco.Search('pascal'); IsChocoRun:= (Pos('Chocolatey', PackageString) >= 1); Assert(IsChocoRun); end; procedure TTestCase1.DivideLines; var DividedLines: TStringList; begin DividedLines:= TStringList.Create; FChoco.DivideLines('abc' + #13#10 + 'def' + #13#10, DividedLines); AssertEquals(2, DividedLines.Count); FChoco.DivideLines('ghi' + #13#10 + 'jkl' + #13#10 + 'mno' + #13#10, DividedLines); AssertEquals(3, DividedLines.Count); DividedLines.Free; end; procedure TTestCase1.PackageInfo; var InfoString: String; P: Integer; begin InfoString:= FChoco.PackageInfo('freepascal'); P:= Pos('freepascal.org', InfoString); AssertTrue(P >= 1); end; initialization RegisterTest(TTestCase1); end.
unit HGM.GraphQL.Method; interface uses System.Generics.Collections, System.SysUtils, HGM.GraphQL.Types, HGM.GraphQL.Fields; type TGraphMethod = class private FName: string; FFields: TGraphFields; FArgs: TGraphArgList; procedure SetArgs(const Value: TGraphArgList); procedure SetFields(const Value: TGraphFields); procedure SetName(const Value: string); public property Name: string read FName write SetName; property Args: TGraphArgList read FArgs write SetArgs; property Fields: TGraphFields read FFields write SetFields; function ToString: string; reintroduce; destructor Destroy; override; end; TGraphMethods = class(TObjectList<TGraphMethod>) constructor Create; reintroduce; function ToString: string; reintroduce; end; implementation { TGraphMethod } destructor TGraphMethod.Destroy; begin if Assigned(FArgs) then FArgs.Free; if Assigned(FFields) then FFields.Free; inherited; end; procedure TGraphMethod.SetArgs(const Value: TGraphArgList); begin FArgs := Value; end; procedure TGraphMethod.SetFields(const Value: TGraphFields); begin FFields := Value; end; procedure TGraphMethod.SetName(const Value: string); begin FName := Value; end; function TGraphMethod.ToString: string; begin Result := FName + ' '; if Assigned(FArgs) then Result := Result + FArgs.ToString + ' '; if Assigned(FFields) then Result := Result + FFields.ToString + ' '; end; { TGraphMethods } constructor TGraphMethods.Create; begin inherited Create; end; function TGraphMethods.ToString: string; var i: Integer; begin for i := 0 to Pred(Count) do Result := Result + Items[i].ToString + ', '; Result := '{' + Result.TrimRight([',', ' ']) + '}'; end; end.
unit AsciiImage.RenderContext.Types; interface uses Graphics, {$if CompilerVersion > 22} System.Types, System.UITypes; {$Else} Types; {$IfEnd} {$If declared(TGraphic)} const Framework = 'VCL'; {$Else} const Framework = 'FM'; const clNone = TAlphaColorRec.Null; const clBlack = TAlphaColorRec.Black; {$IfEnd} type {$If Framework = 'VCL'} TColorValue = TColor; {$Else} TColorValue = TAlphaColor; {$IfEnd} {$if (CompilerVersion > 22) and declared(System.Types.TPointF)} TPointF = System.Types.TPointF; {$Else} TPointF = record X: Single; Y: Single; end; {$IfEnd} {$if (CompilerVersion > 22) and declared(System.Types.TRectF)} TRectF = System.Types.TRectF; {$Else} TRectF = record Left, Top, Right, Bottom: Single; end; {$IfEnd} {$if CompilerVersion > 22} TRect = System.Types.TRect; {$Else} TRect = Types.TRect; {$IfEnd} function PointF(AX, AY: Single): TPointF; inline; function RectF(ALeft, ATop, ARight, ABottom: Single): TRectF; inline; implementation function PointF(AX, AY: Single): TPointF; begin Result.X := AX; Result.Y := AY; end; function RectF(ALeft, ATop, ARight, ABottom: Single): TRectF; begin Result.Left := ALeft; Result.Top := ATop; Result.Right := ARight; Result.Bottom := ABottom; end; end.
object ViewDefault: TViewDefault Left = 0 Top = 0 Align = alClient BorderStyle = bsNone Caption = 'ViewDefault' ClientHeight = 497 ClientWidth = 779 Color = clWhite Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object PanelView: TPanel Left = 0 Top = 0 Width = 779 Height = 497 Align = alClient BevelOuter = bvNone TabOrder = 0 object PanelHeader: TPanel Left = 0 Top = 0 Width = 779 Height = 120 Align = alTop BevelOuter = bvNone ParentBackground = False TabOrder = 0 object PanelTitle: TPanel Left = 0 Top = 0 Width = 441 Height = 120 Align = alLeft BevelOuter = bvNone Padding.Left = 30 Padding.Right = 30 TabOrder = 0 object lblTitle: TLabel Left = 30 Top = 0 Width = 381 Height = 64 Align = alClient AutoSize = False Caption = 'Formul'#225'rio Padr'#227'o' Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -24 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False Layout = tlBottom StyleElements = [] ExplicitLeft = 0 ExplicitWidth = 561 ExplicitHeight = 60 end object lblSubtitle: TLabel Left = 30 Top = 64 Width = 381 Height = 56 Align = alBottom AutoSize = False Caption = 'Descri'#231#227'o do formul'#225'rio padr'#227'o....' WordWrap = True StyleElements = [] ExplicitTop = 60 end end end object PanelContent: TPanel Left = 0 Top = 120 Width = 779 Height = 377 Align = alClient BevelOuter = bvNone Color = clWhite Padding.Left = 20 Padding.Top = 20 Padding.Right = 20 Padding.Bottom = 20 ParentBackground = False TabOrder = 1 object PanelBody: TPanel Left = 20 Top = 20 Width = 739 Height = 337 Align = alClient BevelOuter = bvNone Color = clWhite ParentBackground = False TabOrder = 0 end end end end
{$i deltics.unicode.inc} unit Deltics.Unicode.Class_; interface uses Deltics.Unicode.Types; type Unicode = class public class function AnsiCharToWide(const aChar: AnsiChar): WideChar; class procedure CodepointToSurrogates(const aCodepoint: Codepoint; var aHiSurrogate, aLoSurrogate: WideChar); class procedure CodepointToUtf8(const aCodepoint: Codepoint; var aUtf8Array: Utf8Array); overload; class procedure CodepointToUtf8(const aCodepoint: Codepoint; var aUtf8: PUtf8Char; var aMaxChars: Integer); overload; class function IsHiSurrogate(const aChar: WideChar): Boolean; class function IsLoSurrogate(const aChar: WideChar): Boolean; class function Json(const aChar: WideChar): Utf8String; overload; class function Json(const aCodepoint: Codepoint): Utf8String; overload; class function Ref(const aChar: WideChar): String; overload; class function Ref(const aCodepoint: Codepoint): String; overload; class function SurrogatesToCodepoint(const aHiSurrogate, aLoSurrogate: WideChar): Codepoint; class function Utf8Array(const aChars: array of Utf8Char): Utf8Array; class function Utf8ToCodepoint(const aUtf8: Utf8Array): Codepoint; overload; class function Utf8ToCodepoint(var aUtf8: PUtf8Char; var aUtf8Count: Integer): Codepoint; overload; class function Utf8ToUtf16(const aString: Utf8String): UnicodeString; overload; class procedure Utf8ToUtf16(var aUtf8: PUtf8Char; var aUtf8Count: Integer; var aUtf16: PWideChar; var aUtf16Count: Integer); overload; class function Utf16ToUtf8(const aString: UnicodeString): Utf8String; overload; class procedure Utf16ToUtf8(var aUtf16: PWideChar; var aUtf16Count: Integer; var aUtf8: PUtf8Char; var aUtf8Count: Integer); overload; class procedure Utf16BeToUtf8(var aUtf16: PWideChar; var aUtf16Count: Integer; var aUtf8: PUtf8Char; var aUtf8Count: Integer); class function WideCharToAnsi(const aChar: WideChar): AnsiChar; class function Escape(const aChar: WideChar; const aEncoder: UnicodeEscape): String; overload; class function Escape(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): String; overload; class function EscapeA(const aChar: WideChar; const aEncoder: UnicodeEscape): AnsiString; overload; class function EscapeA(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): AnsiString; overload; class function EscapeUtf8(const aChar: WideChar; const aEncoder: UnicodeEscape): Utf8String; overload; class function EscapeUtf8(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): Utf8String; overload; class function EscapeW(const aChar: WideChar; const aEncoder: UnicodeEscape): UnicodeString; overload; class function EscapeW(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): UnicodeString; overload; end; function ToBin(aChar: Codepoint): String; overload; function ToBin(aChar: Utf8Char): String; overload; implementation uses SysUtils, Windows, Deltics.Unicode.Escape.Index, Deltics.Unicode.Escape.Json, Deltics.Unicode.Exceptions, Deltics.Unicode.Transcode.CodepointToUtf8, Deltics.Unicode.Transcode.Utf8ToCodepoint, Deltics.Unicode.Transcode.Utf8ToUtf16, Deltics.Unicode.Transcode.Utf16ToUtf8; const MAX_Codepoint = $0010ffff; MIN_HiSurrogate : WideChar = #$d800; MAX_HiSurrogate : WideChar = #$dbff; MIN_LoSurrogate : WideChar = #$dc00; MAX_LoSurrogate : WideChar = #$dfff; MIN_Supplemental = $10000; MIN_Surrogate = $d800; MAX_Surrogate = $dfff; const MAP_AnsiToWide : array[AnsiChar] of WideChar = ( #$0000, #$0001, #$0002, #$0003, #$0004, #$0005, #$0006, #$0007, #$0008, #$0009, #$000A, #$000B, #$000C, #$000D, #$000E, #$000F, #$0010, #$0011, #$0012, #$0013, #$0014, #$0015, #$0016, #$0017, #$0018, #$0019, #$001A, #$001B, #$001C, #$001D, #$001E, #$001F, #$0020, #$0021, #$0022, #$0023, #$0024, #$0025, #$0026, #$0027, #$0028, #$0029, #$002A, #$002B, #$002C, #$002D, #$002E, #$002F, #$0030, #$0031, #$0032, #$0033, #$0034, #$0035, #$0036, #$0037, #$0038, #$0039, #$003A, #$003B, #$003C, #$003D, #$003E, #$003F, #$0040, #$0041, #$0042, #$0043, #$0044, #$0045, #$0046, #$0047, #$0048, #$0049, #$004A, #$004B, #$004C, #$004D, #$004E, #$004F, #$0050, #$0051, #$0052, #$0053, #$0054, #$0055, #$0056, #$0057, #$0058, #$0059, #$005A, #$005B, #$005C, #$005D, #$005E, #$005F, #$0060, #$0061, #$0062, #$0063, #$0064, #$0065, #$0066, #$0067, #$0068, #$0069, #$006A, #$006B, #$006C, #$006D, #$006E, #$006F, #$0070, #$0071, #$0072, #$0073, #$0074, #$0075, #$0076, #$0077, #$0078, #$0079, #$007A, #$007B, #$007C, #$007D, #$007E, #$007F, #$20AC, #$0081, #$201A, #$0192, #$201E, #$2026, #$2020, #$2021, #$02C6, #$2030, #$0160, #$2039, #$0152, #$008D, #$017D, #$008F, #$0090, #$2018, #$2019, #$201C, #$201D, #$2022, #$2013, #$2014, #$02DC, #$2122, #$0161, #$203A, #$0153, #$009D, #$017E, #$0178, #$00A0, #$00A1, #$00A2, #$00A3, #$00A4, #$00A5, #$00A6, #$00A7, #$00A8, #$00A9, #$00AA, #$00AB, #$00AC, #$00AD, #$00AE, #$00AF, #$00B0, #$00B1, #$00B2, #$00B3, #$00B4, #$00B5, #$00B6, #$00B7, #$00B8, #$00B9, #$00BA, #$00BB, #$00BC, #$00BD, #$00BE, #$00BF, #$00C0, #$00C1, #$00C2, #$00C3, #$00C4, #$00C5, #$00C6, #$00C7, #$00C8, #$00C9, #$00CA, #$00CB, #$00CC, #$00CD, #$00CE, #$00CF, #$00D0, #$00D1, #$00D2, #$00D3, #$00D4, #$00D5, #$00D6, #$00D7, #$00D8, #$00D9, #$00DA, #$00DB, #$00DC, #$00DD, #$00DE, #$00DF, #$00E0, #$00E1, #$00E2, #$00E3, #$00E4, #$00E5, #$00E6, #$00E7, #$00E8, #$00E9, #$00EA, #$00EB, #$00EC, #$00ED, #$00EE, #$00EF, #$00F0, #$00F1, #$00F2, #$00F3, #$00F4, #$00F5, #$00F6, #$00F7, #$00F8, #$00F9, #$00FA, #$00FB, #$00FC, #$00FD, #$00FE, #$00FF); type TByteArray = array of Byte; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function ToBin(aChar: Codepoint): String; const BIT_CHAR: array[FALSE..TRUE] of Char = ('0', '1'); var i: Integer; mask: Codepoint; begin mask := $80000000; SetLength(result, 32); for i := 1 to 32 do begin result[i] := BIT_CHAR[(aChar and mask) = mask]; mask := mask shr 1; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function ToBin(aChar: Utf8Char): String; const BIT_CHAR: array[FALSE..TRUE] of Char = ('0', '1'); var i: Integer; mask: Codepoint; begin mask := $80; SetLength(result, 8); for i := 1 to 8 do begin result[i] := BIT_CHAR[(Byte(aChar) and mask) = mask]; mask := mask shr 1; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.AnsiCharToWide(const aChar: AnsiChar): WideChar; begin result := MAP_AnsiToWide[aChar]; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Unicode.CodepointToSurrogates(const aCodepoint: Codepoint; var aHiSurrogate: WideChar; var aLoSurrogate: WideChar); var codepoint: Deltics.Unicode.Types.Codepoint; begin if (aCodepoint > MAX_Codepoint) then raise EInvalidCodepoint.Create(aCodepoint); if ((aCodepoint >= MIN_Surrogate) and (aCodepoint <= MAX_Surrogate)) then raise EInvalidCodepoint.Create('The codepoint %s is reserved for surrogate encoding', [Ref(aCodepoint)]); if (aCodepoint < MIN_Supplemental) then raise EInvalidCodepoint.Create('The codepoint %s is not in the Supplementary Plane', [Ref(aCodepoint)]); codepoint := aCodepoint - $10000; aHiSurrogate := WideChar($d800 or ((codepoint shr 10) and $03ff)); aLoSurrogate := WideChar($dc00 or (codepoint and $03ff)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Unicode.CodepointToUtf8(const aCodepoint: Codepoint; var aUtf8: PUtf8Char; var aMaxChars: Integer); begin _CodepointToUtf8(aCodepoint, aUtf8, aMaxChars); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Unicode.CodepointToUtf8(const aCodepoint: Codepoint; var aUtf8Array: Utf8Array); var ptr: PUtf8Char; len: Integer; begin SetLength(aUtf8Array, 4); ptr := @aUtf8Array[0]; len := 4; _CodepointToUtf8(aCodepoint, ptr, len); SetLength(aUtf8Array, 4 - len); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Escape(const aChar: WideChar; const aEncoder: UnicodeEscape): String; begin SetLength(result, aEncoder.EscapedLength(aChar)); {$ifdef UNICODE} aEncoder.EscapeW(aChar, PWideChar(result)); {$else} aEncoder.EscapeA(aChar, PAnsiChar(result)); {$endif} end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Escape(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): String; begin SetLength(result, aEncoder.EscapedLength(aCodepoint)); {$ifdef UNICODE} aEncoder.EscapeW(aCodepoint, PWideChar(result)); {$else} aEncoder.EscapeA(aCodepoint, PAnsiChar(result)); {$endif} end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.EscapeA(const aChar: WideChar; const aEncoder: UnicodeEscape): AnsiString; begin SetLength(result, aEncoder.EscapedLength(aChar)); aEncoder.EscapeA(aChar, PAnsiChar(result)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.EscapeA(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): AnsiString; begin SetLength(result, aEncoder.EscapedLength(aCodepoint)); aEncoder.EscapeA(aCodepoint, PAnsiChar(result)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.EscapeUtf8(const aChar: WideChar; const aEncoder: UnicodeEscape): Utf8String; begin SetLength(result, aEncoder.EscapedLength(aChar)); aEncoder.EscapeA(aChar, PAnsiChar(result)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.EscapeUtf8(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): Utf8String; begin SetLength(result, aEncoder.EscapedLength(aCodepoint)); aEncoder.EscapeA(aCodepoint, PAnsiChar(result)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.EscapeW(const aChar: WideChar; const aEncoder: UnicodeEscape): UnicodeString; begin SetLength(result, aEncoder.EscapedLength(aChar)); aEncoder.EscapeW(aChar, PWideChar(result)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.EscapeW(const aCodePoint: Codepoint; const aEncoder: UnicodeEscape): UnicodeString; begin SetLength(result, aEncoder.EscapedLength(aCodepoint)); aEncoder.EscapeW(aCodepoint, PWideChar(result)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.IsHiSurrogate(const aChar: WideChar): Boolean; begin result := (aChar >= MIN_HiSurrogate) and (aChar <= MAX_HiSurrogate); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.IsLoSurrogate(const aChar: WideChar): Boolean; begin result := (aChar >= MIN_LoSurrogate) and (aChar <= MAX_LoSurrogate); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Json(const aChar: WideChar): Utf8String; begin result := EscapeUtf8(aChar, JsonEscape); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Json(const aCodepoint: Codepoint): Utf8String; begin result := Escapeutf8(aCodepoint, JsonEscape); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Ref(const aChar: WideChar): String; begin result := Escape(aChar, UnicodeIndex); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Ref(const aCodepoint: Codepoint): String; begin result := Escape(aCodepoint, UnicodeIndex); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.SurrogatesToCodepoint(const aHiSurrogate: WideChar; const aLoSurrogate: WideChar): Codepoint; begin if NOT IsHiSurrogate(aHiSurrogate) then raise EInvalidHiSurrogate.Create('%s is not a valid high surrogate character', [Ref(aHiSurrogate)]); if NOT IsLoSurrogate(aLoSurrogate) then raise EInvalidLoSurrogate.Create('%s is not a valid low surrogate character', [Ref(aLoSurrogate)]); result := ((Word(aHiSurrogate) - $d800) shl 10) + (Word(aLoSurrogate) - $dc00) + $10000; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Utf8Array(const aChars: array of Utf8Char): Utf8Array; begin SetLength(result, Length(aChars)); CopyMemory(@result[0], @aChars[0], Length(aChars)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Utf8ToCodepoint(const aUtf8: Utf8Array): Codepoint; var ptr: PUtf8Char; count: Integer; begin ptr := @aUtf8[0]; count := Length(aUtf8); result := _Utf8ToCodepoint(ptr, count); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Utf8ToCodepoint(var aUtf8: PUtf8Char; var aUtf8Count: Integer): Codepoint; begin result := _Utf8ToCodepoint(aUtf8, aUtf8Count); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Utf8ToUtf16(const aString: Utf8String): UnicodeString; var utf8: PUtf8Char; utf8len: Integer; utf16: PWideChar; utf16len: Integer; begin utf8len := Length(aString); utf16len := utf8len; SetLength(result, utf16len); utf8 := PUtf8Char(aString); utf16 := PWideChar(result); _Utf8ToUtf16Le(utf8, utf8len, utf16, utf16len); SetLength(result, Length(result) - utf16len); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Unicode.Utf8ToUtf16(var aUtf8: PUtf8Char; var aUtf8Count: Integer; var aUtf16: PWideChar; var aUtf16Count: Integer); begin _Utf8ToUtf16Le(aUtf8, aUtf8Count, aUtf16, aUtf16Count); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.Utf16ToUtf8(const aString: UnicodeString): Utf8String; var utf8: PUtf8Char; utf8len: Integer; utf16: PWideChar; utf16len: Integer; begin utf16len := Length(aString); utf8len := utf16len * 3; SetLength(result, utf8len); utf16 := PWideChar(aString); utf8 := PUtf8Char(result); _Utf16LeToUtf8(utf16, utf16len, utf8, utf8len); SetLength(result, Length(result) - utf8len); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Unicode.Utf16ToUtf8(var aUtf16: PWideChar; var aUtf16Count: Integer; var aUtf8: PUtf8Char; var aUtf8Count: Integer); begin _Utf16LeToUtf8(aUtf16, aUtf16Count, aUtf8, aUtf8Count); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Unicode.Utf16BeToUtf8(var aUtf16: PWideChar; var aUtf16Count: Integer; var aUtf8: PUtf8Char; var aUtf8Count: Integer); begin _Utf16BeToUtf8(aUtf16, aUtf16Count, aUtf8, aUtf8Count); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Unicode.WideCharToAnsi(const aChar: WideChar): AnsiChar; begin case aChar of #$0000..#$007f, #$0081, #$008d, #$008f, #$0090, #$009d, #$00a0..#$00ff : begin result := AnsiChar(aChar); EXIT; end; else for result := #$80 to #$9f do if aChar = MAP_AnsiToWide[result] then EXIT; end; raise EUnicode.Create('{char} does not map to a single-byte AnsiChar. Use Ansi.FromWide(PWideChar) instead.', [Ref(aChar)]); end; end.
unit Form.MainView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseForm, dxSkinsCore, dxSkinMetropolis, System.ImageList, Vcl.ImgList, cxGraphics, cxClasses, cxLookAndFeels, dxSkinsForm, cxControls, cxLookAndFeelPainters, cxCustomData, cxStyles, cxTL, cxMaskEdit, cxTLdxBarBuiltInMenu, dxSkinscxPCPainter, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView, cxGrid, cxSplitter, cxInplaceContainer, cxDBTL, cxTLData, Vcl.ComCtrls, Vcl.ToolWin, Vcl.ExtCtrls, dxActivityIndicator, Aurelius.Bind.Dataset, System.Generics.Collections, Aurelius.Engine.ObjectManager, Aurelius.Criteria.Linq, ConnectionModule, Model.Entities, cxContainer, cxTextEdit, Vcl.StdCtrls; type TfrmLibraryView = class(TfrmBase) pnlLeft: TPanel; tbCategoryEdit: TToolBar; btnAddCategory: TToolButton; btnEditCategory: TToolButton; btnDelCategory: TToolButton; btnRefresh: TToolButton; lstCategories: TcxDBTreeList; lstCategoriesCategoryID: TcxDBTreeListColumn; lstCategoriesCategoryName: TcxDBTreeListColumn; MainSplitter: TcxSplitter; pnlRight: TPanel; grdBooks: TcxGrid; grdBooksView: TcxGridDBTableView; grdBooksViewID: TcxGridDBColumn; grdBooksViewBOOK_NAME: TcxGridDBColumn; grdBooksViewFILE_LINK: TcxGridDBColumn; grdBooksLevel: TcxGridLevel; tbBookEdit: TToolBar; btnAddBook: TToolButton; btnEditBook: TToolButton; btnDelBook: TToolButton; btnRefreshBook: TToolButton; adsCategories: TAureliusDataset; adsCategoriesSelf: TAureliusEntityField; adsCategoriesID: TIntegerField; adsCategoriesCategoryName: TStringField; adsCategoriesParent: TAureliusEntityField; adsCategoriesBooks: TDataSetField; adsBooks: TAureliusDataset; adsBooksSelf: TAureliusEntityField; adsBooksID: TIntegerField; adsBooksBookName: TStringField; adsBooksBookLink: TStringField; dsCategories: TDataSource; dsBooks: TDataSource; procedure btnAddCategoryClick(Sender: TObject); procedure btnEditCategoryClick(Sender: TObject); procedure btnDelCategoryClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure btnAddBookClick(Sender: TObject); procedure btnEditBookClick(Sender: TObject); procedure btnRefreshBookClick(Sender: TObject); procedure btnDelBookClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure grdBooksViewDblClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure dsBooksDataChange(Sender: TObject; Field: TField); private class var FInstance: TfrmLibraryView; private FManager : TObjectManager; FCategories: TList<TCategory>; FOwnsManager: Boolean; FOnDataChange: TDataChangeEvent; private function GetBookCount: Integer; public procedure LoadData(SelectedId: Integer = 0); public constructor Create(AOwner: TComponent; AManager: TObjectManager; AOwnsManager: Boolean); reintroduce; property BookCount: Integer read GetBookCount; property OnDataChange: TDataChangeEvent read FOnDataChange write FOnDataChange; end; var frmLibraryView: TfrmLibraryView; implementation uses Aurelius.Criteria.Base, Common.Utils, Form.EditCategory, Form.EditBook, System.IniFiles, Vcl.FileCtrl; {$R *.dfm} resourcestring rsConfirmDeleteRecord = 'Вы действительно хотите удалить %s "%s"?'; rsErrorDeleteRecord = 'Не удалось удалить запись "%s"'; { TfrmLibraryView } procedure TfrmLibraryView.btnAddBookClick(Sender: TObject); var Category: TCategory; Book: TBook; begin Category := adsCategories.Current<TCategory>; Book := TBook.Create(''); try if TfrmEditBook.Edit(Book, FManager) then begin FManager.Save(Book); end; finally if not FManager.IsAttached(Book) then Book.Free; end; LoadData(Category.ID); end; procedure TfrmLibraryView.btnAddCategoryClick(Sender: TObject); var Category: TCategory; Book: TBook; begin Category := TCategory.Create; try Category.Parent := adsCategories.Current<TCategory>; if TfrmEditCategory.Edit(Category, FManager) then begin FManager.Save(Category); end; finally for Book in Category.Books do if not FManager.IsAttached(Book) then Book.Free; if not FManager.IsAttached(Category) then Category.Free; end; LoadData(Category.ID); end; procedure TfrmLibraryView.btnDelBookClick(Sender: TObject); var BookName: string; begin BookName := adsBooks.Current<TBook>.BookName; if ShowConfirmFmt(rsConfirmDeleteRecord, ['книгу', BookName]) then begin try adsBooks.Delete; LoadData(adsCategories.Current<TCategory>.ID); except ShowErrorFmt(rsErrorDeleteRecord, [BookName]); end; end; end; procedure TfrmLibraryView.btnDelCategoryClick(Sender: TObject); var CategoryName: string; begin CategoryName := adsCategories.Current<TCategory>.CategoryName; if ShowConfirmFmt(rsConfirmDeleteRecord, ['категорию', CategoryName]) then begin try LoadData(adsCategories.Current<TCategory>.ID); except ShowErrorFmt(rsErrorDeleteRecord, [CategoryName]); end; end; end; procedure TfrmLibraryView.btnEditBookClick(Sender: TObject); var Book: TBook; Edit: Boolean; begin Book := adsBooks.Current<TBook>; if Book = nil then Exit; try Edit := TfrmEditBook.Edit(Book, FManager); if Edit then begin FManager.Flush(Book); end; finally if not FManager.IsAttached(Book) then Book.Free; end; if Edit then LoadData(Book.BooksCategory.ID); end; procedure TfrmLibraryView.btnEditCategoryClick(Sender: TObject); var Category: TCategory; Book: TBook; Edit: Boolean; begin Category := adsCategories.Current<TCategory>; if Category = nil then Exit; Edit := TfrmEditCategory.Edit(Category, FManager); if Edit then begin FManager.Flush(Category); end else begin for Book in Category.Books do if not FManager.IsAttached(Book) then Book.Free; end; if Edit then LoadData(Category.ID); end; procedure TfrmLibraryView.btnRefreshBookClick(Sender: TObject); begin LoadData(adsCategories.Current<TCategory>.ID); end; procedure TfrmLibraryView.btnRefreshClick(Sender: TObject); begin LoadData(adsCategories.Current<TCategory>.ID); end; constructor TfrmLibraryView.Create(AOwner: TComponent; AManager: TObjectManager; AOwnsManager: Boolean); begin inherited Create(AOwner); FManager := AManager; FOwnsManager := AOwnsManager; end; procedure TfrmLibraryView.dsBooksDataChange(Sender: TObject; Field: TField); begin if Assigned(FOnDataChange) then FOnDataChange(Sender, Field); end; procedure TfrmLibraryView.FormDestroy(Sender: TObject); begin with dm do begin adsCategories.Close; adsBooks.Close; end; if FOwnsManager then FManager.Free; end; procedure TfrmLibraryView.FormShow(Sender: TObject); begin inherited; LoadData; end; function TfrmLibraryView.GetBookCount: Integer; begin Result := FManager.Find<TBook>.List.Count; end; procedure TfrmLibraryView.grdBooksViewDblClick(Sender: TObject); var FileName: string; begin // вызов программы-читалки with dm do begin if adsBooks.Current<TBook> = nil then Exit; FileName := adsBooks.Current<TBook>.BookLink; end; ShellExecute(0, '', FileName); end; procedure TfrmLibraryView.LoadData(SelectedId: Integer); var Criteria: TCriteria; Term: string; begin if (SelectedId = 0) and (adsCategories.Current<TCategory> <> nil) then SelectedId := adsCategories.Current<TCategory>.ID; adsCategories.Close; adsBooks.Close; FManager.Clear; Criteria := FManager.Find<TCategory>.OrderBy('ID'); adsCategories.SetSourceCriteria(Criteria); adsCategories.Open; if SelectedId <> 0 then adsCategories.Locate('ID', SelectedId, []); adsBooks.DatasetField := (adsCategories.FieldByName('Books') as TDataSetField); adsBooks.Open; lstCategories.FullExpand; end; end.
unit Player.AudioOutput.HH; interface uses Windows,SysUtils,Classes,Graphics,SyncObjs, Player.AudioOutput.Base,HHDecoder,HHCommon,MediaProcessing.Definitions; type TAudioOutputDecoder_HH = class (TAudioOutputDecoder) private FAudioDecoder : THHAudioDecoder; public function DecodeToPCM(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal; out aPcmFormat: TPCMFormat; out aPcmData: pointer; out aPcmDataSize: cardinal):boolean; override; procedure ResetBuffer; override; constructor Create; override; destructor Destroy; override; end; TPlayerAudioOutput_HH = class (TPlayerAudioOutputWaveOut) public constructor Create; override; end; implementation { THHAudioOutputDirectX } constructor TAudioOutputDecoder_HH.Create; begin inherited Create; FAudioDecoder:=THHAudioDecoder.Create; end; destructor TAudioOutputDecoder_HH.Destroy; begin inherited; FreeAndNil(FAudioDecoder); end; procedure TAudioOutputDecoder_HH.ResetBuffer; begin inherited; //FAudioDecoder.ResetBuffer; end; function TAudioOutputDecoder_HH.DecodeToPCM(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal; out aPcmFormat: TPCMFormat; out aPcmData: pointer; out aPcmDataSize: cardinal):boolean; var pFrameData: PHV_FRAME; aAvInfo: HHAV_INFO; aExtFrame: PEXT_FRAME_HEAD; begin result:=false; if aInfo=nil then begin aAvInfo.nAudioChannels:=aFormat.AudioChannels; aAvInfo.nAudioBits:=aFormat.AudioBitsPerSample; aAvInfo.nAudioSamples:=aFormat.AudioSamplesPerSec; aAvInfo.nAudioEncodeType:=aFormat.biStreamSubType; end else begin Assert(aInfoSize=sizeof(HHAV_INFO)); aAVInfo:= PHHAV_INFO(aInfo)^; end; Assert(aFormat.biMediaType=mtAudio); Assert(PHV_FRAME_HEAD(aData).nByteNum+sizeof(HV_FRAME_HEAD)=aDataSize); pFrameData:=aData; //Мусор? if pFrameData.zeroFlag<>0 then exit; if pFrameData.oneFlag<>1 then exit; if GetExtFrameHead(pFrameData,aExtFrame) then begin aAVInfo.nAudioEncodeType:=aExtFrame.szFrameInfo.szFrameAudio.nAudioEncodeType; aAVInfo.nAudioChannels:=aExtFrame.szFrameInfo.szFrameAudio.nAudioChannels; aAVInfo.nAudioBits:=aExtFrame.szFrameInfo.szFrameAudio.nAudioBits; aAVInfo.nAudioBitrate:=aExtFrame.szFrameInfo.szFrameAudio.nAudioBitrate; aAVInfo.nAudioSamples:=aExtFrame.szFrameInfo.szFrameAudio.nAudioSamples; end; Assert(pFrameData.streamFlag=FRAME_FLAG_A); try FAudioDecoder.DecodeToPCM(pFrameData,aAvInfo); result:=true; except end; if result then begin aPcmFormat.Channels:=aFormat.AudioChannels; aPcmFormat.BitsPerSample:=aFormat.AudioBitsPerSample; aPcmFormat.SamplesPerSec:=aFormat.AudioSamplesPerSec; aPcmData:=FAudioDecoder.CurrentBuffer; aPcmDataSize:=FAudioDecoder.CurrentBufferSize; end; end; { TPlayerAudioOutput_HH } constructor TPlayerAudioOutput_HH.Create; begin inherited Create; RegisterDecoderClass(stHHAU,TAudioOutputDecoder_HH); SetStreamType(stHHAU); end; end.
unit MobileDays.ListVertFrame.Mobile.Controller.SMImage; interface uses System.Classes, System.Net.HttpClient, System.IOUtils, System.Net.HttpClientComponent, System.SysUtils; type TSMImage = class private { private declarations } protected { protected declarations } public class procedure ClearImage(); class function ShowImage(const AName, AImageUrl: string): string; class function GetImage(const AImageUrl: string): TMemoryStream; { public declarations } published { published declarations } end; implementation { TSMImage } class procedure TSMImage.ClearImage; var LPath: string; MySearch: TSearchRec; begin LPath := System.IOUtils.TPath.GetDocumentsPath; LPath := System.IOUtils.TPath.Combine(LPath, 'Image'); FindFirst(System.IOUtils.TPath.Combine(LPath, '*.*'), faAnyFile+faReadOnly, MySearch); DeleteFile(LPath+'\'+MySearch.Name); while FindNext(MySearch)=0 do begin DeleteFile(System.IOUtils.TPath.Combine(LPath, MySearch.Name)); end; FindClose(MySearch); end; class function TSMImage.GetImage(const AImageUrl: string): TMemoryStream; var LResponse: IHttpResponse; HttpClient: TNetHTTPClient; HTTPRequest: TNetHTTPRequest; begin try Result := TMemoryStream.Create; HttpClient := TNetHTTPClient.Create(nil); HTTPRequest := TNetHTTPRequest.Create(nil); HTTPRequest.Client := HttpClient; try LResponse := HTTPRequest.Get( AImageUrl, Result ); Result.Position := 0; // LMemStream.SaveToFile(APathToSave); except // Nao precisa fazer nada, so nao deu p baixar end; finally // FreeAndNil(LMemStream); FreeAndNil(HTTPRequest); FreeAndNil(HttpClient); end; end; class function TSMImage.ShowImage(const AName, AImageUrl: string): string; var LPath: string; LMemStream: TMemoryStream; begin Result := EmptyStr; LPath := System.IOUtils.TPath.GetDocumentsPath; LPath := System.IOUtils.TPath.Combine(LPath, 'Image'); if not (DirectoryExists(LPath)) then ForceDirectories(LPath); LPath := System.IOUtils.TPath.Combine(LPath, AName); if not (FileExists(LPath)) then begin try LMemStream := GetImage(AImageUrl); LMemStream.SaveToFile(LPath); finally FreeAndNil(LMemStream); end; end; Result := LPath; end; end.
unit eComm; interface {$IFDEF OS2}uses use32, os2def, os2base;{$ENDIF} var activeComPort: word; b: byte; {$IFDEF OS2} portHandle: hfile; wrote: ulong; eHandle: hfile; eHandleActive: boolean; const {for modem stuff} IOCTL_ASYNC = $0001; ASYNC_GETINQUECOUNT = $0068; type rxqueue = record Used: SmallWord; Size: SmallWord end; {$ENDIF} function einit(comport, baud: word): boolean; procedure putstring(const s: string); function echarready: boolean; procedure egetchar(var c: char); procedure eputchar(c: char); function echeckdcd: boolean; procedure eclosemodem; function echeckRI: boolean; procedure eFlushOutBuffer; procedure eFlushInBuffer; function eOutBuffUsed: integer; procedure esetDTR(b: boolean); {$IFDEF OS2} function egetahandle: longint; procedure epurgehandle; {$ENDIF} implementation {$IFDEF OS2} procedure setdcb; type dcbinfo = record writetimeout : smallword; readtimeout : smallword; flags1 : byte; flags2 : byte; flags3 : byte; error : byte; break : byte; XON,XOFF : byte; end; var dcb: dcbinfo; plen: ulong; begin dcb.writetimeout := 100; dcb.readtimeout := 100; dcb.flags1 := $01; // enable DTR, dcb.flags2 := $40; // enable RTS, disable XON/XOFF dcb.flags3 := $04; // recv timeout mode dcb.error := 0; // no error translate dcb.break := 0; // no break translate dcb.xon := $11; // standard XON dcb.xoff := $13; // standard XOFF plen:=sizeof(dcb); dosdevioctl(porthandle, IOCTL_ASYNC, ASYNC_SETDCBINFO, @dcb, SizeOf(dcbinfo), @plen, nil, 0, nil); end; {$ENDIF} Function modemInit(port, baud: word): Boolean; {$IFDEF OS2} var Com: string[5]; Action: ulong; Error: apiret; Begin com:='COM'+char(port+48)+#0; Error:=DosOpen(@Com[1], PortHandle, Action, 0, $0000, OPEN_ACTION_OPEN_IF_EXISTS, OPEN_ACCESS_READWRITE OR OPEN_SHARE_DENYNONE, nil); if Error<>NO_ERROR then PortHandle:=0; setdcb; if PortHandle=0 then modemInit:=false else modemInit:=true; {$ELSE} var Temp: Word; Baud57600: boolean; begin activecomport:=port-1; asm mov ah, $04 mov bx, $00 mov dx, activecomPort int $14 mov temp, ax end; If Temp=$1954 then begin modeminit:=True; if Baud <= 38400 then begin case baud of 300 : B:=$43; 600 : B:=$63; 1200 : B:=$83; 2400 : B:=$A3; 4800 : B:=$C3; 9600 : B:=$E3; 19200: B:=$03; else B:=$23; {38400} end; asm mov ah, $00 mov al, b mov dx, activecomPort int $14 end; end else begin if baud=57600 then baud57600:=true else baud57600:=false; asm mov ah, 1Eh mov bx, 0000h mov ch, 03h mov dx, activecomPort cmp baud57600, true je @1 mov cl, 84h jmp @int @1: mov cl, 82h @int: int 14h end; end; end else modeminit:=False; {$ENDIF} end; function einit(comport, baud: word): boolean; begin {initialise the com port (0 based)} activeComPort:=comport; einit:=modemInit(activeComPort, baud); end; procedure putstring(const s: string); var b: byte; begin {$IFDEF OS2} doswrite(porthandle, S[1], length(s), wrote); {$ELSE} for b:=1 to length(s) do eputchar(s[b]); {$ENDIF} end; function echarready: boolean; {$IFDEF OS2} var ParmLen: ulong; Receive: RxQueue; Error : ApiRet; begin ParmLen:=SizeOf(RXQUEUE); Receive.Used:=0; Receive.Size:=$0FFF; Error:=DosDevIoCtl(PortHandle, IOCTL_ASYNC, ASYNC_GETINQUECOUNT, nil, 0, nil, @Receive, SizeOf(Receive), @ParmLen); echarready:=(Error=No_Error) and (Receive.Used>0); {$ELSE} Begin Asm mov ah, $03 mov dx, activecomPort int $14 mov b, ah End; If (B And 1)=1 Then echarready:=True Else echarready:=False; {$ENDIF} end; procedure egetchar(var c: char); begin {$IFDEF OS2} dosread(PortHandle, c, 1, wrote); {$ELSE} b:=0; Asm mov ah, $03 mov dx, activecomport int $14 mov b, ah End; If (B And 1)=1 Then Begin Asm mov ah, $02 mov dx, activecomport int $14 mov b, al End; c:=Chr(B); End; { Asm mov ah, $02 mov dx, activecomPort int $14 mov b, al End; c:=Chr(B);} {$ENDIF} end; procedure eputchar(c: char); begin {$IFDEF OS2} doswrite(porthandle, c, 1, wrote); {$ELSE} B:=Ord(c); Asm mov al, B mov dx, activecomPort mov ah, $01 int $14 End; {$ENDIF} end; function echeckdcd: boolean; begin {$IFDEF OS2} dosdevioctl(porthandle, IOCTL_ASYNC, ASYNC_GETMODEMINPUT, nil, 0, nil, @b, sizeof(b), nil); if ((b and DCD_ON)>0) then echeckdcd:=true else echeckdcd:=false; {$ELSE} Asm mov ah, $03 mov dx, activecomPort int $14 mov b, al End; If (B And $80)<>0 Then echeckdcd:=True Else echeckdcd:=False; {$ENDIF} end; procedure eclosemodem; begin {$IFDEF OS2} DosClose(PortHandle); {$ELSE} Asm mov ah, $05 mov dx, activecomPort int $14 End; {$ENDIF} end; function echeckRI: boolean; const RI = $40; begin {$IFDEF OS2} echeckri:=false; {$ELSE} Asm mov ah, 03h mov dx, activecomport int 14h mov b, al End; echeckri := (b AND RI) = RI; {$ENDIF} end; procedure eFlushOutBuffer; begin {$IFNDEF OS2} Asm mov ah, $08 mov dx, activecomport int $14 End; {$ENDIF} end; procedure eFlushInBuffer; var c: array[1..8064] of byte; begin {$IFDEF OS2} if echarready then dosread(porthandle, c, sizeof(c), wrote); {$ELSE} Asm mov ah, $0A mov dx, activecomPort int $14 End; {$ENDIF} end; function eOutBuffUsed: integer; begin eOutBuffUsed:=0; {allways 0 unless async} end; procedure esetDTR(b: boolean); {$IFDEF OS2} type CommErr = (ReceiveQueueOverrun,ReceiveHardwareOverrun, ParityError,FramingError,Undef4,Undef5,Undef6,Undef7,Undef8); CommErrSet = SET OF CommErr; MODEMSTATUS = RECORD OnMask : BYTE; OffMask : BYTE END; VAR MS: MODEMSTATUS; ERR: ApiRet; COM: CommErrSet; comerr: commerrset; DataLen: ULONG; ParmLen: ULONG; P: POINTER; W: CommErrSet; onmask, offmask: byte; begin {hangup} if b=false then begin onmask:=$00; offmask:=$FE; end else begin onmask:=$01; offmask:=$FF; end; MS.OnMask:=OnMask; MS.OffMask:=OffMask; ParmLen:=SizeOf(MODEMSTATUS); DataLen:=SizeOf(CommErrSet); P:=@ComErr; IF P=NIL THEN P:=@W; DosDevIoCtl(portHandle,IOCTL_ASYNC,ASYNC_SETMODEMCTRL, @MS,SizeOf(MODEMSTATUS),ADDR(ParmLen), P,SizeOf(CommErrSet),ADDR(DataLen)) end; {$ELSE} var x: byte; begin if b=true then x:=1 else x:=0; Asm mov dx, activecomPort mov al, x mov ah, $06 int 14h End; end; {$ENDIF} {$IFDEF OS2} function egetahandle: longint; var Com: string[5]; Action: ulong; Error: apiret; begin com:='COM'+char(activecomport+48)+#0; Error:=DosOpen(@Com[1], eHandle, Action, 0, $0000, OPEN_ACTION_OPEN_IF_EXISTS, OPEN_ACCESS_READWRITE OR OPEN_SHARE_DENYNONE, nil); if Error<>NO_ERROR then eHandle:=0; if eHandle<>0 then eHandleActive:=true; egetahandle:=eHandle; end; procedure epurgehandle; begin if (eHandleActive=true) then dosclose(eHandle); end; {$ENDIF} begin activeComPort:=0; b:=0; {$IFDEF OS2} portHandle:=0; wrote:=0; eHandle:=0; eHandleActive:=false; {$ENDIF} end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 2000-2001 Borland Software Corp. } { } {*******************************************************} unit DBAdaptImg; interface uses Classes, Messages, HTTPApp, WebComp, DB, SiteComp, SysUtils, WebContnrs, WebAdapt, DBAdapt, AdaptReq; type TImageDataSetFieldGetImageEvent = procedure(Sender: TObject; var MimeType: string; var Image: TStream; var Owned: Boolean) of object; TCustomDataSetAdapterImageField = class(TBaseDataSetAdapterImageField, IGetAdapterImage, IGetAdapterItemRequestParams, IAdapterRequestHandler, IWebImageHREF) private FOnGetHREF: TImageFieldGetHREFEvent; FOnGetImage: TImageDataSetFieldGetImageEvent; protected function CheckOrUpdateValue(AActionRequest: IActionRequest; AFieldIndex: Integer; AUpdate: Boolean): Boolean; function GetDataSetFieldValue(Field: TField): Variant; override; { IWebImageHREF } function ImplWebImageHREF(var AHREF: string): Boolean; virtual; function WebImageHREF(var AHREF: string): Boolean; { IAdapterRequestHandler } procedure CreateRequestContext(DispatchParams: IAdapterDispatchParams); procedure ImplCreateRequestContext(DispatchParams: IAdapterDispatchParams); function HandleRequest(DispatchParams: IAdapterDispatchParams): Boolean; function ImplHandleRequest(DispatchParams: IAdapterDispatchParams): Boolean; virtual; { ICheckValueChange } function ImplCheckValueChange(AActionRequest: IActionRequest; AFieldIndex: Integer): Boolean; override; { IUpdateValue } procedure ImplUpdateValue(AActionRequest: IActionRequest; AFieldIndex: Integer); override; { IGetHTMLStyle } function GetDisplayStyleType(const AAdapterMode: string): TAdapterDisplayHTMLElementType; override; function GetInputStyleType(const AAdapterMode: string): TAdapterInputHTMLElementType; override; { IGetAdapterImage } function GetAdapterImage: IInterface; { IRenderAdapterImage } procedure RenderAdapterImage(ARequest: IImageRequest; AResponse: IImageResponse); { IGetAdapterItemRequestParams } procedure GetAdapterItemRequestParams( var AIdentifier: string; AParams: IAdapterItemRequestParams); public constructor Create(AOwner: TComponent); override; property OnGetImage: TImageDataSetFieldGetImageEvent read FOnGetImage write FOnGetImage; property OnGetHREF: TImageFieldGetHREFEvent read FOnGetHREF write FOnGetHREF; end; TDataSetAdapterImageField = class(TCustomDataSetAdapterImageField) published property DataSetField; property ViewAccess; property ModifyAccess; property OnGetImage; property OnGetHREF; property FieldModes; end; implementation uses Variants, WebCntxt, AutoAdap, Graphics, jpeg, SiteConst; { TCustomDataSetAdapterImageField } function TCustomDataSetAdapterImageField.GetAdapterImage: IInterface; begin case Adapter.Mode of amInsert, amQuery: Result := nil else Result := Self; end; end; function TCustomDataSetAdapterImageField.GetDisplayStyleType(const AAdapterMode: string): TAdapterDisplayHTMLElementType; begin Result := htmldImage; end; function TCustomDataSetAdapterImageField.GetInputStyleType(const AAdapterMode: string): TAdapterInputHTMLElementType; begin Result := htmliFile; end; procedure TCustomDataSetAdapterImageField.RenderAdapterImage( ARequest: IImageRequest; AResponse: IImageResponse); var S: TStream; Bmp: TBitmap; JPEG: TJPEGImage; Response: TWebResponse; Field: TField; ContentType: string; ContentStream: TStream; MimeType: string; Image: TStream; Owned: Boolean; begin CheckViewAccess; Response := WebContext.Response; Response.ContentType := 'image/jpeg'; ContentStream := nil; Adapter.ExtractRequestParams(ARequest); if Adapter.SilentLocate(Adapter.LocateParamsList, True) then begin if Assigned(FOnGetImage) then begin Image := nil; Owned := True; S := nil; FOnGetImage(Self, MimeType, Image, Owned); if Image <> nil then begin try if not Owned then begin S := TMemoryStream.Create; S.CopyFrom(Image, 0); end else S := Image; S.Seek(0, soFromBeginning); except if Owned then Image.Free; if Image <> S then S.Free; raise; end; Assert(MimeType <> ''); ContentType := MimeType; ContentStream := S; end; end; if ContentStream = nil then begin ContentType := 'image/jpeg'; Field := Adapter.DataSet.FindField(DataSetField); if Assigned(Field) then begin Bmp := TBitmap.Create; try Bmp.Assign(Field); JPEG := TJPEGImage.Create; try JPEG.Assign(Bmp); S := TMemoryStream.Create; JPEG.SaveToStream(S); S.Seek(0, soFromBeginning); ContentStream := S; finally JPEG.Free; end; finally Bmp.Free; end; end; end; end; Response.ContentType := ContentType; Response.ContentStream := ContentStream; end; function GetActionFieldValues(AActionRequest: IActionRequest): IActionFieldValues; begin if not Supports(AActionRequest, IActionFieldValues, Result) then Assert(False); end; function TCustomDataSetAdapterImageField.CheckOrUpdateValue(AActionRequest: IActionRequest; AFieldIndex: Integer; AUpdate: Boolean): Boolean; var Field: TField; FieldValue: IActionFieldValue; Bmp: TBitmap; begin Result := False; Assert(Adapter <> nil); Assert(Adapter.DataSet <> nil); with GetActionFieldValues(AActionRequest) do FieldValue := Values[AFieldIndex]; if FieldValue.FileCount > 0 then begin Field := Adapter.DataSet.FindField(DataSetField); if Field = nil then Adapter.RaiseFieldNotFound(DataSetField); if FieldValue.FileCount = 1 then begin if AUpdate then begin if FieldValue.Files[0].ContentType = 'image/bmp' then begin Bmp := TBitmap.Create; try Bmp.LoadFromStream(FieldValue.Files[0].Stream); Field.Assign(Bmp); finally Bmp.Free; end; end else raise EAdapterFieldException.Create(Format(sIncorrectImageFormat, [FieldValue.Files[0].ContentType]), FieldName); end else Result := True; end else RaiseMultipleFilesException(FieldName); end else if (FieldValue.ValueCount > 0) and (FieldValue.Values[0] <> '') then raise EAdapterFieldException.Create(sFileExpected, FieldName); end; procedure TCustomDataSetAdapterImageField.ImplUpdateValue(AActionRequest: IActionRequest; AFieldIndex: Integer); begin CheckModifyAccess; CheckOrUpdateValue(AActionRequest, AFieldIndex, True); end; function TCustomDataSetAdapterImageField.GetDataSetFieldValue( Field: TField): Variant; begin // Field.Value will return binary data. Use DisplayText instead. Result := Field.DisplayText; end; function TCustomDataSetAdapterImageField.ImplCheckValueChange( AActionRequest: IActionRequest; AFieldIndex: Integer): Boolean; begin Result := CheckOrUpdateValue(AActionRequest, AFieldIndex, False); end; function TCustomDataSetAdapterImageField.ImplWebImageHREF(var AHREF: string): Boolean; begin if DesigningComponent(Self) and Assigned(GetHTMLSampleImage) then AHREF := GetHTMLSampleImage else begin AHREF := ''; if Assigned(FOnGetHREF) then FOnGetHREF(Self, AHREF); end; Result := AHREF <> ''; end; function TCustomDataSetAdapterImageField.WebImageHREF(var AHREF: string): Boolean; begin Result := ImplWebImageHREF(AHREF); end; procedure TCustomDataSetAdapterImageField.CreateRequestContext( DispatchParams: IAdapterDispatchParams); begin ImplCreateRequestContext(DispatchParams); end; function TCustomDataSetAdapterImageField.HandleRequest( DispatchParams: IAdapterDispatchParams): Boolean; begin Result := ImplHandleRequest(DispatchParams); end; procedure TCustomDataSetAdapterImageField.ImplCreateRequestContext( DispatchParams: IAdapterDispatchParams); var Obj: TBasicImageRequestImpl; begin Obj := TBasicImageRequestImpl.Create(DispatchParams); TBasicImageResponseImpl.Create(Obj); end; function TCustomDataSetAdapterImageField.ImplHandleRequest( DispatchParams: IAdapterDispatchParams): Boolean; var ImageRequest: IImageRequest; ImageResponse: IImageResponse; begin Result := Supports(WebContext.AdapterRequest, IImageRequest, ImageRequest) and Supports(WebContext.AdapterResponse, IImageResponse, ImageResponse); Assert(Result); if Result then RenderAdapterImage(ImageRequest, ImageResponse); end; procedure TCustomDataSetAdapterImageField.GetAdapterItemRequestParams( var AIdentifier: string; AParams: IAdapterItemRequestParams); begin AIdentifier := MakeAdapterRequestIdentifier(Self); Adapter.EncodeActionParamsFlags(AParams, [poLocateParams]); end; constructor TCustomDataSetAdapterImageField.Create(AOwner: TComponent); begin inherited; FieldModes := [amInsert, amEdit, amBrowse {, amQuery}]; end; initialization DataSetAdapterImageFieldClass := TDataSetAdapterImageField; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Vcl.DBOleCtl; interface uses System.Variants, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.OleCtrls, Data.DB, Vcl.DBCtrls, Winapi.ActiveX; type TDBOleControl = class; TDataBindings = class; TDataBindItem = class(TCollectionItem) private FOwner: TDataBindings; FDataLink: TFieldDataLink; FDispId: TDispID; procedure DataChange(Sender: TObject); function GetDataField: string; procedure SetDataField(const Value: string); procedure SetDispID(Value: TDispID); procedure UpdateData(Sender: TObject); public constructor Create(Collection: TCollection); override; destructor Destroy; override; published property DataField: string read GetDataField write SetDataField; property DispID: TDispID read FDispId write SetDispID; end; TDataBindings = class(TCollection) private FDBOleControl: TDBOleControl; function GetItem(Index: Integer): TDataBindItem; procedure SetItem(Index: Integer; Value: TDataBindItem); public constructor Create(DBOleControl: TDBOleControl); function Add: TDataBindItem; procedure Update(Item: TCollectionItem); override; function GetItemByDispID(ADispID: TDispID): TDataBindItem; function GetOwner: TPersistent; override; property Items[Index: Integer]: TDataBindItem read GetItem write SetItem; default; end; TDBOleControl = class(TOleControl) private FDataBindings: TDataBindings; FDataChanging: Boolean; FDataSource: TDataSource; procedure SetDataSource(Value: TDataSource); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; function OnChanged(dispid: TDispID): HResult; override; function OnRequestEdit(dispid: TDispID): HResult; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property DataSource: TDataSource read FDataSource write SetDataSource; property DataBindings: TDataBindings read FDataBindings write FDataBindings; end; implementation { TDataBindItem } constructor TDataBindItem.Create(Collection: TCollection); begin inherited Create(Collection); FOwner := Collection as TDataBindings; FDataLink := TFieldDataLink.Create; FDataLink.Control := FOwner.FDbOleControl; FDataLink.OnDataChange := DataChange; FDataLink.OnUpdateData := UpdateData; end; procedure TDataBindItem.DataChange(Sender: TObject); var LocalVar: OleVariant; begin with FOwner.FDbOleControl do begin FDataChanging := True; try LocalVar := FDataLink.Field.Value; if LocalVar <> Null then SetProperty(FDispID, TVarData(LocalVar)); finally FDataChanging := False; end; end; end; destructor TDataBindItem.Destroy; begin FDataLink.Free; FDataLink := nil; inherited Destroy; end; function TDataBindItem.GetDataField: string; begin Result := FDataLink.FieldName; end; procedure TDataBindItem.SetDataField(const Value: string); begin FDataLink.FieldName := Value; Changed(False); end; procedure TDataBindItem.SetDispID(Value: TDispID); begin if Value <> FDispID then begin FDispID := Value; Changed(False); end; end; procedure TDataBindItem.UpdateData(Sender: TObject); var PropValue: OleVariant; begin FOwner.FDbOleControl.GetProperty(FDispID, TVarData(PropValue)); FDataLink.Field.Value := PropValue; end; { TDataBindings } constructor TDataBindings.Create(DBOleControl: TDBOleControl); begin inherited Create(TDataBindItem); FDBOleControl:= DBOleControl; end; function TDataBindings.Add: TDataBindItem; begin Result:= TDataBindItem(inherited Add); end; function TDataBindings.GetItem(index: Integer): TDataBindItem; begin Result:= TDataBindItem(inherited GetItem(Index)); end; function TDataBindings.GetItemByDispID(ADispID: TDispID): TDataBindItem; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if Items[I].DispID = ADispID then Result := Items[I]; end; function TDataBindings.GetOwner: TPersistent; begin Result:= FDBOleControl; end; procedure TDataBindings.SetItem(index: Integer; Value: TDataBindItem); begin inherited SetItem(Index, Value); end; procedure TDataBindings.Update(Item: TCollectionItem); begin end; { TDBOleControl } constructor TDBOleControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataBindings:= TDataBindings.Create(self); end; destructor TDBOleControl.Destroy; begin FDataBindings.Free; inherited Destroy; end; procedure TDBOleControl.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataSource <> nil) and (AComponent = DataSource) then DataSource := nil; end; function TDBOleControl.OnChanged(DispID: TDispID): HResult; var Item: TDataBindItem; I: Integer; procedure SetItemValue; var PropValue: OleVariant; begin if Item <> nil then begin GetProperty(Item.DispID, TVarData(PropValue)); if (Item.FDatalink <> nil) and (Item.FDatalink.Field <> nil) then begin Item.FDataLink.Edit; Item.FDataLink.Field.Value := PropValue; end; end; end; begin Result := S_OK; try if (not FDataChanging) and ([csLoading, csReading] * ComponentState = []) then begin if DispID = DISPID_UNKNOWN then begin for I := 0 to DataBindings.Count - 1 do begin Item := DataBindings[I]; SetItemValue; end; end else begin Item := DataBindings.GetItemByDispID(DispID); SetItemValue; end; end; except // Return S_OK even in case of error end; end; function TDBOleControl.OnRequestEdit(DispID: TDispID): HResult; var Item: TDataBindItem; begin Result := S_OK; try if not FDataChanging then begin Item := DataBindings.GetItemByDispID(DispID); if (Item <> nil) and not Item.FDataLink.CanModify then Result := S_FALSE; end; except Result := S_FALSE; // Disallow edit if exception was raised end; end; procedure TDBOleControl.SetDataSource(Value: TDataSource); var I: Integer; begin if csLoading in ComponentState then for I := 0 to DataBindings.Count - 1 do if DataBindings[I].FDataLink.DataSourceFixed then Exit; if Value = nil then DataBindings.Clear; FDataSource := Value; if Value <> nil then begin for I := 0 to DataBindings.Count - 1 do DataBindings[I].FDataLink.DataSource := Value; Value.FreeNotification(Self); end; end; end.
unit GridRef; interface uses LatLon; type TOSGridRef = record private fEasting : double; fNorthing : double; public constructor Create(const easting: double; const northing: double); class function LatLongToOSGrid(const point : TLatLon) : TOSGridRef; static; class function OSGridToLatLong(const gridref : TOSGridRef) : TLatLon; static; class function Parse(const value : string) : TOSGridRef; static; function AsString(const digits : integer = 10) : string; property Easting : double read fEasting; property Northing : double read fNorthing; end; implementation uses Math, SysUtils, StrUtils; constructor TOSGridRef.Create(const easting: double; const northing: double); begin fEasting := easting; fNorthing := northing; end; class function TOSGridRef.LatLongToOSGrid (const point : TLatLon) : TOSGridRef; var easting, northing : double; lat, lon, a, b, F0, lat0, lon0, N0, E0, e2, n, n2, n3, cosLat, sinLat, nu, rho, eta2, Ma, Mb, Mc, Md, M : double; cos3lat, cos5lat, tan2lat, tan4lat, I, II, III, IIIA, IV, V, VI, dLon, dLon2, dLon3, dLon4, dlon5, dLon6 : Double; begin lat := DegToRad(point.Lat); lon := DegToRad(point.lon); a := 6377563.396; b := 6356256.910; // Airy 1830 major & minor semi-axes F0 := 0.9996012717; // NatGrid scale factor on central meridian lat0 := DegToRad(49); lon0 := DegToRad(-2); // NatGrid true origin is 49ºN,2ºW N0 := -100000; E0 := 400000; // northing & easting of true origin, metres e2 := 1 - (b * b) / (a * a); // eccentricity squared n := (a - b) / (a + b); n2 := n * n; n3 := n * n * n; cosLat := Cos(lat); sinLat := Sin(lat); nu := a * F0 / Sqrt(1 - e2 * sinLat *sinLat); // transverse radius of curvature rho := a * F0 *(1 - e2)/ Power(1 - e2 * sinLat * sinLat, 1.5); // meridional radius of curvature eta2 := nu/rho-1; Ma := (1 + n + (5/4)*n2 + (5/4)*n3) * (lat-lat0); Mb := (3 * n + 3 * n * n + (21 / 8) * n3) * Sin(lat - lat0) * Cos(lat + lat0); Mc := ((15 / 8) * n2 + (15 / 8) * n3) * Sin(2 *(lat - lat0)) * Cos(2 * (lat + lat0)); Md := (35/24) * n3 * Sin(3 *(lat - lat0)) * Cos(3 * (lat + lat0)); M := b * F0 * (Ma - Mb + Mc - Md); // meridional arc cos3lat := cosLat * cosLat *cosLat; cos5lat := cos3lat * cosLat * cosLat; tan2lat := Tan(lat) * Tan(lat); tan4lat := tan2lat * tan2lat; I := M + N0; II := (nu / 2) * sinLat * cosLat; III := (nu / 24) * sinLat * cos3lat *(5 -tan2lat +9 * eta2); IIIA := (nu / 720) * sinLat * cos5lat *(61 -58 * tan2lat + tan4lat); IV := nu * cosLat; V := (nu / 6) * cos3lat *(nu / rho - tan2lat); VI := (nu / 120) * cos5lat * (5 - 18 * tan2lat + tan4lat + 14 * eta2 - 58 * tan2lat * eta2); dLon := lon - lon0; dLon2 := dLon * dLon; dLon3 := dLon2 * dLon; dLon4 := dLon3 * dLon; dLon5 := dLon4 * dLon; dLon6 := dLon5 * dLon; northing := I + II * dLon2 + III * dLon4 + IIIA * dLon6; easting := E0 + IV * dLon + V * dLon3 + VI * dLon5; Result := TOSGridRef.Create(Trunc(easting), Trunc(northing)); end; class function TOSGridRef.OSGridToLatLong(const gridref : TOSGridRef) : TLatLon; var easting, northing, a, b, F0,lat0,lon0,N0,E0,e2,n,n2,n3,M,Ma,Mb,Mc,Md,cosLat,sinLat,nu,rho,eta2,tanLat,tan2lat : double; tan4lat,tan6lat,secLat,nu3,nu5,nu7,VII,VIII,IX,X,XI,XII,XIIA,dE,dE2,dE3,dE4,dE5,dE6,dE7,lat,lon : double; begin easting := gridref.Easting; northing := gridref.Northing; a := 6377563.396; b := 6356256.910; // Airy 1830 major & minor semi-axes F0 := 0.9996012717; // NatGrid scale factor on central meridian lat0 := 49 * PI / 180; lon0 := - 2 * PI / 180; // NatGrid true origin N0 := -100000; E0 := 400000; // northing & easting of true origin, metres e2 := 1 - (b * b) / (a * a); // eccentricity squared n := (a - b) /(a + b); n2 := n * n; n3 := n * n * n; lat := lat0; M := 0; repeat // until < 0.01mm lat := (northing - N0 - M)/(a*F0) + lat; Ma := (1 + n + (5/4)*n2 + (5/4)*n3) * (lat-lat0); Mb := (3*n + 3*n*n + (21/8)*n3) * Sin(lat-lat0) * Cos(lat+lat0); Mc := ((15/8)*n2 + (15/8)*n3) * Sin(2*(lat-lat0)) * Cos(2*(lat+lat0)); Md := (35/24)*n3 * Sin(3*(lat-lat0)) * Cos(3*(lat+lat0)); M := b * F0 * (Ma - Mb + Mc - Md); // meridional arc until (Northing - N0 - M < 0.00001); cosLat := Cos(lat); sinLat := Sin(lat); nu := a*F0/Sqrt(1-e2*sinLat*sinLat); // transverse radius of curvature rho := a*F0*(1-e2)/Power(1-e2*sinLat*sinLat, 1.5); // meridional radius of curvature eta2 := nu/rho-1; tanLat := Math.tan(lat); tan2lat := tanLat*tanLat; tan4lat := tan2lat*tan2lat; tan6lat := tan4lat*tan2lat; secLat := 1/cosLat; nu3 := nu*nu*nu; nu5 := nu3*nu*nu; nu7 := nu5*nu*nu; VII := tanLat/(2*rho*nu); VIII := tanLat/(24*rho*nu3)*(5+3*tan2lat+eta2-9*tan2lat*eta2); IX := tanLat/(720*rho*nu5)*(61+90*tan2lat+45*tan4lat); X := secLat/nu; XI := secLat/(6*nu3)*(nu/rho+2*tan2lat); XII := secLat/(120*nu5)*(5+28*tan2lat+24*tan4lat); XIIA := secLat/(5040*nu7)*(61+662*tan2lat+1320*tan4lat+720*tan6lat); dE := (easting - E0); dE2 := dE*dE; dE3 := dE2*dE; dE4 := dE2*dE2; dE5 := dE3*dE2; dE6 := dE4*dE2; dE7 := dE5*dE2; lat := lat - VII*dE2 + VIII*dE4 - IX*dE6; lon := lon0 + X*dE - XI*dE3 + XII*dE5 - XIIA*dE7; Result := TLatLon.Create(RadToDeg(lat), RadToDeg(lon)); end; function TOSGridRef.AsString(const digits : integer = 10) : string; var e100k, n100k, l1, l2, e, n : integer; letPair : string; begin // get the 100km-grid indices e100k := Floor(self.Easting / 100000); n100k := Floor(self.Northing / 100000); if (e100k < 0) or (e100k > 6) or (n100k < 0) or (n100k > 12) then begin Result := ''; Exit; end; // translate those into numeric equivalents of the grid letters l1 := (19 - n100k) - (19 - n100k) mod 5 + Floor((e100k + 10) / 5); l2 := (19 - n100k) * 5 mod 25 + e100k mod 5; // compensate for skipped 'I' and build grid letter-pairs if (l1 > 7) then Inc(l1); if (l2 > 7) then Inc(l2); letPair := Chr(l1 + Ord('A')) + Chr(l2 + Ord('A')); // strip 100km-grid indices from easting & northing, and reduce precision e := Floor((Trunc(self.Easting) mod 100000) / Power(10, 5 - digits / 2)); n := Floor((Trunc(self.Northing) mod 100000) / Power(10, 5 - digits / 2)); Result := letPair + ' ' + Format('%.*d', [digits div 2, e]) + ' ' + Format('%.*d', [digits div 2, n]); end; class function TOSGridRef.Parse(const value : string) : TOSGridRef; var gridref : string; l1, l2, e, n : integer; begin gridref := UpperCase(Trim(value)); //get numeric values of letter references, mapping A->0, B->1, C->2, etc: l1 := Ord(gridref[1]) - Ord('A'); l2 := Ord(gridref[2]) - Ord('A'); // shuffle down letters after 'I' since 'I' is not used in grid: if (l1 > 7) then Dec(l1); if (l2 > 7) then Dec(l2); // convert grid letters into 100km-square indexes from false origin (grid square SV): e := ((l1 - 2) mod 5) * 5 + (l2 mod 5); n := (19 - Floor(l1 / 5) * 5) - Floor(l2 / 5); if (e < 0) or (e > 6) or (n < 0) or ( n > 12) then begin Result := TOSGridRef.Create(NaN, NaN); Exit; end; // skip grid letters to get numeric part of ref, stripping any spaces: gridref := StringReplace(RightStr(gridref, Length(gridref) - 2), ' ', '', [rfReplaceAll, rfIgnoreCase]); // append numeric part of references to grid index: e := StrToInt(IntToStr(e) + LeftStr(gridref, Length(gridref) div 2)); n := StrToInt(IntToStr(n) + RightStr(gridref, Length(gridref) div 2)); // normalise to 1m grid, rounding up to centre of grid square: case Length(gridref) of 0 : begin e := e + 50000; n := n + 50000; end; 2 : begin e := e + 5000; n := n + 5000; end; 4 : begin e := e + 500; n := n + 500; end; 6 : begin e := e + 50; n := n + 50; end; 8 : begin e := e + 5; n := n + 5; end; 10 : // 10-digit refs are already 1m else begin Result := TOSGridRef.Create(NaN, NaN); Exit; end; end; Result := TOSGridRef.Create(e, n); end; end.
unit FMX.RESTLight; { author: ZuBy http://rzaripov.kz 2016 } interface uses System.Types, System.SysUtils, System.Classes, System.Net.HTTPClient, System.Net.HTTPClientComponent, System.Net.URLClient, System.Net.Mime, FMX.RESTLight.Types; type TRESTLight = record class function AccessTokenURL(const aAppSettings: TmyAppSettings): string; static; class function Execute(const aMethod: string; const aAppSettings: TmyAppSettings; const aFields: TArray<TmyRestParam>): string; static; class function Execute2(const ARequestURL: string; const aAppSettings: TmyAppSettings; const aFields: TArray<TmyRestParam>): string; static; end; implementation { TRESTLight } class function TRESTLight.AccessTokenURL(const aAppSettings: TmyAppSettings): string; begin Result := aAppSettings.OAuthURL; Result := Result + '?response_type=' + TURI.URLEncode('token'); if aAppSettings.ID <> '' then Result := Result + '&client_id=' + TURI.URLEncode(aAppSettings.ID); if aAppSettings.RedirectURL <> '' then Result := Result + '&redirect_uri=' + TURI.URLEncode(aAppSettings.RedirectURL); if aAppSettings.Scope <> '' then Result := Result + '&scope=' + TURI.URLEncode(aAppSettings.Scope); end; class function TRESTLight.Execute(const aMethod: string; const aAppSettings: TmyAppSettings; const aFields: TArray<TmyRestParam>): string; var AHttp: TNetHTTPClient; AData: TMultipartFormData; AResp: IHTTPResponse; I: Integer; begin Result := ''; AHttp := TNetHTTPClient.Create(nil); try AData := TMultipartFormData.Create(); try for I := Low(aFields) to High(aFields) do begin if aFields[I].is_file then AData.AddFile(aFields[I].Key, aFields[I].value) else AData.AddField(aFields[I].Key, aFields[I].value); end; AResp := AHttp.Post(aAppSettings.BaseURL + aMethod, AData); Result := AResp.ContentAsString(); finally FreeAndNil(AData); end; finally FreeAndNil(AHttp); end; end; class function TRESTLight.Execute2(const ARequestURL: string; const aAppSettings: TmyAppSettings; const aFields: TArray<TmyRestParam>): string; var AHttp: TNetHTTPClient; AData: TMultipartFormData; AResp: IHTTPResponse; I: Integer; begin Result := ''; AHttp := TNetHTTPClient.Create(nil); try AData := TMultipartFormData.Create(); try for I := Low(aFields) to High(aFields) do begin if aFields[I].is_file then AData.AddFile(aFields[I].Key, aFields[I].value) else AData.AddField(aFields[I].Key, aFields[I].value); end; AResp := AHttp.Post(ARequestURL, AData); Result := AResp.ContentAsString(); finally FreeAndNil(AData); end; finally FreeAndNil(AHttp); end; end; end.