text
stringlengths
14
6.51M
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Utils.System; interface type TSystemUtils = class public class function ExpandEnvironmentStrings(const value : string) : string; class function GetEnvironmentVariableDef(const name : string; const default : string = '') : string; class function GetVersionString: string; class procedure GetResourceVersionNumbers(out AMajor, AMinor, ARelease, ABuild: Integer); class procedure OutputDebugString(const value : string); end; implementation uses System.SysUtils, WinApi.Windows; { TSystemUtils } class function TSystemUtils.ExpandEnvironmentStrings(const value : string) : string; var bufferLen : Integer; begin bufferLen := Winapi.Windows.ExpandEnvironmentStrings(PChar(value), nil, 0); SetLength(result, bufferLen); Winapi.Windows.ExpandEnvironmentStrings(PChar(value), PChar(result), bufferLen); result := TrimRight(result); //trim the extr a null char. end; class function TSystemUtils.GetEnvironmentVariableDef(const name, default : string) : string; begin result := GetEnvironmentVariable(name); if result = '' then result := ExpandEnvironmentStrings(default); end; class procedure TSystemUtils.GetResourceVersionNumbers(out AMajor, AMinor, ARelease, ABuild: Integer); var HResource: TResourceHandle; HResData: THandle; PRes: Pointer; InfoSize: DWORD; FileInfo: PVSFixedFileInfo; FileInfoSize: DWORD; begin AMajor := 0; AMinor := 0; ARelease := 0; ABuild := 0; HResource := FindResource(HInstance, MakeIntResource(VS_VERSION_INFO), RT_VERSION); if HResource <> 0 then begin HResData:=LoadResource(HInstance, HResource); if HResData <> 0 then begin PRes:=LockResource(HResData); if Assigned(PRes) then begin InfoSize := SizeofResource(HInstance, HResource); if InfoSize = 0 then exit; //we do not want to raise errors if VerQueryValue(PRes, '\', Pointer(FileInfo), FileInfoSize) then begin AMajor := FileInfo.dwFileVersionMS shr 16; AMinor := FileInfo.dwFileVersionMS and $FFFF; ARelease := FileInfo.dwFileVersionLS shr 16; ABuild := FileInfo.dwFileVersionLS and $FFFF; end; end; end; end; end; class function TSystemUtils.GetVersionString: string; var Major, Minor, Release, Build: Integer; begin GetResourceVersionNumbers(Major,Minor,Release,Build); result := Format('%d.%d.%d.%d',[Major,Minor,Release,Build]); end; class procedure TSystemUtils.OutputDebugString(const value: string); begin {$IFDEF DEBUG} WinApi.Windows.OutputDebugString(PWideChar(value)); {$ENDIF} end; end.
unit TestAStar64_core; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Windows, AStar64.extra, System.Generics.Collections, AStar64.Common, DateUtils, UFileStructures, UGeoSimple, SysUtils, UGeoHash, UGeoPosition, Math, AStar64.core, AStar64.Intf; type PCarKey = ^TCarKey; TCarKey = record Speed: Integer; ///< Средняя скорость машины (не учитывая типы дорог). Zones: UInt64; ///< Биты недоступных для проезда типов зон, 0x0 - все зоны доступны для проезда. end; // Test methods for class TAstar TestTAstar = class(TTestCase) strict private FCarKey: TCarKey; FAstar: TAstar; FReturnValue: Integer; FRDistance, FRDuration: Double; FRHashString: String; FRSpeedlineString: PAnsiChar; function Exec( var RDistance, RDuration: Double; var RHashString: string; // const y1,x1,y2,x2: Double; const AStr: string; const ATimeOut: Integer = CTimeoutDef; const ALenTreshold: Double = CReductionTresholdDef // const AZones: TZonesMask = CZonesMaskDef; // const ARoadSpeeds: PRoadSpeedsRecord = nil ): Integer; procedure cr3(const AFromLatitude, AFromLongitude, AToLatitude, AToLongitude: double); private public procedure SetUp; override; procedure TearDown; override; procedure TestCalc_001; procedure TestCalc_002; procedure TestCountDD; procedure TestMakeHash; procedure TestMakeSpeedline; published procedure TestCalc_Fail; procedure TestCalc_Success_Long_001; procedure TestCalc_Success_Long_001r; procedure TestCalc_Success_Long_002; procedure TestCalc_Success_Long_002r; procedure TestCalc_Success_Long_003; procedure TestCalc_Success_Long_003r; procedure TestCalc_Success_Long_004; procedure TestCalc_Success_Long_004r; procedure TestCalc_Success_Long_005; procedure TestCalc_Success_Long_006; procedure TestCalc_Success_Long_007; procedure TestCalc_Success_Long_008; procedure TestCalc_Success_Long_009; procedure TestCalc_Success_Long_010_Total; procedure TestCalc_Success_CreateRouteWithPath3_001; procedure TestCalc_Success_CreateRouteWithPath3_001_speed; procedure TestCalc_Success_CreateRouteWithPath3_002; procedure TestCalc_Success_CreateRouteWithPath3_003; end; implementation function GetDigits(var s: string): string; var Started: Boolean; begin Result := ''; Started := False; while Length(s) > 0 do begin if (s[1] in ['0'..'9','.']) then begin if not Started then Started := True;; Result := Result + s[1]; end else if Started then Break; Delete(s, 1, 1); end; end; function GetGeo(var s: string): Double; var fs: TFormatSettings; begin fs := TFormatSettings.Create; fs.DecimalSeparator := '.'; Result := StrToFloatDef(GetDigits(s), 0, fs); end; function GetSpeed(var s: string): Integer; begin Result := StrToIntDef(GetDigits(s), 90); end; function GetZones(var s: string): UInt64; begin Result := StrToInt64Def(GetDigits(s), 0); end; //------------------------------------------------------------------------------ //! выдаём скорость на основе "уровня" дороги //------------------------------------------------------------------------------ function RoadSpeedByType( const AType: Integer ): Integer; begin case AType of 11, 12: Result := 110; 13, 14: Result := 90; 15, 16: Result := 70; // 70? 21, 22: Result := 60; 31, 32: Result := 60; 41, 42, 43: Result := 40; else Result := 60; end; end; //------------------------------------------------------------------------------ //! процедура обратного вызова для рассчёта скорости //------------------------------------------------------------------------------ function CallBack( const AHandle: Pointer; const AMetaData: Pointer ): Integer; stdcall; begin Result := RoadSpeedByType(PMetaDataV1(AMetaData)^.RoadType); end; function CreateRouteCallback(const AHandle: Pointer; const AMetaData: Pointer): Integer; stdcall; var pMetaData: PMetaDataV1; pCarHandle: PCarKey; iCarSpeed: Integer; iRoadSpeed: Integer; begin pCarHandle := PCarKey(AHandle); pMetaData := PMetaDataV1(AMetadata); if ((pCarHandle.Zones and pMetaData.Zones) <> 0) then Exit(-1); iCarSpeed := pCarHandle.Speed; iRoadSpeed := pMetaData.Restrictions and $FF; if (iCarSpeed <= 0) and (iRoadSpeed <= 0) then // нет ни скорости машины, ни скорости дороги - ошибка Exit(40) else if (iCarSpeed <= 0) then // нет скорости машины, ипользуем 0.8 от максимальной скорости дороги Exit(Trunc(0.8 * iRoadSpeed)) else if (iRoadSpeed>0) and (iCarSpeed>iRoadSpeed) then// скорость машины больше допустимой по дороге - используем допустимую Exit(iRoadSpeed) else // иначе используем скорость машины Exit(iCarSpeed) end; procedure TestTAstar.SetUp; begin // FAstar := TAstar.Create(@FCarKey, CreateRouteCallback, -1); // FAstar := TAstar.Create(@FCarKey, CreateRouteCallback, 1); FCarKey.Speed := 50; FCarKey.Zones := 0; end; procedure TestTAstar.TearDown; begin // FAstar.Free; // FAstar := nil; end; procedure TestTAstar.cr3(const AFromLatitude, AFromLongitude, AToLatitude, AToLongitude: double); var AstarRequest: TAstarRequest; begin with AstarRequest do begin Version := 1; FromLatitude := AFromLatitude; FromLongitude := AFromLongitude; ToLatitude := AToLatitude; ToLongitude := AToLongitude; ZonesLimit := 0; // RoadSpeedsRecord := CRoadSpeedsDef; with RoadSpeedsRecord do begin// := CRoadSpeedsDef; Motorway := 35; MotorwayLink := Trunc( 35 / 2); Trunk := 35; TrunkLink := Trunc( 35 / 2); Primary := 35; PrimaryLink := Trunc( 35 / 2); Secondary := 35; SecondaryLink := Trunc( 35 / 2); Tertiary := 35; TertiaryLink := Trunc( 35 / 2); Residential := 35; Road := 35; Unclassified := 35; reverse := 35;//60; end; FormatVariant := 0; LenTreshold := CReductionTresholdDef; Timeout := 300; Distance := 0;; Duration := 0; BufferLen := 1000000; HashString := GetMemory(BufferLen); try CheckTrue(CreateRouteWithPath3(@AstarRequest) = 0); finally FreeMemory(HashString); end; end; end; function TestTAstar.Exec( var RDistance, RDuration: Double; var RHashString: string; const AStr: string; // const y1,x1,y2,x2: Double; const ATimeOut: Integer = CTimeoutDef; const ALenTreshold: Double = CReductionTresholdDef // const AZones: TZonesMask = CZonesMaskDef; // const ARoadSpeeds: PRoadSpeedsRecord = nil ): Integer; var s: string; // speeds: t RoadSpeedsRecord: TRoadSpeedsRecord; FromLatitude, FromLongitude, ToLatitude, ToLongitude: Double; Speed: Integer; ZonesLimit: UInt64; HashString: PAnsiChar; begin s := AStr; FromLatitude := GetGeo(s); FromLongitude := GetGeo(s); ToLatitude := GetGeo(s); ToLongitude := GetGeo(s); Speed := GetSpeed(s); GetRoadSpeedsKToDef(@RoadSpeedsRecord, Speed, 0); ZonesLimit:= GetZones(s); // GetGeo(s),GetGeo(s),GetGeo(s),GetGeo(s), ATimeOut, ALenTreshold, GetZones FAstar := TAstar.Create( {@FCarKey, CreateRouteCallback,} FromLatitude, FromLongitude, ToLatitude, ToLongitude, ATimeOut, ALenTreshold, ZonesLimit, @RoadSpeedsRecord);// 0); Result := FAstar.Calc(); if Result = 0 then begin FAStar.CountDD(RDistance, RDuration); FAStar.MakeHash(HashString); // FAStar.MakeSpeedline(RHashString); RHashString := HashString; FreeMem(HashString); end; FAstar.Free; end; procedure TestTAstar.TestCalc_Fail; begin //грейн ReturnValue := FAstar.Calc(54.621196, 39.69051, 56.761304, 60.820014); // ReturnValue := Exec(60.058542,30.426213, 60.029103,30.405511); // ReturnValue := Exec(60.029103,30.405511, 60.024293,30.395171); // ReturnValue := Exec(60.024293,30.395171, 59.986214,30.296321); // ReturnValue := Exec(59.986214,30.296321, 60.005324,30.328022); // ReturnValue := Exec(60.005324,30.328022, 60.052384,30.339889); // ReturnValue := Exec(60.052384,30.339889, 60.046949,30.326693); // ReturnValue := Exec(60.046949,30.326693, 60.047483,30.320117); // ReturnValue := Exec(60.047483,30.320117, 60.005437,30.299034); // ReturnValue := Exec(60.005437,30.299034, 60.001989,30.279992); // ReturnValue := Exec(60.001989,30.279992, 60.000285,30.271949); // ReturnValue := Exec(60.000285,30.271949, 60.007492,30.270512); // ReturnValue := Exec(60.007492,30.270512, 60.020832,30.256801); // ReturnValue := Exec(60.020832,30.256801, 60.021461,30.252811); // ReturnValue := Exec(60.021461,30.252811, 60.027327,30.235765); // ReturnValue := Exec(60.027327,30.235765, 60.018012,30.228990); // ReturnValue := Exec(60.018012,30.228990, 60.011387,30.261987); // ReturnValue := Exec(60.011387,30.261987, 60.010951,30.261457); // ReturnValue := Exec(60.010951,30.261457, 60.008074,30.257408); // ReturnValue := Exec(60.008074,30.257408, 60.009107,30.248971); // ReturnValue := Exec(60.009107,30.248971, 59.989612,30.201162); // ReturnValue := Exec(59.989612,30.201162, 60.002122,30.243372); // ReturnValue := Exec(60.002122,30.243372, 59.988640,30.208933); // ReturnValue := Exec(59.988640,30.208933, 59.987114,30.234148); // ReturnValue := Exec(59.987114,30.234148, 59.984834,30.259887); // ReturnValue := Exec(59.984834,30.259887, 59.987669,30.305478); // ReturnValue := Exec(59.987669,30.305478, 60.000303,30.328238); // ReturnValue := Exec(60.000303,30.328238, 60.058542,30.426213); // ReturnValue := Exec(60.058542,30.426213, 60.056170,30.323605); // ReturnValue := Exec(60.056170,30.323605, 59.859998,30.248539); // ReturnValue := Exec(59.859998,30.248539, 59.838164,30.269811); // ReturnValue := Exec(59.838164,30.269811, 59.814928,30.291040); // ReturnValue := Exec(59.814928,30.291040, 59.841341,30.159171); // ReturnValue := Exec(59.841341,30.159171, 59.850929,30.193347); // ReturnValue := Exec(59.850929,30.193347, 59.852335,30.247785); // ReturnValue := Exec(59.852335,30.247785, 59.827514,30.399124); // ReturnValue := Exec(59.827514,30.399124, 59.828774,30.399031); // // // ReturnValue := Exec(59.8277984601301,30.3988930312805, 59.8280141707264,30.3987750055294) // ReturnValue := Exec(59.877332,30.318928, 60.058542,30.426213); // ReturnValue := Exec(60.058542,30.426213, 60.103446,29.975820); // ReturnValue := Exec(60.103446,29.975820, 59.871995,29.913810); // //грейн //ReturnValue := Exec(54.621196,39.69051, 56.761304,60.820014); //от виктора //ReturnValue := Exec(55.746406,49.110684, 55.621755,51.794757); //ReturnValue := Exec(55.621755,51.794757, 55.674783,52.307264); //ReturnValue := Exec(55.674783,52.307264, 55.585454,52.490215); //ReturnValue := Exec(55.585454,52.490215, 55.635070,52.624061); //ReturnValue := Exec(55.635070,52.624061, 55.743482,52.435022); //ReturnValue := Exec(55.743482,52.435022, 55.721600,52.385669); //ReturnValue := Exec(55.721600,52.385669, 55.757237,51.999564); //ReturnValue := Exec(55.757237,51.999564, 55.763741,49.197539); //ReturnValue := Exec(55.763741,49.197539, 55.746406,49.110684); //ReturnValue := Exec(55.746406,49.110684, 55.788500,49.126195); //ReturnValue := Exec(55.788500,49.126195, 55.791820,49.111534); //ReturnValue := Exec(55.791820,49.111534, 55.828850,49.080848); //ReturnValue := Exec(55.828850,49.080848, 55.867526,49.001994); //ReturnValue := Exec(55.867526,49.001994, 55.828632,49.194673); //ReturnValue := Exec(55.828632,49.194673, 55.825042,49.196129); //ReturnValue := Exec(55.825042,49.196129, 55.845421,49.320238); //ReturnValue := Exec(55.845421,49.320238, 55.836453,52.089989); //ReturnValue := Exec(55.836453,52.089989, 55.746406,49.110684); //ReturnValue := Exec(55.746406,49.110684, 55.621755,51.794757); //ReturnValue := Exec(55.621755,51.794757, 55.721600,52.385669); //ReturnValue := Exec(55.721600,52.385669, 55.635070,52.624061); //ReturnValue := Exec(55.635070,52.624061, 55.585454,52.490215); //ReturnValue := Exec(55.585454,52.490215, 55.674783,52.307264); //ReturnValue := Exec(55.674783,52.307264, 55.757237,51.999564); //ReturnValue := Exec(55.757237,51.999564, 55.763741,49.197539); //ReturnValue := Exec(55.746406,49.110684, 55.845421,49.320238); //ReturnValue := Exec(55.845421,49.320238, 55.828632,49.194673); //ReturnValue := Exec(55.828632,49.194673, 55.825042,49.196129); //ReturnValue := Exec(55.825042,49.196129, 55.867526,49.001994); //ReturnValue := Exec(55.867526,49.001994, 55.828850,49.080848); //ReturnValue := Exec(55.828850,49.080848, 55.791820,49.111534); //ReturnValue := Exec(55.791820,49.111534, 55.788500,49.126195); //ReturnValue := Exec(55.788500,49.126195, 55.743482,52.435022); //55,8262087223964 //37,342441457116 //55,6670981127791 //37,5582490172535 //ReturnValue := Exec(53.1716328883847, 49.6098135679024, 53.1962722768539, 50.1208025788914);//254с //ReturnValue := Exec(54.633253913531, 39.7249634572296, 56.8446582019898, 60.3771373702731); //ReturnValue := Exec(53.5273870541503, 49.4143662356438, 53.2277247811449, 50.2472429479726);//6.5с //55,8272669428288, 37,3437554349533, 55,7033714191695, 37,4559446383596 end; //длинные маршруты procedure TestTAstar.TestCalc_Success_CreateRouteWithPath3_001; var AstarRequest: TAstarRequest; begin with AstarRequest do begin Version := 1; FromLatitude := 55.8269984008765; FromLongitude := 37.3439161109207; ToLatitude := 55.705152673129; ToLongitude := 37.45480097221; ZonesLimit := 0; RoadSpeedsRecord := CRoadSpeedsDef; FormatVariant := 0; LenTreshold := CReductionTresholdDef; Timeout := 300; Distance := 0;; Duration := 0; BufferLen := 1000000; HashString := GetMemory(BufferLen); try CheckTrue(CreateRouteWithPath3(@AstarRequest) = 0); finally FreeMemory(HashString); end; end; end; procedure TestTAstar.TestCalc_Success_CreateRouteWithPath3_001_speed; var AstarRequest: TAstarRequest; begin with AstarRequest do begin Version := 1; FromLatitude := 55.8269984008765; FromLongitude := 37.3439161109207; ToLatitude := 55.705152673129; ToLongitude := 37.45480097221; ZonesLimit := 0; RoadSpeedsRecord := CRoadSpeedsDef; FormatVariant := 1; LenTreshold := CReductionTresholdDef; Timeout := 300; Distance := 0;; Duration := 0; BufferLen := 1000000; HashString := GetMemory(BufferLen); try CheckTrue(CreateRouteWithPath3(@AstarRequest) = 0); finally FreeMemory(HashString); end; end; end; procedure TestTAstar.TestCalc_Success_CreateRouteWithPath3_002; begin cr3(60.058542, 30.426213, 59.838164, 30.269811); end; procedure TestTAstar.TestCalc_Success_CreateRouteWithPath3_003; begin cr3(55.978543, 37.174820, 55.892127, 37.179203); end; procedure TestTAstar.TestCalc_Success_Long_001; begin //1 FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '53.2422731630489, 50.2571932238876, 53.2679465040196, 49.185764652459' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_001r; begin //1 rev FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '53.2679465040196, 49.185764652459, 53.2422731630489, 50.2571932238876' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_002; begin //2 FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '53.2049316881607, 50.1532115126348, 53.5074794177191, 49.4573211016759' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_002r; begin //2 rev FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '53.5074794177191, 49.4573211016759, 53.2049316881607, 50.1532115126348' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_003; begin //3 FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '55.8269984008765, 37.3439161109207, 55.705152673129, 37.45480097221' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_003r; begin //3 rev FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '55.705152673129, 37.45480097221, 55.8269984008765, 37.3439161109207' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_004; begin //4 FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '54.633253913531, 39.7249634572296, 56.846340799665, 60.5510504137514' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_004r; begin //4 rev FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '56.846340799665, 60.5510504137514, 54.633253913531, 39.7249634572296' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_005; begin //4 rev FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '54.618092, 39.678047, 57.777973, 40.934197' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_006; begin FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '57.306543, 61.921052, 57.058126, 63.777969' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_007; begin FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '57.012293, 63.732155, 57.282946, 62.000634' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_008; begin FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '[56.504506,60.815460]-[57.282946,62.000634] 50 0' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_009; begin FReturnValue := Exec( FRDistance, FRDuration, FRHashString, '[55.765124,37.852585]-[55.782358,37.868465] 90 4' ); CheckEquals(FReturnValue, 0); end; procedure TestTAstar.TestCalc_Success_Long_010_Total; begin CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.762738,37.670717] 28 2 = 0.135s 22.7355 0.0352494 26.8746 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.762738,37.670717]-[55.766830,37.657997] 28 2 = 0.057s 1.952 0.00287672 28.273 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.766830,37.657997]-[55.783139,37.642671] 28 2 = 0.071s 3.04064 0.00468659 27.0331 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.783139,37.642671]-[55.797073,37.633473] 28 2 = 0.06s 3.50388 0.00525843 27.764 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.797073,37.633473]-[55.818154,37.646651] 28 2 = 0.051s 4.83923 0.0071795 28.0848 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.818154,37.646651]-[55.816600,37.637965] 28 2 = 0.049s 1.45083 0.00226825 26.6511 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.816600,37.637965]-[55.806565,37.628963] 28 2 = 0.075s 1.83595 0.00315258 24.2651 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.806565,37.628963]-[55.793915,37.615479] 28 2 = 0.096s 3.43572 0.00555383 25.7759 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.793915,37.615479]-[55.784395,37.622244] 28 2 = 0.081s 1.84933 0.00309839 24.8695 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.784395,37.622244]-[55.785878,37.601034] 28 2 = 0.099s 2.53826 0.00444485 23.7941 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.785878,37.601034]-[55.776958,37.607529] 28 2 = 0.063s 1.55815 0.00244365 26.5681 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.776958,37.607529]-[55.780122,37.632592] 28 2 = 0.091s 2.3203 0.00443192 21.8143 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.780122,37.632592]-[55.774973,37.631909] 28 2 = 0.062s 0.828875 0.00100115 34.4969 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.774973,37.631909]-[55.770314,37.624642] 28 2 = 0.083s 1.58158 0.00217484 30.3007 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.770314,37.624642]-[55.760099,37.646848] 28 2 = 1.857s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.760099,37.646848]-[55.754086,37.652661] 28 2 = 0.453s 2.22146 0.00295403 31.3337 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.754086,37.652661]-[55.757278,37.612856] 28 2 = 1.669s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.757278,37.612856]-[55.747976,37.596022] 28 2 = 2.419s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.747976,37.596022]-[55.754913,37.566678] 28 2 = 1.765s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.754913,37.566678]-[55.744406,37.567401] 28 2 = 0.039s 3.16823 0.00528747 24.9665 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.744406,37.567401]-[55.731901,37.607763] 28 2 = 0.036s 4.2163 0.00628002 27.9743 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.731901,37.607763]-[55.713679,37.615866] 28 2 = 0.036s 6.06154 0.00943578 26.7666 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.713679,37.615866]-[55.635243,37.658122] 28 2 = 0.032s 12.165 0.0182149 27.8274 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.635243,37.658122]-[55.755327,37.645321] 28 2 = 2.034s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.755327,37.645321]-[55.675419,37.938276] 28 2 = 2.042s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.720859,37.787084] 28 6 = 0.041s 13.0184 0.0197963 27.4008 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.720859,37.787084]-[55.705665,37.767869] 28 6 = 0.028s 3.97492 0.00673595 24.5877 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.705665,37.767869]-[55.698827,37.770951] 28 6 = 0.024s 1.96856 0.00266937 30.7277 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.698827,37.770951]-[55.696788,37.745232] 28 6 = 0.024s 2.54282 0.00372749 28.4242 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.696788,37.745232]-[55.702815,37.736554] 28 6 = 0.02s 1.90025 0.00355728 22.2578 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.702815,37.736554]-[55.701075,37.657233] 28 6 = 0.045s 12.4513 0.0209032 24.8193 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.701075,37.657233]-[55.729138,37.709497] 28 6 = 0.023s 5.92029 0.00841726 29.3063 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.729138,37.709497]-[55.738485,37.777760] 28 6 = 0.036s 10.2492 0.0155233 27.5103 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.738485,37.777760]-[55.749354,37.786213] 28 6 = 0.023s 1.87299 0.00243447 32.0569 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.749354,37.786213]-[55.758934,37.773502] 28 6 = 0.022s 3.05548 0.00459779 27.6897 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.758934,37.773502]-[55.752090,37.761806] 28 6 = 0.022s 2.92608 0.00527253 23.1236 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.752090,37.761806]-[55.749177,37.750667] 28 6 = 0.021s 1.78871 0.0024972 29.8454 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.749177,37.750667]-[55.753255,37.715552] 28 6 = 0.029s 9.11618 0.01578 24.071 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.753255,37.715552]-[55.754578,37.694953] 28 6 = 0.032s 4.70792 0.00575977 34.0575 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.754578,37.694953]-[55.781291,37.711509] 28 6 = 0.041s 6.44509 0.00903987 29.7068 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.781291,37.711509]-[55.784091,37.690731] 28 6 = 0.025s 1.59225 0.00240766 27.5553 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.784091,37.690731]-[55.786455,37.678837] 28 6 = 0.029s 1.34736 0.00197294 28.4549 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.786455,37.678837]-[55.792326,37.706470] 28 6 = 0.029s 2.79523 0.00417044 27.927 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.792326,37.706470]-[55.797402,37.720447] 28 6 = 0.023s 2.30249 0.00335365 28.6068 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.797402,37.720447]-[55.675419,37.938276] 28 6 = 0.383s 25.4584 0.0422542 25.1043 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.774517,37.543434] 28 6 = 0.08s 33.6315 0.0508446 27.5607 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.774517,37.543434]-[55.784622,37.523177] 28 6 = 0.054s 2.74687 0.00429722 26.6342 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.784622,37.523177]-[55.794006,37.511589] 28 6 = 0.036s 2.51478 0.00402573 26.0282 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.794006,37.511589]-[55.805189,37.516727] 28 6 = 0.05s 5.59181 0.0095094 24.5012 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.805189,37.516727]-[55.789411,37.571821] 28 6 = 0.038s 5.15536 0.0090621 23.7039 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.789411,37.571821]-[55.797326,37.578585] 28 6 = 0.054s 3.34731 0.00509122 27.3945 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.797326,37.578585]-[55.800565,37.586509] 28 6 = 0.072s 2.47397 0.00349566 29.4885 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.800565,37.586509]-[55.812089,37.576816] 28 6 = 0.061s 2.91971 0.00471581 25.7971 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.812089,37.576816]-[55.825507,37.569755] 28 6 = 0.046s 2.91563 0.00444459 27.3332 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.825507,37.569755]-[55.838430,37.573842] 28 6 = 0.047s 2.23505 0.00312216 29.8277 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.838430,37.573842]-[55.777783,37.586877] 28 6 = 1.059s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.777783,37.586877]-[55.874334,37.513817] 28 6 = 0.812s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.874334,37.513817]-[55.880086,37.520168] 28 6 = 0.017s 1.55091 0.00214817 30.082 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.880086,37.520168]-[55.919967,37.500648] 28 6 = 0.019s 6.56557 0.010557 25.9131 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.919967,37.500648]-[55.905714,37.544701] 28 6 = 0.015s 6.52677 0.0106257 25.5935 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.905714,37.544701]-[55.845789,37.579789] 28 6 = 0.02s 10.2912 0.0154597 27.7367 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.845789,37.579789]-[55.809398,37.597118] 28 6 = 0.025s 4.85742 0.00811543 24.9392 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.809398,37.597118]-[55.820920,37.623870] 28 6 = 0.027s 3.80202 0.00610244 25.9597 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.820920,37.623870]-[55.675419,37.938276] 28 6 = 0.429s 33.2113 0.0522117 26.5038 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.834912,37.657614] 28 14 = 0.891s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.834912,37.657614]-[55.854805,37.650918] 28 14 = 1.144s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.854805,37.650918]-[55.867036,37.638485] 28 14 = 2.069s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.867036,37.638485]-[55.865147,37.594540] 28 14 = 1.126s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.865147,37.594540]-[55.890058,37.587964] 28 14 = 0.777s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.890058,37.587964]-[55.900193,37.585808] 28 14 = 0.891s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.900193,37.585808]-[55.926000,37.605751] 28 14 = 0.504s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.926000,37.605751]-[55.961883,37.584928] 28 14 = 0.039s 12.8265 0.0206711 25.8545 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.961883,37.584928]-[56.014821,37.483050] 28 14 = 0.034s 14.0258 0.0213786 27.3361 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.014821,37.483050]-[56.075423,37.550136] 28 14 = 0.024s 16.7497 0.0257592 27.0933 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.075423,37.550136]-[55.949375,37.646687] 28 14 = 0.058s 28.6209 0.0461622 25.8336 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.949375,37.646687]-[55.923528,37.660170] 28 14 = 0.014s 3.79854 0.00585062 27.0523 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.923528,37.660170]-[55.869849,37.660314] 28 14 = 1.021s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.869849,37.660314]-[55.863328,37.681191] 28 14 = 0.854s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.863328,37.681191]-[55.948704,37.831479] 28 14 = 1.086s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.948704,37.831479]-[55.675419,37.938276] 28 14 = 19.984s 49.7602 0.0831638 24.9308 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.790656,37.800281] 28 6 = 0.085s 22.319 0.0359826 25.8446 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.790656,37.800281]-[55.797387,37.815669] 28 6 = 0.029s 2.33178 0.00381523 25.4658 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.797387,37.815669]-[55.806904,37.799805] 28 6 = 0.025s 2.37315 0.00396841 24.9171 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.806904,37.799805]-[55.806940,37.780015] 28 6 = 0.034s 2.82302 0.00398176 29.5412 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.806940,37.780015]-[55.817232,37.765457] 28 6 = 0.036s 2.79245 0.00427486 27.2177 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.817232,37.765457]-[55.789608,37.752481] 28 6 = 0.032s 6.06922 0.0102439 24.6863 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.789608,37.752481]-[55.781626,37.734578] 28 6 = 0.031s 2.27352 0.00395936 23.9256 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.781626,37.734578]-[55.660297,37.760270] 28 6 = 0.229s 19.0283 0.0305773 25.9292 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.660297,37.760270]-[55.654340,37.765749] 28 6 = 0.023s 2.35751 0.00369868 26.558 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.654340,37.765749]-[55.650323,37.731236] 28 6 = 0.022s 3.73645 0.00581081 26.7923 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.650323,37.731236]-[55.646914,37.746912] 28 6 = 0.02s 2.03715 0.00290535 29.2156 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.646914,37.746912]-[55.618791,37.715022] 28 6 = 0.031s 7.54838 0.0119331 26.3566 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.618791,37.715022]-[55.600384,37.796104] 28 6 = 0.025s 8.05061 0.0129753 25.8523 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.600384,37.796104]-[55.658439,37.839268] 28 6 = 0.019s 16.5559 0.0262771 26.2522 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.658439,37.839268]-[55.675419,37.938276] 28 6 = 0.028s 9.55221 0.0159667 24.9274 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.727009,37.471587] 28 6 = 0.527s 40.266 0.0619513 27.0818 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.727009,37.471587]-[55.725803,37.435610] 28 6 = 0.047s 4.00075 0.00627574 26.5623 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.725803,37.435610]-[55.716448,37.406971] 28 6 = 0.031s 2.80602 0.00498975 23.4315 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.716448,37.406971]-[55.724515,37.385924] 28 6 = 0.032s 3.21066 0.00450344 29.7056 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.724515,37.385924]-[55.746122,37.405094] 28 6 = 0.04s 4.75436 0.00697222 28.4125 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.746122,37.405094]-[55.746649,37.421353] 28 6 = 0.041s 1.67711 0.00255307 27.3708 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.746649,37.421353]-[55.770568,37.421380] 28 6 = 0.04s 4.05799 0.00693858 24.3685 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.770568,37.421380]-[55.758772,37.434118] 28 6 = 0.035s 2.35987 0.00306324 32.0994 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.758772,37.434118]-[55.780826,37.452112] 28 6 = 0.047s 7.38159 0.0112078 27.4422 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.780826,37.452112]-[55.790216,37.483014] 28 6 = 0.045s 4.56455 0.00780677 24.3621 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.790216,37.483014]-[55.809686,37.465960] 28 6 = 0.036s 2.91026 0.00478081 25.3641 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.809686,37.465960]-[55.823789,37.441393] 28 6 = 0.033s 5.77972 0.00931967 25.8401 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.823789,37.441393]-[55.675419,37.938276] 28 6 = 0.123s 41.5284 0.0632031 27.3776 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.888760,37.433526] 28 6 = 0.094s 47.1033 0.0720685 27.2329 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.888760,37.433526]-[55.900128,37.382393] 28 6 = 0.025s 5.17934 0.00843827 25.5747 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.900128,37.382393]-[55.854249,37.357402] 28 6 = 0.067s 11.3068 0.0184474 25.5385 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.854249,37.357402]-[55.841832,37.366565] 28 6 = 0.025s 3.30937 0.00481502 28.6376 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.841832,37.366565]-[55.798374,37.388245] 28 6 = 0.03s 8.02954 0.0124604 26.8501 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.798374,37.388245]-[55.791953,37.381021] 28 6 = 0.021s 1.39885 0.00179069 32.549 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.791953,37.381021]-[55.835275,37.292544] 28 6 = 0.047s 13.0945 0.0195143 27.9592 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.835275,37.292544]-[55.836494,37.295643] 28 6 = 0.018s 1.75868 0.00250783 29.2197 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.836494,37.295643]-[55.836494,37.295643] 28 6 = 0.017s 0.426689 0.000444468 40 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.836494,37.295643]-[55.837025,37.293038] 28 6 = 0.014s 2.3283 0.00306358 31.6664 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.837025,37.293038]-[55.890542,37.300575] 28 6 = 0.256s 15.8418 0.0244746 26.9698 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.890542,37.300575]-[55.675419,37.938276] 28 6 = 0.086s 53.1989 0.0801295 27.663 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.700562,37.692663] 28 2 = 0.071s 22.7802 0.0355076 26.7316 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.700562,37.692663]-[55.707867,37.700487] 28 2 = 0.03s 1.80973 0.00261901 28.7915 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.707867,37.700487]-[55.717274,37.677804] 28 2 = 0.028s 3.1548 0.00492905 26.6685 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.717274,37.677804]-[55.710002,37.662722] 28 2 = 0.026s 2.31102 0.0031964 30.1253 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.710002,37.662722]-[55.692861,37.662210] 28 2 = 0.028s 4.92668 0.00710223 28.9034 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.692861,37.662210]-[55.676042,37.666566] 28 2 = 0.032s 2.7309 0.00381951 29.7911 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.676042,37.666566]-[55.690419,37.601456] 28 2 = 0.063s 8.29075 0.0140536 24.5807 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.690419,37.601456]-[55.682737,37.625612] 28 2 = 0.059s 5.92086 0.00993929 24.8209 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.682737,37.625612]-[55.678707,37.634631] 28 2 = 0.049s 2.72243 0.00483624 23.4552 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.678707,37.634631]-[55.653644,37.620698] 28 2 = 0.044s 4.31199 0.00780262 23.0264 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.653644,37.620698]-[55.625791,37.636590] 28 2 = 0.063s 7.80944 0.013457 24.1803 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.625791,37.636590]-[55.675419,37.938276] 28 2 = 0.207s 26.6158 0.0451294 24.5736 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.632586,37.476752] 28 2 = 0.149s 39.986 0.0613059 27.1765 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.632586,37.476752]-[55.658759,37.487362] 28 2 = 0.023s 4.84915 0.00695085 29.0681 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.658759,37.487362]-[55.675555,37.498932] 28 2 = 0.031s 3.77328 0.00571299 27.5198 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675555,37.498932]-[55.684924,37.524363] 28 2 = 0.037s 3.46637 0.00493973 29.2388 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.684924,37.524363]-[55.723359,37.517545] 28 2 = 0.047s 8.24726 0.0136358 25.2011 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.723359,37.517545]-[55.736980,37.525738] 28 2 = 0.07s 9.17903 0.0147196 25.983 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.736980,37.525738]-[55.688872,37.568848] 28 2 = 0.052s 8.6464 0.0135558 26.5766 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.688872,37.568848]-[55.708633,37.521893] 28 2 = 0.039s 5.31413 0.00937275 23.624 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.708633,37.521893]-[55.702295,37.505982] 28 2 = 0.027s 1.84706 0.00249629 30.83 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.702295,37.505982]-[55.654041,37.539401] 28 2 = 0.045s 9.41054 0.0160184 24.4785 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.654041,37.539401]-[55.662933,37.522486] 28 2 = 0.034s 2.75517 0.00426409 26.9222 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.662933,37.522486]-[55.675419,37.938276] 28 2 = 0.319s 35.3379 0.0550176 26.7625 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.907935,37.866019] 28 14 = 2.529s 44.4759 0.0729013 25.4201 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.907935,37.866019]-[55.943981,37.875964] 28 14 = 0.024s 6.46019 0.0110066 24.4558 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.943981,37.875964]-[55.967622,37.937606] 28 14 = 0.259s 13.657 0.0255767 22.2484 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.967622,37.937606]-[55.974907,37.899670] 28 14 = 0.015s 3.50699 0.00630584 23.1729 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.974907,37.899670]-[55.964685,37.888639] 28 14 = 0.014s 1.78096 0.00309375 23.986 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.964685,37.888639]-[55.944223,37.853748] 28 14 = 0.034s 9.47207 0.0179782 21.9526 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.944223,37.853748]-[55.920189,37.857539] 28 14 = 0.02s 4.21733 0.0072691 24.1738 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.920189,37.857539]-[55.905694,37.850209] 28 14 = 0.014s 2.57604 0.00392121 27.3729 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.905694,37.850209]-[55.908727,37.702921] 28 14 = 0.043s 13.9893 0.023861 24.4285 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.908727,37.702921]-[55.858822,37.424300] 28 14 = 1.002s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.858822,37.424300]-[55.675419,37.938276] 28 14 = 1.167s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.660480,37.991819] 28 14 = 0.048s 10.7409 0.0162716 27.5041 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.660480,37.991819]-[55.699172,38.028228] 28 14 = 0.103s 10.8962 0.0181705 24.9862 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.699172,38.028228]-[55.740015,38.015212] 28 14 = 0.043s 7.21774 0.0130976 22.9614 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.740015,38.015212]-[55.793693,38.011753] 28 14 = 0.05s 12.3519 0.0221284 23.2581 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.793693,38.011753]-[55.820728,37.968670] 28 14 = 0.029s 8.14904 0.0147186 23.0691 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.820728,37.968670]-[55.798409,37.961879] 28 14 = 0.026s 3.00073 0.00476092 26.2619 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.798409,37.961879]-[55.727435,37.972712] 28 14 = 0.035s 10.7377 0.0190462 23.4905 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.727435,37.972712]-[55.597135,37.986240] 28 14 = 0.337s 22.6419 0.0367416 25.677 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.597135,37.986240]-[55.670351,37.950757] 28 14 = 0.045s 11.1326 0.0175428 26.4415 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.670351,37.950757]-[55.702972,37.962543] 28 14 = 0.156s 13.5191 0.0232729 24.204 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.702972,37.962543]-[55.675419,37.938276] 28 14 = 0.037s 8.65193 0.0154298 23.3636 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.501993,37.601978] 28 6 = 0.047s 37.7826 0.0580945 27.0985 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.501993,37.601978]-[55.538183,37.661652] 28 6 = 0.091s 13.1839 0.0219142 25.0673 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.538183,37.661652]-[55.351298,37.632350] 28 6 = 0.222s 36.2924 0.058812 25.7121 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.351298,37.632350]-[55.408736,37.572737] 28 6 = 0.04s 18.1184 0.027841 27.1159 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.408736,37.572737]-[55.473082,37.543740] 28 6 = 0.043s 10.7914 0.0169934 26.4597 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.473082,37.543740]-[55.542915,37.723538] 28 6 = 0.603s 25.2959 0.0412965 25.5226 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.542915,37.723538]-[55.592571,37.612686] 28 6 = 0.04s 15.0101 0.0238865 26.183 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.592571,37.612686]-[55.606075,37.556397] 28 6 = 0.037s 9.99042 0.0162121 25.6763 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.606075,37.556397]-[55.604097,37.607862] 28 6 = 0.057s 11.5804 0.0182991 26.3682 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.604097,37.607862]-[55.668356,37.523294] 28 6 = 0.051s 12.4554 0.02038 25.4649 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.668356,37.523294]-[55.675419,37.938276] 28 6 = 0.448s 33.456 0.0511648 27.2453 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.778274,37.893634] 28 14 = 0.425s 18.3487 0.0323076 23.6641 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.778274,37.893634]-[55.773565,37.846499] 28 14 = 0.796s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.773565,37.846499]-[55.769079,37.832611] 28 14 = 0.922s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.769079,37.832611]-[55.711650,37.888010] 28 14 = 1.298s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.711650,37.888010]-[55.691587,37.919622] 28 14 = 0.04s 6.77405 0.0112922 24.9954 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.691587,37.919622]-[55.753225,37.868382] 28 14 = 0.049s 11.2235 0.0187479 24.944 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.753225,37.868382]-[55.734658,37.831021] 28 14 = 0.218s 8.31581 0.0135942 25.4881 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.734658,37.831021]-[55.718735,37.824634] 28 14 = 0.683s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.718735,37.824634]-[55.678209,37.886214] 28 14 = 0.498s 0 0 -nan(ind) ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.678209,37.886214]-[55.675419,37.938276] 28 14 = 0.016s 4.56362 0.00704504 26.9908 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.923478,37.814043] 28 14 = 14.081s 48.3175 0.0796222 25.2848 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.923478,37.814043]-[55.932798,37.824670] 28 14 = 0.027s 6.03328 0.00994304 25.2827 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.932798,37.824670]-[56.011590,37.858033] 28 14 = 0.018s 11.3237 0.0184701 25.545 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.011590,37.858033]-[56.062047,37.858159] 28 14 = 0.019s 7.44529 0.0124919 24.8338 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.062047,37.858159]-[55.963350,37.808330] 28 14 = 0.714s 18.0222 0.0319589 23.4966 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.963350,37.808330]-[55.967582,37.759848] 28 14 = 0.016s 3.99816 0.0066069 25.2145 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.967582,37.759848]-[55.930428,37.775110] 28 14 = 0.015s 8.19201 0.0131096 26.0369 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.930428,37.775110]-[55.930055,37.795367] 28 14 = 0.043s 11.0243 0.0174929 26.2589 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.930055,37.795367]-[55.922661,37.789357] 28 14 = 0.024s 6.13758 0.00988793 25.8631 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.922661,37.789357]-[55.675419,37.938276] 28 14 = 14.629s 51.0889 0.0840476 25.3273 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.594107,38.126450] 28 6 = 0.039s 22.4639 0.0339584 27.563 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.594107,38.126450]-[55.565814,38.176684] 28 6 = 0.018s 6.74934 0.0120976 23.2461 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.565814,38.176684]-[55.329667,38.219803] 28 6 = 5.457s 41.3184 0.0623074 27.6307 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.329667,38.219803]-[55.241893,38.202142] 28 6 = 0.012s 11.2958 0.0171028 27.5193 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.241893,38.202142]-[55.195729,38.363390] 28 6 = 0.024s 23.1519 0.0382723 25.2052 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.195729,38.363390]-[55.419422,38.254577] 28 6 = 0.1s 35.4051 0.0560935 26.2992 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.419422,38.254577]-[55.716935,38.215913] 28 6 = 1.714s 48.8882 0.0838512 24.2931 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.716935,38.215913]-[55.658850,38.100695] 28 6 = 0.355s 18.3476 0.0310614 24.612 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.658850,38.100695]-[55.675419,37.938276] 28 6 = 0.16s 18.3438 0.0276371 27.6558 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.892127,37.179203] 28 0 = 0.315s 63.0105 0.0957536 27.4187 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.892127,37.179203]-[55.860292,37.120957] 28 0 = 0.085s 9.96788 0.0158904 26.1371 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.860292,37.120957]-[55.857584,37.117804] 28 0 = 0.019s 0.560746 0.000683796 34.1687 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.857584,37.117804]-[55.811240,37.080542] 28 0 = 0.08s 12.4023 0.0217532 23.7557 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.811240,37.080542]-[55.791719,37.039345] 28 0 = 0.027s 7.07121 0.0118649 24.8325 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.791719,37.039345]-[55.672494,37.281144] 28 0 = 0.511s 33.9524 0.0534682 26.4584 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.672494,37.281144]-[55.840892,37.177874] 28 0 = 0.299s 26.9658 0.0492316 22.8222 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.840892,37.177874]-[55.675419,37.938276] 28 0 = 0.325s 59.0948 0.089182 27.6096 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.919135,37.757943] 28 14 = 24.67s 52.699 0.0870462 25.2256 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.919135,37.757943]-[55.911058,37.748125] 28 14 = 0.016s 2.21122 0.00288571 31.9278 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.911058,37.748125]-[55.891214,37.730428] 28 14 = 0.057s 8.37945 0.0126526 27.5945 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.891214,37.730428]-[55.969597,37.719693] 28 14 = 0.209s 13.7015 0.0235592 24.2324 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.969597,37.719693]-[55.998025,37.712030] 28 14 = 0.023s 4.90715 0.00818088 24.993 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.998025,37.712030]-[55.933080,37.753434] 28 14 = 0.02s 11.0414 0.0179585 25.6179 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.933080,37.753434]-[55.900854,37.736024] 28 14 = 0.025s 6.8246 0.0105683 26.9067 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.900854,37.736024]-[55.675419,37.938276] 28 14 = 19.862s 56.3987 0.0933394 25.1764 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.190323,37.427812] 28 6 = 0.173s 82.8061 0.123075 28.0337 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.190323,37.427812]-[55.155494,37.467203] 28 6 = 0.014s 7.49472 0.0121952 25.6067 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.155494,37.467203]-[55.152547,37.617249] 28 6 = 0.012s 16.6137 0.0286649 24.1493 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.152547,37.617249]-[55.255677,37.617294] 28 6 = 0.037s 31.8806 0.0507384 26.1805 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.255677,37.617294]-[55.675419,37.938276] 28 6 = 0.147s 76.8004 0.119233 26.8384 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.983489,37.408930] 28 6 = 0.121s 60.7532 0.0937156 27.0113 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.983489,37.408930]-[55.992754,37.215799] 28 6 = 0.023s 15.8254 0.0255213 25.8369 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.992754,37.215799]-[56.012179,37.202075] 28 6 = 0.009s 2.98213 0.00407812 30.4688 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.012179,37.202075]-[55.978543,37.174820] 28 6 = 0.014s 6.11958 0.00889921 28.6523 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.978543,37.174820]-[55.938482,37.313592] 28 6 = 0.059s 12.1011 0.0224098 22.4997 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.938482,37.313592]-[55.675419,37.938276] 28 6 = 0.075s 56.4839 0.0869575 27.0649 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.387095,38.186161] 28 6 = 0.03s 44.9485 0.0684343 27.3672 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.387095,38.186161]-[55.339283,37.808482] 28 6 = 0.016s 25.8046 0.0398254 26.9976 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.339283,37.808482]-[55.920401,37.729835] 28 6 = 0.051s 77.4664 0.117095 27.5654 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.920401,37.729835]-[55.829436,37.817951] 28 6 = 0.041s 19.4874 0.0298729 27.1809 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.829436,37.817951]-[55.675419,37.938276] 28 6 = 0.034s 23.4461 0.037446 26.0888 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.675419,37.938276]-[55.540918,37.082823] 28 0 = 0.121s 66.6257 0.101383 27.3819 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.540918,37.082823]-[55.477960,37.008227] 28 0 = 0.025s 15.0008 0.0254014 24.6062 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.477960,37.008227]-[55.345007,37.148140] 28 0 = 0.045s 28.6631 0.0449292 26.5817 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.345007,37.148140]-[55.413090,37.188321] 28 0 = 0.01s 13.3555 0.0198804 27.9913 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.413090,37.188321]-[55.675419,37.938276] 28 0 = 0.053s 68.9138 0.106201 27.0375 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.862201,37.986582] 28 6 = 0.375s 30.3181 0.0491796 25.6865 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.862201,37.986582]-[55.916966,37.992646] 28 6 = 0.02s 8.74095 0.0130247 27.9627 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.916966,37.992646]-[55.928638,37.988523] 28 6 = 0.013s 2.6665 0.00415474 26.7415 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.928638,37.988523]-[55.955685,38.059472] 28 6 = 0.013s 6.58471 0.0108108 25.3787 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.955685,38.059472]-[55.675419,37.938276] 28 6 = 0.361s 43.3364 0.0685319 26.3481 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.629262,37.002092] 28 6 = 0.366s 70.3427 0.106462 27.5305 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.629262,37.002092]-[55.729184,36.859493] 28 6 = 0.012s 18.3006 0.0282403 27.0013 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.729184,36.859493]-[55.673966,37.038976] 28 6 = 0.117s 25.8025 0.0464787 23.1311 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.673966,37.038976]-[55.675419,37.938276] 28 6 = 0.11s 66.8088 0.101753 27.3574 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.675419,37.938276]-[56.078146,37.057985] 28 2 = 0.132s 79.0944 0.120084 27.444 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.078146,37.057985]-[56.178859,36.986263] 28 2 = 0.013s 17.4361 0.0270187 26.8889 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.178859,36.986263]-[56.121496,37.057958] 28 2 = 0.008s 13.8443 0.0220654 26.1425 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.121496,37.057958]-[55.675419,37.938276] 28 2 = 0.086s 82.3443 0.125291 27.3844 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.427693,37.273446] 28 6 = 0.05s 61.9363 0.0954785 27.0289 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.427693,37.273446]-[55.516909,37.352039] 28 6 = 0.011s 16.8529 0.028563 24.5843 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.516909,37.352039]-[55.687462,37.547944] 28 6 = 0.022s 25.3704 0.0384684 27.4797 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.687462,37.547944]-[55.675419,37.938276] 28 6 = 0.07s 30.6855 0.047254 27.0572 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.194727,37.878856] 28 2 = 0.038s 71.0352 0.0977376 30.2831 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.194727,37.878856]-[55.373675,38.044012] 28 2 = 0.036s 33.2484 0.0556348 24.9007 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.373675,38.044012]-[55.486872,37.979126] 28 2 = 0.016s 25.9433 0.0437605 24.702 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.486872,37.979126]-[55.675419,37.938276] 28 2 = 0.374s 34.6923 0.0541847 26.6775 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.873950,37.399946] 28 2 = 0.065s 47.4706 0.073064 27.0714 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.873950,37.399946]-[55.902596,37.401429] 28 2 = 0.022s 5.53746 0.00897448 25.7093 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '55.902596,37.401429]-[55.675419,37.938276] 28 2 = 0.094s 48.1641 0.0737167 27.2236 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.740674,37.500567] 28 2 = 0.133s 33.9753 0.0526634 26.8808 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.740674,37.500567]-[55.777930,37.515425] 28 2 = 0.049s 7.4344 0.0128666 24.0753 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.777930,37.515425]-[55.675419,37.938276] 28 2 = 0.191s 34.3224 0.0530116 26.9771 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.654396,37.441431] 28 2 = 0.296s 42.3344 0.0644761 27.358 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.654396,37.441431]-[55.450879,37.743381] 28 2 = 0.039s 39.6311 0.0588316 28.0682 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.450879,37.743381]-[55.675419,37.938276] 28 2 = 0.084s 39.6156 0.0582992 28.3135 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[55.373470,37.377480] 28 2 = 0.184s 58.1367 0.0910636 26.6008 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.373470,37.377480]-[55.641920,37.523456] 28 2 = 0.774s 42.7013 0.0662533 26.8548 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.641920,37.523456]-[55.675419,37.938276] 28 2 = 1.397s 36.9025 0.0596364 25.7829 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[55.675419,37.938276]-[56.088549,37.498698] 28 14 = 74.357s 91.1518 0.150403 25.2521 ')); CheckEquals(0, Exec(FRDistance, FRDuration, FRHashString, '[56.088549,37.498698]-[55.563634,38.262724] 28 14 = 232.187s 117.803 0.191005 25.6981 ')); end; procedure TestTAstar.TestCalc_001; begin // ReturnValue := FAstar.Calc( // 54.621196, 39.69051, // 56.761304, 60.820014 // ); end; procedure TestTAstar.TestCalc_002; var FReturnValue: Integer; begin // ReturnValue := FAstar.Calc( // 56.761304, 60.820014, // 54.621196, 39.69051 // ); end; //[59.877332,30.318928]-[60.058542,30.426213] 35 0 = 20.469s 27.8639 0.793527 //[60.058542,30.426213]-[60.103446,29.975820] 35 0 = 47.417s 37.8186 1.07854 //[60.103446,29.975820]-[59.871995,29.913810] 35 0 = 76.091s 50.8725 1.45244 procedure TestTAstar.TestCountDD; begin // TODO: Setup method call parameters FAstar.CountDD(FRDistance, FRDuration); // TODO: Validate method results end; procedure TestTAstar.TestMakeHash; begin // TODO: Setup method call parameters // FAstar.MakeHash(FRHashString); // TODO: Validate method results end; procedure TestTAstar.TestMakeSpeedline; begin // TODO: Setup method call parameters // FAstar.MakeSpeedline(FRSpeedlineString); // TODO: Validate method results end; initialization // Register any test cases with the test runner RegisterTest(TestTAstar.Suite); end.
unit AST.Targets; interface uses SysUtils; type TNPLAbstractTarget = class abstract public class function TargetName: string; virtual; abstract; class function PointerSize: Integer; virtual; abstract; class function NativeIntSize: Integer; virtual; abstract; end; TNPLTarget = class of TNPLAbstractTarget; TANY_Target = class(TNPLAbstractTarget) public class function TargetName: string; override; class function PointerSize: Integer; override; class function NativeIntSize: Integer; override; end; TWINX86_Target = class(TNPLAbstractTarget) public class function TargetName: string; override; class function PointerSize: Integer; override; class function NativeIntSize: Integer; override; end; TWINX64_Target = class(TNPLAbstractTarget) public class function TargetName: string; override; class function PointerSize: Integer; override; class function NativeIntSize: Integer; override; end; function FindTarget(const Name: string): TNPLTarget; implementation var RegisteredTargets: array of TNPLTarget; function FindTarget(const Name: string): TNPLTarget; var Target: TNPLTarget; UpperName: string; begin UpperName := UpperCase(Name); for Target in RegisteredTargets do if Target.TargetName = UpperName then Exit(Target); Result := nil; end; procedure RegisterTarget(const TargetClass: TNPLTarget); begin RegisteredTargets := RegisteredTargets + [TargetClass]; end; { TANY_Target } class function TANY_Target.TargetName: string; begin Result := 'ANY'; end; class function TANY_Target.PointerSize: Integer; begin Result := -1; end; class function TANY_Target.NativeIntSize: Integer; begin Result := -1; end; { TWINX86_Target } class function TWINX86_Target.TargetName: string; begin Result := 'WIN-X86'; end; class function TWINX86_Target.PointerSize: Integer; begin Result := 4; end; class function TWINX86_Target.NativeIntSize: Integer; begin Result := 4; end; { TWINX64_Target } class function TWINX64_Target.TargetName: string; begin Result := 'WIN-X64'; end; class function TWINX64_Target.PointerSize: Integer; begin Result := 8; end; class function TWINX64_Target.NativeIntSize: Integer; begin Result := 8; end; initialization RegisterTarget(TANY_Target); RegisterTarget(TWINX86_Target); RegisterTarget(TWINX64_Target); end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit ApplyForce; interface uses Test, Box2D.Dynamics; type TApplyForce = class(TTest) protected m_body: b2BodyWrapper; public constructor Create; class function CreateTest: TTest; static; procedure Keyboard(key: Integer); override; end; implementation uses System.Math, Box2D.Common, Box2D.Collision, DebugDraw; { TApplyForce } constructor TApplyForce.Create; const k_restitution = 0.4; gravity = 10.0; var I: Integer; ground, body: b2BodyWrapper; bd: b2BodyDef; shape: b2EdgeShapeWrapper; shape2: b2PolygonShapeWrapper; sd, sd1, sd2: b2FixtureDef; fd: b2FixtureDef; xf1, xf2: b2Transform; vertices: array [0..2] of b2Vec2; poly1, poly2: b2PolygonShapeWrapper; inertia, mass, radius: Float32; jd: b2FrictionJointDef; begin inherited; m_world.SetGravity(b2Vec2.Create(0.0, 0.0)); bd := b2BodyDef.Create; bd.position.&Set(0.0, 20.0); ground := m_world.CreateBody(@bd); shape := b2EdgeShapeWrapper.Create; sd := b2FixtureDef.Create; sd.shape := shape; sd.density := 0.0; sd.restitution := k_restitution; // Left vertical shape.&Set(b2Vec2.Create(-20.0, -20.0), b2Vec2.Create(-20.0, 20.0)); ground.CreateFixture(@sd); // Right vertical shape.&Set(b2Vec2.Create(20.0, -20.0), b2Vec2.Create(20.0, 20.0)); ground.CreateFixture(@sd); // Top horizontal shape.&Set(b2Vec2.Create(-20.0, 20.0), b2Vec2.Create(20.0, 20.0)); ground.CreateFixture(@sd); // Bottom horizontal shape.&Set(b2Vec2.Create(-20.0, -20.0), b2Vec2.Create(20.0, -20.0)); ground.CreateFixture(@sd); xf1 := b2Transform.Create; xf1.q.&Set(0.3524 * Pi); xf1.p := xf1.q.GetXAxis; vertices[0] := b2Mul(xf1, b2Vec2.Create(-1.0, 0.0)); vertices[1] := b2Mul(xf1, b2Vec2.Create(1.0, 0.0)); vertices[2] := b2Mul(xf1, b2Vec2.Create(0.0, 0.5)); poly1 := b2PolygonShapeWrapper.Create; poly1.&Set(@vertices[0], 3); sd1 := b2FixtureDef.Create; sd1.shape := poly1; sd1.density := 4.0; xf2 := b2Transform.Create; xf2.q.&Set(-0.3524 * Pi); xf2.p := -xf2.q.GetXAxis; vertices[0] := b2Mul(xf2, b2Vec2.Create(-1.0, 0.0)); vertices[1] := b2Mul(xf2, b2Vec2.Create(1.0, 0.0)); vertices[2] := b2Mul(xf2, b2Vec2.Create(0.0, 0.5)); poly2 := b2PolygonShapeWrapper.Create; poly2.&Set(@vertices[0], 3); sd2 := b2FixtureDef.Create; sd2.shape := poly2; sd2.density := 2.0; bd := b2BodyDef.Create; bd.&type := b2_dynamicBody; bd.angularDamping := 2.0; bd.linearDamping := 0.5; bd.position.&Set(0.0, 2.0); bd.angle := pi; bd.allowSleep := false; m_body := m_world.CreateBody(@bd); m_body.CreateFixture(@sd1); m_body.CreateFixture(@sd2); shape2 := b2PolygonShapeWrapper.Create; shape2.SetAsBox(0.5, 0.5); fd := b2FixtureDef.Create; fd.shape := shape2; fd.density := 1.0; fd.friction := 0.3; for I := 0 to 10 - 1 do begin bd := b2BodyDef.Create; bd.&type := b2_dynamicBody; bd.position.&Set(0.0, 5.0 + 1.54 * I); body := m_world.CreateBody(@bd); body.CreateFixture(@fd); inertia := body.GetInertia; mass := body.GetMass; // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m) radius := sqrt(2.0 * I / mass); jd := b2FrictionJointDef.Create; jd.localAnchorA.SetZero; jd.localAnchorB.SetZero; jd.bodyA := ground; jd.bodyB := body; jd.collideConnected := true; jd.maxForce := mass * gravity; jd.maxTorque := mass * radius * gravity; m_world.CreateJoint(@jd); end; shape.Destroy; poly1.Destroy; poly2.Destroy; shape2.Destroy; end; class function TApplyForce.CreateTest: TTest; begin Result := TApplyForce.Create; end; procedure TApplyForce.Keyboard(key: Integer); var f, p: b2Vec2; begin case key of Ord('W'), Ord('w'): begin f := m_body.GetWorldVector(b2Vec2.Create(0.0, -200.0)); p := m_body.GetWorldPoint(b2Vec2.Create(0.0, 2.0)); m_body.ApplyForce(f, p, true); end; Ord('A'), Ord('a'): m_body.ApplyTorque(50.0, true); Ord('D'), Ord('d'): m_body.ApplyTorque(-50.0, true); end; end; initialization RegisterTest(TestEntry.Create('ApplyForce', @TApplyForce.CreateTest)); end.
PROGRAM Prim; FUNCTION IsPrime(number: INTEGER): BOOLEAN; VAR counter: INTEGER; BEGIN IF number = 2 THEN {* Schritt 1 *} IsPrime := true ELSE IF (number mod 2 = 0) OR (number <= 1) THEN {* Schritt 2 *} IsPrime := false ELSE BEGIN {* Schritt 3 *} IsPrime := true; counter := 3; WHILE counter <= number-1 DO BEGIN {* Schritt 4 *} IF number mod counter = 0 THEN BEGIN IsPrime := false; END; counter := counter + 2 END END END; PROCEDURE DisplayPrimeNumbers(n: INTEGER); VAR counter: INTEGER; BEGIN FOR counter := 0 TO n DO IF (IsPrime(counter)) THEN Write(counter, ' '); WriteLn() END; PROCEDURE AssertIsPrime(n: INTEGER; expectedResult: BOOLEAN); BEGIN IF IsPrime(n) = expectedResult THEN WriteLn('IsPrime(', n ,') should return value: ' , expectedResult , ' --> OK') ELSE WriteLn('IsPrime(', n ,') should return value: ' , expectedResult , ' --> X') END; BEGIN DisplayPrimeNumbers(20); AssertIsPrime(0, false); AssertIsPrime(1, false); AssertIsPrime(2, true); AssertIsPrime(3, true); AssertIsPrime(19, true); AssertIsPrime(20, false); AssertIsPrime(-32787, true); {* Grenzfall 1 *} AssertIsPrime(32771, false); {* Grenzfall 2 *} END.
unit ScrolBox; { Bombela 20/06/2004 20/06/2004 Petite ScrollBox limitÚe Ó 255 strings. Le pointer DATA de la TStringList (Strings) est la couleur du texte. } interface uses CRT, TextList; type TScrollBox = object private FCursorX, FCursorY: byte; TopLine: byte; MargeBotom, MargeWidth: byte; LeftLine, LargeLine: byte; SauvCursorVisible, CursorVisible: boolean; procedure SaveContext; procedure RestoreContext; procedure PaintLigne(Index: byte; Num: byte); procedure PaintLigneSelect(Selected: byte); public Top, Left, Heigth, Width: byte; BorderColor: byte; ScrollColor: byte; ScrollButtonColor: byte; SelectedColor: byte; Strings: TStringList; constructor Init; destructor Free; procedure Paint(Delete: boolean); procedure SetCursorBotom; function Select(var Selected: byte): boolean; end; implementation constructor TscrollBox.Init; begin Top := 10; Left := 10; Heigth := 10; Width := 50; BorderColor := white; TopLine := 0; MargeBotom := 0; MargeWidth := 0; ScrollColor := 13; ScrollButtonColor := 14; SelectedColor := 7; LeftLine := 0; LargeLine := 0; CursorVisible := true; Strings.Init; end; destructor TscrollBox.Free; begin Strings.Free; end; procedure TscrollBox.SaveContext; begin FCursorX := WhereX; FCursorY := WhereY; end; procedure TscrollBox.RestoreContext; begin GotoXY(FCursorX, FCursorY); NormVideo; end; procedure TscrollBox.Paint(Delete: boolean); var b,b2, b3: byte; Text: string; begin SaveContext; if Delete then TextColor(Black) else TextColor(BorderColor); GotoXY(Left, Top); write('┌'); for b := 1 to Width-2 do write('─'); writeln('┐'); for b := 1 to Heigth-2 do begin GotoXY(Left, WhereY); write('│'); for b2 := 1 to Width-2 do write(' '); writeln('│'); end; GotoXY(Left, WhereY); write('└'); for b := 1 to Width-2 do write('─'); writeln('┘'); If (Strings.count > 0) and (not Delete) then begin if TopLine >= Strings.count then TopLine := 0; b3 := (TopLine+Heigth-2-MargeBotom); if b3 > Strings.count then b3 := Strings.count; if Strings.count > Heigth-2 then MargeWidth := 1 else MargeWidth := 0; LargeLine := 0; for b := TopLine to b3-1 do begin Strings.GetText(b,Text); if length(Text) > LargeLine then LargeLine := length(Text); end; if LeftLine+Width-2-MargeWidth > LargeLine then LeftLine := LargeLine-Width+2+MargeWidth; if LargeLine > Width-2-MargeWidth then begin textcolor(ScrollColor); GotoXY(Left+1,Top+Heigth-2); for b := 1 to Width-2-MargeWidth do write('░'); GotoXY(Left+1+trunc((LeftLine / ((LargeLine-(Width-2-MargeWidth)) / (Width-3-MargeWidth)))),Top+Heigth-2); textcolor(ScrollButtonColor); write('█'); MargeBotom := 1; end else begin MargeBotom := 0; LargeLine := 0; LeftLine := 0; end; b3 := (TopLine+Heigth-2-MargeBotom); if b3 > Strings.count then b3 := Strings.count; If Strings.count > Heigth-2 then begin textcolor(ScrollColor); for b := Top+1 to Top+Heigth-2-MargeBotom do begin GotoXY(Left+Width-2,b); write('░'); end; GotoXY(Left+Width-2,Top+1+trunc((TopLine / ((Strings.count-(Heigth-2-MargeBotom)) / (Heigth-3-MargeBotom)) ))); textcolor(ScrollButtonColor); write('█'); end; b2 := 0; for b := TopLine+1 to b3 do begin inc(b2); PaintLigne(b-1, b2); end; end; RestoreContext; end; procedure TscrollBox.PaintLigne(Index: byte; Num: byte); var Txt: string; Color, i,i2: byte; Selectable: boolean; begin GotoXY(Left+1,Top+Num); Strings.Get(Index,Txt,Color,Selectable); TextColor(byte(Color)); i2 := LeftLine+(Width-2)-MargeWidth; if i2 > length(Txt) then i2 := length(Txt); for i := LeftLine+1 to i2 do write(Txt[i]); end; procedure TscrollBox.PaintLigneSelect(Selected: byte); var Txt: string; Color: pointer; begin if strings.count > 0 then begin SaveContext; TextBackGround(SelectedColor); PaintLigne(Selected,Selected+1-TopLine); RestoreContext; end; end; function TscrollBox.Select(var Selected: byte): boolean; const Key_Echap = #27; Key_Up = #72; Key_Down = #80; Key_Left = #75; Key_Width = #77; Key_Enter = #13; var Key: char; Selectable: boolean; begin {ShowCursor(false);} Select := false; Selected := 0; Paint(False); PaintLigneSelect(Selected); repeat Key := ReadKey; If Key = #0 then begin Key := ReadKey; case Key of Key_Up: begin if Selected > 0 then begin dec(Selected); if Selected < TopLine then begin dec(TopLine); end; Paint(False); PaintLigneSelect(Selected); end; end; Key_Down: begin if Selected < Strings.count-1 then begin inc(Selected); if Selected-TopLine > Heigth-3-MargeBotom then begin inc(TopLine); end; Paint(False); PaintLigneSelect(Selected); end; end; Key_Left: begin if LeftLine > 0 then begin dec(LeftLine); Paint(False); PaintLigneSelect(Selected); end; end; Key_Width:begin if LeftLine+Width-MargeWidth-2 < LargeLine then begin inc(LeftLine); Paint(False); PaintLigneSelect(Selected); end; end; end; end else if (key = Key_Enter) and (strings.count > 0) then begin Strings.GetSelectable(Selected,Selectable); if Selectable then begin Key := Key_Echap; Select := true; end; end; until Key = Key_Echap; {ShowCursor(true);} end; procedure TscrollBox.SetCursorBotom; begin GotoXY(1, Top+Heigth); end; end.
unit EQDBxlExport; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, db, Variants, comobj, Clipbrd, DDEMan, DDEML, Math, TypInfo, Grids, DBGrids; const CaptionSize = 1; type TXlsManagerKind = (xmkUnknown, xmkExel, xmkOpenOffice); TExporter = class; TExportEvent = procedure(Exporter: TExporter) of object; TEQDBxlExport = class(TComponent) private FCustomFit: boolean; FDBGrid: TDbGrid; FDataSet: TDataSet; FSheetName: string; FRowOffset: Integer; FColOffset: Integer; FOnBeforeExport: TExportEvent; FOnAfterExport: TExportEvent; procedure InitSettings; procedure DoBeforeExport(Exporter: TExporter); virtual; procedure DoAfterExport(Exporter: TExporter); virtual; public procedure StartExport; published property CustomFit: Boolean read FCustomFit write FCustomFit; property DBGrid: TDBGrid read FDBGrid write FDBGrid; property DataSet: TDataSet read FDataSet write FDataSet; property SheetName: string read FSheetName write FSheetName; property ColOffset: Integer read FColOffset write FColOffset; property RowOffset: Integer read FRowOffset write FRowOffset; property OnAfterExport: TExportEvent read FOnAfterExport write FOnAfterExport; property OnBeforeExport: TExportEvent read FOnBeforeExport write FOnBeforeExport; end; TExporter = class(TObject) private FFieldList: TStringList; FEQDBxlExport: TEQDBxlExport; procedure PrepareFieldsFromDataSet; procedure PrepareFieldsFromGrid; procedure AddField(Field: TField; Caption: string = ''); procedure SaveFieldCaptions; protected FCurrentExportedRecord: integer; FOleExporter: Variant; procedure PrepareOleExporter; virtual; abstract; procedure SaveCurrentRecord; virtual; abstract; procedure CommitData; virtual; abstract; procedure AddFieldCaption(FieldCaption: string); virtual; abstract; procedure FormatStringColumn(ColumnIdx: integer); virtual; procedure BeforeExecute; virtual; procedure PrepareFields; virtual; function DataRange: TRect; public class function CreateExporter: TExporter; constructor Create(OleExporter: Variant); destructor Destroy; override; procedure Execute(EQDBxlExport: TEQDBxlExport); end; TExelExporter = class(TExporter) private FExportData: string; FSheet: Variant; FFieldCaptions: string; function CurrentRecordToString: string; procedure AppendValue(var SourceStr: string; const AdditionStr: string); protected procedure PrepareOleExporter; override; procedure SaveCurrentRecord; override; procedure CommitData; override; procedure FormatStringColumn(ColumnIdx: integer); override; procedure AddFieldCaption(FieldCaption: string); override; procedure PrepareFields; override; public destructor Destroy; override; end; TOpenOfficeExporter = class(TExporter) private FDesktop: Variant; FDocument: Variant; FSheet: Variant; FRange: Variant; FFieldIdx: integer; // used as an external variable for AddFieldCaption function PointToRange(x, y: integer): string; protected procedure PrepareOleExporter; override; procedure SaveCurrentRecord; override; procedure CommitData; override; procedure BeforeExecute; override; procedure AddFieldCaption(FieldCaption: string); override; end; TxlDdeClient = class(TDDEClientConv) public function xlPokeData(const Item: string; Data: PChar): Boolean; end; procedure CreateOleXlsManager(out XlsManager: Variant; out XlsManagerKind: TXlsManagerKind); function xlColl(x: Integer): string; function xlCell(x, y: Integer): string; const //from excel2000; xlR1C1 = $FFFFEFCA; xlContinuous = 1; implementation procedure CreateOleXlsManager(out XlsManager: Variant; out XlsManagerKind: TXlsManagerKind); var FirstAttempt: boolean; begin XlsManager := varNull; XlsManagerKind := xmkUnknown; FirstAttempt := True; while True do begin try if FirstAttempt then begin XlsManager := CreateOleObject('Excel.Application'); XlsManagerKind := xmkExel; end else begin XlsManager := CreateOleObject('com.sun.star.ServiceManager'); XlsManagerKind := xmkOpenOffice; end; Break; except on e: EOleSysError do begin if e.ErrorCode = -2147221005 then // Инициализация провалилась begin if FirstAttempt then FirstAttempt := False else begin MessageDlg('Ни Exel ни OpenOffice не найдены.', mtInformation, [mbOK], 0); Exit; // ни экселя ни ОпенОфиcа не найдено - тихо выйти end; end else raise; end; end; end; end; { TxlDDEClient } function TxlDdeClient.xlPokeData(const Item: string; Data: PChar): Boolean; var hszDat: HDDEData; hdata: HDDEData; hszItem: HSZ; begin Result := False; if (Conv = 0) or WaitStat then Exit; hszItem := DdeCreateStringHandle(ddeMgr.DdeInstId, PChar(Item), CP_WINANSI); if hszItem = 0 then Exit; hszDat := DdeCreateDataHandle(ddeMgr.DdeInstId, Data, StrLen(Data) + 1, 0, hszItem, CF_TEXT, 0); if hszDat <> 0 then begin hdata := DdeClientTransaction(Pointer(hszDat), DWORD(-1), Conv, hszItem, CF_TEXT, XTYP_POKE, 10000, nil); Result := hdata <> 0; end; DdeFreeStringHandle(ddeMgr.DdeInstId, hszItem); end; function xlColl(x: Integer): string; begin Result := ''; while x > 0 do begin Dec(x); Result := Chr(Ord('A') + x mod 24) + result; x := x div 24; end; if Result = '' then Result := 'A'; end; function xlCell(x, y: Integer): string; begin Result := xlColl(x) + IntToStr(y); end; procedure TEQDBxlExport.DoBeforeExport(Exporter: TExporter); begin if Assigned(FOnBeforeExport) then FOnBeforeExport(Exporter); end; procedure TEQDBxlExport.DoAfterExport(Exporter: TExporter); begin if Assigned(FOnAfterExport) then FOnAfterExport(Exporter); end; procedure TEQDBxlExport.InitSettings; begin if not Assigned(DataSet) then raise Exception.Create('DBxlExport requires dataset.'); if not DataSet.Active then raise Exception.Create('Dataset for this component must bee active.'); if Trim(SheetName) = '' then SheetName := 'Лист 1'; end; procedure TEQDBxlExport.StartExport; var Exporter: TExporter; OldCursor: TCursor; begin InitSettings; Exporter := TExporter.CreateExporter; if not Assigned(Exporter) then Exit; OldCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try DoBeforeExport(Exporter); Exporter.Execute(Self); finally DoAfterExport(Exporter); Screen.Cursor := OldCursor; Exporter.Free; end; end; { TExporter } procedure TExporter.AddField(Field: TField; Caption: string); var FieldCaption: string; begin if Caption <> '' then FieldCaption := Caption else if Field.DisplayLabel <> '' then FieldCaption := Field.DisplayLabel else FieldCaption := Field.FieldName; FFieldList.AddObject(FieldCaption, Field); end; procedure TExporter.BeforeExecute; begin PrepareOleExporter; PrepareFields; FEQDBxlExport.DataSet.DisableControls; FEQDBxlExport.DataSet.First; end; constructor TExporter.Create(OleExporter: Variant); begin inherited Create(); FOleExporter := OleExporter; FFieldList := TStringList.Create; end; class function TExporter.CreateExporter: TExporter; var OleExporter: Variant; ManagerKind: TXlsManagerKind; begin Result := nil; // make the compiler happy CreateOleXlsManager(OleExporter, ManagerKind); case ManagerKind of xmkExel: Result := TExelExporter.Create(OleExporter); xmkOpenOffice: Result := TOpenOfficeExporter.Create(OleExporter); else Assert(False, 'CreateOleXlsManager returned unknown ManagerKind: ' + GetEnumName(TypeInfo(TXlsManagerKind), Integer(ManagerKind))); end; end; function TExporter.DataRange: TRect; begin Result.Left := 1 + FEQDBxlExport.ColOffset; Result.Top := 1 + FEQDBxlExport.RowOffset; Result.Right := FFieldList.Count + FEQDBxlExport.ColOffset; Result.Bottom := FEQDBxlExport.DataSet.RecordCount + CaptionSize + FEQDBxlExport.RowOffset; end; destructor TExporter.Destroy; begin FFieldList.Free; inherited; end; procedure TExporter.Execute(EQDBxlExport: TEQDBxlExport); var TmpBookmark: TBookmark; begin FEQDBxlExport := EQDBxlExport; FCurrentExportedRecord := 1; TmpBookmark := FEQDBxlExport.DataSet.GetBookmark; BeforeExecute; SaveFieldCaptions; try while not FEQDBxlExport.DataSet.Eof do begin // reformat record fields in csv SaveCurrentRecord; Inc(FCurrentExportedRecord); FEQDBxlExport.DataSet.Next; end; CommitData; finally FEQDBxlExport.DataSet.GotoBookmark(TmpBookmark); FEQDBxlExport.DataSet.FreeBookmark(TmpBookmark); FEQDBxlExport.DataSet.EnableControls; end; end; procedure TExporter.FormatStringColumn(ColumnIdx: integer); begin // do nothing here end; procedure TExporter.PrepareFields; begin if Assigned(FEQDBxlExport.DBGrid) then PrepareFieldsFromGrid else PrepareFieldsFromDataSet; end; procedure TExporter.PrepareFieldsFromDataSet; var i, CurrentExportFieldIdx: integer; begin CurrentExportFieldIdx := 0; for i := 0 to Pred(FEQDBxlExport.DataSet.Fields.Count) do if FEQDBxlExport.DataSet.Fields[i].Visible then begin AddField(FEQDBxlExport.DataSet.Fields[i]); {исправление конверсии '1/5' в '1 января' другие типы не обрабатываем что бы не превращать RecNo в '123.12'} if FEQDBxlExport.DataSet.Fields[CurrentExportFieldIdx].DataType = ftString then FormatStringColumn(CurrentExportFieldIdx + 1); Inc(CurrentExportFieldIdx); end; end; procedure TExporter.PrepareFieldsFromGrid; var i, j: integer; begin for i := 0 to FEQDBxlExport.DBGrid.Columns.Count - 1 do begin if FEQDBxlExport.DBGrid.Columns[i].Visible then AddField(FEQDBxlExport.DBGrid.Columns[i].Field, FEQDBxlExport.DBGrid.Columns[i].Title.Caption); end; end; procedure TExporter.SaveFieldCaptions; var i: integer; begin for i := 0 to FFieldList.Count - 1 do AddFieldCaption(FFieldList[i]); end; { TExelExporter } procedure TExelExporter.AddFieldCaption(FieldCaption: string); begin AppendValue(FFieldCaptions, FieldCaption); end; procedure TExelExporter.AppendValue(var SourceStr: string; const AdditionStr: string); begin SourceStr := SourceStr + AdditionStr + #9; end; procedure TExelExporter.CommitData; var IRange: OLEVariant; i: integer; begin FFieldCaptions := FFieldCaptions + #10; IRange := FOleExporter.Range[ xlCell(DataRange.Left, DataRange.Top), xlCell(DataRange.Right, DataRange.Bottom)]; with TxlDdeClient.Create(FEQDBxlExport) do try if SetLink('EXCEL', FOleExporter.ActiveSheet.Name) then xlPokeData(IRange.Address[ReferenceStyle := xlR1C1], PChar(FFieldCaptions + FExportData)); finally Free; end; // free dinamicly allocated memory FExportData := ''; FOleExporter.Range[ xlCell(DataRange.Left, DataRange.Top), xlCell(DataRange.Right, DataRange.Top + CaptionSize - 1)].Select; FOleExporter.Selection.Interior.ColorIndex := 15; FOleExporter.Selection.Borders.LineStyle := xlContinuous; for i := 1 to FFieldList.Count do if not FEQDBxlExport.CustomFit then FOleExporter.Columns[xlColl(i)].AutoFit; end; function TExelExporter.CurrentRecordToString: string; var i: integer; CurrentFieldValue: string; begin Result := ''; for i := 0 to Pred(FFieldList.Count) do begin CurrentFieldValue := StringReplace(TField(FFieldList.Objects[i]).AsString, '"', '""', [rfReplaceAll]); CurrentFieldValue := StringReplace(CurrentFieldValue, #13#10, ' ', [rfReplaceAll]); if (CurrentFieldValue = '') or (CurrentFieldValue[1] = '=') then CurrentFieldValue := '"' + CurrentFieldValue + '"'#9 else CurrentFieldValue := CurrentFieldValue + #9; Result := Result + CurrentFieldValue; end; Result := Result + #10; end; destructor TExelExporter.Destroy; begin FOleExporter.Range['A1'].Select; FOleExporter.Visible := True; inherited; end; procedure TExelExporter.FormatStringColumn(ColumnIdx: integer); begin FOleExporter.Columns[xlColl(ColumnIdx)].NumberFormat := '@'; end; procedure TExelExporter.PrepareFields; begin FFieldCaptions := ''; inherited; end; procedure TExelExporter.PrepareOleExporter; begin FOleExporter.Visible := False; FOleExporter.Workbooks.Add(1); FOleExporter.ActiveSheet.Name := FEQDBxlExport.SheetName; FSheet := FOleExporter.ActiveSheet; end; procedure TExelExporter.SaveCurrentRecord; begin FExportData := FExportData + CurrentRecordToString; end; { TOpenOfficeExporter } procedure TOpenOfficeExporter.AddFieldCaption(FieldCaption: string); begin FRange[FFieldIdx, 1] := FieldCaption; inc(FFieldIdx); end; procedure TOpenOfficeExporter.BeforeExecute; begin FFieldIdx := 1; FEQDBxlExport.DataSet.Last; // make all records fetched inherited; FRange := VarArrayCreate([1, FFieldList.Count, 1, FEQDBxlExport.DataSet.RecordCount + CaptionSize], varVariant); end; procedure TOpenOfficeExporter.CommitData; var i: integer; Cell: Variant; begin FSheet.GetCellRangeByName( PointToRange(DataRange.Left, DataRange.Top) + ':' + PointToRange(DataRange.Right, DataRange.Bottom) ).SetDataArray(FRange); for i := 1 to FFieldList.Count do begin Cell := FSheet.getCellByPosition(i - 1, 0); Cell.getColumns.getByIndex(0).OptimalWidth := True; Cell.CellBackColor := TColor($D0D0D0); end; end; function TOpenOfficeExporter.PointToRange(x, y: integer): string; const Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var s1, s2: string; k: integer; begin repeat k := x mod 27; s1 := Letters[k] + s1; k := x div 26; until k <= x; s2 := IntToStr(y); Result := s1 + s2 end; procedure TOpenOfficeExporter.PrepareOleExporter; begin FDesktop := FOleExporter.createInstance('com.sun.star.frame.Desktop'); FDocument := FDesktop.LoadComponentFromURL('private:factory/scalc', '_blank', 0, VarArrayCreate([0, - 1], varVariant)); FSheet := FDocument.GetSheets.getByIndex(0); end; procedure TOpenOfficeExporter.SaveCurrentRecord; var i: integer; Value: Variant; Field: TField; begin for i := 0 to FFieldList.Count - 1 do begin Field := TField(FFieldList.Objects[i]); Value := Field.Value; if VarIsNull(Value) or VarIsEmpty(Value) then Value := '' else if Field.DataType = ftDate then Value := DateToStr(Value) else if Field.DataType = ftDateTime then Value := DateTimeToStr(Value); FRange[i + 1, FCurrentExportedRecord + CaptionSize] := Value; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) MaleLabel: TLabel; FemaleLabel: TLabel; NeutralLabel: TLabel; MaleInfo: TLabel; FemaleInfo: TLabel; NeutralInfo: TLabel; LanguageButton: TButton; procedure FormCreate(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateValues; end; var Form1: TForm1; implementation {$R *.dfm} uses NtPattern, NtLanguageDlg; procedure TForm1.UpdateValues; resourcestring // Contains two patterns: male and female. SMessageGender = '{gender, male {%s will bring his bicycle} female {%s will bring her bicycle}}'; //loc 0: Name of a person // Contains three patterns: neutral, male and female. SOtherMessageGender = '{gender, male {%s will bring his bicycle} female {%s will bring her bicycle} other {%s will bring a bicycle}}'; //loc 0: Name of a person procedure Process(gender: TGender; const name: String; messageLabel, infoLabel: TLabel); var actualGender: TGender; begin // Update message label messageLabel.Caption := TMultiPattern.Format(SOtherMessageGender, gender, [name]); // Update info label actualGender := TMultiPattern.GetGender(SOtherMessageGender, gender); if actualGender <> gender then infoLabel.Font.Style := [fsBold] else infoLabel.Font.Style := []; infoLabel.Caption := TMultiPattern.GetGenderName(actualGender); end; begin Process(geMale, 'John', MaleLabel, MaleInfo); Process(geFemale, 'Jill', FemaleLabel, FemaleInfo); Process(geNeutral, 'Amazon', NeutralLabel, NeutralInfo); end; procedure TForm1.FormCreate(Sender: TObject); begin UpdateValues; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin if TNtLanguageDialog.Select then UpdateValues; end; end.
unit Config; interface uses Winapi.Windows, Registry, SysUtils; type TConfig = class(TObject) usi : string; storeImages : boolean; launchRustOnStartup : boolean; launchRustOnStartupAndConnectToServer : boolean; rustServerAddress : string; closeStashPicOnRustClose : boolean; serverAddress : string; scale : real; hotkeyCaptureFullscreen : string; hotkeyCaptureFullscreenCode : string; hotkeyCaptureRectangleCenter : string; hotkeyCaptureRectangleCenterCode : string; hotkeyCaptureStashArea : string; hotkeyCaptureStashAreaCode : string; hotkeyCaptureFullscreenMapPart : string; hotkeyCaptureFullscreenMapPartCode : string; picsFolder : string; automaticUpdate : boolean; updateToken : string; tab : string; formTop : integer; formLeft : integer; const key = 'Software\StashPic\'; picsFolderDefault = '\pics'; procedure load(); procedure save(); procedure init(baseDir : string); function newUsi():string; end; implementation procedure TConfig.load(); var reg : TRegistry; begin reg := TRegistry.Create(KEY_READ); reg.OpenKey(key, False); usi := reg.ReadString('usi'); storeImages := reg.ReadBool('storeImages'); picsFolder := reg.ReadString('picsFolder'); launchRustOnStartup := reg.ReadBool('launchRustOnStartup'); launchRustOnStartupAndConnectToServer := reg.ReadBool('launchRustOnStartupAndConnectToServer'); rustServerAddress := reg.ReadString('rustServer'); closeStashPicOnRustClose := reg.ReadBool('closeStashPicOnRustClose'); serverAddress := reg.ReadString('serverAddress'); scale := reg.ReadFloat('scale'); hotkeyCaptureFullscreen := reg.ReadString('hotkeyCaptureFullscreen'); hotkeyCaptureFullscreenCode := reg.ReadString('hotkeyCaptureFullscreenCode'); hotkeyCaptureRectangleCenter := reg.ReadString('hotkeyCaptureRectangleCenter'); hotkeyCaptureRectangleCenterCode := reg.ReadString('hotkeyCaptureRectangleCenterCode'); hotkeyCaptureStashArea := reg.ReadString('hotkeyCaptureStashArea'); hotkeyCaptureStashAreaCode := reg.ReadString('hotkeyCaptureStashAreaCode'); hotkeyCaptureFullscreenMapPart := reg.ReadString('hotkeyCaptureFullscreenMapPart'); hotkeyCaptureFullscreenMapPartCode := reg.ReadString('hotkeyCaptureFullscreenMapPartCode'); automaticUpdate := reg.ReadBool('automaticUpdate'); updateToken := reg.ReadString('updateToken'); tab := reg.ReadString('tab'); formLeft := reg.ReadInteger('formLeft'); formTop := reg.ReadInteger('formTop'); reg.CloseKey(); reg.Free; end; procedure TConfig.save(); var reg : TRegistry; begin reg := TRegistry.Create(KEY_WRITE); reg.OpenKey(key, False); reg.WriteString('usi', usi); reg.WriteBool('storeImages', storeImages); reg.WriteString('picsFolder', picsFolder); reg.WriteBool('launchRustOnStartup', launchRustOnStartup); reg.WriteBool('launchRustOnStartupAndConnectToServer', launchRustOnStartupAndConnectToServer); reg.WriteString('rustServer', rustServerAddress); reg.WriteBool('closeStashPicOnRustClose', closeStashPicOnRustClose); reg.WriteString('serverAddress', serverAddress); reg.WriteFloat('scale', scale); reg.WriteString('hotkeyCaptureFullscreen', hotkeyCaptureFullscreen); reg.WriteString('hotkeyCaptureFullscreenCode', hotkeyCaptureFullscreenCode); reg.WriteString('hotkeyCaptureRectangleCenter', hotkeyCaptureRectangleCenter); reg.WriteString('hotkeyCaptureRectangleCenterCode', hotkeyCaptureRectangleCenterCode); reg.WriteString('hotkeyCaptureStashArea', hotkeyCaptureStashArea); reg.WriteString('hotkeyCaptureStashAreaCode', hotkeyCaptureStashAreaCode); reg.WriteString('hotkeyCaptureFullscreenMapPart', hotkeyCaptureFullscreenMapPart); reg.WriteString('hotkeyCaptureFullscreenMapPartCode', hotkeyCaptureFullscreenMapPartCode); reg.WriteBool('automaticUpdate', automaticUpdate); reg.WriteString('updateToken', updateToken); reg.WriteString('tab', tab); reg.WriteInteger ('formLeft', formLeft); reg.WriteInteger('formTop', formTop); reg.CloseKey(); reg.Free; end; procedure TConfig.init(baseDir : string); var reg : TRegistry; begin reg := TRegistry.Create(KEY_READ); if (reg.KeyExists(key)) then exit; reg.Access := KEY_WRITE; if (not reg.OpenKey(key,True)) then halt; usi := newUsi(); storeImages := true; picsFolder := baseDir + picsFolderDefault; launchRustOnStartup := false; launchRustOnStartupAndConnectToServer := false; rustServerAddress := ''; closeStashPicOnRustClose := false; serverAddress := 'http://stashmap.net/map/add/picLoad'; scale := 1; hotkeyCaptureFullscreen := 'Alt + 1'; hotkeyCaptureFullscreenCode := '010049'; hotkeyCaptureRectangleCenter := 'Alt + 2'; hotkeyCaptureRectangleCenterCode := '010050'; hotkeyCaptureStashArea := 'Alt + 3'; hotkeyCaptureStashAreaCode := '010051'; hotkeyCaptureFullscreenMapPart := 'Alt + 4'; hotkeyCaptureFullscreenMapPartCode := '010052'; automaticUpdate := true; updateToken := ''; formLeft := 300; formTop := 200; tab := 'settings'; save(); end; function TConfig.newUsi():string; var usi, chars : string; i : integer; begin chars := '0123456789abcde0123456789fghijklm0123456789nopqrst0123456789uvwxyz0123456789'; randomize; usi := ''; for i := 1 to 15 do usi := usi + chars[Random(length(chars))+1]; Result := usi; end; end.
{******************************************************************************* * uFControl * * * * Библиотека компонентов для работы с формой редактирования (qFControls) * * Базовый класс (TqFControl) * * Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit uFControl; interface uses Controls, Graphics, Classes, DB, Registry; type TqFControl = class(TWinControl) private FFieldName: String; FDisplayName: String; FInterval: Integer; FLabelColor: TColor; FRequired: Boolean; FSemicolon: Boolean; FAsterisk: Boolean; FEnabled: Boolean; FDefault: Variant; FBlocked: Boolean; FAutoSaveToRegistry : Boolean; // vallkor protected FOnChange: TNotifyEvent; FOldColor: TColor; procedure SetDisplayName(Name: String); virtual; procedure SetInterval(Int: Integer); virtual; procedure SetLabelColor(Color: TColor); virtual; procedure SetSemicolon(Val: Boolean); virtual; procedure SetAsterisk(Val: Boolean); virtual; procedure SetRequired(Val: Boolean); virtual; procedure SetValue(Val: Variant); virtual; function GetValue: Variant; virtual; procedure Loaded; override; procedure SetFieldName(FieldName: String); virtual; public constructor Create(AOwner: TComponent); override; function Check: String; virtual; procedure Highlight(HighlightOn: Boolean); virtual; procedure ShowFocus; virtual; function ToString: String; virtual; procedure Block(Flag: Boolean); virtual; procedure Clear; virtual; procedure Load(DataSet: TDataSet); virtual; procedure LoadFromRegistry(reg: TRegistry); virtual; procedure SaveIntoRegistry(reg: TRegistry); virtual; published property FieldName: String read FFieldName write SetFieldName; property DisplayName: String read FDisplayName write SetDisplayName; property Interval: Integer read FInterval write SetInterval; property Value: Variant read GetValue write SetValue; property LabelColor: TColor read FLabelColor write SetLabelColor; property Required: Boolean read FRequired write SetRequired; property Semicolon: Boolean read FSemicolon write SetSemicolon; property Asterisk: Boolean read FAsterisk write SetAsterisk; property Enabled: Boolean read FEnabled write FEnabled; property OnChange: TNotifyEvent read FOnChange write FOnChange; property Default: Variant read FDefault write FDefault; property Blocked: Boolean read FBlocked write Block; property TabOrder; property AutoSaveToRegistry : Boolean read FAutoSaveToRegistry write FAutoSaveToRegistry; // vallkor end; implementation uses qFStrings, Variants, SysUtils, ComCtrls; constructor TqFControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FLabelColor := qFDefaultLabelColor; FInterval := qFDefaultInterval; Width := qFDefaultWidth; Height := qFDefaultHeight; FDisplayName := qFDefaultDisplayName; FRequired := True; FSemicolon := True; FAsterisk := True; FEnabled := True; ParentBackground := True; end; procedure TqFControl.Load(DataSet: TDataSet); var field: TField; begin if not Enabled then Exit; if DataSet.IsEmpty then Exit; field := DataSet.FindField(UpperCase(FFieldName)); if field <> nil then Value := field.Value; end; procedure TqFControl.Loaded; begin if ( not VarIsNull(Default) ) and ( not VarIsEmpty(Default) ) then Value := Default; end; procedure TqFControl.Clear; begin if not Blocked then Value := Null; end; procedure TqFControl.Block(Flag: Boolean); begin FBlocked := Flag; end; function TqFControl.Check: String; begin Result := ''; end; procedure TqFControl.Highlight(HighlightOn: Boolean); var tab: TTabSheet; begin if Parent is TTabSheet then begin tab := Parent as TTabSheet; if tab.Parent is TPageControl then (tab.Parent as TPageControl).ActivePage := tab; end; end; procedure TqFControl.SetRequired(Val: Boolean); begin FRequired := Val; end; function TqFControl.ToString: String; begin Result := Null; end; procedure TqFControl.SetSemicolon(Val: Boolean); begin FSemicolon := Val; end; procedure TqFControl.SetAsterisk(Val: Boolean); begin FAsterisk := Val; end; procedure TqFControl.ShowFocus; var tab: TTabSheet; begin if Parent is TTabSheet then begin tab := Parent as TTabSheet; if tab.Parent is TPageControl then (tab.Parent as TPageControl).ActivePage := tab; end; end; procedure TqFControl.SetValue(Val: Variant); begin end; function TqFControl.GetValue: Variant; begin Result := Null; end; procedure TqFControl.SetDisplayName(Name: String); begin FDisplayName := Name; end; procedure TqFControl.SetInterval(Int: Integer); begin FInterval := Int; end; procedure TqFControl.SetLabelColor(Color: TColor); begin FLabelColor := Color; end; procedure TqFControl.LoadFromRegistry(reg: TRegistry); begin end; procedure TqFControl.SaveIntoRegistry(reg: TRegistry); begin end; procedure TqFControl.SetFieldName(FieldName: String); begin FFieldName := FieldName; end; end.
unit TestUTemplateFcxVO; interface uses TestFramework, SysUtils, Atributos, UCondominioVO, Generics.Collections, UGenericVO, Classes, Constantes, UTemplateFcxVO; type TestTTemplateFcxVO = class(TTestCase) strict private FTemplateFcxVO: TTemplateFcxVO; public procedure SetUp; override; procedure TearDown; override; published procedure TestValidarCamposObrigatorios; procedure TestValidarCamposErro; end; implementation procedure TestTTemplateFcxVO.SetUp; begin FTemplateFcxVO := TTemplateFcxVO.Create; end; procedure TestTTemplateFcxVO.TearDown; begin FTemplateFcxVO.Free; FTemplateFcxVO := nil; end; procedure TestTTemplateFcxVO.TestValidarCamposErro; var TemplateFcx : TTemplateFcxVO; begin TemplateFcx := TTemplateFcxVO.Create; TemplateFcx.idTemplate := StrToInt('1'); TemplateFcx.Classificacao := '10'; TemplateFcx.descricao := ''; TemplateFcx.flTipo := '0'; try TemplateFcx.ValidarCamposObrigatorios; check(true,'Erro'); except on E: Exception do Check(true,'Sucesso'); end; end; procedure TestTTemplateFcxVO.TestValidarCamposObrigatorios; var TemplateFcx : TTemplateFcxVO; begin TemplateFcx := TTemplateFcxVO.Create; TemplateFcx.idTemplate := StrToInt('1'); TemplateFcx.Classificacao := '10'; TemplateFcx.descricao := 'Atividades'; TemplateFcx.flTipo := '0'; try TemplateFcx.ValidarCamposObrigatorios; check(true,'Sucesso'); except on E: Exception do Check(false,'Erro'); end; end; initialization RegisterTest(TestTTemplateFcxVO.Suite); end.
unit Test.Core.ObjectMapping.Address; interface {$M+} uses System.SysUtils, DUnitX.TestFramework, Test.Address.Classes, Nathan.ObjectMapping.Core, Nathan.ObjectMapping.Config; type [TestFixture] TTestObjectMapping = class private FCut: INathanObjectMappingCore<IAddress, IAddressDTO>; public [Setup] procedure Setup(); [TearDown] procedure TearDown(); [Test] procedure Test_Map_Address_AddressDTO; end; {$M-} implementation procedure TTestObjectMapping.Setup(); begin FCut := nil; end; procedure TTestObjectMapping.TearDown(); begin FCut := nil; end; procedure TTestObjectMapping.Test_Map_Address_AddressDTO; var FCut2: TNathanObjectMappingCore<IAddress, TAddressDTO>; Actual: IAddressDTO; begin // Arrange... FCut2 := TNathanObjectMappingCore<IAddress, TAddressDTO>.Create; // Act... Actual := FCut2 .Config(TNathanObjectMappingConfig<IAddress, TAddressDTO> .Create .UserMap( procedure(ADest: IAddress; ASrc: TAddressDTO) begin (ASrc as IAddressDto).Zipcode := ADest.Zip.Zipcode; (ASrc as IAddressDto).City := ADest.Zip.City; end) .CreateMap) .Map(TAddressFactory.CreateAddress); // Assert... Assert.IsNotNull(Actual); Assert.AreEqual('Nathan Thurnreiter', Actual.Name); Assert.AreEqual(1234, Actual.Zipcode); Assert.AreEqual('City', Actual.City); end; initialization TDUnitX.RegisterTestFixture(TTestObjectMapping, 'Map.TOrder'); end.
namespace RemObjects.Elements.System; interface uses java.util.concurrent, java.util; type TaskState = enum(Created, Queued, Started, Done) of Integer; Task = public class(Runnable) assembly fState: TaskState; fException: Throwable; fAsyncState: Object; fDelegate: Object; // callable<T>; runnable fDoneHandlers: Object; // nil, arraylist or task fLock: Object := new Object; method Done(ex: Throwable); method AddOrRunContinueWith(aTask: Task); constructor(aDelegate: Object; aState: Object); constructor; empty; public method run; virtual; constructor(aIn: Runnable; aState: Object := nil); method ContinueWith(aAction: remobjects.elements.system.Action1<Task>; aState: Object := nil): Task; method ContinueWith<T>(aAction: remobjects.elements.system.Func2<Task, T>; aState: Object := nil): Task1<T>; class method Run(aIn: Runnable): Task; class method Run<T>(aIn: Callable<T>): Task1<T>; property Exception: Throwable read fException; property AsyncState: Object read fAsyncState; property IsFaulted: Boolean read fException <> nil; property IsCompleted: Boolean read fState = TaskState.Done; method &Await(aCompletion: IAwaitCompletion): Boolean; // true = yield; false = long done {$HIDE W38} method Wait; reintroduce;virtual; {$SHOW W38} method Wait(aTimeoutMSec: Integer): Boolean; virtual; method Start(aScheduler: Executor := nil); virtual; class constructor; class property Threadpool: ExecutorService; readonly; class property ThreadSyncHelper: IThreadSyncHelper; class property CompletedTask: Task read new Task(fState := TaskState.Done); lazy; class method FromResult<T>(x: T): Task1<T>; begin exit new Task1<T>(fState := TaskState.Done, fResult := x); end; end; Task1<T> = public class(Task) assembly fResult: T; method getResult: T; constructor; empty; constructor(aDelegate: Object; aState: Object); empty; public constructor(aIn: Callable<T>; aState: Object := nil); method ContinueWith(aAction: Action1<Task1<T>>; aState: Object := nil): Task; method ContinueWith<TR>(aAction: Func2<Task1<T>, TR>; aState: Object := nil): Task1<TR>; method run; override; property &Result: T read getResult; end; TaskCompletionSource<T> = public class private fTask: Task1<T>; public constructor(aState: Object := nil); method SetException(ex: Throwable); method SetResult(val: T); property Task: Task1<T> read fTask; end; IAwaitCompletion = public interface method moveNext(aState: Object); end; IThreadSyncHelper = public interface method GetThreadContext: Object; method SyncBack(aContext: Object; aAction: Runnable); end; AndroidThreadSyncHelper = public class(IThreadSyncHelper) private fHandlerPost, fMyLooper: java.lang.reflect.&Method; fHandlerCtor: java.lang.reflect.Constructor; public constructor; method SyncBack(aContext: Object; aAction: Runnable); method GetThreadContext: Object; end; AWTThreadSyncHelper = public class(IThreadSyncHelper) private fisDispatchThread, finvokeLater: java.lang.reflect.&Method; fType: &Class; public constructor; method SyncBack(aContext: Object; aAction: Runnable); method GetThreadContext: Object; end; TaskCompletionSourceTask<T> = class(Task1<T>) assembly public method run; override; empty; end; ThreadpoolFactory nested in Task = class(ThreadFactory) private public method newThread(arg: Runnable): Thread; end; implementation constructor Task(aDelegate: Object; aState: Object); begin fDelegate := aDelegate; fAsyncState := aState; end; constructor Task(aIn: Runnable; aState: Object); begin if aIn = nil then raise new IllegalArgumentException('aIn'); constructor(Object(aIn), aState); end; method Task.run; begin locking fLock do fState := TaskState.Started; try Runnable(fDelegate)(); Done(nil); except on ex: Throwable do Done(ex); end; end; method Task.Done(ex: Throwable); begin fException := ex; var lCW: Object; locking fLock do begin fState := TaskState.Done; lCW := fDoneHandlers; fDoneHandlers := nil; fLock.notifyAll; end; if lCW <> nil then begin var lTask := Task(lCW); if lTask <> nil then begin lTask.run; end else begin var lList := ArrayList<Task>(lCW); for i: Integer := 0 to lList.size -1 do lList[i].run; end; end; end; method Task.ContinueWith(aAction: remobjects.elements.system.Action1<Task>; aState: Object): Task; begin result := new Task(-> aAction(self), aState); result.fState := TaskState.Queued; AddOrRunContinueWith(result); end; method Task.ContinueWith<T>(aAction: remobjects.elements.system.Func2<Task,T>; aState: Object): Task1<T>; begin var r: Callable<T> := -> aAction(self); result := new Task1(r, aState); result.fState := TaskState.Queued; AddOrRunContinueWith(result); end; method Task.AddOrRunContinueWith(aTask: Task); begin var lDone := false; if fState = TaskState.Done then lDone := true else locking self do begin if fState = TaskState.Done then lDone := true else begin if fDoneHandlers = nil then fDoneHandlers := aTask else begin var lNew := new ArrayList(); lNew.add(fDoneHandlers); lNew.add(aTask); fDoneHandlers := lNew; end; end; end; if lDone then begin aTask.run; end; end; method Task.Wait; begin if fState = TaskState.Done then exit; locking fLock do begin if fState = TaskState.Done then exit; while fState <> TaskState.Done do begin fLock.wait() end; end; end; method Task.Wait(aTimeoutMSec: Integer): Boolean; begin if fState = TaskState.Done then exit true; locking fLock do begin if fState = TaskState.Done then exit true; var lTO := System.currentTimeMillis + aTimeoutMSec; while fState <> TaskState.Done do begin var lMS := lTO - System.currentTimeMillis; if lMS <= 0 then exit false; fLock.wait(lMS); end; exit true; end; end; method Task.Start(aScheduler: Executor); begin locking fLock do begin if fState <> TaskState.Created then raise new IllegalStateException('Task already started/queued/done'); fState := TaskState.Queued; end; coalesce(aScheduler, Executor(Threadpool)).execute(self); end; class method Task.Run(aIn: Runnable): Task; begin result := new Task(aIn); result.Start; end; class method Task.Run<T>(aIn: Callable<T>): Task1<T>; begin result := new Task1<T>(aIn); result.Start; end; method Task1<T>.getResult: T; begin Wait(); if fException <> nil then raise fException; exit fResult; end; method Task1<T>.run; begin locking fLock do fState := TaskState.Started; try fResult := Callable<T>(fDelegate)(); Done(nil); except on ex: Throwable do Done(ex); end; end; constructor Task1<T>(aIn: Callable<T>; aState: Object); begin if aIn = nil then raise new IllegalArgumentException('aIn'); inherited constructor(aIn, aState); end; method Task1<T>.ContinueWith(aAction: Action1<Task1<T>>; aState: Object): Task; begin result := new Task(-> aAction(self), aState); result.fState := TaskState.Queued; AddOrRunContinueWith(result); end; method Task1<T>.ContinueWith<TR>(aAction: Func2<Task1<T>,TR>; aState: Object): Task1<TR>; begin var r: Callable<T> := -> aAction(self); result := new Task1(r, aState); result.fState := TaskState.Queued; AddOrRunContinueWith(result); end; constructor TaskCompletionSource<T>(aState: Object); begin fTask := new TaskCompletionSourceTask<T>(Object(nil), aState); fTask.fState := TaskState.Started; end; method TaskCompletionSource<T>.SetException(ex: Throwable); begin locking fTask.fLock do begin if fTask.fState = TaskState.Done then raise new IllegalStateException('Task already done'); fTask.fException := ex; fTask.fState := TaskState.Done; end; fTask.Done(ex); end; method TaskCompletionSource<T>.SetResult(val: T); begin locking fTask.fLock do begin if fTask.fState = TaskState.Done then raise new IllegalStateException('Task already done'); fTask.fResult := val; fTask.fState := TaskState.Done; end; fTask.Done(nil); end; method Task.Await(aCompletion: IAwaitCompletion): Boolean; begin if IsCompleted then exit false; var tc := ThreadSyncHelper.GetThreadContext(); if tc = nil then begin ContinueWith(a -> aCompletion.moveNext(a), nil); end else begin ContinueWith(a -> begin ThreadSyncHelper.SyncBack(tc, -> aCompletion(a)); end); end; exit true; end; class constructor Task; begin Threadpool := Executors.newCachedThreadPool(new ThreadpoolFactory); try &Class.forName("android.app.Activity"); ThreadSyncHelper := new AndroidThreadSyncHelper; except ThreadSyncHelper := new AWTThreadSyncHelper; end; end; method AWTThreadSyncHelper.SyncBack(aContext: Object; aAction: Runnable); begin finvokeLater.invoke(aAction); end; method AWTThreadSyncHelper.GetThreadContext: Object; begin if Boolean(fisDispatchThread.invoke(nil)) then exit self; exit nil; // AWT has no looper concept end; constructor AWTThreadSyncHelper; begin fType := typeOf(AWTThreadSyncHelper).ClassLoader.loadClass('java.awt.EventQueue'); fisDispatchThread := fType.getMethod('isDispatchThread'); finvokeLater := fType.getMethod('invokeLater', typeOf(Runnable)); end; constructor AndroidThreadSyncHelper; begin var lType := typeOf(AndroidThreadSyncHelper).ClassLoader.loadClass('android.os.Looper'); fMyLooper := lType.getMethod('myLooper'); var lType2 := typeOf(AndroidThreadSyncHelper).ClassLoader.loadClass('android.os.Handler'); fHandlerCtor := lType2.getConstructor(lType); fHandlerPost := lType2.getMethod('post', typeOf(Runnable)); end; method AndroidThreadSyncHelper.SyncBack(aContext: Object; aAction: Runnable); begin fHandlerPost.invoke(fHandlerCtor.newInstance(aContext), aAction); end; method AndroidThreadSyncHelper.GetThreadContext: Object; begin exit fMyLooper.invoke(nil); end; method Task.ThreadpoolFactory.newThread(arg: Runnable): Thread; begin result := new Thread(arg); result.Daemon := true; end; end.
unit uPubThreadQuery; interface uses SysUtils, ZLib, Variants, ComObj, DB, Classes, ADODB, StrUtils, UntTIO, Windows, Messages,Registry,Math,SConnect,DBClient,Forms,Controls,FrmCliDM,Pub_Fun; type TPubQueryThread=class(TThread) protected procedure Execute;override; public cdsPub: TClientDataSet; SckCon: TSocketConnection; PHandle: LongWord; SQL : String; ResultMsgNumber : integer; FType : integer; // 0:执行查询方法 1:执行无结果返回的语句 //构造方法 constructor Create;virtual; //释放对象 destructor Destroy; override; function ConnectSckCon(var ErrMsg: string): boolean; //------------方法列表------------------- //OPEN SQL function OpenSQL(var _cds: TClientDataSet; SqlStr: string; var ErrMsg: string): Boolean; //执行SQL function ExecSQL(SqlStr: string; var ErrMsg: string): Boolean; //查询提醒中心数据 function QueryRemind(var _cds: TClientDataSet; var ErrMsg: string): Boolean; end; implementation { TQueryThread } constructor TPubQueryThread.Create; begin SckCon:= TSocketConnection.Create(nil); SckCon.ServerName := 'PosServer.KD_PosServer'; SckCon.ServerGUID := '{717432D5-8CAB-422F-A1E3-913E792C50C8}'; SckCon.SupportCallbacks := False; inherited Create(True); end; procedure TPubQueryThread.Execute; var RstErrMsg : string; begin inherited; if cdsPub = nil then cdsPub := TClientDataSet.Create(nil); if FType = 0 then begin if not OpenSQL(cdsPub,SQL,RstErrMsg) then begin RstErrMsg := RstErrMsg+#0; PostMessage(PHandle,WM_I3Message,ErrMsgNO,Integer(Pchar(RstErrMsg))); end else begin PostMessage(PHandle,WM_I3Message,ResultMsgNumber,0); end; end else if FType = 1 then begin if not ExecSQL(SQL,RstErrMsg) then begin RstErrMsg := RstErrMsg+#0; PostMessage(PHandle,WM_I3Message,ErrMsgNO,Integer(Pchar(RstErrMsg))); end else begin PostMessage(PHandle,WM_I3Message,ResultMsgNumber,0); end; end else if FType = 3 then //提醒中心 begin if not QueryRemind(cdsPub,RstErrMsg) then begin RstErrMsg := RstErrMsg+#0; PostMessage(PHandle,WM_I3Message,ErrMsgNO,Integer(Pchar(RstErrMsg))); end else begin PostMessage(PHandle,WM_I3Message,ResultMsgNumber,0); end; end; end; function TPubQueryThread.ConnectSckCon(var ErrMsg: string): boolean; begin Result := True; try if not SckCon.Connected then SckCon.Open; except on E: Exception do begin ErrMsg := '线程类连接服务器失败,请检查网络!'; Gio.AddShow('线程类连接服务器错误:' + E.Message); Result := False; Exit; end; end; end; function TPubQueryThread.OpenSQL(var _cds: TClientDataSet; SqlStr: string; var ErrMsg: string): Boolean; var Data: OleVariant; begin Result := True; Result := ConnectSckCon(ErrMsg); if not Result then Exit; try Gio.AddShow(Format('查询数据 - 开始:%s', [SqlStr])); Result := SckCon.AppServer.Pub_QuerySQL(SqlStr, Data, ErrMsg) = 0; if Result then begin //解压缩数据包 Data := UnZip_OleVariant(Data); try _cds.Data := Data; except on e : Exception do begin ErrMsg := e.Message; Gio.AddShow(Format('查询数据 - 出错:%s', [ErrMsg])); Result := False; end; end; end else Gio.AddShow(Format('查询数据 - 出错:%s', [ErrMsg])); finally if SckCon.Connected then SckCon.Close; end; end; function TPubQueryThread.ExecSQL(SqlStr: string; var ErrMsg: string): Boolean; begin Result := True; Result := ConnectSckCon(ErrMsg); if not Result then exit; try Gio.AddShow(Format('执行脚本 - 开始:%s', [SqlStr])); Result := SckCon.AppServer.Pub_ExecSql(SqlStr, ErrMsg) = 0; if Result then begin Gio.AddShow(Format('执行脚本 - 完成:%s', [SqlStr])); end else Gio.AddShow(Format('执行脚本 - 出错:%s', [ErrMsg])); finally if SckCon.Connected then SckCon.Close; end; end; function TPubQueryThread.QueryRemind(var _cds: TClientDataSet; var ErrMsg: string): Boolean; var Data: OleVariant; Rst : Integer; begin Result := True; Result := ConnectSckCon(ErrMsg); Data := _cds.Data; if not Result then exit; try try Gio.AddShow('获取提醒中心数据 - 开始...'); { TODO : jibin_guo暂时调整 } rst := 0; //SckCon.AppServer.E_Get_RemindList(userinfo.LoginUser_FID, userinfo.Branch_ID,Data,ErrMsg); if Rst = 0 then begin _cds.Data := Data; Result := True; Gio.AddShow('获取提醒中心数据 - 完成...'); end else if Rst = -1 then begin Result := False; Gio.AddShow('获取提醒中心数据 - 出错:'+ErrMsg); end else if Rst = 1 then begin Result := True; Gio.AddShow('获取提醒中心:当前用户没有提醒项...'); end; except on e : Exception do begin ErrMsg := e.Message; Gio.AddShow(Format('获取提醒中心数据 - 出错:%s', [ErrMsg])); Result := False; end; end; finally if SckCon.Connected then SckCon.Close; end; end; destructor TPubQueryThread.Destroy; begin if SckCon.Connected then begin SckCon.Close; end; SckCon.Free; end; end.
{ PC98 key testing program Copyright (c) 2020 Adrian Siekierka 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. } program KeyTest; uses Dos; function KeyPressed: boolean; var regs: Registers; begin regs.AH := $01; Intr($18, regs); { KeyPressed := (regs.Flags and $02) <> 0; } KeyPressed := regs.BH <> 0; end; function ReadKey: char; var regs: Registers; begin regs.AH := $00; Intr($18, regs); if (regs.AL <= $02) and (regs.AH <= $80) then ReadKey := Chr(regs.AH or $80) else ReadKey := Chr(regs.AL); end; var c: char; running: boolean; begin running := true; while running do begin if KeyPressed then begin c := ReadKey; if c = #13 then running := false else Writeln('Read character ', Ord(c)); end; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2012 Alan Fletcher. // You may use thius software in any way you want and contribute back to the // author with any improvements you may have made to it. // You are also allowed to use this software or part of it for any purposes as long // as you retain this message and credit the author for it's contribuition. //--------------------------------------------------------------------------- unit fBase; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs; type TfrmBase = class(TForm) private { Private declarations } public { Public declarations } function GetObjectByName(objName: string; Number: integer): TComponent; end; var frmBase: TfrmBase; implementation {$R *.fmx} // Helper function that allows forms to find it's components by name and number // - MediaPlayer and 8 will look for MediaPlayer8 // and if it finds will return the component otw returns nil function TfrmBase.GetObjectByName(objName: string; Number: integer): TComponent; var ComponentName: String; begin // Volume Commands can only came from TTrackbar ComponentName := objName + IntToStr(Number); Result := FindComponent(ComponentName); end; end.
unit AStarBlitzCode; //Degenerated from: //A* Pathfinder by Patrick Lester. Used by permission. //================================================================== //Last updated 4/7/04 //http://www.policyalmanac.org/games/aStarTutorial.htm //A* Pathfinding for Beginners //This version of the aStar library has been modified to handle //pathfinding around other units. interface uses AStarGlobals, forms;//application.ProcessMessages; Function BlitzFindPath( pathfinderID, startingX, startingY,//mode=normal targetX, targetY, mode:Integer):Integer; implementation uses AStarBlitzUnit;//for the other procedures //--------------------------------------------------------------------------- // Name: FindPath // Desc: Finds a path using A* {Function FindPath(unit.unit,targetX,targetY,mode=normal) ;Random move mode is used when a unit's main target is ;currently unreachable. After the random move, the unit ;will try to pathfind to its original target again. Random ;moves can break up units that happen to be approaching ;each other from opposite directions down tight corridors. ;See the UpdatePath() function. If mode = randomMove Then useDijkstras = True} //Please note that targetX and targetY //are pixel-based coordinates relative to the //upper left corner of the map, which is 0,0. //--------------------------------------------------------------------------- Function BlitzFindPath ( pathfinderID, startingX, startingY,//mode=normal targetX, targetY, mode:Integer):Integer; var useDijkstras:Boolean; dx1,dx2,dy1,dy2,cross,//Tiebreakers XDistance,YDistance,HDistance, //Heuristic options startX,startY,x,y, onOpenList, parentXval, parentYval, a, b, m, u, v, temp, corner, numberOfOpenListItems, addedGCost, tempGcost, node, //path,//moved to global tempx, pathX, pathY, cellPosition, newOpenListItemID:Integer; //13.If there is no path to the selected target, set the pathfinder's //xPath and yPath equal to its current location //and return that the path is nonexistent. procedure noPath; begin UnitRecordArray[pathfinderID].xPath := startingX; UnitRecordArray[pathfinderID].yPath := startingY; result:= nonexistent; end; procedure noPathRedirect; begin UnitRecordArray[pathfinderID].xPath := startingX; UnitRecordArray[pathfinderID].yPath := startingY; result:= RedirectFailed; end; procedure noPathTarget; begin UnitRecordArray[pathfinderID].xPath := startingX; UnitRecordArray[pathfinderID].yPath := startingY; result:= Targetunwalkable; end; Begin If mode = randomMove Then useDijkstras := True else useDijkstras:=False; //onOpenList:=0; //New changes made these un-initialized..buggy ? parentXval:=0; parentYval:=0; //corner:=0; addedGCost:=0; //a:=0; b:=0; m:=0; u:=0; v:=0; //temp:=0; numberOfOpenListItems:=0; //path := 0; // tempx:=0; pathX:=0; pathY:=0; cellPosition:=0; //tempGcost := 0; newOpenListItemID:=0; node:=0; //1. Convert location data (in pixels) //to coordinates in the walkability array. startX := startingX div ProjectRecord.tileSize; startY := startingY div ProjectRecord.tileSize; targetX := targetX div ProjectRecord.tileSize; targetY := targetY div ProjectRecord.tileSize; //2.Quick Path Checks: Under the some circumstances no path needs to // be generated ... //2. Check for redirects result := CheckRedirect(pathfinderID,targetX,targetY); //target is unwalkable and could not find a redirect. If result = CheckRedirectFailed Then //noPath; begin noPathRedirect; exit;{current procedure} end else If result = CheckRedirectsucceeded Then begin //island and Claimed nodes already made! targetX := gInt1; //Actual Target X,Y already reset targetY := gInt2; //by CheckRedirect end;// targetX := gInt1 else targetY := gInt2; //If starting location and target are in the same location... //Blitz sets other stuff..this does it at end... if ((startX = targetX) and (startY = targetY) and (UnitRecordArray[pathfinderID].pathLocation > 0)) then result:= found; if ((startX = targetX) and (startY = targetY) and (UnitRecordArray[pathfinderID].pathLocation = 0)) then result:= nonexistent; //If target square is unwalkable, return that it's a nonexistent path. if (walkability[targetX][targetY] = unwalkable)then begin noPathTarget; exit;{current procedure} end;//goto noPath; //3.Reset some variables that need to be cleared if (onClosedList > 1000000)then //reset whichList occasionally begin for x := 0 to mapWidth-1 do for y := 0 to mapHeight-1 do whichList [x][y] := 0; onClosedList := 10; end; //changing the values of onOpenList and onClosed list //is faster than redimming whichList() array onClosedList := onClosedList+5; //+2; onOpenList := onClosedList-1; tempUnwalkable := onClosedList-2; penalized := onClosedList-3; UnitRecordArray[pathfinderID].pathLength := notStarted;//i.e, = 0 UnitRecordArray[pathfinderID].pathLocation:= notStarted;//i.e, = 0 Gcost[startX][startY] := 0; //reset starting square's G value to 0 //b. Create a footprint for any nearby unit that the pathfinding unit //may be about to collide with. Such nodes are designated as tempUnwalkable. CreateFootPrints(pathfinderID{unit.unit}); //4.Add the starting location to the open list of squares to be checked. numberOfOpenListItems := 1; //assign it as the top (and currently only) item in the open list, // which is maintained as a binary heap (explained below) openList[1] := 1; openX[1] := startX ; openY[1] := startY; LostinaLoop:=True; //5.Do the following until a path is found or deemed nonexistent. while (LostinaLoop)//Do until path is found or deemed nonexistent do begin Application.ProcessMessages; // If () then LostinaLoop :=False; //6.If the open list is not empty, take the first cell off of the list. //This is the lowest F cost cell on the open list. if (numberOfOpenListItems <> 0) then begin //6.7. Pop the first item off the open list. parentXval := openX[openList[1]]; //record cell coordinates of the item parentYval := openY[openList[1]]; //add the item to the closed list whichList[parentXval][parentYval] := onClosedList; //Open List = Binary Heap: Delete this item from the open list, which //is maintained as a binary heap. //For more information on binary heaps, see: //http://www.policyalmanac.org/games/binaryHeaps.htm //reduce number of open list items by 1 numberOfOpenListItems := numberOfOpenListItems - 1; //Delete the top item in binary heap and reorder the heap, //with the lowest F cost item rising to the top. //move the last item in the heap up to slot #1 openList[1] := openList[numberOfOpenListItems+1]; v := 1; //Repeat the following until the new item in slot #1 //sinks to its proper spot in the heap. while LostinaLoop//(not KeyDown(27))//reorder the binary heap do begin Application.ProcessMessages; //Allow user to Cancel u := v; //if both children exist if (2*u+1 <= numberOfOpenListItems)then begin //Check if the F cost of the parent is greater than each child. //Select the lowest of the two children. if (Fcost[openList[u]] >= Fcost[openList[2*u]])then v := 2*u; if (Fcost[openList[v]] >= Fcost[openList[2*u+1]])then v := 2*u+1; end else begin //if only child #1 exists if (2*u <= numberOfOpenListItems)then begin //Check if the F cost of the parent is greater than child #1 if (Fcost[openList[u]] >= Fcost[openList[2*u]])then v := 2*u; end; end; //!= if (u <> v)then //if parent's F is > one of its children, swap them begin temp := openList[u]; openList[u] := openList[v]; openList[v] := temp; end else break; //otherwise, exit loop end; //while LostinaLoop //7.Check the adjacent squares. (Its "children" -- these path children //are similar, conceptually, to the binary heap children mentioned //above, but don't confuse them. They are different. Path children //are portrayed in Demo 1 with grey pointers pointing toward //their parents.) Add these adjacent child squares to the open list //for later consideration if appropriate (see various if statements //below). for b := parentYval-1 to parentYval+1 do begin for a := parentXval-1 to parentXval+1do begin //If not off the map //(do this first to avoid array out-of-bounds errors) if ( (a <> -1) and (b <> -1) and (a <> mapWidth) and (b <> mapHeight) )then begin //If not already on the closed list (items on the closed list have //already been considered and can now be ignored). if (whichList[a][b] <> onClosedList)then begin //If not a wall/obstacle square. if (walkability [a][b] <> unwalkable) then begin //If not an adjacent node that is temporarily unwalkable //as defined by CreateFootprints() If tempUnwalkability[a,b] <> tempUnwalkable then node := unwalkable; //If not occupied by a stopped unit If claimedNode[a,b] = 0{Null} then node := walkable Else If claimedNode[a,b]{\pathStatus} <>tempStopped{ stopped }then node := walkable;//{End If If node = walkable then begin //Don't cut across corners corner := walkable; if (a = parentXval-1)then begin if (b = parentYval-1)then begin if ( (walkability[parentXval-1][parentYval] = unwalkable) or (walkability[parentXval][parentYval-1] = unwalkable)) then corner := unwalkable; end else if (b = parentYval+1)then begin if ((walkability[parentXval][parentYval+1] = unwalkable) or (walkability[parentXval-1][parentYval] = unwalkable)) then corner := unwalkable; end; end else if (a = parentXval+1)then begin if (b = parentYval-1)then begin if ((walkability[parentXval][parentYval-1] = unwalkable) or (walkability[parentXval+1][parentYval] = unwalkable)) then corner:= unwalkable; end else if (b = parentYval+1)then begin if ((walkability[parentXval+1][parentYval] = unwalkable) or (walkability[parentXval][parentYval+1] = unwalkable)) then corner := unwalkable; end; end; if (corner = walkable)then begin //If not already on the open list, add it to the open list. if (whichList[a][b] <> onOpenList)then begin //Create a new open list item in the binary heap. //each new item has a unique ID # newOpenListItemID := newOpenListItemID + 1; m := numberOfOpenListItems+1; //place the new open list item //(actually, its ID#) at the bottom of the heap openList[m] := newOpenListItemID; //record the x and y coordinates of the new item openX[newOpenListItemID] := a; openY[newOpenListItemID] := b; //Figure out its G cost if ((abs(a-parentXval) = 1) and (abs(b-parentYval) = 1)) //cost of going to diagonal squares then addedGCost := 14 //cost of going to non-diagonal squares else addedGCost := 10; Gcost[a][b] := Gcost[parentXval][parentYval] +Trunc((GCostData[a,b] *ProjectRecord.TerrainValueAlphaD)) + addedGCost; //If the node lies along the path of a nearby unit, add a penalty G cost. If nearByPath[a,b] = penalized then Gcost[a,b] := Gcost[a,b]+Trunc(20*ProjectRecord.AdjacentPathPenaltyD) Else If ((a<>parentXval) And (b<>parentYval)) then If ((nearByPath[a,parentYval] = penalized) or (nearByPath[parentXval,b] = penalized)) then Gcost[a,b] := Gcost[a,b]+Trunc(28*ProjectRecord.AdjacentPathPenaltyD); //Figure out its H and F costs and parent If useDijkstras then Hcost[openList[m]] :=Trunc(ProjectRecord.AverageTerrainD){0} else //Hcost[openList[m]] := 10*(abs(a - targetX) + abs(b - targetY)); Case UnitRecordArray[pathfinderID].SearchMode of 0:Hcost[openList[m]] :=Trunc(ProjectRecord.AverageTerrainD);//0; //Dijkstra 1://Diagonal Begin XDistance:=abs(a - targetX); YDistance:=abs(b - targetY); If XDistance > YDistance then HDistance:=( (14*YDistance) + (10*(XDistance-YDistance))) else HDistance:=( (14*XDistance) + (10*(YDistance-XDistance))); Hcost[openList[m]] :=Trunc(HDistance+ProjectRecord.AverageTerrainD); End; 2: //Manhattan Hcost[openList[m]] := Trunc(ProjectRecord.AverageTerrainD+ (10*(abs(a - targetX) + abs(b - targetY)))); 3: //BestFirst..Overestimated h Hcost[openList[m]] := Trunc(ProjectRecord.AverageTerrainD+ (10*((a - targetX)*(a - targetX) + (b - targetY)*(b - targetY)))); 4: Hcost[openList[m]] := Trunc(ProjectRecord.AverageTerrainD+ (10*SQRT(((a - targetX)*(a - targetX) + (b - targetY)*(b - targetY))))); End; //record the F cost of the new square //Fcost[openList[m]] := Gcost[a][b] + Hcost[openList[m]]; Case UnitRecordArray[pathfinderID].TieBreakerMode of 0:Fcost[openList[m]] := Gcost[a][b] + Hcost[openList[m]]; 1:begin //straight dx1:=(a - targetX); dx2:=(b - targetY); dy1:=(UnitRecordArray[pathfinderID].startXLoc-UnitRecordArray[pathfinderID].targetX); dy2:=(UnitRecordArray[pathfinderID].startYLoc-UnitRecordArray[pathfinderID].targetY ); cross:=abs((dx1*dy2) - (dx2*dy1)); //Round or Trunc ? //* Fcost[openList[m]] := Trunc(Gcost[a][b] + Hcost[openList[m]]+(cross/0.001)); end; 2:Fcost[openList[m]] := Trunc(Gcost[a][b] + Hcost[openList[m]]-(0.1*Hcost[openList[m]])); //close 3:Fcost[openList[m]] := Trunc(Gcost[a][b] + Hcost[openList[m]]+(0.1*Hcost[openList[m]])); //far end; //record the parent of the new square parentX[a][b] := parentXval ; parentY[a][b] := parentYval; //Move the new open list item to the proper place //in the binary heap. Starting at the bottom, //successively compare to parent items, //swapping as needed until //the item finds its place in the heap //or bubbles all the way to the top //(if it has the lowest F cost). //While item hasn't bubbled to the top (m=1) while (m <> 1)do begin //Check if child's F cost is < parent's F cost. //If so, swap them. if (Fcost[openList[m]] <= Fcost[openList[m div 2]])then begin temp := openList[m div 2];//[m/2]; openList[m div 2]{[m/2]} := openList[m]; openList[m] := temp; m := m div 2;//m/2; end else break; end; //add one to the number of items in the heap numberOfOpenListItems := numberOfOpenListItems+1; //Change whichList to show //that the new item is on the open list. whichList[a][b] := onOpenList; end //8.If adjacent cell is already on the open list, //check to see if this path to that cell //from the starting location is a better one. //If so, change the parent of the cell and its G and F costs else //If whichList(a,b) = onOpenList begin //Figure out the G cost of this possible new path if ((abs(a-parentXval) = 1) and (abs(b-parentYval) = 1)) //cost of going to diagonal tiles then addedGCost := 14 //cost of going to non-diagonal tiles else addedGCost := 10; //tempGcost := Gcost[parentXval][parentYval] + addedGCost; tempGcost := Gcost[parentXval][parentYval]+Trunc(GCostData[a,b]*ProjectRecord.TerrainValueAlphaD) + addedGCost; //;If the node lies along the path of a nearby unit, //add a penalty G cost. If nearByPath[a,b] = penalized then tempGcost := tempGcost+Trunc(20*ProjectRecord.AdjacentPathPenaltyD) Else If ((a<>parentXval) And (b<>parentYval))then begin If ((nearByPath[a,parentYval] = penalized) or (nearByPath[parentXval,b] = penalized))then tempGcost := tempGcost+Trunc(28*ProjectRecord.AdjacentPathPenaltyD); End; //If this path is shorter (G cost is lower) then change //the parent cell, G cost and F cost. if (tempGcost < Gcost[a][b])then //if G cost is less, begin //change the square's parent parentX[a][b] := parentXval; parentY[a][b] := parentYval; Gcost[a][b] := tempGcost;//change the G cost //Because changing the G cost also changes the F cost, //if the item is on the open list we need to change //the item's recorded F cost //and its position on the open list to make //sure that we maintain a properly ordered open list. //look for the item in the heap for x := 1 to numberOfOpenListItems do begin //item found if ( (openX[openList[x]] = a) and (openY[openList[x]] = b))then begin //change the F cost Fcost[openList[x]] := Gcost[a][b] + Hcost[openList[x]]; //See if changing the F score bubbles the item up // from it's current location in the heap m := x; //While item hasn't bubbled to the top (m=1) while (m <> 1)do begin //Check if child is < parent. If so, swap them. if (Fcost[openList[m]] < Fcost[openList[m div 2]]) then begin temp := openList[m div 2]; // openList[m div 2] := openList[m]; //m/2 openList[m] := temp; m := m div 2; end else break; end; break; //exit for x = loop end; //If openX(openList(x)) = a end; //For x = 1 To numberOfOpenListItems end;//If tempGcost < Gcost(a,b) end;//else If whichList(a,b) = onOpenList end;//If not cutting a corner { End If ;If not already on the open list End If ;If corner = walkable} End;// If ;If not occupied by a stopped unit // End;// If ;If not an adjacent, temporarily unwalkable node { End If ;If not a wall/obstacle cell. End If ;If not already on the closed list End If ;If not off the map.} end;//If not a wall/obstacle square. end;//If not already on the closed list end;//If not off the map end;//for (a = parentXval-1; a <= parentXval+1; a++){ end;//for (b = parentYval-1; b <= parentYval+1; b++){ end//if (numberOfOpenListItems != 0) //9.If open list is empty then there is no path. else begin //pathStatus[pathfinderID] := nonexistent; UnitRecordArray[pathfinderID].pathStatus := nonexistent; break; end; //If target is added to open list then path has been found. //See 10 below (* if (whichList[targetX][targetY] = onOpenList)then begin //pathStatus[pathfinderID] := found; UnitRecordArray[pathfinderID].pathStatus := found; break; end; end; *) //10.Check to see if desired target has been found. If mode = normal then// ;exit when target is added to open list. begin If whichList[targetX,targetY] = onOpenList Then begin UnitRecordArray[pathfinderID].pathStatus := found; break;//: Exit end; end Else If mode = randomMove then If Gcost[parentXval,parentYVal] > (20 + Random(20))then begin targetX := parentXval;// : targetY := parentYval; pathStatus[pathfinderID] := found;// : Exit break; end; end; {End If End If} //10.Save the path if it exists. if (UnitRecordArray[pathfinderID].pathStatus = found)then begin //a.Working backwards from the target to the starting location by checking //each cell's parent, figure out the length of the path. pathX := targetX; pathY := targetY; while ((pathX <> startX) or (pathY <> startY))do begin //Look up the parent of the current cell. tempx := parentX[pathX][pathY]; pathY := parentY[pathX][pathY]; pathX := tempx; //Figure out the path length //pathLength[pathfinderID] := pathLength[pathfinderID] + 1; UnitRecordArray[pathfinderID].pathLength := UnitRecordArray[pathfinderID].pathLength + 1; end; {;b. Resize the data bank to the right size (leave room to store step 0, ;which requires storing one more step than the length) ResizeBank unit\pathBank,(unit\pathLength+1)*4} //b.Resize the data bank to the right size in bytes {pathBank[pathfinderID] := (int* ) realloc (pathBank[pathfinderID], pathLength[pathfinderID]*8);} //8 ? 4 byte =int ? +1 //setlength(pathBank[pathfinderID],(pathLength[pathfinderID])*2); setlength(UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank,pathfinderID],(UnitRecordArray[pathfinderID].pathLength)*2); //c. Now copy the path information over to the databank. Since we are //working backwards from the target to the start location, we copy //the information to the data bank in reverse order. The result is //a properly ordered set of path data, from the first step to the last. pathX := targetX; pathY := targetY; //cellPosition := pathLength[pathfinderID]*2;//start at the end cellPosition := ((UnitRecordArray[pathfinderID].pathLength)*2);//start at the end while ((pathX <> startX) or (pathY <> startY))do begin cellPosition := cellPosition - 2;//work backwards 2 integers //error C messing with stuffing integers into a byte array type of thing //pathBank[pathfinderID] [cellPosition] := pathX; //pathBank[pathfinderID] [cellPosition+1] := pathY; UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID][cellPosition] := pathX; UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID][cellPosition+1] := pathY; //d.Look up the parent of the current cell. tempx := parentX[pathX][pathY]; pathY := parentY[pathX][pathY]; pathX := tempx; //e.If we have reached the starting square, exit the loop. end; //11.Read the first path step into xPath/yPath arrays //Change C..Blitz ? //BlitzReadPath(pathfinderID,startingX,startingY,1); UnitRecordArray[pathfinderID].yPath := ProjectRecord.tileSize* UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID] [UnitRecordArray[pathfinderID].pathLocation*2-1]; UnitRecordArray[pathfinderID].xPath := ProjectRecord.tileSize*UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID] [UnitRecordArray[pathfinderID].pathLocation*2-2]; end; result:= UnitRecordArray[pathfinderID].pathStatus; End; end.
unit Demo.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Net.HttpClient; type TfrmMain = class(TForm) Button1: TButton; Memo1: TMemo; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation uses InfluxDB, InfluxDB.Interfaces, System.Diagnostics, System.TimeSpan, System.Threading; {$R *.dfm} procedure TfrmMain.Button1Click(Sender: TObject); var Influx: IInfluxDB; begin Influx := TInfluxDB.CreateClient('localhost', 8086); Influx.CreateDatabase('MyDB', 1, duWeek); end; procedure TfrmMain.Button2Click(Sender: TObject); var Influx: IInfluxDB; begin Influx := TInfluxDB.CreateClient('localhost', 8086); Memo1.Lines.AddStrings(Influx.ShowDatabases); end; procedure TfrmMain.Button3Click(Sender: TObject); var Influx: IInfluxDB; begin Influx := TInfluxDB.CreateClient('localhost', 8086); if Influx.Write('TestDB', 'bucket,id=ABC temp=45') then ShowMessage('1. Data written to DB'); end; procedure TfrmMain.Button4Click(Sender: TObject); var Influx: IInfluxDB; Val: TInfluxValue; begin Influx := TInfluxDB.CreateClient('localhost', 8086); Val := TInfluxValue.Create('MyMeasurement', Now); Val.AddField('temp', 77); Val.AddField('value', 77); Val.AddTag('id', '5498'); if Influx.Write('TestDB', Val) then ShowMessage('2. Data written to DB'); end; procedure TfrmMain.Button5Click(Sender: TObject); var Influx: IInfluxDB; Stopwatch: TStopwatch; Elapsed: TTimeSpan; I: Integer; begin Stopwatch := TStopwatch.StartNew; Influx := TInfluxDB.CreateClient('localhost', 8086); for I := 0 to 1000 do begin Influx.Write('TestDB', 'temp temp=' + Random(200).ToString); end; Elapsed := Stopwatch.Elapsed; ShowMessage(Elapsed.TotalSeconds.ToString); end; procedure TfrmMain.Button6Click(Sender: TObject); var Influx: IInfluxDB; begin Influx := TInfluxDB.CreateClient('localhost', 8086); Memo1.Lines.Text := Influx.ServerVersion; end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXANSWE0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {* TAdModem waits for the phone to ring twice *} {* and answers the modem. *} {*********************************************************} unit Exanswe0; interface uses WinTypes, WinProcs, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, AdPort, StdCtrls, Buttons, OoMisc, AdMdm; type TForm1 = class(TForm) ListBox1: TListBox; BitBtn1: TBitBtn; ApdComPort1: TApdComPort; AdModem1: TAdModem; procedure FormCreate(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure AdModem1ModemCallerID(Modem: TAdCustomModem; CallerID: TApdCallerIDInfo); procedure AdModem1ModemConnect(Modem: TAdCustomModem); procedure AdModem1ModemDisconnect(Modem: TAdCustomModem); procedure AdModem1ModemFail(Modem: TAdCustomModem; FailCode: Integer); procedure AdModem1ModemLog(Modem: TAdCustomModem; LogCode: TApdModemLogCode); procedure AdModem1ModemStatus(Modem: TAdCustomModem; ModemState: TApdModemState); private { Private declarations } public { Public declarations } procedure AddStatus(const Msg : String); end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.AddStatus(const Msg : String); begin Listbox1.Items.Add(Msg); Listbox1.ItemIndex := Pred(Listbox1.Items.Count); end; procedure TForm1.FormCreate(Sender: TObject); {Event OnCreate from TForm1} begin ApdComPort1.Open := True; end; procedure TForm1.BitBtn1Click(Sender: TObject); {Begin answering in two rings} begin AdModem1.AnswerOnRing := 2; AdModem1.AutoAnswer; end; procedure TForm1.AdModem1ModemCallerID(Modem: TAdCustomModem; CallerID: TApdCallerIDInfo); { we received caller id information } begin AddStatus('CallerID Name: ' + CallerID.Name); AddStatus('CallerID Number: ' + CallerID.Number); end; procedure TForm1.AdModem1ModemConnect(Modem: TAdCustomModem); { we are connected } begin AddStatus('Connected!'); end; procedure TForm1.AdModem1ModemDisconnect(Modem: TAdCustomModem); { we have been disconnected } begin AddStatus('Disconnected'); end; procedure TForm1.AdModem1ModemFail(Modem: TAdCustomModem; FailCode: Integer); begin AddStatus('Failed: ' + Modem.FailureCodeMsg(FailCode)); end; procedure TForm1.AdModem1ModemLog(Modem: TAdCustomModem; LogCode: TApdModemLogCode); begin AddStatus('Log event: ' + Modem.ModemLogToString(LogCode)); end; procedure TForm1.AdModem1ModemStatus(Modem: TAdCustomModem; ModemState: TApdModemState); begin AddStatus('Status event: ' + Modem.ModemStatusMsg(ModemState)); end; end.
unit uFRAMEcadCli; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.ImgList, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.Edit, FMX.DateTimeCtrls, FMX.TabControl, System.ImageList, FMX.ListBox; type TframeCadCliente = class(TFrame) tcCadastro: TTabControl; tabBasic: TTabItem; vsBasic: TVertScrollBox; gridBasic: TGridPanelLayout; dtNasc: TDateEdit; edtCPF_CNPJ: TEdit; edtEndereco: TMemo; edtFone1: TEdit; edtFone2: TEdit; edtNome: TEdit; edtRG_IE: TEdit; imgCPF: TGlyph; imgData: TGlyph; imgFone: TGlyph; imgLocation: TGlyph; imgNome: TGlyph; lblNasc: TLabel; lblSexo: TLabel; gridSexo: TGridLayout; lblMasc: TLabel; swSexo: TSwitch; lblFem: TLabel; lblEndereco: TLabel; tabExtras: TTabItem; vsExtras: TVertScrollBox; gridExtras: TGridPanelLayout; imgEmail: TGlyph; edtEmail: TEdit; imgLimiteCompras: TGlyph; edtLimite: TEdit; picFoto1: TImage; lblFotoDoc: TLabel; picFoto2: TImage; imgObs: TGlyph; edtObs: TMemo; lblObs: TLabel; btnFoto1: TButton; btnFoto2: TButton; ToolBar1: TToolBar; btnVoltar: TButton; btnSalvar: TButton; ilFrame: TImageList; tcFunc: TTabControl; tbCad: TTabItem; tbDetalhe: TTabItem; ListBox1: TListBox; ListBoxHeader1: TListBoxHeader; lbiNome: TListBoxItem; lbiNasc: TListBoxItem; lbiDoc: TListBoxItem; lbiFone1: TListBoxItem; lbiFone2: TListBoxItem; lbiCompras: TListBoxItem; ListBoxItem7: TListBoxItem; Label1: TLabel; btnBack: TButton; procedure FrameClick(Sender: TObject); procedure lblMascClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.fmx} procedure TframeCadCliente.FrameClick(Sender: TObject); begin tcFunc.ActiveTab := tbDetalhe; end; procedure TframeCadCliente.lblMascClick(Sender: TObject); begin swSexo.IsChecked := false; end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {**********************************************************} {* VIEWMAIN.PAS *} {**********************************************************} {**********************Description************************} {* A fax viewer that allows you to view APF files. *} {*********************************************************} unit ViewMain; interface uses WinTypes, WinProcs, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls, Buttons, StdCtrls, ooMisc, AdFView, AdFaxPrn, AdFPStat, WComp, Percent; type TMainForm = class(TForm) MainMenu: TMainMenu; FaxViewer: TApdFaxViewer; FileItem: TMenuItem; OpenItem: TMenuItem; N1: TMenuItem; PrintSetupItem: TMenuItem; PrintItem: TMenuItem; N2: TMenuItem; ExitItem: TMenuItem; EditItem: TMenuItem; SelectAllItem: TMenuItem; CopyItem: TMenuItem; ViewItem: TMenuItem; N25PercentItem: TMenuItem; N50PercentItem: TMenuItem; N75PercentItem: TMenuItem; N100PercentItem: TMenuItem; N200PercentItem: TMenuItem; N400PercentItem: TMenuItem; N3: TMenuItem; OtherSizeItem: TMenuItem; WhitespaceCompOption: TMenuItem; ZoomInItem: TMenuItem; ZoomOutItem: TMenuItem; N4: TMenuItem; OpenDialog: TOpenDialog; FaxPrinter: TApdFaxPrinter; PrinterStatus: TApdFaxPrinterStatus; N5: TMenuItem; Rotate90Item: TMenuItem; Rotate180Item: TMenuItem; Rotate270Item: TMenuItem; NoRotateItem: TMenuItem; StatusPanel: TPanel; CloseItem: TMenuItem; Panel1: TPanel; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; procedure OpenItemClick(Sender: TObject); procedure PrintSetupItemClick(Sender: TObject); procedure PrintItemClick(Sender: TObject); procedure ExitItemClick(Sender: TObject); procedure SelectAllItemClick(Sender: TObject); procedure CopyItemClick(Sender: TObject); procedure ZoomInItemClick(Sender: TObject); procedure ZoomOutItemClick(Sender: TObject); procedure N25PercentItemClick(Sender: TObject); procedure N50PercentItemClick(Sender: TObject); procedure N75PercentItemClick(Sender: TObject); procedure N100PercentItemClick(Sender: TObject); procedure N200PercentItemClick(Sender: TObject); procedure N400PercentItemClick(Sender: TObject); procedure OtherSizeItemClick(Sender: TObject); procedure WhitespaceCompOptionClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure NoRotateItemClick(Sender: TObject); procedure Rotate90ItemClick(Sender: TObject); procedure Rotate180ItemClick(Sender: TObject); procedure Rotate270ItemClick(Sender: TObject); procedure FaxViewerPageChange(Sender: TObject); procedure FaxViewerViewerError(Sender: TObject; ErrorCode: Integer); procedure CloseItemClick(Sender: TObject); procedure NextClick(Sender: TObject); procedure PrevClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FaxViewerDropFile(Sender: TObject; FileName: String); private { Private declarations } public ViewPercent : Integer; procedure UpdateViewPercent(const NewPercent : Integer); procedure EnableZoomChoices; procedure DisableZoomChoices; procedure UncheckZoomChoices; procedure EnableRotationChoices; procedure DisableRotationChoices; procedure UncheckRotationChoices; procedure OpenFile(const FileName : string); procedure CloseFile; end; var MainForm: TMainForm; implementation {$R *.DFM} procedure TMainForm.CloseFile; begin FaxViewer.FileName := ''; DisableZoomChoices; DisableRotationChoices; SelectAllItem.Enabled := False; CopyItem.Enabled := False; StatusPanel.Caption := ' No file loaded'; FaxViewer.Invalidate; end; procedure TMainForm.OpenFile(const FileName : string); begin FaxViewer.BeginUpdate; FaxViewer.Scaling := False; FaxViewer.HorizMult := 1; FaxViewer.HorizDiv := 1; FaxViewer.VertMult := 1; FaxViewer.VertDiv := 1; FaxViewer.EndUpdate; UncheckZoomChoices; UncheckRotationChoices; try FaxViewer.FileName := FileName; EnableZoomChoices; EnableRotationChoices; SelectAllItem.Enabled := True; CopyItem.Enabled := True; N100PercentItem.Checked := True; NoRotateItem.Checked := True; ViewPercent := 100; StatusPanel.Caption := Format(' Viewing page 1 of %d in %s', [FaxViewer.NumPages, FaxViewer.FileName]); except CloseFile; MessageDlg('Error opening fax file '+FileName, mtError, [mbOK], 0); end; end; procedure TMainForm.OpenItemClick(Sender: TObject); begin if OpenDialog.Execute then OpenFile(OpenDialog.FileName); end; procedure TMainForm.CloseItemClick(Sender: TObject); begin CloseFile; end; procedure TMainForm.PrintSetupItemClick(Sender: TObject); begin FaxPrinter.PrintSetup; end; procedure TMainForm.PrintItemClick(Sender: TObject); begin if (FaxViewer.FileName <> '') then begin FaxPrinter.FileName := FaxViewer.FileName; FaxPrinter.PrintFax; end; end; procedure TMainForm.ExitItemClick(Sender: TObject); begin Close; end; procedure TMainForm.SelectAllItemClick(Sender: TObject); begin FaxViewer.SelectImage; end; procedure TMainForm.CopyItemClick(Sender: TObject); begin FaxViewer.CopyToClipBoard; end; procedure TMainForm.ZoomInItemClick(Sender: TObject); var TempPercent : Integer; begin if ((ViewPercent mod 25) = 0) then TempPercent := ViewPercent + 25 else TempPercent := ViewPercent + (25 - (ViewPercent mod 25)); if (TempPercent > 400) then begin MessageBeep(0); Exit; end; UpdateViewPercent(TempPercent); end; procedure TMainForm.ZoomOutItemClick(Sender: TObject); var TempPercent : Integer; begin if ((ViewPercent mod 25) = 0) then TempPercent := ViewPercent - 25 else TempPercent := ViewPercent - (25 - (ViewPercent mod 25)); if (TempPercent < 25) then begin MessageBeep(0); Exit; end; UpdateViewPercent(TempPercent); end; procedure TMainForm.N25PercentItemClick(Sender: TObject); begin UpdateViewPercent(25); end; procedure TMainForm.N50PercentItemClick(Sender: TObject); begin UpdateViewPercent(50); end; procedure TMainForm.N75PercentItemClick(Sender: TObject); begin UpdateViewPercent(75); end; procedure TMainForm.N100PercentItemClick(Sender: TObject); begin UpdateViewPercent(100); end; procedure TMainForm.N200PercentItemClick(Sender: TObject); begin UpdateViewPercent(200); end; procedure TMainForm.N400PercentItemClick(Sender: TObject); begin UpdateViewPercent(400); end; procedure TMainForm.OtherSizeItemClick(Sender: TObject); var Frm : TPercentForm; TempPercent : Integer; begin Frm := TPercentForm.Create(Self); Frm.ShowModal; if (Frm.ModalResult = mrOK) then TempPercent := StrToInt(Frm.PercentEdit.Text) else TempPercent := -1; Frm.Free; if (TempPercent <> -1) then UpdateViewPercent(TempPercent); end; procedure TMainForm.WhitespaceCompOptionClick(Sender: TObject); var Frm : TWhitespaceCompForm; Tmp : Integer; begin Frm := TWhitespaceCompForm.Create(Self); Frm.CompEnabledBox.Checked := FaxViewer.WhitespaceCompression; if FaxViewer.WhitespaceCompression then begin Frm.FromEdit.Text := IntToStr(FaxViewer.WhitespaceFrom); Frm.ToEdit.Text := IntToStr(FaxViewer.WhitespaceTo); end; if (Frm.ShowModal = mrOK) then begin FaxViewer.WhitespaceCompression := Frm.CompEnabledBox.Checked; if FaxViewer.WhitespaceCompression then begin Tmp := StrToInt(Frm.FromEdit.Text); FaxViewer.WhitespaceFrom := Tmp; Tmp := StrToInt(Frm.ToEdit.Text); FaxViewer.WhitespaceTo := Tmp; end; end; Frm.Free; end; procedure TMainForm.FormCreate(Sender: TObject); begin ViewPercent := 100; DisableZoomChoices; SelectAllItem.Enabled := False; CopyItem.Enabled := False; end; procedure TMainForm.UpdateViewPercent(const NewPercent : Integer); begin if (NewPercent = ViewPercent) then Exit; ViewPercent := NewPercent; if (NewPercent = 100) then FaxViewer.Scaling := False else begin FaxViewer.BeginUpdate; FaxViewer.Scaling := True; FaxViewer.HorizMult := NewPercent; FaxViewer.HorizDiv := 100; FaxViewer.VertMult := NewPercent; FaxViewer.VertDiv := 100; FaxViewer.EndUpdate; end; UncheckZoomChoices; case ViewPercent of 25 : N25PercentItem.Checked := True; 50 : N50PercentItem.Checked := True; 75 : N75PercentItem.Checked := True; 100: N100PercentItem.Checked := True; 200: N200PercentItem.Checked := True; 400: N400PercentItem.Checked := True; else OtherSizeItem.Checked := True; end; end; procedure TMainForm.EnableZoomChoices; begin N25PercentItem.Enabled := True; N50PercentItem.Enabled := True; N75PercentItem.Enabled := True; N100PercentItem.Enabled := True; N200PercentItem.Enabled := True; N400PercentItem.Enabled := True; OtherSizeItem.Enabled := True; ZoomInItem.Enabled := True; ZoomOutItem.Enabled := True; end; procedure TMainForm.DisableZoomChoices; begin N25PercentItem.Enabled := False; N50PercentItem.Enabled := False; N75PercentItem.Enabled := False; N100PercentItem.Enabled := False; N200PercentItem.Enabled := False; N400PercentItem.Enabled := False; OtherSizeItem.Enabled := False; ZoomInItem.Enabled := False; ZoomOutItem.Enabled := False; end; procedure TMainForm.UncheckZoomChoices; begin N25PercentItem.Checked := False; N50PercentItem.Checked := False; N75PercentItem.Checked := False; N100PercentItem.Checked := False; N200PercentItem.Checked := False; N400PercentItem.Checked := False; OtherSizeItem.Checked := False; end; procedure TMainForm.EnableRotationChoices; begin NoRotateItem.Enabled := True; Rotate90Item.Enabled := True; Rotate180Item.Enabled := True; Rotate270Item.Enabled := True; end; procedure TMainForm.DisableRotationChoices; begin NoRotateItem.Enabled := False; Rotate90Item.Enabled := False; Rotate180Item.Enabled := False; Rotate270Item.Enabled := False; end; procedure TMainForm.UncheckRotationChoices; begin NoRotateItem.Checked := False; Rotate90Item.Checked := False; Rotate180Item.Checked := False; Rotate270Item.Checked := False; end; procedure TMainForm.NoRotateItemClick(Sender: TObject); begin FaxViewer.Rotation := vr0; UncheckRotationChoices; NoRotateItem.Checked := True; end; procedure TMainForm.Rotate90ItemClick(Sender: TObject); begin FaxViewer.Rotation := vr90; UncheckRotationChoices; Rotate90Item.Checked := True; end; procedure TMainForm.Rotate180ItemClick(Sender: TObject); begin FaxViewer.Rotation := vr180; UncheckRotationChoices; Rotate180Item.Checked := True; end; procedure TMainForm.Rotate270ItemClick(Sender: TObject); begin FaxViewer.Rotation := vr270; UncheckRotationChoices; Rotate270Item.Checked := True; end; procedure TMainForm.FaxViewerPageChange(Sender: TObject); var W : Word; begin if (FaxViewer.FileName <> '') then begin StatusPanel.Caption := Format(' Viewing page %d of %d in %s', [FaxViewer.ActivePage, FaxViewer.NumPages, FaxViewer.FileName]); W := FaxViewer.PageFlags; CheckBox1.Checked := W and ffHighRes <> 0; CheckBox2.Checked := W and ffHighWidth <> 0; CheckBox3.Checked := W and ffLengthWords <> 0; end else begin StatusPanel.Caption := ' No file loaded'; Panel1.Caption := ''; end; end; procedure TMainForm.FaxViewerViewerError(Sender: TObject; ErrorCode: Integer); begin MessageDlg(Format('Viewer error %d', [ErrorCode]), mtError, [mbOK], 0); end; procedure TMainForm.NextClick(Sender: TObject); begin if FaxViewer.ActivePage < FaxViewer.NumPages then FaxViewer.ActivePage := FaxViewer.ActivePage + 1; end; procedure TMainForm.PrevClick(Sender: TObject); begin if FaxViewer.ActivePage > 1 then FaxViewer.ActivePage := FaxViewer.ActivePage - 1; end; procedure TMainForm.FormShow(Sender: TObject); begin if ParamCount > 0 then OpenFile(ParamStr(1)); end; procedure TMainForm.FaxViewerDropFile(Sender: TObject; FileName: String); begin EnableZoomChoices; EnableRotationChoices; SelectAllItem.Enabled := True; CopyItem.Enabled := True; N100PercentItem.Checked := True; NoRotateItem.Checked := True; ViewPercent := 100; StatusPanel.Caption := Format(' Viewing page 1 of %d in %s', [FaxViewer.NumPages, FaxViewer.FileName]); end; end.
unit uPlotHIDHandler; { ***************************************************************************** * This file is part of Multiple Acronym Math and Audio Plot - MAAPlot * * * * See the file COPYING. * * for details about the copyright. * * * * 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. * * * * MAAplot for Lazarus/fpc * * (C) 2014 Stefan Junghans * ***************************************************************************** } {$mode objfpc}{$H+} //{$DEFINE GTK2} interface uses Classes, SysUtils, Controls, uPlotClass, math, uPlotUtils, useriesmarkers, uPlotDataTypes, Forms; // ExtCtrls; { handels events for Left mouse (+Shift / + CNTRL) and wheel (+shift) for - zoom - pan - adhocmarker // fixed implementation: wheel change during adhoc marker on changes active series } type { TPlotHIDHandler } TPlotHIDHandler = class(TPlotHIDHandlerBase) private FStatesUsed: set of THIDMouseState; FZoomState: THIDMouseState; FPanState: THIDMouseState; FAdHocMarkerState: THIDMouseState; FMouseActionActive: THIDAction; FAdHocMarkerIndex: Integer; FAdHocSeriesIndex: Integer; procedure _MarkerChangeActiveSeries(AIncrement: Integer); protected procedure DoMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure DoMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); public constructor Create(AOwnerPlot: TPlot);override; destructor Destroy; override; procedure GetHIDActionStatesAvail(AHIDAction: THIDAction; out AHIDMouseStates: THIDMouseStates);override; function SetHIDAction(AHIDAction: THIDAction; AHIDMouseState: THIDMouseState): Integer; override; function GetHIDAction(out AHIDAction: THIDAction; AShiftState: TShiftState; AMouseButton: TMouseButton): Integer; // action for given state function GetHIDAction(out AHIDAction: THIDAction; AShiftState: TShiftState; AWheelDelta: Integer): Integer; // action for given state procedure GetHIDActionState(AHIDAction: THIDAction; out AHIDMouseState: THIDMouseState); override; // state for given action end; const cMouseWheelZoomButtonPan = false; //TRUE; cHID_MOUSESTATE_Names: array[mcNone..mcShiftWheel] of String = ('disabled','Mouse left', 'shift + Mouse left', 'ctrl + Mouse left','Mouse wheel', 'shift + Mouse wheel'); implementation uses uPlotSeries, uPlotRect; { TPlotHIDHandler } procedure TPlotHIDHandler._MarkerChangeActiveSeries(AIncrement: Integer); var vNewSeriesIndex: Integer; vXYZValue: TXYZValue; begin IF FMouseActionActive <> haAdHocMarker THEN exit; IF FOwnerPlot.SeriesCount < 2 THEN exit; vNewSeriesIndex := EnsureRange(FAdHocSeriesIndex + AIncrement, 0, FOwnerPlot.SeriesCount-1); // exchange the markers TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.RemoveMarker(TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.Marker[FAdHocMarkerIndex]); FAdHocSeriesIndex := vNewSeriesIndex; FAdHocMarkerIndex := TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.AddMarker; TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.Marker[FAdHocMarkerIndex].MarkerMode := mmFixedXValue; TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.Marker[FAdHocMarkerIndex].MarkerType := mtValue; ScreenToXY(OwnerPlot.Axis[TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).XAxis],OwnerPlot.Axis[TPLotSeries(OwnerPlot.Series[0]).YAxis], vXYZValue.X, vXYZValue.Y, Point(ZoomInfo.dwNewRect.Left,ZoomInfo.dwNewRect.Bottom) ); vXYZValue.Z := 0; TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.Marker[FAdHocMarkerIndex].FixedValueXYZ := vXYZValue; TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.UpdateMarker(FAdHocMarkerIndex); end; procedure TPlotHIDHandler.DoMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var vRequestedAction: THIDAction; begin // check if a HID action is associated, when yes, // -perform action (zoom) // -remove AdHocMarker (adhoc marker) // .. if no, // - remove adhocmarker (if present) // finally set activeMouseaction to haNone; // writeln('mouse Lup'); IF FMouseActionActive = haNone THEN exit; FZoomInfo.dbZooming:=false; OwnerPlot.PlotRect[Zoominfo.PlotRectIndex].Zooming := false; GetHIDAction(vRequestedAction, Shift, Button); // ccheck pressed mouseaction CASE FMouseActionActive OF haZoom: begin if vRequestedAction = haZoom then OwnerPlot.Zoom(ZoomInfo); end; haPan: begin // nothing to to, pan is immediate end; haAdHocMarker: begin TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.RemoveMarker(TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.Marker[FAdHocMarkerIndex]); FAdHocMarkerIndex := -1; TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.UpdateMarker(-1); end; END; FMouseActionActive := haNone; //FOnMouseMoveProc := nil; OwnerPlot.PlotImage.OnMouseMove:=nil; end; procedure TPlotHIDHandler.DoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var vIndex: Integer; vMouseAction: THIDAction; vXYZValue: TXYZValue; begin // check if a HID action is associated, when yes, // -set mouse action active // -connect mousemove IF Button <> mbLeft THEN exit; // remove when btnRight is also used //writeln('mouse Ldown'); IF OwnerPlot.ScrCoordToPlotRect(X, Y, vIndex) = 0 THEN begin // TODO: remove dbZooming here and in plotrect // add FZoomInfo.dwHIDAction ? GetHIDAction(vMouseAction, Shift, Button); //writeln('mouseaction: ', IntToStr(ord(vMouseAction))); FMouseActionActive := vMouseAction; if FMouseActionActive = haNone then exit; FZoomInfo.PlotRectIndex := vIndex; //writeln('vIndex: ', IntToStr(vIndex), ' Zoominfo.PlotrectIndex = ', IntToStr(ZoomInfo.PlotRectIndex)); OwnerPlot.PlotImage.OnMouseMove:=Self.OnMouseMove; //FOnMouseMoveProc := @DoMouseMove; FZoomInfo.dbZooming:=false; FZoomInfo.dwNewRect.Left:=X; FZoomInfo.dwNewRect.Top:=Y; FZoomInfo.dwNewRect.Right:=X; FZoomInfo.dwNewRect.Bottom:=Y; FZoomInfo.dwOldRect.Left:=X; FZoomInfo.dwOldRect.Top:=Y; FZoomInfo.dwOldRect.Right:=X; FZoomInfo.dwOldRect.Bottom:=Y; IF FMouseActionActive = haZoom then begin FZoomInfo.dbZooming:=TRUE; OwnerPlot.PlotRect[Zoominfo.PlotRectIndex].Zooming := true; end ELSE IF (FMouseActionActive = haAdHocMarker) then begin if (OwnerPlot.SeriesCount > 0) then begin FAdHocSeriesIndex := 0; FAdHocMarkerIndex := TPLotSeries(OwnerPlot.Series[0]).MarkerContainer.AddMarker; TPLotSeries(OwnerPlot.Series[0]).MarkerContainer.Marker[FAdHocMarkerIndex].MarkerMode := mmFixedXValue; TPLotSeries(OwnerPlot.Series[0]).MarkerContainer.Marker[FAdHocMarkerIndex].MarkerType := mtValue; ScreenToXY(OwnerPlot.Axis[TPLotSeries(OwnerPlot.Series[0]).XAxis],OwnerPlot.Axis[TPLotSeries(OwnerPlot.Series[0]).YAxis], vXYZValue.X, vXYZValue.Y, Point(X,Y) ); vXYZValue.Z := 0; TPLotSeries(OwnerPlot.Series[0]).MarkerContainer.Marker[FAdHocMarkerIndex].FixedValueXYZ := vXYZValue; TPLotSeries(OwnerPlot.Series[0]).MarkerContainer.UpdateMarker(FAdHocMarkerIndex); end else begin FAdHocSeriesIndex := -1; FMouseActionActive := haNone; end; end; // TODO: if action = adhoc marker, create marker and remember its index, set for XFixedValue mode and to XValue == Xpos end; end; procedure TPlotHIDHandler.DoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var vPos: TPoint; vXYZValue: TXYZValue; begin {$IFDEF GTK2} Application.ProcessMessages; {$ENDIF} //NOTE: gtk2 does not stop firing mousemove events, once dragging started //writeln('mouse move'); // exit if no action associated IF FMouseActionActive = haNone THEN exit; // assure coordinates vPos.X := EnsureRange(X,TPlotRect(OwnerPlot.PlotRect[FZoomInfo.PlotRectIndex]).DataRect.Left+1, TPlotRect(OwnerPlot.PlotRect[FZoomInfo.PlotRectIndex]).DataRect.Right ); vPos.Y := EnsureRange(Y,TPlotRect(OwnerPlot.PlotRect[FZoomInfo.PlotRectIndex]).DataRect.Top, TPlotRect(OwnerPlot.PlotRect[FZoomInfo.PlotRectIndex]).DataRect.Bottom-1 ); //writeln('X / Y: ', IntToStr(X), ' / ', IntToStr(Y)); Mouse.CursorPos := OwnerPlot.ClientToScreen(vPos); CASE FMouseActionActive OF haZoom: begin FZoomInfo.dwNewRect.Right:=vPos.X; FZoomInfo.dwNewRect.Bottom:=vPos.Y; OwnerPlot.DrawZoomRect(FZoomInfo); FZoomInfo.dwOldRect := FZoomInfo.dwNewRect; end; haPan: begin FZoomInfo.dwNewRect.Right:=vPos.X; FZoomInfo.dwNewRect.Bottom:=vPos.Y; //writeln('rect left old/new ', IntToStr(FZoomInfo.dwOldRect.Left), '/', IntToStr(FZoomInfo.dwNewRect.Left)); // pan OwnerPlot.Pan(ZoomInfo); FZoomInfo.dwOldRect := FZoomInfo.dwNewRect; end; haAdHocMarker: begin // TODO: to implement // TODO: change relevant series somehow (key or wheel ?) // for now, use first series FZoomInfo.dwNewRect.Right:=vPos.X; FZoomInfo.dwNewRect.Bottom:=vPos.Y; if FAdHocMarkerIndex >= 0 then begin ScreenToXY(OwnerPlot.Axis[TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).XAxis],OwnerPlot.Axis[TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).YAxis], vXYZValue.X, vXYZValue.Y, Point(X,Y) ); // needs vPos ? vXYZValue.Z := 0; //writeln('adhoc change to X= ', FloatToStrF(vXYZValue.X, ffExponent, 4, 4)); TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.Marker[FAdHocMarkerIndex].FixedValueXYZ := vXYZValue; TPLotSeries(OwnerPlot.Series[FAdHocSeriesIndex]).MarkerContainer.UpdateMarker(FAdHocMarkerIndex); end; end; END; end; procedure TPlotHIDHandler.DoMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); var //vPos: TPoint; //vINside: Boolean; vPlotRectIdx: Integer; //vCoords: Integer; vHIDAction: THIDAction; vState: THIDMouseState; const cZFactor = 1.19; begin // fixed series change implementation IF FMouseActionActive = haAdHocMarker THEN begin _MarkerChangeActiveSeries(1* sign(WheelDelta)); exit; end; //writeln('mouse wheel'); // writeln('wheeldata: ', IntToStr(WheelDelta)); // writeln('mousepos : ', IntToStr(MousePos.X), ' / ', INtToStr(MousePos.Y)); // check if a HID action is associated, when yes, do it (wheel actions immediate) GetHIDAction(vHIDAction, Shift, WheelDelta); // leave mouse position at same place ! // zoom 10% //writeln('MO zooming...X/Y ', IntToStr(MousePos.X), '/', IntToStr(MousePos.Y)); if OwnerPlot.ScrCoordToPlotRect(MousePos.X, MousePos.Y, vPlotRectIdx) <> 0 then exit; if (not IsInsideRect(MousePos, TPlotRect(OwnerPlot.PlotRect[vPlotRectIdx]).DataRect)) then exit; if vHIDAction <> haZoom then exit; // only zoom implemented for wheel so far GetHIDActionState(vHIDAction, vState); // if HIDaction = ShiftWheel then we zoom X AND Y at the same time // otherwise if HIDAction = Wheel then we zoom only X (shiftWheel: Y) if vState = mcWheel then begin if [ssShift] <= Shift then OwnerPlot.Zoom(ZoomInfo, MousePos, 1, power(cZFactor, sign(WheelDelta)) ) else OwnerPlot.Zoom(ZoomInfo, MousePos, power(cZFactor, sign(WheelDelta)), 1 ); end else OwnerPlot.Zoom(ZoomInfo, MousePos, power(cZFactor, sign(WheelDelta)), power(cZFactor, sign(WheelDelta)) ); end; constructor TPlotHIDHandler.Create(AOwnerPlot: TPlot); begin Inherited Create(AOwnerPlot); FOnMouseDownProc := @DoMouseDown; FOnMouseUpProc:= @DoMouseUp ; FOnMouseWheelProc := @DoMouseWheel; FOnMouseMoveProc := @DoMouseMove; // nil; // zuweisung geht nicht FStatesUsed := []; FZoomState := mcNone; FPanState := mcNone; FPanState := mcNone; FAdHocMarkerIndex := -1; FAdHocSeriesIndex := 0; //SetHIDAction(haZoom, mcMLeft); SetHIDAction(haZoom, mcWheel); SetHIDAction(haPan, mcShiftMLeft); SetHIDAction(haAdHocMarker, mcCtrlMLeft); end; destructor TPlotHIDHandler.Destroy; begin inherited Destroy; end; procedure TPlotHIDHandler.GetHIDActionStatesAvail(AHIDAction: THIDAction; out AHIDMouseStates: THIDMouseStates); var vStates: THIDMouseStates; //vLoop: Integer; //vAvailSet: set of THIDMouseState; vOldState: THIDMouseState; begin vStates := [mcNone, mcMLeft, mcShiftMLeft, mcCtrlMLeft, mcWheel, mcShiftWheel]; GetHIDActionState(AHIDAction, vOldState); CASE AHIDAction OF haZoom: begin vStates := vStates - FStatesUsed; end; haPan, haAdHocMarker: begin vStates := vStates - FStatesUsed - [mcShiftWheel, mcWheel]; end; END; Include(vStates, vOldState); AHIDMouseStates := vStates; end; function TPlotHIDHandler.SetHIDAction(AHIDAction: THIDAction; AHIDMouseState: THIDMouseState): Integer; begin Result := -1; // check present if (AHIDMouseState <> mcNone) and (AHIDMouseState in FStatesUsed) then exit; CASE AHIDAction OF haZoom: begin Exclude(FStatesUsed, FZoomState); FZoomState := AHIDMouseState; Result := 0; end; haPan: begin Exclude(FStatesUsed, FPanState); FPanState := AHIDMouseState; Result := 0; end; haAdHocMarker: begin Exclude(FStatesUsed, FAdHocMarkerState); FAdHocMarkerState := AHIDMouseState; Result := 0; end; END; if (Result = 0) and (AHIDMouseState <> mcNone) then Include(FStatesUsed, AHIDMouseState); end; function TPlotHIDHandler.GetHIDAction(out AHIDAction: THIDAction; AShiftState: TShiftState; AMouseButton: TMouseButton): Integer; var vPressedMouseState, vMouseState: THIDMouseState; vLoop: Integer; begin Result := 0; //writeln('GetHIDaction') ; // convert to HIDmousestate vMouseState := mcNone; vPressedMouseState := mcNone; IF AMouseButton <> mbLeft then begin AHIDAction := haNone; exit; end; //IF AShiftState <= [ssCtrl] THEN vPressedMouseState := mcCtrlMLeft else //IF AShiftState <= [ssShift] THEN vPressedMouseState := mcShiftMLeft else //IF AShiftState <= [] THEN vPressedMouseState := mcMLeft; IF [ssCtrl] <= AShiftState THEN vPressedMouseState := mcCtrlMLeft else IF [ssShift] <= AShiftState THEN vPressedMouseState := mcShiftMLeft else IF [] <= AShiftState THEN vPressedMouseState := mcMLeft; //writeln('vPressedMouseState: ', IntToStr(ord(vPressedMouseState))); // check if there is an associated HID action for vLoop := ord(haNone) to ord(haAdHocMarker) do begin GetHIDActionState(THIDAction(vLoop), vMouseState); if vMouseState = vPressedMouseState then begin Result := vLoop; break; end; end; AHIDAction := THIDAction(Result); //writeln('AHIDAction: ', IntToStr(ord(AHIDAction))); end; function TPlotHIDHandler.GetHIDAction(out AHIDAction: THIDAction; AShiftState: TShiftState; AWheelDelta: Integer): Integer; var vMouseState: THIDMouseState; vLoop: Integer; begin // we want wheel actions with and without shift, so respect both Result := 0; // convert to HIDmousestate vMouseState := mcNone; //IF AShiftState = [] THEN vPressedMouseState := mcWheel; //IF AShiftState = [ssShift] THEN vPressedMouseState := mcShiftWheel; // check if there is an associated HID action for vLoop := ord(haNone) to ord(haAdHocMarker) do begin GetHIDActionState(THIDAction(vLoop), vMouseState); if (vMouseState = mcWheel) or (vMouseState = mcShiftWheel) then begin Result := vLoop; break; end; end; AHIDAction := THIDAction(Result); end; procedure TPlotHIDHandler.GetHIDActionState(AHIDAction: THIDAction; out AHIDMouseState: THIDMouseState); begin CASE AHIDAction OF haNone: AHIDMouseState := mcNone; haZoom: AHIDMouseState := FZoomState; haPan: AHIDMouseState := FPanState; haAdHocMarker: AHIDMouseState := FAdHocMarkerState; END; end; end.
unit CrossCrypt_PasswordConfirm; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TCrossCrypt_PasswordConfirm_F = class(TForm) lblMultipleKeyMode: TLabel; rePasswords: TRichEdit; lblPasswordCount: TLabel; pbCancel: TButton; pbOK: TButton; Label2: TLabel; procedure FormShow(Sender: TObject); procedure rePasswordsChange(Sender: TObject); private FMultipleKey: boolean; FPasswords: TStringList; procedure ClearPasswords(); procedure UpdatePasswordCount(); public property MultipleKey: boolean read FMultipleKey write FMultipleKey; // Clear down the dialog's internals... procedure Wipe(); end; implementation {$R *.DFM} uses OTFECrossCrypt_DriverAPI;//for MULTIKEY_PASSWORD_REQUIREMENT procedure TCrossCrypt_PasswordConfirm_F.FormShow(Sender: TObject); begin rePasswords.Lines.Clear(); rePasswords.PlainText := TRUE; if MultipleKey then begin lblMultipleKeyMode.caption := '(Multiple key)'; rePasswords.WordWrap := FALSE; end else begin lblMultipleKeyMode.caption := '(Single key)'; rePasswords.WordWrap := TRUE; end; end; procedure TCrossCrypt_PasswordConfirm_F.ClearPasswords(); var i: integer; begin for i:=0 to (FPasswords.count-1) do begin FPasswords[i] := StringOfChar('X', length(FPasswords[i])); end; FPasswords.Clear(); end; procedure TCrossCrypt_PasswordConfirm_F.Wipe(); begin // Cleardown the internal store... ClearPasswords(); FMultipleKey := FALSE; end; procedure TCrossCrypt_PasswordConfirm_F.UpdatePasswordCount(); begin if (MultipleKey) then begin lblPasswordCount.caption := 'Passwords entered: '+inttostr(rePasswords.lines.count)+'/'+inttostr(MULTIKEY_PASSWORD_REQUIREMENT); end else begin lblPasswordCount.caption := ''; end; end; procedure TCrossCrypt_PasswordConfirm_F.rePasswordsChange(Sender: TObject); begin UpdatePasswordCount(); end; END.
{: This help file explain all the base types defined in the CADSys 4.0 library for both the 2D and 3D use. These types are defined in the CS4BaseTypes unit file that you must include in the <B=uses> clause in all of your units that use CADSys. } {$REALCOMPATIBILITY ON} unit CS4BaseTypes; interface uses Classes, Windows, Graphics; type {: To let the library to use any floating point precision value in defining the coordinates of points and so on, all floating point number used by the library is of this type. At the moment the precision is set to Single but you don't rely on this assumption when you create new kind of shapes classes or use the library. <B=Note>: I don't think that this type will change due to storage and speed efficency. } TRealType = Single; TCADActionMode = (tamNone,tamPan,tamZoom,tamZoomArea,tamRealZoom, tamSearch,tamDistance,tamReference,tamMove,tamAreaMove, tamEdit, tamAtemel, tamDelObject, tamAdd,tamIns, tamDel, tamDraw, tamLine2d, tamPolyline2d,tamClosedPolyLine2d, tamFrame2d,tamCircle2d,tamEllipse2d, tamArc2d,tamSpline2d, tamJustifiedVectText2D,tamText2d,tamRectangle2D,tamPolygon2d,tamFilledEllipse2d, tamBitmap2d); TGridLineType = (grlSolid, grlDash, grlDot, grlPoint, grlDashDot, grlClear); TObjName = string[15]; // Középpont koordináták objektuma T2DPoint = Class(TPersistent) private fx,fy : TRealType; FOnChange: TNotifyEvent; procedure Setx(Value:TRealType); procedure Sety(Value:TRealType); procedure Changed; dynamic; public constructor Create; published property OnChange: TNotifyEvent read FOnChange write FOnChange; property x:TRealType read fx write Setx; property y:TRealType read fy write Sety; end; { ID - ket azonosító objektum kigyüjtésekhez } TIndexObj = Class(TObject) private fID: LongInt; public constructor Create(ID: LongInt); property ID: LongInt read fID write fID; end; TPontrecord = record {Térkép pontok *.trk adatbázisa} reteg : byte; No : Longint; x,y,z : real; pkod : integer; {-1 = Infópont, -2 = Jelkulcs} info : longint; {Infokód v. Jelkulcskód} obj : word; {Objektum kód} jelzo : byte; end; TVonalrecord = packed record {Térkép vonalak *.lin adatbázisa} reteg : byte; x1,y1,z1 : real48; x2,y2,z2 : real48; vastag : byte; {Ha vastagság és vonaltipus = 0, akkor} tipus : word; {a réteg alapértelmezése él} obj1 : word; {Objektum kód a vonal két oldalán} obj2 : word; jelzo : byte; end; TSzovegrecord = packed record {Térkép feliratok *.szv adatbázisa} reteg : byte; x,y : real; kozsegkod : word; {Jelenleg az irányítószám} szoveg : string[20]; font : byte; {Windows font megjelölés} szeles : byte; stilus : byte; {normál,vastag,dőlt, ...} szog : word; obj : word; {Objektum kód} jelzo : byte; end; TJelkulcsRecord = record {Térkép jelkulcsok *.jlk adatbázisa} kod : word; reteg : byte; x,y : real; meret : word; {a méret szorzó 100-szorosa} szog : word; obj : word; {Objektum kód} jelzo : byte; end; TRetegRecord = packed record {Térkép rétegek *.rtg adatbázisa} retegszam : byte; retegnev : string[20]; pontszin : TColor; vonalszin : TColor; vonalvastag : word; vonalstylus : byte; szovegszin : TColor; fontnev : string[20]; fontmeret : byte; fontstylus : byte; vedett : boolean; end; TJelkulcsHeader = record jkkod : longint; jkcim : longint; jkdb : byte; {Jelkulcs rajzelemek száma} jknev : string[20]; end; TJkRecord = record kod : word; x1,y1 : integer; x2,y2 : integer; szin : TColor; vastag : byte; end; {------------ ITR adatrekordok ------------------} { *.PT file-ban} ITRPontHeader = packed record dummy : array[1..18] of char; end; ITRPontRecord = packed record {Hossza : 39} azonosito : byte; x,y,z : Longint; No : Longint; valami : Longint; pkod : Word; vonalszam : byte; reteg : byte; reteg1 : byte; a : Longint; b : Longint; dummy : array[1..5] of char; end; { *.el file-ban} ITRVonalHeader = packed record dummy : array[1..18] of char; end; ITRVonalRecord = packed record {Hossz = 44} azonosito: word; {1=élő, 0=törölt vonal} vonal1 : word; {előlről csatlakozó vonal sorszáma} valami1 : Longint; { FF 00 } vonal2 : word; {hátulról csatlakozó vonal sorszáma} valami2 : Longint; { FF FF } y1 : Longint; x1 : Longint; y2 : Longint; x2 : Longint; reteg : byte; reteg1 : byte; stylus : Array[1..8] of byte; { FF FF FF FF FF FF FF FF } sorveg : Longint; { 00 00 00 C0 } end; { *.TX file-ban} ITRTextHeader = packed record dummy : array[1..18] of char; end; ITRTextRecord = packed record {rekord hossz = 53} azonosito : byte; y1 : Longint; x1 : Longint; reteg : byte; szovtip : byte; toll : byte; dummi1 : Array[1..3] of char; szog : word; dummi2 : Array[1..4] of char; text : Array[1..11] of char; a : Longint; b : Longint; c1 : Longint; c2 : Longint; d : byte; e : Longint; end; { *.si jelkulcsadatok } ITRJelkulcsHeader = packed record dummy : array[1..18] of char; end; ITRJelkulcsRecord = packed record {rekord hossz = 21} azonosito : byte; valami : word; y,x : Longint; toll : byte; a1 : byte; reteg : byte; jkkod : byte; jkszog : word; dummy : array[1..4] of char; end; { *.lay Rétegparaméterek } ITRRetegHeader = packed record dummy : array[1..18] of char; end; ITRRetegRecord = packed record {rekord hossz = 31} reteg : byte; retegnev : Array[1..12] of char; dummy : array[1..18] of char; end; {: This type is the result information of a clipping method. The clipping functions are used internally by the library and you don't need to use them directly. The tags have the following meanings: <LI=<I=ccFirst> the clipping function has modified the first point of the segment> <LI=<I=ccSecond> the clipping function has modified the second point of the segment> <LI=<I=ccNotVisible> the segment to be clipped is not visible> <LI=<I=ccVisible> the segment to be clipped is fully visible> } TClipCode = (ccFirst, ccSecond, ccNotVisible, ccVisible); {: This type is a set of <See Type=TClipCode> tags. A clipping function may return such a set. } TClipResult = set of TClipCode; {: This type define the point position against view frustum. } TOutPos = (left, bottom, right, top, neareye, fareye); {: This type define the point position against view frustum. } TOutCode = set of TOutPos; {: This type defines a 2D point in homogeneous coordinates. All point informations in the library are in homogeneous coordinates that is they have a third coordinate W. This coordinate may be treated as divisor coefficient for the X and Y coordinates. A 2D point in the euclidean space (the normally used point) can be obtained by dividing each X and Y coordinates by W: <Code= Xe := X / W;<BR> Ye := Y / W;<BR>. > A point to be valid must have at least one of its coordinates not zero. If a point has W = 0 it is called a point at infinitum and it is not allowed in the library. Normally this kind of points is used to rapresent a direction but in the library the <See Type=TVector2D> type is used instead. } TPoint2D = record X, Y, W: TRealType; end; {: This type defines a 2D vector or direction. Use this type when you need to defines directions in the 2D space. In the case of 2D application this type may be used in defining parametric segments or to specify ortogonal segments. } TVector2D = record X, Y: TRealType; end; {: This type defines a 2D axis aligned rectangle. The rectangle is specified by two of its corners, the lower-left ones and the upper-right ones. Consider that the origin of the coordinates of the library is different from the Windows' one. Use <See Function=Rect2DToRect> and <See Function=RectToRect2D> functions to convert from the two coordinate systems. This type is useful to defines bounding boxes of shapes. } TRect2D = record case Byte of 0: (Left, Bottom, W1, Right, Top, W2: TRealType); 1: (FirstEdge, SecondEdge: TPoint2D); end; {: This type defines a 2D transformation for homogeneous points and vectors. The convention used by the library is that a matrix premultiply a point, that is: <Code=TP = M * T> where <I=TP> and <I=T> are points and <I=M> is a matrix. The matrix is specified by columns, that is <I=M[2, 1]> is the element at row 2 and column 1 and <I=M[1, 2]> is the element at row 1 anc column 2. } TTransf2D = array[1..3, 1..3] of TRealType; {: Vector of 2D points. } TVectPoints2D = array [0..0] of TPoint2D; {: Pointer to vector of 2D points. } PVectPoints2D = ^TVectPoints2D; {: This class defines a decorative pen, that is a special Window pen that can have any pattern. The pattern is defined by a string of bits like '1110001100', in which a one rapresent a colored pixel and a zero rapresent a transparent pixel. By using this pen the redrawing of the image will be slower, so use it only where necessary. Because a decorative pen is associated to a layer you can manage it better. <B=Note>: The decorative pen use LineDDA functions to draw the lines and can only be used for lines and polylines (so no ellipses are drawed using the pattern). } TDecorativePen = class(TObject) private fPStyle: TBits; fCnv: TCanvas; fCurBit: Word; fStartPt, fEndPt, fLastPt: TPoint; procedure SetBit(const Idx: Word; const B: Boolean); function GetBit(const Idx: Word): Boolean; function GetMaxBit: Word; procedure CallLineDDA; public constructor Create; destructor Destroy; override; procedure Assign(Source: TObject); procedure MoveTo(Cnv: TCanvas; X, Y: Integer); procedure MoveToNotReset(Cnv: TCanvas; X, Y: Integer); procedure LineTo(Cnv: TCanvas; X, Y: Integer); procedure TextOut(Cnv: TCanvas; X, Y: Integer; s: string); procedure Polyline(Cnv: TCanvas; Pts: Pointer; NPts: Integer); {: Specify the pattern for lines. The pattern is defined by a string of bits like '1110001100', in which a one rapresent a colored pixel and a zero rapresent a transparent pixel. By using this pen the redrawing of the image will be slower, so use it only where necessary. Because a decorative pen is associated to a layer you can manage it better. } procedure SetPenStyle(const SString: String); {: Contains the patter for lines. The pattern is defined by a string of bits like '1110001100', in which a one rapresent a colored pixel and a zero rapresent a transparent pixel. By using this pen the redrawing of the image will be slower, so use it only where necessary. Because a decorative pen is associated to a layer you can manage it better. } property PenStyle[const Idx: Word]: Boolean read GetBit write SetBit; property PatternLenght: Word read GetMaxBit; end; {: Defines an object that contains a DecorativePen and a Canvas. By using the decorative pen methods you can draw patterned lines, and by using the Canvas property you can draw using the canvas. See also <See Class=TDecorativePen> for details. } TDecorativeCanvas = class(TObject) private fDecorativePen: TDecorativePen; fCanvas: TCanvas; public constructor Create(ACanvas: TCanvas); destructor Destroy; override; procedure MoveTo(X, Y: Integer); procedure LineTo(X, Y: Integer); procedure Polyline(Points: Pointer; NPts: Integer); procedure TextOut(X, Y: Integer; s: string); property DecorativePen: TDecorativePen read fDecorativePen; property Canvas: TCanvas read fCanvas write fCanvas; end; const TWOPI = 2 * Pi; SQRT2 = 1.414213562373; {: Constant used with the picking functions. See also <See Method=TCADViewport2D@PickObject> and <See Method=TCADViewport3D@PickObject>. } PICK_NOOBJECT = -200; {: Constant used with the picking functions. See also <See Method=TCADViewport2D@PickObject> and <See Method=TCADViewport3D@PickObject>. } PICK_INBBOX = -100; {: Constant used with the picking functions. See also <See Method=TCADViewport2D@PickObject> and <See Method=TCADViewport3D@PickObject>. } PICK_ONOBJECT = -1; {: Constant used with the picking functions. See also <See Method=TCADViewport2D@PickObject> and <See Method=TCADViewport3D@PickObject>. } PICK_INOBJECT = -2; {: This is the identity matrix for 2D transformation. } IdentityTransf2D: TTransf2D = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)); {: This is the null matrix for 2D transformation. } NullTransf2D: TTransf2D = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0)); {: This is the minimum value for coordinates. } MinCoord = -1.0E8; {: This is the maximun value for coordinates. } MaxCoord = 1.0E8; const crKez1 = 19000; crKez2 = 19001; crRealZoom = 19002; crNyilUp = 19003; crNyilDown = 19004; crNyilLeft = 19005; crNyilRight= 19006; crZoomIn = 19007; crZoomOut = 19008; crKereszt = 19009; crHelp = 19100; implementation {$R StView32_Cursors.res} constructor TIndexObj.Create(ID: LongInt); begin inherited Create; fID := ID; end; { TDecorativeCanvas } constructor TDecorativeCanvas.Create(ACanvas: TCanvas); begin inherited Create; fCanvas := ACanvas; fDecorativePen := TDecorativePen.Create; end; destructor TDecorativeCanvas.Destroy; begin fDecorativePen.Free; inherited Destroy; end; procedure TDecorativeCanvas.MoveTo(X, Y: Integer); begin fDecorativePen.MoveTo(fCanvas, X, Y); end; procedure TDecorativeCanvas.LineTo(X, Y: Integer); begin fDecorativePen.LineTo(fCanvas, X, Y); end; procedure TDecorativeCanvas.Polyline(Points: Pointer; NPts: Integer); begin fDecorativePen.Polyline(fCanvas, Points, NPts); end; procedure TDecorativeCanvas.TextOut(X, Y: Integer; s: string); begin fDecorativePen.TextOut(fCanvas, x, y, s); end; { TDecorativePen } procedure LineDDAMethod1(X, Y: Integer; lpData: Pointer); stdcall; var NextBit: Integer; begin with TDecorativePen(lpData) do begin NextBit := (fCurBit + Abs(X - fLastPt.X)) mod GetMaxBit; fLastPt := Point(X, Y); if (fCurBit < GetMaxBit) and (fPStyle[fCurBit] and not fPStyle[NextBit]) then fCnv.Polyline([Point(fStartPt.X, fStartPt.Y), Point(X, Y)]) else if not fPStyle[fCurBit] then fStartPt := Point(X, Y); if (X = fEndPt.X - 1) or (X = fEndPt.X + 1) then fCnv.Polyline([Point(fStartPt.X, fStartPt.Y), Point(X, Y)]); fCurBit := NextBit; end; end; procedure LineDDAMethod2(X, Y: Integer; lpData: Pointer); stdcall; var NextBit: Integer; begin with TDecorativePen(lpData) do begin NextBit := (fCurBit + Abs(Y - fLastPt.Y)) mod GetMaxBit; fLastPt := Point(X, Y); if (fCurBit < GetMaxBit) and (fPStyle[fCurBit] and not fPStyle[NextBit]) then fCnv.Polyline([Point(fStartPt.X, fStartPt.Y), Point(X, Y)]) else if not fPStyle[fCurBit] then fStartPt := Point(X, Y); if (Y = fEndPt.Y - 1) or (Y = fEndPt.Y + 1) then fCnv.Polyline([Point(fStartPt.X, fStartPt.Y), Point(X, Y)]); fCurBit := NextBit; end end; procedure TDecorativePen.SetBit(const Idx: Word; const B: Boolean); begin fPStyle[Idx] := B; end; function TDecorativePen.GetBit(const Idx: Word): Boolean; begin Result := fPStyle[Idx]; end; function TDecorativePen.GetMaxBit: Word; begin Result := fPStyle.Size; end; procedure TDecorativePen.CallLineDDA; begin if (Abs(fEndPt.X - fStartPt.X) > Abs(fEndPt.Y - fStartPt.Y)) then LineDDA(fStartPt.X, fStartPt.Y, fEndPt.X, fEndPt.Y, @LineDDAMethod1, Integer(Self)) else LineDDA(fStartPt.X, fStartPt.Y, fEndPt.X, fEndPt.Y, @LineDDAMethod2, Integer(Self)); end; constructor TDecorativePen.Create; begin inherited; fPStyle := TBits.Create; end; destructor TDecorativePen.Destroy; begin fPStyle.Free; inherited; end; procedure TDecorativePen.Assign(Source: TObject); var Cont: Integer; begin if (Source = Self) then Exit; if Source is TDecorativePen then begin fPStyle.Size := 0; for Cont := 0 to TDecorativePen(Source).fPStyle.Size - 1 do fPStyle[Cont] := TDecorativePen(Source).fPStyle[Cont]; end; end; procedure TDecorativePen.MoveTo(Cnv: TCanvas; X, Y: Integer); begin if( fPStyle.Size > 0 ) then begin fStartPt := Point(X, Y); fEndPt := Point(X, Y); fLastPt := fStartPt; fCurBit := 0; end else Cnv.MoveTo(X, Y); end; procedure TDecorativePen.MoveToNotReset(Cnv: TCanvas; X, Y: Integer); begin if( fPStyle.Size > 0 ) then begin fStartPt := Point(X, Y); fEndPt := Point(X, Y); fLastPt := fStartPt; end else Cnv.MoveTo(X, Y); end; procedure TDecorativePen.LineTo(Cnv: TCanvas; X, Y: Integer); begin if( fPStyle.Size > 0 ) then begin fEndPt := Point(X, Y); fCnv := Cnv; CallLineDDA; fStartPt := Point(X, Y); fLastPt := fStartPt; end else Cnv.LineTo(X, Y); end; procedure TDecorativePen.TextOut(Cnv: TCanvas; X, Y: Integer; s: string); begin Cnv.Font.Name := 'MS Sans Serif'; //agl Cnv.Font.Charset := DEFAULT_CHARSET; //agl Cnv.TextOut(X, Y, s); end; procedure TDecorativePen.Polyline(Cnv: TCanvas; Pts: Pointer; NPts: Integer); type TPoints = array[0..0] of TPoint; var Cont: Integer; TmpPts: ^TPoints; begin if NPts <= 1 then Exit; TmpPts := Pts; if( fPStyle.Size > 0 ) then begin fCnv := Cnv; fCurBit := 0; fLastPt := TmpPts^[0]; for Cont := 0 to NPts - 2 do begin if Cont > 0 then fStartPt := fLastPt else fStartPt := TmpPts^[Cont]; fEndPt := TmpPts^[Cont + 1]; CallLineDDA; end; end else Windows.Polyline(Cnv.Handle, TmpPts^, NPts); end; procedure TDecorativePen.SetPenStyle(const SString: String); var Cont: Integer; begin fPStyle.Size := Length(SString); for Cont := 1 to fPStyle.Size do if SString[Cont] = '1' then SetBit(Cont - 1, True) else SetBit(Cont - 1, False); end; { ----------- T2DPoint --------- } constructor T2DPoint.Create; begin inherited Create; fx := 0; fy := 0; end; procedure T2DPoint.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure T2DPoint.Setx(Value:TRealType); begin If fx<>Value then begin Fx:=Value; Changed; end; end; procedure T2DPoint.Sety(Value:TRealType); begin If fy<>Value then begin Fy:=Value; Changed; end; end; end.
{------------------------------------------------------------------------------------} {program p038_000 exercises production #038 } {expression_list -> expression } {------------------------------------------------------------------------------------} {Author: Thomas R. Turner } {E-Mail: trturner@uco.edu } {Date: January, 2012 } {------------------------------------------------------------------------------------} {Copyright January, 2012 by Thomas R. Turner } {Do not reproduce without permission from Thomas R. Turner. } {------------------------------------------------------------------------------------} program p038_000; function max(a,b:integer):integer; begin{max} if a>b then max:=a else max:=b end{max}; procedure print(a:integer;b:integer); begin{print} writestring('The maximum of '); writeinteger(a); writestring(' and '); writeinteger(b); writestring(' is '); writeinteger(max(a,b)); writeln end{print}; begin{p038_000} print(2,3) end{p038_000}.
(*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@3@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* Unit Character *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* [2006/??/??] Helios - No author stated ================================================================================ License: (FreeBSD, plus commercial with written permission clause.) ================================================================================ Project Helios - Copyright (c) 2005-2007 All rights reserved. Please refer to Helios.dpr for full license terms. ================================================================================ Overview: ================================================================================ Class, interface, and common defaults for a "Character" are defined here. ================================================================================ Revisions: ================================================================================ (Format: [yyyy/mm/dd] <Author> - <Desc of Changes>) [2007/07/24] RaX - Created Header. *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*) unit Character; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} Types, {Project} GameObject, Being, GameConstants, LuaTypes, Inventory, Mailbox, Equipment, ChatRoom, {Third Party} IdContext, List32 ; type TCharaScriptStatus = ( SCRIPT_RUNNING, SCRIPT_NOTRUNNING, SCRIPT_YIELD_WAIT, SCRIPT_YIELD_INPUT, SCRIPT_YIELD_MENU, SCRIPT_YIELD_INSTANCEREQUEST ); (*= CLASS =====================================================================* TCharacter *------------------------------------------------------------------------------* Overview: *------------------------------------------------------------------------------* This class represents a Character. It descends from TBeing, and handles all Character specific properties not already defined and handled in TBeing. Parts of TCharacter that may look like reduplication are actually not: since we must flag when data is altered, some of the TBeing Set* methods for properties have to be overriden to properly flag when the object's state has changed, and thus, must be saved. *------------------------------------------------------------------------------* Revisions: *------------------------------------------------------------------------------* (Format: [yyyy/mm/dd] <Author> - <Description of Change>) [2007/04/28] CR - Modified Class header. Eliminated private section - all internal fields used for properties are now protected, instead. Removed GetBaseStat property method (unneeded). Altered SetBaseStat to model the changes I made in TBeing last commit. Eliminated public variables that were IDENTICAL to those in TBeing (to avoid a repeat of problems like we had with fZeny in an earlier commit). Changed ParamUP and ParamBonus so they use the ByteStatArray type like TBeing uses for ParamBase. [2007/05/28] Tsusai - Added ScriptID, to store current(/last?) script id in use [2008/06/28] Tsusai - Added eAPacketVer to hold the packetdb ea number. *=============================================================================*) TCharacter = class; //Declaration PCharacter = ^TCharacter; // Add Pointer version TCharacter = class(TBeing) protected fCharacterNumber : Byte; fStatusPts : Integer; fSkillPts : Integer; fIsMarried : Boolean; // Spre fWeight : LongWord; fMaxWeight : LongWord; fKarma : Word; fManner : Word; fPartyID : LongWord; fGuildID : LongWord; fPetID : LongWord; fHair : Word; fHairColor : Word; fClothesColor : Word; fRightHand : Word; fLeftHand : Word; fArmor : Word; fGarment : Word; fShoes : Word; fAccessory1 : Word; fAccessory2 : Word; fHeadTop : Word; fHeadMid : Word; fHeadBottom : Word; fSaveMap : String; fSaveMapPt : TPoint; fPartnerID : LongWord; fParentID1 : LongWord; fParentID2 : LongWord; fBabyID : LongWord; fOnline : Byte; fHomunID : LongWord; fDataChanged : Boolean; //For timed save procedure to activate. fTimeToSave : TDateTime; fJobName : String; //Start New info for jobchange [Spre] //fUnEquipAll : Byte; // Unequips all gears [Spre] Will be written when items are done //fUpdateOption : Byte; // Removed options from character. //Reset Look to Zero GM Command. [Spre] fResetLook : Integer; fPermanantBan : String; procedure SetSaveTime(Value : Boolean); procedure SetCharaNum(Value : Byte); procedure SetName( const Value : String );override; procedure SetJID(Value : Word); override; procedure SetBaseLV(Value : Word); override; procedure SetJobLV(Value : Word); override; procedure SetBaseEXP(Value : LongWord); override; procedure SetJobEXP(Value : LongWord); override; procedure SetBaseEXPToNextLevel(Value : LongWord); procedure SetJobEXPToNextLevel(Value : LongWord); procedure SetZeny(Value : Integer); override; procedure SetBaseStats( const Index: Byte; const Value: Integer ); override; procedure SetMaxHP(Value : LongWord); override; procedure SetHP(Value : LongWord); override; procedure SetMaxSP(Value : Word); override; procedure SetSP(Value : Word); override; procedure SetOption(Value : Word); override; procedure SetMap(Value : String); override; procedure SetPosition(Value : TPoint); override; procedure SetSpeed(Value : Word); override; procedure SetASpeed(Value : Word);override; procedure SetKarma(Value : Word); procedure SetManner(Value : Word); procedure SetPartyID(Value : LongWord); procedure SetGuildID(Value : LongWord); procedure SetPetID(Value : LongWord); procedure SetHair(Value : Word); procedure SetHairColor(Value : Word); procedure SetClothesColor(Value : Word); procedure SetRightHand(Value : Word); procedure SetLeftHand(Value : Word); procedure SetArmor(Value : Word); procedure SetGarment(Value : Word); procedure SetShoes(Value : Word); procedure SetAccessory1(Value : Word); procedure SetAccessory2(Value : Word); procedure SetHeadTop(Value : Word); procedure SetHeadMid(Value : Word); procedure SetHeadBottom(Value : Word); procedure SetStatusPts(Value : Integer); function GetMarried:boolean; // Spre procedure SetSkillPts(Value : Integer); procedure SetSMap(Value : String); procedure SetSMapPt(Value : TPoint); procedure SetPartnerID(Value : LongWord); procedure SetParentID1(Value : LongWord); procedure SetParentID2(Value : LongWord); procedure SetWeight(Value : LongWord); procedure SetMaxWeight(Value : LongWord); procedure SetPermanantBan(Value : String); procedure SetBabyID( const Value : LongWord ); procedure SetOnline( const Value : Byte ); procedure SetHomunID( const Value : LongWord ); procedure BaseLevelUp(Levels : Integer); procedure JobLevelUp(Levels : Integer); public AccountID : LongWord; DcAndKeepData : Boolean; LuaInfo : TLuaInfo; //personal lua "thread" ScriptStatus : TCharaScriptStatus; //lets us know what is going on with lua, ScriptBeing : TBeing; ClientInfo : TIdContext; ParamUP : StatArray; ParamBonus : StatArray; //Our Character's inventory Inventory : TInventory; Equipment : TEquipment; //Stat Calculations should fill these in //Maybe a record type for this crap for shared info between mobs and chars //Hell...maybe..properties? o_O AttackRange : Word; //No idea what 0..5 is from. Stats? //Commenting below, ATK + items + skills needs to be worked out before this // ATK : array[R_HAND..L_HAND] of array[0..5] of Word; // Displayed ATK power //Which packet array (since arrays start at 0) holds all the packets that are compatible. ClientVersion : Integer; //eA's Packet Version, relates toPACKET_VER in the packet_db.txt EAPACKETVER : Integer; OnTouchIDs : TIntList32; // How many friends? Friends : Byte; Mails : TMailBox; ChatRoom : TChatRoom; //It doesn't create when TCharacter create. procedure CalcMaxHP; override; procedure CalcMaxSP; override; procedure CalcSpeed; override; procedure CalcMaxWeight; procedure CalcHIT; procedure CalcFLEE; procedure CalcMATK; procedure CalcPerfectDodge; procedure CalcFalseCritical; procedure CalcCritical; procedure CalcDEF2; procedure CalcMDEF2; procedure CalcATK; procedure SendSubStat( const Mode : Word; const DataType : Word; const Value : LongWord ); procedure SendParamBaseAndBonus( const Stat : Byte; const Value : LongWord; const Bonus : LongWord ); procedure SendRequiredStatusPoint(const Stat : Byte;const Value : Byte); procedure CalculateCharacterStats; procedure SendCharacterStats(UpdateView : boolean = false); procedure ResetStats; procedure SendFriendList; procedure Death; override; procedure LoadInventory; procedure ChangeJob(JobID : Word); procedure GenerateWeight; Constructor Create(AClient : TIdContext); Destructor Destroy; override; property DataChanged : Boolean read fDataChanged write SetSaveTime; //For timed save procedure to activate. property BaseEXP : LongWord read fBaseEXP write SetBaseEXP; property JobEXP : LongWord read fJobEXP write SetJobEXP; property BaseEXPToNextLevel : LongWord read fBaseEXPToNextLevel write SetBaseEXPToNextLevel; property JobEXPToNextLevel : LongWord read fJobEXPToNextLevel write SetJobEXPToNextLevel; property Zeny : Integer read fZeny write SetZeny; property CharaNum : Byte read fCharacterNumber write SetCharaNum; property StatusPts : Integer read fStatusPts write SetStatusPts; property SkillPts : Integer read fSkillPts write SetSkillPts; property IsMarried : Boolean read GetMarried; //IsMarried Var [Spre] property Karma : Word read fKarma write SetKarma; property Manner : Word read fManner write SetManner; property PartyID : LongWord read fPartyID write SetPartyID; property GuildID : LongWord read fGuildID write SetGuildID; property PetID : LongWord read fPetID write SetPetID; property Hair : Word read fHair write SetHair; property HairColor : Word read fHairColor write SetHairColor; property ClothesColor: Word read fClothesColor write SetClothesColor; // property RightHand : Word read fRightHand write SetRightHand; // property LeftHand : Word read fLeftHand write SetLeftHand; // property Armor : Word read fArmor write SetArmor; // property Garment : Word read fGarment write SetGarment; // property Shoes : Word read fShoes write SetShoes; // property Accessory1: Word read fAccessory1 write SetAccessory1; // property Accessory2: Word read fAccessory1 write SetAccessory2; // property HeadTop : Word read fHeadTop write SetHeadTop; // property HeadMid : Word read fHeadMid write SetHeadMid; // property HeadBottom: Word read fHeadBottom write SetHeadBottom; property SaveMap : String read fSaveMap write SetSMap; property SavePoint : TPoint read fSaveMapPt write SetSMapPt; property PartnerID : LongWord read fPartnerID write SetPartnerID; property ParentID1 : LongWord read fParentID1 write SetParentID1; property ParentID2 : LongWord read fParentID2 write SetParentID2; property BabyID : LongWord read fBabyID write SetBabyID; property Online : Byte read fOnline write SetOnline; property HomunID : LongWord read fHomunID write SetHomunID; property Weight : LongWord read fWeight write SetWeight; property MaxWeight : LongWord read fMaxWeight write SetMaxWeight; property JobName : String read fJobName; // property UnEquipAll : Byte read fUnEquipAll write SetUnEquipAll; // property UpdateOption : Byte read fUpdateOption write SetUpdateOption; property PermanantBan : String read fPermanantBan write SetPermanantBan; end;{TCharacter} implementation uses {RTL/VCL} Math, SysUtils, Classes, {Project} Main, BufferIO, Globals, GameTypes, PacketTypes, LuaCoreRoutines, TCPServerRoutines, BeingList, AreaLoopEvents, ItemInstance, ZoneSend, ParameterList {Third Party} //none ; //------------------------------------------------------------------------------ //SetSaveTime PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the last time the character was saved to the database. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetSaveTime( Value : Boolean ); begin if Value and not fDataChanged then begin fDataChanged := TRUE; fTimeToSave := IncMinute(Now,5); end; end;{SetSaveTime} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetCharaNum PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the CharaNum to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetCharaNum( Value : byte ); begin DataChanged := TRUE; fCharacterNumber := Value; end;{SetCharaNum} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetName PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Name to Value. // Also, lets our object know that data has changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2006/22/06] RaX - Created Header. // [2007/04/28] CR - Changed Header, made parameter constant (efficient use of // strings). //------------------------------------------------------------------------------ procedure TCharacter.SetName( const Value : String ); Begin DataChanged := TRUE; fName := Value; end;{SetName} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetJob PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Class to Value. Also, lets our object know that data has // changed. // -- // Pre: // Inplement UpdateOption, UnEquipAll Routines. // Post: // TODO // -- // Changes - // September 25, 2008 - Spre -Updated Routine with some jobchange code. // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetJID( Value : Word ); begin DataChanged := TRUE; fJID := Value; case fJID of JOB_NOVICE : fJobName := 'Novice'; JOB_SWORDMAN : fJobName := 'Swordman'; JOB_MAGE : fJobName := 'Magician'; JOB_ARCHER : fJobName := 'Archer'; JOB_ACOLYTE : fJobName := 'Acolyte'; JOB_MERCHANT : fJobName := 'Merchant'; JOB_THIEF : fJobName := 'Thief'; JOB_KNIGHT : fJobName := 'Knight'; JOB_PRIEST : fJobName := 'Priest'; JOB_WIZARD : fJobName := 'Wizard'; JOB_BLACKSMITH : fJobName := 'Blacksmith'; JOB_HUNTER : fJobName := 'Hunter'; JOB_ASSASSIN : fJobName := 'Assassin'; JOB_CRUSADER : fJobName := 'Crusader'; JOB_MONK : fJobName := 'Monk'; JOB_SAGE : fJobName := 'Sage'; JOB_ROGUE : fJobName := 'Rogue'; JOB_ALCHEMIST : fJobName := 'Alchemist'; JOB_BARD : fJobName := 'Bard'; JOB_DANCER : fJobName := 'Dancer'; JOB_SNOVICE : fJobName := 'Super_Novice'; JOB_GUNSLINGER : fJobName := 'Gunslinger'; JOB_NINJA : fJobName := 'Ninja'; HJOB_HIGH_NOVICE : fJobName := 'High_Novice'; HJOB_HIGH_SWORDMAN : fJobName := 'High_Swordman'; HJOB_HIGH_MAGE : fJobName := 'High_Magician'; HJOB_HIGH_ARCHER : fJobName := 'High_Archer'; HJOB_HIGH_ACOLYTE : fJobName := 'High_Acolyte'; HJOB_HIGH_MERCHANT : fJobName := 'High_Merchant'; HJOB_HIGH_THIEF : fJobName := 'High_Thief'; HJOB_LORD_KNIGHT : fJobName := 'Lord_Knight'; HJOB_HIGH_PRIEST : fJobName := 'High_Priest'; HJOB_HIGH_WIZARD : fJobName := 'High_Wizard'; HJOB_WHITESMITH : fJobName := 'Whitesmith'; HJOB_SNIPER : fJobName := 'Sniper'; HJOB_ASSASSIN_CROSS : fJobName := 'Assassin_Cross'; HJOB_PALADIN : fJobName := 'Paladin'; HJOB_CHAMPION : fJobName := 'Champion'; HJOB_PROFESSOR : fJobName := 'Scholar'; HJOB_STALKER : fJobName := 'Stalker'; HJOB_CREATOR : fJobName := 'Biochemist'; HJOB_CLOWN : fJobName := 'Clown'; HJOB_GYPSY : fJobName := 'Gypsy'; HJOB_BABY : fJobName := 'Baby_Novice'; HJOB_BABY_SWORDMAN : fJobName := 'Baby_Swordman'; HJOB_BABY_MAGE : fJobName := 'Baby_Magician'; HJOB_BABY_ARCHER : fJobName := 'Baby_Archer'; HJOB_BABY_ACOLYTE : fJobName := 'Baby_Acolyte'; HJOB_BABY_MERCHANT : fJobName := 'Baby_Merchant'; HJOB_BABY_THIEF : fJobName := 'Baby_Thief'; HJOB_BABY_KNIGHT : fJobName := 'Baby_Knight'; HJOB_BABY_PRIEST : fJobName := 'Baby_Priest'; HJOB_BABY_WIZARD : fJobName := 'Baby_Wizard'; HJOB_BABY_BLACKSMITH : fJobName := 'Baby_Blacksmith'; HJOB_BABY_HUNTER : fJobName := 'Baby_Hunter'; HJOB_BABY_ASSASSIN : fJobName := 'Baby_Assassin'; HJOB_BABY_CRUSADER : fJobName := 'Baby_Crusader'; HJOB_BABY_MONK : fJobName := 'Baby_Monk'; HJOB_BABY_SAGE : fJobName := 'Baby_Sage'; HJOB_BABY_ROGUE : fJobName := 'Baby_Rogue'; HJOB_BABY_ALCHEMIST : fJobName := 'Baby_Alchemist'; HJOB_BABY_BARD : fJobName := 'Baby_Bard'; HJOB_BABY_DANCER : fJobName := 'Baby_Dancer'; HJOB_BABY_SNOVICE : fJobName := 'Baby_Super_Novice'; HJOB_EXPANDED_TAEKWON : fJobName := 'Taekwon'; HJOB_EXPANDED_STAR_GLADIATOR : fJobName := 'Star_Gladiator'; HJOB_EXPANDED_STAR_GLADIATOR_2 : fJobName := 'Star_Gladiator'; HJOB_EXPANDED_SOUL_LINKER : fJobName := 'Soul_Linker'; end; end;{SetJID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetBaseLV PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the BaseLV to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetBaseLV( Value : Word ); begin //we do not inherit here for a reason! See BaseLevelUp DataChanged := TRUE; BaseLevelUp(EnsureRange(Value-fBaseLv, -CHAR_BLEVEL_MAX, CHAR_BLEVEL_MAX)); end;{SetBaseLV} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetJobLV PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the JobLV to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // March 12th, 2007 - Aeomin - Fix Header Typo // //------------------------------------------------------------------------------ procedure TCharacter.SetJobLV( Value : Word ); begin //we do not inherit here for a reason! See JobLevelUp DataChanged := TRUE; JobLevelUp(EnsureRange(Value-fJobLv, -CHAR_JLEVEL_MAX, CHAR_JLEVEL_MAX)); end;{SetJobLV} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetBaseEXP PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the BaseEXP to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetBaseEXP( Value : LongWord ); var Index : Integer; OldBaseEXPToNextLevel: LongWord; begin Inherited; if ZoneStatus = isOnline then begin for Index := 1 to MainProc.ZoneServer.Options.MaxBaseLevelsPerEXPGain do begin if (BaseEXP > BaseEXPToNextLevel) and (BaseLv <= MainProc.ZoneServer.Options.MaxBaseLevel) then begin BaseLv := BaseLv + 1; end else begin Break; end; end; if BaseEXP > BaseEXPToNextLevel then begin OldBaseEXPToNextLevel := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetBaseEXPToNextLevel(self, BaseLv-1) div MainProc.ZoneServer.Options.BaseXPMultiplier; BaseEXP := (BaseEXPToNextLevel - OldBaseEXPToNextLevel) DIV 2 + OldBaseEXPToNextLevel; end; SendSubStat(1, $0001, BaseEXP); end; end;{SetBaseEXP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetJobEXP PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets JobEXP to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetJobEXP( Value : LongWord ); var Index : Integer; OldJobEXPToNextLevel : LongWord; begin Inherited; if ZoneStatus = isOnline then begin for Index := 1 to MainProc.ZoneServer.Options.MaxJobLevelsPerEXPGain do begin if Value > JobEXPToNextLevel then begin JobLv := JobLv + 1; end else begin Break; end; end; if (JobEXP > JobEXPToNextLevel) AND (JobLv <= MainProc.ZoneServer.Options.MaxJobLevel) then begin OldJobEXPToNextLevel := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetJobEXPToNextLevel(self, JobLv-1) div MainProc.ZoneServer.Options.JobXPMultiplier; JobEXP := (JobEXPToNextLevel - OldJobEXPToNextLevel) DIV 2 + OldJobEXPToNextLevel; end; SendSubStat(1, $0002, JobEXP); end; end;{SetJobEXP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetBaseEXPToNextLevel PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets BaseEXPToNextLevel to Value. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // July 27th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetBaseEXPToNextLevel( Value : LongWord ); begin fBaseEXPToNextLevel := Value; SendSubStat(1, $0016, BaseEXPToNextLevel); end;{SetBaseEXPToNextLevel} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetJobEXPToNextLevel PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets JobEXPToNextLevel to Value. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // July 27th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetJobEXPToNextLevel( Value : LongWord ); begin fJobEXPToNextLevel := Value; SendSubStat(1, $0017, JobEXPToNextLevel); end;{SetJobEXPToNextLevel} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetZeny PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Zeny to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // [2007/07/22] Tsusai - Added sending of update packet. // //------------------------------------------------------------------------------ procedure TCharacter.SetZeny( Value : Integer ); begin Inherited; DataChanged := TRUE; // Update Zeny SendSubStat(1, $0014, Zeny); end;{SetZeny} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetBaseStats PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets Base Stat at Index to Value. // // Passes off to the ancestor routine which does range checking via Asserts, // and then flags DataChanged for saving the Character Data when that event is // next triggered. // -- // Pre: // Index must be between STR..LUK (Checked by the inherited method) // Post: // DataChanged is True // -- // Changes - // [2006/12/22] RaX - Created Header. // [2007/04/28] CR - Altered Comment Header, improved description, noted Pre and // Post conditions. Altered parameters to match TBeing. //------------------------------------------------------------------------------ procedure TCharacter.SetBaseStats( const Index : Byte; const Value : Integer ); begin Inherited; SendParamBaseAndBonus(Index, ParamBase[Index], ParamBonus[Index]); ParamUP[Index] := 2 + (Value - 1) DIV 10; SendRequiredStatusPoint(Index, EnsureRange(ParamUP[Index], 0, High(Byte))); DataChanged := TRUE; end;{SetBaseStats} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetMaxHP PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the MaxHP to Value. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetMaxHP( Value : LongWord ); begin Inherited; SendSubStat(0, $0006, MAXHP); DataChanged := TRUE; end;{SetMaxHP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetHP PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the HP to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetHP( Value : LongWord ); begin Inherited; SendSubStat(0, $0005, HP); DataChanged := TRUE; if HP <= 0 then begin Death; end; end;{SetHP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetMaxSP PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the MaxSP to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetMaxSP( Value : word ); begin Inherited; SendSubStat(0, $0008, MAXSP); DataChanged := TRUE; end;{SetMaxSP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetName PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the SP to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetSP( Value : word ); begin Inherited; SendSubStat(0, $0007, SP); DataChanged := TRUE; end;{SetSP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetStatusPts PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the StatusPoints to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetStatusPts( Value : Integer ); begin DataChanged := TRUE; fStatusPts := EnsureRange(Value, 0, CHAR_STATPOINT_MAX); SendSubStat(0,$0009,fStatusPts); end;{SetStatusPts} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetSkillPts PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the SkillPoints to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetSkillPts( Value : Integer ); begin DataChanged := TRUE; fSkillPts := EnsureRange(Value, 0, CHAR_SKILLPOINT_MAX); SendSubStat(0,$000c,fSkillPts); end;{SetSkillPts} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetMarried FUNCTION //------------------------------------------------------------------------------ // What it does- // Checks if a Character is married or not. Used in LuaNPCCommands.pas // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 31nd, 2007 - Spre - Added cde t check IsMarried // //------------------------------------------------------------------------------ function TCharacter.GetMarried : Boolean; begin Result := (PartnerID > 0); end;{GetMarried} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetOption PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Option to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetOption( Value : word ); begin Inherited; DataChanged := TRUE; end;{SetOption} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetKarma PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Karma to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetKarma( Value : word ); begin DataChanged := TRUE; fKarma := Value; end;{SetName} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetManner PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Manner to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetManner( Value : word ); begin DataChanged := TRUE; fManner := Value; end;{SetManner} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetPartyID PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the PartyID to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetPartyID( Value : LongWord ); begin DataChanged := TRUE; fPartyID := Value; end;{SetPartyID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetGuildID PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the GuildID to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetGuildID( Value : LongWord ); begin DataChanged := TRUE; fGuildID := Value; end;{SetGuildID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetPetID PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the PetID to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetPetID( Value : LongWord ); begin DataChanged := TRUE; fPetID := Value; end;{SetPetID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetHair PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Hair to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetHair( Value : word ); begin DataChanged := TRUE; fHair := Value; end;{SetHair} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetHairColor PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the HairColor to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetHairColor( Value : word ); begin DataChanged := TRUE; fHairColor := Value; end;{SetHairColor} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetClothesColor PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the ClothesColor to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetClothesColor( Value : word ); begin DataChanged := TRUE; fClothesColor := Value; end;{SetClothesColor} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetRightHand PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Right Hand to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetRightHand( Value : word ); begin DataChanged := TRUE; fRightHand := Value; end;{SetWeapon} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetLeftHand PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Shield to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetLeftHand( Value : word ); begin DataChanged := TRUE; fLeftHand := Value; end;{SetShield} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetArmor PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Armor to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 15th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetArmor( Value : word ); begin DataChanged := TRUE; fArmor := Value; end;{SetArmor} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetGarment PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Garment to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 15th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetGarment( Value : word ); begin DataChanged := TRUE; fGarment := Value; end;{SetGarment} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetShoes PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Shoes to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 15th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetShoes( Value : word ); begin DataChanged := TRUE; fShoes := Value; end;{SetShoes} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetAccessory1 PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Accessory1 to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 15th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetAccessory1( Value : word ); begin DataChanged := TRUE; fAccessory1 := Value; end;{SetAccessory1} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetAccessory2 PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Accessory2 to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 15th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetAccessory2( Value : word ); begin DataChanged := TRUE; fAccessory2 := Value; end;{SetAccessory2} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetHeadTop PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the HeadTop to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetHeadTop( Value : word ); begin DataChanged := TRUE; fHeadTop := Value; end;{SetHeadTop} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetHeadMid PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the HeadMid to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetHeadMid( Value : word ); begin DataChanged := TRUE; fHeadMid := Value; end;{SetHeadMid} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetHeadBottom PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the HeadBottom to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetHeadBottom( Value : word ); begin DataChanged := TRUE; fHeadBottom := Value; end;{SetHeadBottom} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetMap PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Map to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetMap( Value : string ); begin Inherited; if ZoneStatus = isOnline then begin RemoveFromMap; end; DataChanged := TRUE; end;{SetMap} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetPosition PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the MapPt to Value. Also, lets our object know that data has // changed. Moves the character from the old position to the new in the map. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetPosition( Value : TPoint ); begin Inherited; DataChanged := TRUE; end;{SetMapPt} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetSpeed PROCEDURE //------------------------------------------------------------------------------ // What it does- // Update player's walking speed // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2007/11/26] Aeomin created // //------------------------------------------------------------------------------ procedure TCharacter.SetSpeed( Value : Word ); begin inherited; SendSubStat(0, 0, Value); end;{SetSpeed} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetSMap PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the SMap(SaveMap) to Value. Also, lets our object know that data // has changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetSMap( Value : string ); begin fSaveMap := Value; DataChanged := TRUE; end;{SetSMap} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetSMapPt PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the SMapPt to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetSMapPt( Value : TPoint ); begin fSaveMapPt := Value; DataChanged := TRUE; end;{SetSMapPt} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetPartnerID PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the PartnerID to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetPartnerID( Value : LongWord ); begin DataChanged := TRUE; fPartnerID := Value; end;{SetPartnerID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetParentID PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the ParentID to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetParentID1( Value : LongWord ); begin DataChanged := TRUE; fParentID1 := Value; end;{SetParentID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetParentID2 PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the ParentID2 to Value. Also, lets our object know that data has // changed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure TCharacter.SetParentID2( Value : LongWord ); begin DataChanged := TRUE; fParentID2 := Value; end;{SetParentID2} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetBabyID PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Online flag to Value, and flags DataChanged, if and only if Value // differs. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2006/12/22] RaX - Created Header. // [2007/05/06] CR - Altered routine and description, to minimize data saves. // Value parameter made constant. //------------------------------------------------------------------------------ procedure TCharacter.SetBabyID( const Value : LongWord ); begin if (Value <> fBabyID) then begin DataChanged := TRUE; fBabyID := Value; end; end;{SetBabyID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetOnline PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Online flag to Value, and flags DataChanged, if and only if Value // differs. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2006/12/22] RaX - Created Header. // [2007/05/06] CR - Altered routine and description, to minimize data saves. // Value parameter made constant. //------------------------------------------------------------------------------ procedure TCharacter.SetOnline( const Value : Byte ); begin if (Value <> fOnline) then begin DataChanged := TRUE; fOnline := Value; end; end;{SetOnline} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetWeight PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Weight // -- // Pre: // TODO // Post: // TODO // -- // Changes - // August 8th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetWeight( Value : LongWord ); var PreviousPercentage : Byte; CurrentPercentage : Byte; begin PreviousPercentage := 0; CurrentPercentage := 0; if MaxWeight > 0 then begin PreviousPercentage := Trunc((Weight / MaxWeight)*100); CurrentPercentage := Trunc((Value / MaxWeight)*100); end; // PreviousPercentage := Weight * 100 div fMaxWeight; // CurrentPercentage := Value * 100 DIV fMaxWeight; if (PreviousPercentage >= 50) AND (CurrentPercentage < 50) then begin if PreviousPercentage >= 90 then begin SendStatusIcon( Self, 36, False ); end else begin SendStatusIcon( Self, 35, False ); end; end else if (PreviousPercentage >= 50) AND (CurrentPercentage >= 50) then begin if (PreviousPercentage >= 50) AND (PreviousPercentage < 90) AND (CurrentPercentage >= 90) then begin SendStatusIcon( Self, 35, False ); SendStatusIcon( Self, 36, True ); end else if (PreviousPercentage >= 90)AND (CurrentPercentage >= 50) AND (CurrentPercentage < 90) then begin SendStatusIcon( Self, 35, True ); SendStatusIcon( Self, 36, False ); end; end else if (PreviousPercentage < 50) AND (CurrentPercentage >= 50) then begin if CurrentPercentage >= 90 then begin SendStatusIcon( Self, 36, True ); end else begin SendStatusIcon( Self, 35, True ); end; end; fWeight := Value; SendSubStat(0, $0018, Value); DataChanged := TRUE; end;{SetWeight} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetMaxWeight PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the Max Weight // -- // Pre: // TODO // Post: // TODO // -- // Changes - // August 8th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SetMaxWeight( Value : LongWord ); begin fMaxWeight := Value; SendSubStat(0, $0019, Value); DataChanged := TRUE; end;{SetMaxWeight} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetHomunID PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sets the HomunID to Value and flags DataChanged, if and only if Value is // different. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2006/12/22] RaX - Created Header. // [2007/05/06] CR - Make Set only change if the Value is different. Altered // comment header. //------------------------------------------------------------------------------ procedure TCharacter.SetHomunID( const Value : LongWord ); begin if (Value <> fHomunID) then begin DataChanged := TRUE; fHomunID := Value; end; end;{SetHomunID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcMaxHP PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's Maximum HP. // [2007/04/28] CR - This routine appears to be used as an initialization. // Repeatedly calling this routine looks like it will be wasteful. AND... // This routine IS repeatedly called. // // Nota Bene: MaxHP values do not depend on the HP the character currently // has AT ALL! // However... MaxHP DOES depend on the following properties: // JobName/JID, (via the GetBaseMaxHP call) // BaseLV, VIT // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2006/12/22] RaX - Created Header. // [2007/04/28] CR - Altered Comment Header, added further description of the // routine. Used an internal variable to simplify/shorten the span where the // Database connection is open to retrieve the BaseMaxHP value. Reindented the // formula for initializing MaxHP. Boy is it clearer to read without that long // abomination of a method name to retrieve "GetBaseMaxHP"! :P~~ //------------------------------------------------------------------------------ procedure TCharacter.CalcMaxHP; var BaseMaxHP : Word; begin if ClientInfo <> nil then begin BaseMaxHP := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetMaxHP(Self); fMaxHP := EnsureRange( ( BaseMaxHP * (100 + ParamBase[VIT]) div 100 ), 1, High(fMaxHP) ); if (HP > MaxHP) then begin fHP := MaxHP; end; end; end;{CalcMaxHP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendSubStat PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send sub stat defined by Mode(speed, Def,MDef etc...), // send party info, and Recalculate Weight // /// Parameters- // Mode: either 0 or 1, since its $00b0 or $00b1 (Its $00b0 + Mode) // [2007/03/19] CR - Should Mode be a WordBool instead, if it's only 0 or 1? // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2007/03/12] Aeomin - Added Comment Header // [2007/03/24] CR - Parameters passed are not altered, thus all parameters are // now explicitly constant. // [2007/03/24] CR - Moved first section of this routine into local procedure // Send_00b0. Moved the non-implemented blocks into local routines as well. // Made all parameters constant, which self-documents these, and makes calling // the routine more efficient. //------------------------------------------------------------------------------ Procedure TCharacter.SendSubStat( const Mode : Word; const DataType : Word; const Value : LongWord ); Var OutBuffer : TBuffer; //---------------------------------------------------------------------- //Send_00b0 LOCAL PROCEDURE //---------------------------------------------------------------------- // [2007/03/24] CR - Extracted verbatim // from main body. //---------------------------------------------------------------------- procedure Send_00b0; begin WriteBufferWord(0, $00b0 + Mode, OutBuffer); WriteBufferWord(2, DataType, OutBuffer); WriteBufferLongWord(4, Value, OutBuffer); if (Online <> 0) then begin SendBuffer( ClientInfo, OutBuffer, PacketDB.GetLength($00b0 + Mode, ClientVersion) ); end; end;{Send_00b0} //---------------------------------------------------------------------- //---------------------------------------------------------------------- //PartyInfo LOCAL PROCEDURE //---------------------------------------------------------------------- // Not yet Implemented. // -- // [2007/03/24] CR - Extracted // from main body. //---------------------------------------------------------------------- procedure PartyInfo; begin {[2007/03/24] CR - already disabled, no comment about this routine} //Party Info from prometheus { if (tc.PartyName <> '') and (Mode = 0) and ((DType = 5) or (DType = 6)) then begin WriteBufferWord( 0, $0106); WriteBufferLongWord( 2, tc.AccountID); WriteBufferWord( 6, tc.HP); WriteBufferWord( 8, tc.MAXHP); SendPCmd(tc, OutBuffer, 10, True, True); end; } end;{PartyInfo} //---------------------------------------------------------------------- //---------------------------------------------------------------------- //OverweightTest LOCAL PROCEDURE //---------------------------------------------------------------------- // Not yet Implemented. // -- // [2007/03/24] CR - Extracted // from main body. //---------------------------------------------------------------------- procedure OverweightTest; { var WeightPercent : Integer; } begin {[2007/03/24] CR - already disabled, no comment about this routine} //Party Info from prometheus { if (tc.PartyName <> '') and (Mode = 0) and ((DType = 5) or (DType = 6)) then begin WriteBufferWord( 0, $0106); WriteBufferLongWord( 2, tc.AccountID); WriteBufferWord( 6, tc.HP); WriteBufferWord( 8, tc.MAXHP); SendPCmd(tc, OutBuffer, 10, True, True); end; } end;{OverweightTest} //---------------------------------------------------------------------- begin If ZoneStatus = IsOnline then begin Send_00b0; {[2007/03/24] CR - These are "empty" - not yet implemented. } PartyInfo; OverweightTest; end; end;{SendSubStats} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalculateCharacterStats PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculate character status, but don't send 'em // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2008/10/29] Aeomin - Create // //------------------------------------------------------------------------------ procedure TCharacter.CalculateCharacterStats; begin //Calculate all stats and substats before sending CalcMaxHP; CalcMaxSP; CalcMaxWeight; CalcSpeed; CalcASpeed; CalcHIT; CalcFLEE; CalcMATK; CalcPerfectDodge; CalcFalseCritical; CalcCritical; CalcDEF2; CalcMDEF2; CalcATK; end;{CalculateCharacterStats} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendCharacterStats PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sends a character's stats to the client. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // March 12th, 2007 - Aeomin - Created Header // July 24th, 2007 - RaX - updated header // //------------------------------------------------------------------------------ procedure TCharacter.SendCharacterStats( UpdateView : boolean = false ); var idx :integer; OutBuffer : TBuffer; begin //Speed SendSubStat(0, 0, Speed); //HPSP // SendSubStat(0, 5, HP); SendSubStat(0, 6, MAXHP); // SendSubStat(0, 7, SP); SendSubStat(0, 8, MAXSP); // Update status points and points needed to level up. WriteBufferWord( 0, $00bd, OutBuffer); WriteBufferWord( 2, EnsureRange(Self.StatusPts, 0, High(SmallInt)), OutBuffer); for idx := STR to LUK do begin WriteBufferByte((idx)*2+4, EnsureRange(ParamBase[idx], 0, High(Byte)), OutBuffer); WriteBufferByte((idx)*2+5, EnsureRange(ParamUp[idx], 0, High(Byte)), OutBuffer); end; WriteBufferWord(16, ATK{[0][0]}, OutBuffer); //Taking array out until later WriteBufferWord(18, {ATK[1][0] + ATK[0][4]} 0, OutBuffer); //Taking this out until later WriteBufferWord(20, MATK2, OutBuffer); WriteBufferWord(22, MATK1, OutBuffer); WriteBufferWord(24, DEF1, OutBuffer); WriteBufferWord(26, DEF2, OutBuffer); WriteBufferWord(28, MDEF1, OutBuffer); WriteBufferWord(30, MDEF2, OutBuffer); WriteBufferWord(32, HIT, OutBuffer); WriteBufferWord(34, FLEE1, OutBuffer); WriteBufferWord(36, PerfectDodge, OutBuffer); WriteBufferWord(38, FalseCritical, OutBuffer); WriteBufferWord(40, AttackDelay DIV 2, OutBuffer); WriteBufferWord(42, 0, OutBuffer); SendBuffer(ClientInfo, OutBuffer, PacketDB.GetLength($00bd,ClientVersion)); // Update base XP SendSubStat(1, 1, BaseEXP); SendSubStat(1, $0016, BaseEXPToNextLevel); // Update job XP SendSubStat(1, 2, JobEXP); SendSubStat(1, $0017, JobEXPToNextLevel); // Update Zeny SendSubStat(1, $0014, Zeny); // Update weight SendSubStat(0, $0018, Weight); SendSubStat(0, $0019, MaxWeight); // Send status points. for idx := 0 to 5 do begin WriteBufferWord( 0, $0141, OutBuffer); WriteBufferLongWord( 2, 13+idx, OutBuffer); WriteBufferLongWord( 6, ParamBase[idx], OutBuffer); WriteBufferLongWord(10, ParamBonus[idx], OutBuffer); SendBuffer(ClientInfo, OutBuffer, PacketDB.GetLength($0141,ClientVersion)); end; // Send attack range. WriteBufferWord(0, $013a, OutBuffer); WriteBufferWord(2, AttackRange, OutBuffer); SendBuffer(ClientInfo, OutBuffer, PacketDB.GetLength($013a,ClientVersion)); // Update the character's view packets if necessary. if UpdateView then begin {tc.UpdateLook(3, tc.Head3, 0, True); tc.UpdateLook(4, tc.Head1, 0, True); tc.UpdateLook(5, tc.Head2, 0, True); if (tc.Shield > 0) then begin tc.UpdateLook(2, tc.WeaponSprite[0], tc.Shield); end else begin tc.UpdateLook(2, tc.WeaponSprite[0], tc.WeaponSprite[1]); end;} end; //To force showing values higher than 32767, These lines are to update stats //that the above packets don't handle... StatusPts := StatusPts; end;{SendCharacterStats} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendParamBaseAndBonus PROCEDURE //------------------------------------------------------------------------------ // What it does- // Sends a characters ParamBase to the client. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // August 14th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ Procedure TCharacter.SendParamBaseAndBonus( const Stat : Byte; const Value : LongWord; const Bonus : LongWord ); var OutBuffer : TBuffer; begin if zoneStatus = IsOnline then begin WriteBufferWord(0, $0141, OutBuffer); WriteBufferLongWord(2, $000000d + Stat, OutBuffer); WriteBufferLongWord(6, Value, OutBuffer); WriteBufferLongWord(10, Bonus, OutBuffer); if (Online <> 0) then begin SendBuffer( ClientInfo, OutBuffer, PacketDB.GetLength($0141, ClientVersion) ); end; end; end;{SendParamBaseAndBonus} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendRequiredStatusPoint PROCEDURE //------------------------------------------------------------------------------ // What it does- // Update stat point requirement for client // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2007/08/20] - Aeomin - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SendRequiredStatusPoint( const Stat : Byte; const Value : Byte ); var OutBuffer : TBuffer; begin if ZoneStatus = IsOnline then begin WriteBufferWord(0, $00be, OutBuffer); //Gravity's trick ^V^ WriteBufferWord(2, Stat + $0020, OutBuffer); WriteBufferByte(4, Value, OutBuffer); if (Online <> 0) then begin SendBuffer( ClientInfo, OutBuffer, PacketDB.GetLength($00be, ClientVersion) ); end; end; end;{SendRequiredStatusPoint} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcMaxSP PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's Maximum SP. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 17th, 2007 - RaX - Created. // July 24th, 2007 - RaX - Cleaned up super long calculation to make it // easier to read, also added try finally around connect/disconnect. // //------------------------------------------------------------------------------ procedure TCharacter.CalcMaxSP; begin if ClientInfo <> nil then begin fMAXSP := EnsureRange( TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetMaxSP(self) * LongWord((100 + ParamBase[INT]) div 100), 0, High(fMaxSP)); if SP > MAXSP then begin fSP := MAXSP; end; end; end;{CalcMaxSP} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcSpeed PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's Speed. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 17th, 2007 - RaX - Created. // July 24th, 2007 - RaX - Changed to use the inherited calculation first to // set the default value rather than having the default set in two places. //------------------------------------------------------------------------------ procedure TCharacter.CalcSpeed; begin inherited; end;{CalcSpeed} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcMaxWeight PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's Maximum weight. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 24th, 2007 - RaX - Created. // July 24th, 2007 - RaX - Cleaned up super long calculation to make it // easier to read, also added try finally around connect/disconnect. // September 20th, 2008 - RabidCh - Addition of ParamBonus[STR] instead of // subtraction. // //------------------------------------------------------------------------------ procedure TCharacter.CalcMaxWeight; begin if ClientInfo <> nil then begin fMaxWeight := EnsureRange( LongWord((ParamBase[STR] + ParamBonus[STR]) * 300) + TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetMaxWeight(self) , 0, High(fMaxWeight)); end; end;{CalcMaxWeight} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcHIT PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's HIT (Rate) // -- // Pre: // TODO // Post: // Status effects on HIT // -- // Changes - // September 20th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcHIT; begin HIT := EnsureRange(Word(ParamBase[DEX] + ParamBonus[DEX] + fBaseLv), 0, High(HIT)); end;{CalcHIT} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcFLEE PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's FLEE (Rate) // -- // Pre: // TODO // Post: // Status effects on FLEE // -- // Changes - // September 21th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcFLEE; begin FLEE1 := EnsureRange(Word(ParamBase[AGI] + ParamBonus[AGI] + fBaseLv), 0, High(FLEE1)); end;{CalcFLEE} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcMATK PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's Min and Max MATK // -- // Pre: // TODO // Post: // TODO // -- // Changes - // September 22th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcMATK; begin //Calculate Min MATK MATK1 := EnsureRange( Word(ParamBase[INT] + ParamBonus[INT] + Sqr( (ParamBase[INT] + ParamBonus[INT]) DIV 7 )), 0, High(MATK1) ); //Calculate Max MATK MATK2 := EnsureRange( Word(ParamBase[INT] + ParamBonus[INT] + Sqr( (ParamBase[INT] + ParamBonus[INT]) DIV 5 )), 0, High(MATK2) ); end;{CalcMATK} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcPerfectDodge PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's Perfect Dodge (Rate) // -- // Pre: // TODO // Post: // Status modifiers // -- // Changes - // September 24th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcPerfectDodge; begin PerfectDodge := EnsureRange(Byte( (((ParamBase[LUK] + ParamBonus[LUK]) div 10) + 1) ), 0, High(PerfectDodge) ); end;{CalcPerfectDodge} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcFalseCritical PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's CRIT rate in the status window which is false. // -- // Pre: // TODO // Post: // Status modifiers // -- // Changes - // September 24th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcFalseCritical; begin FalseCritical := EnsureRange(Word( ((ParamBase[LUK] + ParamBonus[LUK]) div 3) ), 0, High(FalseCritical) ); end;{CalcFalseCritical} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcCritical PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's real CRIT rate. // -- // Pre: // TODO // Post: // Status modifiers // -- // Changes - // September 30th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcCritical; begin Critical := EnsureRange(Word( 1 + ((ParamBase[LUK] + ParamBonus[LUK]) * 3 div 10) ), 0, High(Critical) ); end;{CalcCritical} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcDEF2 PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's VIT-based defense. // -- // Pre: // TODO // Post: // Skill additives and status modifiers // -- // Changes - // September 30th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcDEF2; begin DEF2 := EnsureRange(Word( ((ParamBase[VIT] + ParamBonus[VIT]) div 2) + (Max( Floor(((ParamBase[VIT] + ParamBonus[VIT]) * 3 DIV 10)), (( Sqr((ParamBase[VIT] + ParamBonus[VIT])) DIV 150) - 1) )) ), 0, High(DEF2)); end;{CalcDEF2} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcMDEF2 PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's INT-based magic defense. // -- // Pre: // TODO // Post: // Skill additives and status modifiers // -- // Changes - // September 30th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcMDEF2; begin MDEF2 := EnsureRange(Word(ParamBase[INT] + ParamBonus[INT]), 0, High(MDEF2)); end;{CalcMDEF2} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //CalcATK PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculates the character's ATK. Incomplete for now. // -- // Pre: // TODO // Post: // Actual implementation, current is just placeholder. // -- // Changes - // September 30th, 2008 - RabidCh - Created. // //------------------------------------------------------------------------------ procedure TCharacter.CalcATK; begin ATK := EnsureRange(Word( ParamBase[STR] + ParamBonus[STR] + Floor(Sqr((ParamBase[STR] + ParamBonus[STR]) div 10)) + Floor((ParamBase[DEX] + ParamBonus[DEX]) div 5) + Floor(((ParamBase[LUK] + ParamBonus[LUK]) div 5))) , 0, High(ATK)); end;{CalcATK} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //BaseLevelUp PROCEDURE //------------------------------------------------------------------------------ // What it does- // Increases the character's level and updates all changed fields. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // July 25th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.BaseLevelUp( Levels : Integer ); var TempEXP : LongWord;//Temporary BaseEXP. TempLevel : Word;//Temporary BaseLv TempStatusPts : Integer;//Temporary StatusPts ParamBaseStatPoints : Integer;//How many stat points a character's stats are worth. LastLevelStatusPoints : Integer;//The total status points for the last level in //the database. //---------------------------------------------------------------------- //GetParamBaseWorthInStatPoints LOCAL PROCEDURE //---------------------------------------------------------------------- // Gets the amount of stat points all a character's stats are worth together. //---------------------------------------------------------------------- function GetParamBaseWorthInStatPoints : Integer; var TempResult : Int64; StatIndex : Integer; StatPoints : Integer; begin TempResult := 0; For StatIndex := STR to LUK do begin For StatPoints := 2 to ParamBase[StatIndex] do begin {Here, we're figuring out how many points each stat is worth based on how high the stat is. For every 10 points we go up each stat is worth one extra point.} TempResult := TempResult + 2 + (StatPoints DIV 10); end; end; Result := EnsureRange(TempResult, 0, High(Integer)); end;{GetParamBaseWorthInStatPoints} //---------------------------------------------------------------------- begin if ZoneStatus = isOnline then begin TempLevel := Max(Min(fBaseLv+Levels, MainProc.ZoneServer.Options.MaxBaseLevel), 1); {Gets the base experience to next level, divides by the multiplier to lower numbers, prevent overflows, and prevent large integer math. Also, this is only calculated at level up rather than at each experience gain.} TempEXP := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetBaseEXPToNextLevel( self, TempLevel ); {If there is EXP to be gotten for the next level and we aren't leveling to the same level...} if (TempEXP > 0) AND(TempLevel <> BaseLv) then begin //Get stat points from database TempStatusPts := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetStatPoints(TempLevel); LastLevelStatusPoints := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetStatPoints(fBaseLv); //Get stats' worth in points. ParamBaseStatPoints := GetParamBaseWorthInStatPoints; //check if we're going up or down in level if fBaseLv < TempLevel then begin //remove stats from statpoints to get the amount of statuspts free. LastLevelStatusPoints := StatusPts + ParamBaseStatPoints - LastLevelStatusPoints; //raise stat points if we leveled. StatusPts := TempStatusPts - ParamBaseStatPoints + LastLevelStatusPoints; end else begin //remove stats from statpoints to get the amount of statuspts free. LastLevelStatusPoints := StatusPts - LastLevelStatusPoints;//-48 StatusPts := TempStatusPts+LastLevelStatusPoints+ParamBaseStatPoints; //reset stats since we deleveled. ParamBase[STR] := 1; ParamBase[AGI] := 1; ParamBase[DEX] := 1; ParamBase[VIT] := 1; ParamBase[INT] := 1; ParamBase[LUK] := 1; end; //assign our new level. fBaseLv := TempLevel; //Run stat calculations. BaseEXPToNextLevel := TempEXP DIV MainProc.ZoneServer.Options.BaseXPMultiplier; //Update character's stats SendCharacterStats; //Set hp and sp to full if enabled in the ini. if MainProc.ZoneServer.Options.FullHPOnLevelUp then begin HP := MAXHP; end; if MainProc.ZoneServer.Options.FullSPOnLevelUp then begin SP := MAXSP; end; //Send Base Level packet SendSubStat(0, $000b, BaseLv); end; end else begin fBaseLV := fBaseLV + Levels; end; end;{BaseLevelUp} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //JobLevelUp PROCEDURE //------------------------------------------------------------------------------ // What it does- // Increases the character's job level and updates all changed fields. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // July 25th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ procedure TCharacter.JobLevelUp( Levels : Integer ); var TempEXP : LongWord; TempLevel : Word; TempStatArray : StatArray; TempSkillPts: Word; Index : Integer; begin if ZoneStatus = isOnline then begin //Make sure fJobLv is in range. TempLevel := Max(Min(fJobLv+Levels, MainProc.ZoneServer.Options.MaxJobLevel), 1); //Update job experience to next level from static database. TempEXP := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetJobEXPToNextLevel(self, TempLevel); if (TempEXP > 0) AND (TempLevel <> JobLv) then begin JobEXPToNextLevel := TempEXP DIV MainProc.ZoneServer.Options.JobXPMultiplier; TempSkillPts := TThreadLink(Clientinfo.Data).DatabaseLink.CharacterConstant.GetSkillPoints(self,TempLevel); //Will be used once skills are implemented to "remember" added skill points. //OldSkillPts := TThreadLink(Clientinfo.Data).DatabaseLink.CharacterConstant.GetSkillPoints(self,JobLv); //Will be changed once skills are implemented, extra skill points will be //'remembered' between levels. if TempLevel > fJobLv then begin //if we gain a level set skill points. SkillPts := TempSkillPts; end else begin //If we delevel... //TODO reset skills here SkillPts := TempSkillPts; end; //Apply job bonuses TempStatArray := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetJobBonus(self, TempLevel); ParamBonus := TempStatArray; fJobLv := TempLevel; SendSubStat(0, $0037, JobLv); for Index := STR to DEX do begin SendParamBaseAndBonus(Index,ParamBase[Index],ParamBonus[Index]); end; end; end else begin fJobLV := fJobLV+Levels; end; end;{JobLevelUp} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ResetStats PROCEDURE //------------------------------------------------------------------------------ // What it does- // Reset character's stats // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2007/08/20] - Aeomin - Created. // [2008/09/22] - RabidCh - Added SendCharacterStats to update status window. // //------------------------------------------------------------------------------ procedure TCharacter.ResetStats; begin StatusPts := 0; StatusPts := TThreadLink(ClientInfo.Data).DatabaseLink.CharacterConstant.GetStatPoints(BaseLV); ParamBase[STR] := 1; ParamBase[AGI] := 1; ParamBase[DEX] := 1; ParamBase[VIT] := 1; ParamBase[INT] := 1; ParamBase[LUK] := 1; //Update status SendCharacterStats; end;{ResetStats} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendFriendList PROCEDURE //------------------------------------------------------------------------------ // What it does- // Send friend list to character. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2007/12/05] Aeomin - Created. // //------------------------------------------------------------------------------ procedure TCharacter.SendFriendList; var OutBuffer : TBuffer; FriendList : TBeingList; Char : TCharacter; Index : Byte; begin FriendList := TBeingList.Create(TRUE); TThreadLink(ClientInfo.Data).DatabaseLink.Friend.LoadList(FriendList, Self); if FriendList.Count > 0 then begin WriteBufferWord(0, $0201, OutBuffer); WriteBufferWord(2, 4 + ( 32 * FriendList.Count ), OutBuffer); for Index := 0 to FriendList.Count - 1 do begin Char := FriendList.Items[Index] as TCharacter; WriteBufferLongWord(4 + 32 * Index + 0, Char.AccountID, OutBuffer); WriteBufferLongWord(4 + 32 * Index + 4, Char.ID, OutBuffer); WriteBufferString(4 + 32 * Index + 8, Char.Name, NAME_LENGTH, OutBuffer); end; SendBuffer(ClientInfo, OutBuffer, 4 + ( 32 * FriendList.Count )); end; Friends := FriendList.Count; FriendList.Clear; FriendList.Free; end;{SendFriendList} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Death PROCEDURE //------------------------------------------------------------------------------ // What it does- // DIE DIE..simple // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2007/12/28] Aeomin - Created // //------------------------------------------------------------------------------ procedure TCharacter.Death; begin inherited; BeingState := BeingDead; end;{Death} //------------------------------------------------------------------------------ procedure TCharacter.SetASpeed(Value : Word); begin if ASpeed <> Value then begin inherited; if ZoneStatus = isOnline then begin SendsubStat(0, ASPD, AttackDelay DIV 2); end; end; end; //Permanant Ban procedure TCharacter.SetPermanantBan(Value : String); begin if ZoneStatus = isOnline then begin PermanantBan := Value end; end;{PermanantBan} //------------------------------------------------------------------------------ //LoadInventory PROCEDURE //------------------------------------------------------------------------------ // What it does- // Load all items in inventory // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2008/09/17] Aeomin - Created // //------------------------------------------------------------------------------ procedure TCharacter.LoadInventory; begin TThreadLink(ClientInfo.Data).DatabaseLink.Items.FillInventory( Self ); end;{LoadInventory} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ChangeJob PROCEDURE //------------------------------------------------------------------------------ // What it does- // Changes a character's job. // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2008/09/26] RaX - Created // //------------------------------------------------------------------------------ Procedure TCharacter.ChangeJob(JobID: Word); var ParameterList : TParameterList; begin if ZoneStatus = isOnline then begin ParameterList := TParameterList.Create; ParameterList.AddAsLongWord(1,JID); JID := JobId; JobLV := 1; AreaLoop(JobChange, False, ParameterList); ParameterList.Free; SendCharacterStats; //this also recalculated stats //TODO //Send skill list; end; end;{ChangeJob} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GenerateWeight PROCEDURE //------------------------------------------------------------------------------ // What it does- // Calculate total weight for items // -- // Pre: // TODO // Post: // TODO // -- // Changes - // [2008/10/01] Aeomin - Created // //------------------------------------------------------------------------------ procedure TCharacter.GenerateWeight; begin Weight := Inventory.Weight; end;{GenerateWeight} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does- // Creates our character // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 24th, 2007 - RaX - Created. // [2007/05/28] Tsusai - Sets character to standing on create. // //------------------------------------------------------------------------------ Constructor TCharacter.Create( AClient : TIdContext ); begin inherited Create; ClientInfo := AClient; fPosition := Point(-1, -1); OnTouchIDs := TIntList32.Create; Equipment := TEquipment.Create(Self); Inventory := TInventory.Create(Self,Equipment); ScriptStatus := SCRIPT_NOTRUNNING; BeingState := BeingStanding; ZoneStatus := isOffline; CharaNum := 255; Mails := TMailbox.Create(Self); end;{Create} //------------------------------------------------------------------------------ { //------------------------------------------------------------------------------ //SetSendStats PROCEDURE //------------------------------------------------------------------------------ // What it does- // Should Send stats to the server on jobchange // -- //------------------------------------------------------------------------------ procedure TCharacter.SetBaseStats( const AClient : TIdContext; ); begin end;} //Needs finished [Spre] //------------------------------------------------------------------------------ //Destroy DESTRUCTOR //------------------------------------------------------------------------------ // What it does- // Destroys our character // -- // Pre: // TODO // Post: // TODO // -- // Changes - // January 24th, 2007 - RaX - Created. // //------------------------------------------------------------------------------ Destructor TCharacter.Destroy; begin Equipment.Free; Inventory.Free; OnTouchIDs.Free; TerminateLuaThread(LuaInfo); Mails.Free; inherited; end;{Destroy} //------------------------------------------------------------------------------ end{Character}.
unit DSA.List_Stack_Queue.LinkedListQueue; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Rtti, DSA.Interfaces.DataStructure; type { TLinkedListQueue } generic TLinkedListQueue<T> = class(TInterfacedObject, specialize IQueue<T>) private type { TNode } TNode = class public Elment: T; Next: TNode; constructor Create(newE: T; newNext: TNode = nil); overload; constructor Create(); overload; function ToString: string; override; end; var __head, __tail: TNode; __size: integer; public function GetSize: integer; function IsEmpty: boolean; procedure EnQueue(e: T); function DeQueue: T; function Peek: T; constructor Create; function ToString: string; override; end; implementation { TLinkedListQueue } constructor TLinkedListQueue.Create; begin __head := nil; __tail := nil; __size := 0; end; function TLinkedListQueue.DeQueue: T; var resNode: TNode; begin if IsEmpty then raise Exception.Create('Cannot dequeue from an empty queue.'); resNode := __head; __head := __head.Next; resNode.Next := nil; if __head = nil then __tail := nil; Dec(__size); Result := resNode.Elment; FreeAndNil(resNode); end; procedure TLinkedListQueue.EnQueue(e: T); begin if __tail = nil then begin __tail := TNode.Create(e); __head := __tail; end else begin __tail.Next := TNode.Create(e); __tail := __tail.Next; end; Inc(__size); end; function TLinkedListQueue.Peek: T; begin Result := __head.Elment; end; function TLinkedListQueue.GetSize: integer; begin Result := __size; end; function TLinkedListQueue.IsEmpty: boolean; begin Result := __size = 0; end; function TLinkedListQueue.ToString: string; var res: TStringBuilder; cur: TNode; begin res := TStringBuilder.Create; try res.Append('Queue: front '); cur := __head; while cur <> nil do begin res.Append(cur.ToString + ' -> '); cur := cur.Next; end; res.Append('nil'); Result := res.ToString; finally res.Free; end; end; { TLinkedListQueue.TNode } constructor TLinkedListQueue.TNode.Create(newE: T; newNext: TNode); begin Elment := newE; Next := newNext; end; constructor TLinkedListQueue.TNode.Create; begin Self.Create(default(T)); end; function TLinkedListQueue.TNode.ToString: string; var Value: TValue; res: string; begin TValue.Make(@Elment, TypeInfo(T), Value); if not (Value.IsObject) then res := Value.ToString else res := Value.AsObject.ToString; Result := res; end; end.
unit untFuncoesServer; interface uses FireDAC.Comp.Client, unt_Conexao, System.StrUtils, Guia.Controle, JSON, system.net.httpclient, System.Classes, FMX.Maps, System.Math, FMX.StdCtrls, ACBrMail; type TResultArray = array of string; function QueryToLog(Q: TFDQuery): string; function TextoFiltrado(ATexto : String) : String; function DataAtual: TDateTime; function IndiceCalculoAvaliacao(AIdCom : Integer) : Integer; procedure LoadControleServer; procedure EnviarPush(ATokenCelular, ATitulo, AMensagem, AImagem, AAnuncio : String; ALog : TStringList); function GetDistancia(LatOrigem, LongOrigem, LatDestino, LongDestino : Double) : String; function getSqlRaio(AIdPush, ASQL : String; ARaio : Integer; AParams : String = '') : String; function ApenasNumeros(S: String): String; function ValidaEMail(const EMailIn: String): Boolean; function BoolToStrValue(AValue : Boolean) : String; function StrToBoolValue(AValue, ATrue, AFalse : String) : Boolean; procedure ConfigEmail(AACBrEmail : TACBrMail; AAssunto, ANomeFrom : String; AHtml : Boolean); implementation uses System.Types, Data.DB, System.SysUtils; var AQueryTmp : TFDQuery; LatDestino, LongDestino : Double; function StrToBoolValue(AValue, ATrue, AFalse : String) : Boolean; begin If AValue = ATrue then Result := True; If AValue = AFalse then Result := False; end; function BoolToStrValue(AValue : Boolean) : String; begin case AValue of True : Result := 'T'; False : Result := 'F'; end; end; function getValueControle(AControle : String) : String; var AQuery : TFDQuery; begin try AQuery := TFDQuery.Create(nil); AQuery.Connection := dmConexao.fdConexao; AQuery.Close; AQuery.SQL.Clear; AQuery.SQL.Add('SELECT VALOR_CONTROLE FROM ALCONTROLE'); AQuery.SQL.Add('WHERE NOME_CONTROLE = ' + QuotedStr(AControle)); AQuery.Open; finally Result := AQuery.FieldByName('VALOR_CONTROLE').AsString; AQuery.DisposeOf; end; end; procedure ConfigEmail(AACBrEmail : TACBrMail; AAssunto, ANomeFrom : String; AHtml : Boolean); begin with AACBrEmail do begin Clear; Host := getValueControle('EMAILSMTP' ); Port := getValueControle('EMAILPORTA' ); Username := getValueControle('EMAILUSUARIO'); Password := getValueControle('EMAILSENHA' ); From := getValueControle('EMAILUSUARIO'); Subject := AAssunto; SetSSL := StrToBoolValue(getValueControle('EMAIL_SSL'), '1','0'); SetTLS := StrToBoolValue(getValueControle('EMAIL_TSL'), '1','0'); ReadingConfirmation := False; UseThread := True ; IsHTML := AHtml; FromName := ANomeFrom; end; end; function ValidaEMail(const EMailIn: String): Boolean; const CaraEsp: array [1 .. 41] of string = ('!', '#', '$', '%', '¨', '&', '*', '(', ')', '+', '=', '§', '¬', '¢', '¹', '²', '³', '£', '´', '`', 'ç', 'Ç', ',', ';', ':', '<', '>', '~', '^', '?', '/', '', '|', '[', ']', '{', '}', 'º', 'ª', '°', ' '); var I, cont: Integer; EMail: String; begin EMail := EMailIn; Result := true; cont := 0; if EMail <> '' then if (Pos('@', EMail) <> 0) and (Pos('.', EMail) <> 0) then // existe @ . begin if (Pos('@', EMail) = 1) or (Pos('@', EMail) = Length(EMail)) or (Pos('.', EMail) = 1) or (Pos('.', EMail) = Length(EMail)) or (Pos(' ', EMail) <> 0) then begin Result := False; Exit; end else // @ seguido de . e vice-versa if (abs(Pos('@', EMail) - Pos('.', EMail)) = 1) then begin Result := False; Exit; end else begin for I := 1 to 40 do // se existe Caracter Especial if Pos(CaraEsp[I], EMail) <> 0 then begin Result := False; Exit; end; for I := 1 to Length(EMail) do begin // se existe apenas 1 @ if EMail[I] = '@' then cont := cont + 1; // . seguidos de . if (EMail[I] = '.') and (EMail[I + 1] = '.') then begin Result := False; Exit; end; end; // . no f, 2ou+ @, . no i, - no i, _ no i if (cont >= 2) or (EMail[Length(EMail)] = '.') or (EMail[1] = '.') or (EMail[1] = '_') or (EMail[1] = '-') then begin Result := False; Exit; end; // @ seguido de COM e vice-versa if (abs(Pos('@', EMail) - Pos('com', EMail)) = 1) then begin Result := False; Exit; end; // @ seguido de - e vice-versa if (abs(Pos('@', EMail) - Pos('-', EMail)) = 1) then begin Result := False; Exit; end; // @ seguido de _ e vice-versa if (abs(Pos('@', EMail) - Pos('_', EMail)) = 1) then begin Result := False; Exit; end; if Pos('.', EMail) = Length(EMail) then begin Result := False; Exit; end; if Pos('-', EMail) = Length(EMail) then begin Result := False; Exit; end; if Pos('_', EMail) = Length(EMail) then begin Result := False; Exit; end; if (Copy(EMail,Length(Email),1) = '.') or (Copy(EMail,Length(Email),1) = '-') or (Copy(EMail,Length(Email),1) = '_') then begin Result := False; Exit; end; end; end else Result := False; end; function ApenasNumeros(S: String): String; var vText: PChar; begin vText := PChar(S); Result := ''; while (vText^ <> #0) do begin {$IFDEF UNICODE} if CharInSet(vText^, ['0' .. '9']) then {$ELSE} if vText^ in ['0' .. '9'] then {$ENDIF} Result := Result + vText^; Inc(vText); end; end; function getPosUsuario(AIdPush : String) : TMapCoordinate; var AQueryTmpPos : TFDQuery; begin FormatSettings.DecimalSeparator := '.'; FormatSettings.ThousandSeparator := ','; Try AQueryTmpPos := TFDQuery.Create(nil); AQueryTmpPos.Connection := dmConexao.fdConexao; AQueryTmpPos.Close; AQueryTmpPos.SQL.Clear; AQueryTmpPos.Sql.Add('SELECT ULTIMALATITUDE, ULTIMALONGITUDE FROM ALCHAVESPUSH'); AQueryTmpPos.Sql.Add('WHERE KEYPUSH = ' + QuotedStr(AIdPush)); AQueryTmpPos.Open; Result.Latitude := StringReplace(AQueryTmpPos.FieldByName('ULTIMALATITUDE').AsString,',','.',[rfReplaceAll]).ToDouble; Result.Longitude := StringReplace(AQueryTmpPos.FieldByName('ULTIMALONGITUDE').AsString,',','.',[rfReplaceAll]).ToDouble; Finally AQueryTmpPos.DisposeOf; FormatSettings.DecimalSeparator := ','; FormatSettings.ThousandSeparator := '.'; End; end; function sgn(a: real): real; begin if a < 0 then sgn := -1 else sgn := 1; end; function atan2(y, x: real): real; begin if x > 0 then atan2 := arctan(y/x) else if x < 0 then atan2 := arctan(y/x) + pi else atan2 := pi/2 * sgn(y); end; function GetDistancia(LatOrigem, LongOrigem, LatDestino, LongDestino : Double) : String; var vRes,Val1, Val2, Long, Lat: Double; begin LatOrigem := LatOrigem * pi / 180.0; LongOrigem := LongOrigem * pi / 180.0; LatDestino := LatDestino * pi / 180.0; longDestino := longDestino * pi / 180.0; Lat := LatDestino - LatOrigem; Long := longDestino - LongOrigem; Val1 := 6371.0; Val2 := sin(Lat / 2) * sin(Lat / 2) + cos(LatOrigem) * cos(LatDestino) * sin(Long / 2) * sin(Long / 2); Val2 := 2 * ATan2(sqrt(Val2), sqrt(1 - Val2)); vRes := Val1 * Val2; Result := FloatToStrF(vRes,ffNumber,12,1); end; function getSqlRaio(AIdPush, ASQL : String; ARaio : Integer; AParams : String = '') : String; var //{"parametro":IDCOM,"campo":"26"} ARes : String; ADistancia : String; JSONObj : TJSONObject; S, FCampo, FValor : String; ACoordenada : TMapCoordinate; begin Try if AParams <> '' then begin JSONObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(AParams), 0) as TJSONObject; FCampo := TJSONObject(JSONObj).GetValue('campo').Value; FValor := TJSONObject(JSONObj).GetValue('parametro').Value; end; AQueryTmp := TFDQuery.Create(nil); AQueryTmp.Connection := dmConexao.fdConexao; AQueryTmp.Close; AQueryTmp.SQL.Clear; AQueryTmp.Sql.Add(ASQL); if AParams <> '' then AQueryTmp.ParamByName(FCampo).AsString := FValor; S := QueryToLog(AQueryTmp); AQueryTmp.Open; AQueryTmp.First; while not AQueryTmp.Eof do begin FormatSettings.DecimalSeparator := '.'; LatDestino := AQueryTmp.FieldByName('LATCOM' ).AsFloat; LongDestino := AQueryTmp.FieldByName('LONGCOM').AsFloat; ADistancia := GetDistancia(getPosUsuario(AIdPush).Latitude, getPosUsuario(AIdPush).Longitude, LatDestino, LongDestino); ADistancia := Copy(ADistancia, 1, Pos(',',ADistancia) - 1); if ADistancia.ToInteger <= ARaio then begin if Pos(AQueryTmp.FieldByName('IDCOM').AsString, ARes) <= 0 then begin ARes := ARes + AQueryTmp.FieldByName('IDCOM').AsString + ','; AQueryTmp.Next; end else begin AQueryTmp.Next; end; end else begin AQueryTmp.Next; end; end; if Copy(ARes, 1, Length(ARes) - 1) = '' then Result := '0' else Result := Copy(ARes, 1, Length(ARes) - 1); Finally FormatSettings.DecimalSeparator := ','; AQueryTmp.DisposeOf; End; end; procedure EnviarPush(ATokenCelular, ATitulo, AMensagem, AImagem, AAnuncio : String; ALog : TStringList); var client : THTTPClient; v_json : TJSONObject; v_jsondata : TJSONObject; v_data : TStringStream; v_response : TStringStream; url_google : string; begin try url_google := 'https://fcm.googleapis.com/fcm/send'; //-------------------------------- v_json := TJSONObject.Create; v_json.AddPair('to', ATokenCelular); v_jsondata := TJSONObject.Create; v_jsondata.AddPair('body', AMensagem); v_jsondata.AddPair('title', ATitulo); v_json.AddPair('notification', v_jsondata); v_jsondata := TJSONObject.Create; v_jsondata.AddPair('Mensagem',AMensagem); v_jsondata.AddPair('Titulo' ,ATitulo); v_jsondata.AddPair('Imagem' ,AImagem); v_jsondata.AddPair('Anuncio' ,AAnuncio); v_json.AddPair('data', v_jsondata); client := THTTPClient.Create; client.ContentType := 'application/json'; client.CustomHeaders['Authorization'] := 'key=' + ctrKEYPUSH; ALog.Add('JSON ENVIO ---------------------'); ALog.Add(v_json.ToString); ALog.Add(''); v_data := TStringStream.Create(v_json.ToString, TEncoding.UTF8); V_data.Position := 0; v_response := TStringStream.Create; client.Post(url_google, v_data, v_response); v_response.Position := 0; ALog.Add('RETORNO ---------------------'); ALog.Add(v_response.DataString); ALog.Add(''); except on e:exception do begin ALog.Add('ERRO ---------------------'); ALog.Add(e.Message); ALog.Add(''); end; end; end; procedure LoadControleServer; var SQueryTMP : TFDQuery; AMemTable : TFDMemTable; begin Try AMemTable := TFDMemTable.Create(nil); SQueryTMP := TFDQuery.Create(nil); SQueryTMP.Connection := dmConexao.fdConexao; SQueryTMP.Close; SQueryTMP.SQL.Clear; SQueryTMP.SQL.Add('SELECT * FROM ALCONTROLE'); SQueryTMP.Open; AMemTable.CopyDataSet(SQueryTMP); LoadControle(AMemTable); Finally SQueryTMP.DisposeOf; AMemTable.DisposeOf; End; end; function DataAtual: TDateTime; var fQueryTmp : TFDQuery; fTSAgora : String; begin Try fQueryTmp := TFDQuery.Create(nil); fQueryTmp.Connection := dmConexao.fdConexao; fQueryTmp.Close; fQueryTmp.SQL.Clear; fQueryTmp.SQL.Add('select current_time as hora, current_date as data from rdb$database'); fQueryTmp.Open; fTSAgora := fQueryTmp.FieldByName('data').AsString + ' ' + fQueryTmp.FieldByName('hora').AsString; Result := StrToDateTime(fTSAgora); Finally fQueryTmp.DisposeOf; End; end; function QueryToLog(Q: TFDQuery): string; var i: Integer; r: string; begin Result := Q.SQL.Text; for i := 0 to Q.Params.Count - 1 do begin case Q.Params.Items[i].DataType of ftString, ftDate, ftDateTime: r := QuotedStr(Q.Params[i].AsString); else r := Q.Params[i].AsString; end; Result := ReplaceText(Result, ':' + Q.Params.Items[i].Name, r); end; end; procedure SQLQuery(AQuery : TFDQuery; ASQL : String); begin AQuery := TFDQuery.Create(nil); AQuery.Connection := dmConexao.fdConexao; AQuery.Close; AQuery.SQL.Clear; AQuery.SQL.Text := ASql; end; function FiltroPalavras : String; var AQueryTmp : TFDQuery; begin Try AQueryTmp := TFDQuery.Create(nil); AQueryTmp.Connection := dmConexao.fdConexao; AQueryTmp.Close; AQueryTmp.SQL.Clear; AQueryTmp.SQL.Add('SELECT * FROM ALCONTROLE'); AQueryTmp.SQL.Add('WHERE NOME_CONTROLE = ' + QuotedStr('FILTROPALAVRAS')); AQueryTmp.Open; Finally Result := AQueryTmp.FieldByName('VALOR_BLOB').AsString; AQueryTmp.DisposeOf; End; end; function CountPalavras(APalavras, ASeparador : String) : Integer; var ARes : Integer; begin ARes := 0; for var i := 0 to Length(APalavras) - 1 do begin if APalavras[i] = ASeparador then ARes := ARes + 1; end; Result := ARes + 1; end; function TextoFiltrado(ATexto : String) : String; var APalavras: TStringDynArray; AFimPalavras : Boolean; AIndex : Integer; AResult : String; ATotalPalavras : Integer; begin AResult := ATexto; APalavras := SplitString(FiltroPalavras, ','); AFimPalavras := False; AIndex := 0; ATotalPalavras := CountPalavras(FiltroPalavras, ','); for AIndex := 0 to ATotalPalavras do begin if Pos(APalavras[AIndex], AResult) > 0 then AResult := StringReplace(AResult, APalavras[AIndex], '@#$',[rfReplaceAll]); end; Result := AResult; end; function IndiceCalculoAvaliacao(AIdCom : Integer) : Integer; var ASQL : String; AIndice : Integer; var AQueryTmp : TFDQuery; begin Try AQueryTmp := TFDQuery.Create(nil); AQueryTmp.Connection := dmConexao.fdConexao; AQueryTmp.Close; AQueryTmp.SQL.Clear; AQueryTmp.SQL.Add('SELECT AVALIAAMBIENTECOM, AVALIAATENDIMENTOCOM, AVALIALIMPEZACOM, AVALIALOCALCOM, AVALIAPRECOCOM FROM ALCOMERCIO'); AQueryTmp.SQL.Add('WHERE IDCOM = ' + QuotedStr(AIdCom.ToString)); AQueryTmp.Open; AIndice := 0; if AQueryTmp.FieldByName('AVALIAAMBIENTECOM' ).AsString = 'T' then AIndice := AIndice + 1; if AQueryTmp.FieldByName('AVALIAATENDIMENTOCOM').AsString = 'T' then AIndice := AIndice + 1; if AQueryTmp.FieldByName('AVALIALIMPEZACOM' ).AsString = 'T' then AIndice := AIndice + 1; if AQueryTmp.FieldByName('AVALIALOCALCOM' ).AsString = 'T' then AIndice := AIndice + 1; if AQueryTmp.FieldByName('AVALIAPRECOCOM' ).AsString = 'T' then AIndice := AIndice + 1; Result := AIndice; Finally AQueryTmp.DisposeOf; End; end; end.
unit NFSEditButton; interface uses Winapi.Messages, Winapi.Windows, System.SysUtils, System.Classes, System.Contnrs, System.UITypes, Vcl.Controls, Vcl.Forms, Vcl.Menus, Vcl.Graphics, Vcl.StdCtrls, Vcl.GraphUtil, Vcl.ImgList, Vcl.Themes, Winapi.ShellAPI, nfsCustomMaskEdit; type TNFSMaskButtonedEdit = class(TNfsCustomMaskEdit) public Images: TImageList; end; type TtbEditButton = class(TPersistent) strict private type TButtonState = (bsNormal, bsHot, bsPushed); TGlyph = class(TCustomControl) private FButton: TtbEditButton; FState: TButtonState; protected procedure Click; override; procedure CreateWnd; override; procedure Paint; override; procedure WndProc(var Message: TMessage); override; public constructor Create(AButton: TtbEditButton); reintroduce; virtual; end; protected type TButtonPosition = (bpLeft, bpRight); strict private FDisabledImageIndex: System.UITypes.TImageIndex; FDropDownMenu: TPopupMenu; FEditControl: TNFSMaskButtonedEdit; FGlyph: TGlyph; FHotImageIndex: System.UITypes.TImageIndex; FImageIndex: System.UITypes.TImageIndex; FPosition: TButtonPosition; FPressedImageIndex: System.UITypes.TImageIndex; function GetEnabled: Boolean; function GetCustomHint: TCustomHint; function GetHint: string; function GetImages: TImageList; function GetVisible: Boolean; procedure SetDisabledImageIndex(const Value: System.UITypes.TImageIndex); procedure SetEnabled(const Value: Boolean); procedure SetCustomHint(const Value: TCustomHint); procedure SetHint(const Value: string); procedure SetHotImageIndex(const Value: System.UITypes.TImageIndex); procedure SetImageIndex(const Value: System.UITypes.TImageIndex); procedure SetPressedImageIndex(const Value: System.UITypes.TImageIndex); procedure SetVisible(const Value: Boolean); protected function GetOwner: TPersistent; override; procedure UpdateBounds; dynamic; property EditControl: TNFSMaskButtonedEdit read FEditControl; property Glyph: TGlyph read FGlyph; property Images: TImageList read GetImages; property Position: TButtonPosition read FPosition; public constructor Create(EditControl: TNFSMaskButtonedEdit; APosition: TButtonPosition); reintroduce; virtual; destructor Destroy; override; published property CustomHint: TCustomHint read GetCustomHint write SetCustomHint; property DisabledImageIndex: System.UITypes.TImageIndex read FDisabledImageIndex write SetDisabledImageIndex default -1; property DropDownMenu: TPopupMenu read FDropDownMenu write FDropDownMenu; property Enabled: Boolean read GetEnabled write SetEnabled default True; property Hint: string read GetHint write SetHint; property HotImageIndex: System.UITypes.TImageIndex read FHotImageIndex write SetHotImageIndex default -1; property ImageIndex: System.UITypes.TImageIndex read FImageIndex write SetImageIndex default -1; property PressedImageIndex: System.UITypes.TImageIndex read FPressedImageIndex write SetPressedImageIndex default -1; property Visible: Boolean read GetVisible write SetVisible default False; end; implementation { TtbEditButton } uses nfsMaskButtonedEdit; constructor TtbEditButton.Create(EditControl: TNFSMaskButtonedEdit; APosition: TButtonPosition); begin inherited Create; FEditControl := EditControl; FGlyph := TGlyph.Create(Self); FHotImageIndex := -1; FImageIndex := -1; FPosition := APosition; FPressedImageIndex := -1; FDisabledImageIndex := -1; end; destructor TtbEditButton.Destroy; begin FGlyph.Parent.RemoveControl(FGlyph); FGlyph.Free; inherited; end; function TtbEditButton.GetCustomHint: TCustomHint; begin Result := FGlyph.CustomHint; end; function TtbEditButton.GetEnabled: Boolean; begin Result := FGlyph.Enabled; end; function TtbEditButton.GetHint: string; begin Result := FGlyph.Hint; end; function TtbEditButton.GetImages: TImageList; begin Result := FEditControl.Images; end; function TtbEditButton.GetOwner: TPersistent; begin Result := FEditControl; end; function TtbEditButton.GetVisible: Boolean; begin Result := FGlyph.Visible; end; procedure TtbEditButton.SetCustomHint(const Value: TCustomHint); begin if Value <> FGlyph.CustomHint then FGlyph.CustomHint := Value; end; procedure TtbEditButton.SetDisabledImageIndex(const Value: System.UITypes.TImageIndex); begin if Value <> FDisabledImageIndex then begin FDisabledImageIndex := Value; if not Enabled then FGlyph.Invalidate; end; end; procedure TtbEditButton.SetEnabled(const Value: Boolean); begin if Value <> FGlyph.Enabled then begin FGlyph.Enabled := Value; FGlyph.Invalidate; end; end; procedure TtbEditButton.SetHint(const Value: string); begin if Value <> FGlyph.Hint then FGlyph.Hint := Value; end; procedure TtbEditButton.SetHotImageIndex(const Value: System.UITypes.TImageIndex); begin if Value <> FHotImageIndex then begin FHotImageIndex := Value; if FGlyph.FState = bsHot then FGlyph.Invalidate; end; end; procedure TtbEditButton.SetImageIndex(const Value: System.UITypes.TImageIndex); begin if Value <> FImageIndex then begin FImageIndex := Value; if FGlyph.FState = bsNormal then FGlyph.Invalidate; end; end; procedure TtbEditButton.SetPressedImageIndex(const Value: System.UITypes.TImageIndex); begin if Value <> FPressedImageIndex then begin FPressedImageIndex := Value; if FGlyph.FState = bsPushed then FGlyph.Invalidate; end; end; procedure TtbEditButton.SetVisible(const Value: Boolean); begin if Value <> FGlyph.Visible then begin FGlyph.Visible := Value; FEditControl.UpdateEditMargins; end; end; procedure TtbEditButton.UpdateBounds; var EdgeSize, NewLeft: Integer; begin if FGlyph <> nil then begin if Images <> nil then begin FGlyph.Width := Images.Width; FGlyph.Height := Images.Height; end else begin FGlyph.Width := 0; FGlyph.Height := 0; end; FGlyph.Top := 0; NewLeft := FGlyph.Left; if not StyleServices.Enabled then FGlyph.Top := 1; case FPosition of bpLeft: begin if StyleServices.Enabled then NewLeft := 0 else NewLeft := 1; end; bpRight: begin NewLeft := FEditControl.Width - FGlyph.Width; if FEditControl.BorderStyle <> bsNone then Dec(NewLeft, 4); if FEditControl.BevelKind <> bkNone then begin EdgeSize := 0; if FEditControl.BevelInner <> bvNone then Inc(EdgeSize, FEditControl.BevelWidth); if FEditControl.BevelOuter <> bvNone then Inc(EdgeSize, FEditControl.BevelWidth); if beRight in FEditControl.BevelEdges then Dec(NewLeft, EdgeSize); if beLeft in FEditControl.BevelEdges then Dec(NewLeft, EdgeSize); end; if not StyleServices.Enabled then Dec(NewLeft); end; end; if (not FEditControl.Ctl3D) and (FEditControl.BorderStyle <> bsNone) then begin FGlyph.Top := 2; Inc(NewLeft, 2); end; FGlyph.Left := NewLeft; if (csDesigning in FEditControl.ComponentState) and not Visible then FGlyph.Width := 0; end; end; { TtbEditButton.TGlyph } procedure TtbEditButton.TGlyph.Click; begin if Assigned(OnClick) and (Action <> nil) and not DelegatesEqual(@OnClick, @Action.OnExecute) then OnClick(FButton.EditControl) else if not (csDesigning in ComponentState) and (ActionLink <> nil) then ActionLink.Execute(FButton.EditControl) else if Assigned(OnClick) then OnClick(FButton.EditControl); end; constructor TtbEditButton.TGlyph.Create(AButton: TtbEditButton); begin inherited Create(AButton.FEditControl); FButton := AButton; FState := bsNormal; Parent := FButton.FEditControl; Visible := False; end; procedure TtbEditButton.TGlyph.CreateWnd; begin inherited; if Visible then FButton.FEditControl.UpdateEditMargins; end; procedure TtbEditButton.TGlyph.Paint; var LIndex: Integer; begin inherited; if (FButton.Images <> nil) and Visible then begin LIndex := FButton.ImageIndex; if Enabled then begin case FState of bsHot: if FButton.HotImageIndex <> -1 then LIndex := FButton.HotImageIndex; bsPushed: if FButton.PressedImageIndex <> -1 then LIndex := FButton.PressedImageIndex; end; end else if FButton.DisabledImageIndex <> -1 then LIndex := FButton.DisabledImageIndex; if LIndex <> -1 then FButton.Images.Draw(Canvas, 0, 0, LIndex); end; end; procedure TtbEditButton.TGlyph.WndProc(var Message: TMessage); var LPoint: TPoint; begin if (Message.Msg = WM_CONTEXTMENU) and (FButton.EditControl.PopupMenu = nil) then Exit; inherited; case Message.Msg of CM_MOUSEENTER: FState := bsHot; CM_MOUSELEAVE: FState := bsNormal; WM_LBUTTONDOWN: if FButton.FDropDownMenu <> nil then begin if not (csDesigning in Parent.ComponentState) then begin LPoint := ClientToScreen(Point(0, FButton.EditControl.Height)); FButton.FDropDownMenu.Popup(LPoint.X, LPoint.Y); end; end else FState := bsPushed; WM_LBUTTONUP: FState := bsHot; CM_VISIBLECHANGED: FButton.UpdateBounds; else Exit; end; Invalidate; end; end.
unit ThListSource; interface uses Classes, ThHeaderComponent, ThNotifierList; type IThListSource = interface ['{0B9415E1-4421-46A1-992A-BDA5622899DB}'] function GetItems: TStrings; function GetNamePath: string; function GetNotifiers: TThNotifierList; property Items: TStrings read GetItems; property Name: string read GetNamePath; property Notifiers: TThNotifierList read GetNotifiers; end; // TThListSource = class(TThHeaderComponent, IThListSource) private FNotifiers: TThNotifierList; protected function GetItems: TStrings; virtual; abstract; function GetNotifiers: TThNotifierList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateItems; virtual; abstract; public property Notifiers: TThNotifierList read GetNotifiers; property Items: TStrings read GetItems; end; implementation { TThListSource } constructor TThListSource.Create(AOwner: TComponent); begin inherited; FNotifiers := TThNotifierList.Create; end; destructor TThListSource.Destroy; begin FNotifiers.Free; inherited; end; function TThListSource.GetNotifiers: TThNotifierList; begin Result := FNotifiers; end; end.
unit Grids.Helper; interface uses Classes, Windows, Graphics, SysUtils, Vcl.Grids, Vcl.DBGrids, Data.DB; type TGetParams = procedure(Index: integer; Values: TStrings) of object; TQueryDocExecute = procedure(Sender: TObject; Date: TDateTime; Name: string; GetData: TGetParams; Count: integer) of object; TQueryDocFind = function(Sender: TObject; Date: TDateTime; Param: integer): Cardinal of object; TGridFields = class; TGridField = class private FList: TGridFields; FName: string; FTitle: string; FColumn: integer; FWidth: integer; FOnChanged: TNotifyEvent; procedure SetTitle(const Value: string); procedure SetColumn(Value: integer); procedure SetWidth(Value: integer); procedure DoChanged; public property List: TGridFields read FList; property Name: string read FName; property Title: string read FTitle write SetTitle; property Column: integer read FColumn write SetColumn; property Width: integer read FWidth write SetWidth; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; end; TStringGrid = class; TGridFields = class(TList) private FGrid: TStringGrid; FOnChanged: TNotifyEvent; FDisabledControls: boolean; FChanged: boolean; protected function Get(Index: integer): TGridField; reintroduce; function GetColumn(Name: string): integer; procedure DoChanged; procedure OnFieldChanged(Sender: TObject); procedure UpdateColumn(Sender: TGridField; NewColumn: integer); public constructor Create; reintroduce; destructor Destroy; override; procedure DisableControls; procedure EnableControls; function IndexOf(Name: string): integer; reintroduce; function Find(Name: string): TGridField; function Add(Name: string; Title: string; Column: integer): TGridField; reintroduce; overload; function Add(Name: string; Title: string): TGridField; reintroduce; overload; procedure Clear; override; procedure Delete(Index: integer); reintroduce; overload; procedure Delete(Name: string); reintroduce; overload; procedure Reindex; procedure Realign; property Items[Index: integer]: TGridField read Get; default; property Column[Name: string]: integer read GetColumn; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; property Grid: TStringGrid read FGrid; end; TStringGrid = class(Vcl.Grids.TStringGrid) private FFields: TGridFields; protected procedure OnChangeField(Sender: TObject); procedure KeyDown(var Key: Word; Shift: TShiftState); override; function GetCount: integer; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetExists(ARow: integer): boolean; procedure DoDeleteRow(ARow: integer); procedure DoInsertRow(ARow: integer); function GetValue(Index: integer; ValueName: string): string; procedure GetValues(Index: integer; Values: TStrings); procedure SetValues(Index: integer; Values: TStrings); property Count: integer read GetCount; property Fields: TGridFields read FFields; procedure LoadFromFile(FileName: string); procedure SaveToFile(FileName: string); end; TDBGrid = class(Vcl.DBGrids.TDBGrid) private FOnChangeReadOnly: TNotifyEvent; function DoGetReadOnly: boolean; procedure DoSetReadOnly(const AValue: boolean); public function GetDataName: string; procedure UpdateColumnStyle; published property OnChangeReadOnly: TNotifyEvent read FOnChangeReadOnly write FOnChangeReadOnly; property ReadOnly: boolean read DoGetReadOnly write DoSetReadOnly; end; TCsv = class private FHeader: array of record Name: string; Column: integer; end; function GetValue(var source: string; var Value: string): boolean; procedure sethead(source: string); procedure setdata(Grid: Vcl.Grids.TStringGrid; row: integer; source: string); public procedure LoadFromFile(Destination: Vcl.Grids.TStringGrid; Fields: TGridFields; FileName: string); procedure SaveToFile(source: Vcl.Grids.TStringGrid; Fields: TGridFields; FileName: string); end; implementation // TGridField procedure TGridField.SetTitle(const Value: string); begin if FTitle <> Value then begin FTitle := Value; DoChanged; end; end; procedure TGridField.SetColumn(Value: integer); begin if FColumn <> Value then begin FList.UpdateColumn(Self, Value); FColumn := Value; DoChanged; end; end; procedure TGridField.SetWidth(Value: integer); begin if FWidth <> Value then begin FWidth := Value; DoChanged; end; end; procedure TGridField.DoChanged; begin if Assigned(FOnChanged) then FOnChanged(Self); end; // TGridFields constructor TGridFields.Create; begin inherited Create; FGrid := nil; FChanged := false; EnableControls; end; destructor TGridFields.Destroy; begin DisableControls; inherited Destroy; end; procedure TGridFields.DisableControls; begin FDisabledControls := true; end; procedure TGridFields.EnableControls; begin FDisabledControls := false; if FChanged then DoChanged; end; procedure TGridFields.DoChanged; begin FChanged := true; if not FDisabledControls then begin if Assigned(FOnChanged) then FOnChanged(Self); FChanged := false; end; end; procedure TGridFields.OnFieldChanged(Sender: TObject); begin DoChanged; end; procedure TGridFields.UpdateColumn(Sender: TGridField; NewColumn: integer); var Index: integer; LItem: TGridField; begin for Index := 0 to Count - 1 do begin LItem := Items[Index]; if not LItem.Equals(Sender) then begin if LItem.Column = NewColumn then begin LItem.FColumn := Sender.Column; end; end; end; end; function TGridFields.Get(Index: integer): TGridField; begin Result := TGridField(inherited Get(Index)); end; function TGridFields.GetColumn(Name: string): integer; var LItem: TGridField; begin LItem := Find(Name); if Assigned(LItem) then Result := LItem.Column else Result := -1; end; function TGridFields.Find(Name: string): TGridField; var Index: integer; begin Index := IndexOf(Name); if Index < 0 then Result := nil else Result := Items[Index]; end; function TGridFields.IndexOf(Name: string): integer; var LItem: TGridField; Index: integer; begin Result := -1; Name := AnsiLowerCase(Name); for Index := 0 to Count - 1 do begin LItem := Items[Index]; if LItem.Name = Name then begin Result := Index; exit; end; end; end; function TGridFields.Add(Name: string; Title: string; Column: integer): TGridField; begin Result := TGridField.Create; Result.FList := Self; Result.FName := AnsiLowerCase(Name); Result.FTitle := Title; Result.FColumn := Column; Result.FWidth := 0; Result.FOnChanged := OnFieldChanged; inherited Add(Result); DoChanged; end; function TGridFields.Add(Name: string; Title: string): TGridField; begin if Count > 0 then Result := Add(Name, Title, Items[Count - 1].Column + 1) else Result := Add(Name, Title, 0); end; procedure TGridFields.Clear; var Index: integer; begin for Index := 0 to Count - 1 do Items[Index].Free; inherited Clear; DoChanged; end; procedure TGridFields.Delete(Index: integer); begin Items[Index].Free; inherited Delete(Index); DoChanged; end; procedure TGridFields.Delete(Name: string); var Index: integer; begin Index := IndexOf(Name); if Index >= 0 then Delete(Index); end; procedure TGridFields.Reindex; var Index: integer; begin for Index := 0 to Count - 1 do Items[Index].Column := Index; end; procedure TGridFields.Realign; var Index, LWidth: integer; LItem: TGridField; begin if Assigned(FGrid) then for Index := 0 to Count - 1 do begin LItem := Items[Index]; LWidth := FGrid.ColWidths[LItem.Column]; if LWidth < 20 then LWidth := 20; LItem.FWidth := LWidth; end; end; // TDBGrid procedure TDBGrid.UpdateColumnStyle; const ccolor: array [boolean] of TColor = (clWindowText, clGreen); var Index: integer; Field: TField; begin for Index := 0 to Columns.Count - 1 do begin Field := Columns[Index].Field; if Assigned(Field) then begin Columns[Index].Font.Color := ccolor[Field.ReadOnly]; end; end; end; function TDBGrid.GetDataName: string; var ds: TDataSet; begin Result := ''; if Assigned(DataSource) then begin ds := DataSource.DataSet; if Assigned(ds) then if ds.Active then begin Result := ds.Name; end; end; end; function TDBGrid.DoGetReadOnly: boolean; begin Result := inherited ReadOnly; end; procedure TDBGrid.DoSetReadOnly(const AValue: boolean); begin inherited ReadOnly := AValue; if Assigned(FOnChangeReadOnly) then FOnChangeReadOnly(Self); end; // TStringGrid constructor TStringGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); FFields := TGridFields.Create; FFields.FGrid := Self; FFields.OnChanged := OnChangeField; end; destructor TStringGrid.Destroy; begin FFields.Free; inherited Destroy; end; procedure TStringGrid.OnChangeField(Sender: TObject); var Index: integer; LField: TGridField; begin ColCount := FFields.Count; for Index := 0 to FFields.Count - 1 do begin LField := FFields[Index]; if ColCount <= LField.Column then ColCount := LField.Column + 1; Cells[LField.Column, 0] := LField.Title; if LField.Width > 0 then ColWidths[LField.Column] := LField.Width; end; if ColCount > 1 then FixedCols := 1; if RowCount > 1 then FixedRows := 1; end; function TStringGrid.GetCount: integer; begin Result := 0; if RowCount = 2 then begin if GetExists(1) then Result := 1; end else if RowCount > 2 then begin Result := RowCount - 1; if not GetExists(Result) then Dec(Result); end; end; function TStringGrid.GetValue(Index: integer; ValueName: string): string; var Field: TGridField; begin Result := ''; Field := FFields.Find(ValueName); if Assigned(Field) then if (Field.Column >= 0) and (Field.Column < ColCount) then if (Index >= 0) and (Index < (RowCount - 1)) then begin Result := Trim(Cells[Field.Column, Index + 1]); end; end; procedure TStringGrid.GetValues(Index: integer; Values: TStrings); var n: integer; begin if (Index >= 0) and (Index < (RowCount - 1)) then begin Inc(Index); for n := 0 to FFields.Count - 1 do begin Values.Values[FFields[n].Name] := Trim(Cells[FFields[n].Column, Index]); end; end; end; procedure TStringGrid.SetValues(Index: integer; Values: TStrings); var n: integer; begin if (Index >= 0) and (Index < RowCount) then begin Inc(Index); if RowCount < (Index + 1) then RowCount := Index + 1; for n := 0 to FFields.Count - 1 do begin Cells[FFields[n].Column, Index] := Trim(Values.Values[FFields[n].Name]); end; end; end; procedure TStringGrid.KeyDown(var Key: Word; Shift: TShiftState); begin case Key of 40: if (Shift = []) and (row = (RowCount - 1)) then begin // Down if GetExists(RowCount - 1) then begin RowCount := RowCount + 1; Rows[RowCount - 1].Clear; row := RowCount - 1; exit; end; end; 38: if (Shift = []) and ((RowCount > 2) and (row = (RowCount - 1))) then begin // Up if not GetExists(RowCount - 1) then begin RowCount := RowCount - 1; row := RowCount - 1; exit; end; end; 46: if (Shift = [ssCtrl]) and (row > 0) then begin // Del DoDeleteRow(row); end; 45: if (Shift = [ssCtrl]) and (row > 0) then begin // Insert DoInsertRow(row); end; end; inherited KeyDown(Key, Shift); end; function TStringGrid.GetExists(ARow: integer): boolean; begin Result := false; if pos(#13#10, Trim(Rows[RowCount - 1].Text)) > 0 then begin Result := true; end; end; procedure TStringGrid.DoDeleteRow(ARow: integer); var n: integer; begin if (ARow = 1) and (RowCount = 2) then begin Rows[1].Clear; end else if (ARow > 0) and (RowCount > 2) then begin if (ARow < (RowCount - 1)) then for n := ARow to RowCount - 2 do begin Rows[n].Assign(Rows[n + 1]); end; RowCount := RowCount - 1; end; end; procedure TStringGrid.DoInsertRow(ARow: integer); var n: integer; begin if (ARow > 0) then if GetExists(ARow) then begin RowCount := RowCount + 1; for n := RowCount - 1 downto ARow + 1 do begin Rows[n].Assign(Rows[n - 1]); end; Rows[ARow].Clear; end; end; procedure TStringGrid.LoadFromFile(FileName: string); var f: TCsv; begin f := TCsv.Create; try f.LoadFromFile(Self, FFields, FileName); finally f.Free; end; end; procedure TStringGrid.SaveToFile(FileName: string); var f: TCsv; begin f := TCsv.Create; try f.SaveToFile(Self, FFields, FileName); finally f.Free; end; end; // TCsv function TCsv.GetValue(var source: string; var Value: string): boolean; var j: integer; begin j := pos(';', source); if j > 0 then begin Value := Trim(copy(source, 1, j - 1)); source := copy(source, j + 1); Result := true; end else begin Value := Trim(source); source := ''; Result := Value <> ''; end; end; procedure TCsv.sethead(source: string); var buff: string; n: integer; begin SetLength(FHeader, 0); while source <> '' do begin if GetValue(source, buff) then begin n := Length(FHeader); SetLength(FHeader, n + 1); FHeader[n].Name := buff; FHeader[n].Column := -1; end; end; end; procedure TCsv.setdata(Grid: Vcl.Grids.TStringGrid; row: integer; source: string); var lcol: integer; buff: string; begin lcol := 0; if Grid.RowCount <= row then Grid.RowCount := row + 1; Grid.Rows[row].Clear; while (lcol < Length(FHeader)) and (source <> '') do begin if GetValue(source, buff) then begin with FHeader[lcol] do if Column >= 0 then Grid.Cells[Column, row] := buff; end; Inc(lcol); end; end; procedure TCsv.LoadFromFile(Destination: Vcl.Grids.TStringGrid; Fields: TGridFields; FileName: string); var f: TextFile; buff: string; row: integer; begin AssignFile(f, FileName); Reset(f); try if not eof(f) then begin ReadLn(f, buff); sethead(buff); for row := 0 to Length(FHeader) - 1 do FHeader[row].Column := Fields.IndexOf(FHeader[row].Name); row := 0; while not eof(f) do begin ReadLn(f, buff); Inc(row); setdata(Destination, row, buff); end; end; finally CloseFile(f); end; end; procedure TCsv.SaveToFile(source: Vcl.Grids.TStringGrid; Fields: TGridFields; FileName: string); var f: TextFile; lrow: integer; n: integer; fld: TGridField; begin AssignFile(f, FileName); Rewrite(f); try for n := 0 to Fields.Count - 1 do begin fld := Fields[n]; Write(f, fld.Name + ';'); end; WriteLn(f, ''); for lrow := 1 to source.RowCount - 1 do begin for n := 0 to Fields.Count - 1 do begin fld := Fields[n]; Write(f, source.Cells[fld.Column, lrow] + ';'); end; WriteLn(f, ''); end; finally CloseFile(f); end; end; end.
{ A sample that shows how to perform a runtime language switch. The sample also show how to use extensions to enable language switch for untrivial data types such as image, tree views, and list view. } unit Unit1; interface uses Classes, Graphics, StdCtrls, Controls, ComCtrls, ExtCtrls, Forms, pngimage; type TForm1 = class(TForm) Label1: TLabel; TreeView1: TTreeView; Label2: TLabel; ListView1: TListView; ListBox1: TListBox; Image1: TImage; LanguageButton: TButton; procedure FormShow(Sender: TObject); procedure LanguageButtonClick(Sender: TObject); private procedure UpdateItems; end; var Form1: TForm1; implementation {$R *.dfm} uses NtBase, NtPictureTranslator, // Enables runtime language switch of TImage.Picture NtListViewTranslator, // Enables runtime language switch of TListView NtTreeViewTranslator, // Enables runtime language switch of TTreeView NtLanguageDlg; // This procedure initializes the properties that are set on run time procedure TForm1.UpdateItems; resourcestring SSample = 'This is another sample'; begin Label2.Caption := SSample; end; procedure TForm1.FormShow(Sender: TObject); begin // Set the properties for first time UpdateItems; end; procedure TForm1.LanguageButtonClick(Sender: TObject); begin // Show a language select dialog and turn on the selected language if TNtLanguageDialog.Select('en', '', lnBoth, [], [], poMainFormCenter, lcUpper) then begin // Language has been changed. // Properties that were set on run time must be reset. UpdateItems; end; end; initialization //ReportMemoryLeaksOnShutdown := True; end.
unit Myloo.Comp.Coll.Utils; interface uses Generics.Collections; type TArraySliceForEach<t> = reference to procedure ( const Index: Integer; const Value: T; var ABreak: Boolean); TArraySlice<t> = record private FArray: TArray<t>; FOffset: Integer; FCount: Integer; FOriginalLength: Integer; private function GetRealIndex(const Value: Integer): Integer; function GetItem(Index: Integer): T; procedure SetItem(Index: Integer; const Value: T); public /// /// returns low bound /// function Low: Integer; /// /// returns high bound /// function High: Integer; /// /// returns true if the array size has changed since slice was initialized /// function ArraySizeChanged: Boolean; /// /// returns a reference to the MAIN array /// function GetMainArray: TArray<t>; /// /// resturns a NEW array based on slice information /// function ToArray: TArray<t>; /// /// initializes the slice /// procedure SliceArray(const Value: TArray<t>; const AtIndex, ACount: Integer); /// /// loop through all elements of the slice /// procedure ForEach(Callback: TArraySliceForEach<t>); /// /// loop through all elements of main array /// procedure ForEachAll(Callback: TArraySliceForEach<t>); public /// /// returns number of elements in array /// property Count: Integer read FCount; /// /// get or set array item /// property Item[Index: Integer]: T read GetItem write SetItem; default; end; implementation uses SysUtils,Classes; { TArraySlice<t> } function TArraySlice<t>.ArraySizeChanged: Boolean; begin Result := FOriginalLength <> Length(FArray); end; procedure TArraySlice<t>.ForEach(Callback: TArraySliceForEach<t>); var Index: Integer; LBreak: Boolean; begin LBreak := False; for Index := Low to High do begin Callback(Index, Item[Index], LBreak); if LBreak then Break; end; end; procedure TArraySlice<t>.ForEachAll(Callback: TArraySliceForEach<t>); var Index: Integer; LBreak: Boolean; begin LBreak := False; for Index := 0 to Length(FArray) -1 do begin Callback(Index, FArray[Index], LBreak); if LBreak then Break; end; end; function TArraySlice<t>.GetMainArray: TArray<t>; begin Result := FArray; end; function TArraySlice<t>.ToArray: TArray<t>; begin Result := Copy(FArray, FOffset, FCount); end; function TArraySlice<t>.GetItem(Index: Integer): T; var LIndex: Integer; begin LIndex := GetRealIndex(Index); Result := FArray[LIndex]; end; function TArraySlice<t>.GetRealIndex(const Value: Integer): Integer; begin if (Value < Low) or (Value > High) then raise Exception.CreateFmt('TArraySlice: Index(%d) Out Of Bounds!', [Value]); Result := FOffset + Value; end; function TArraySlice<t>.High: Integer; begin Result := Count -1; end; function TArraySlice<t>.Low: Integer; begin Result := 0; end; procedure TArraySlice<t>.SetItem(Index: Integer; const Value: T); var LIndex: Integer; begin LIndex := GetRealIndex(Index); FArray[LIndex] := Value; end; procedure TArraySlice<t>.SliceArray(const Value: TArray<t>; const AtIndex, ACount: Integer); begin FArray := Value; FCount := ACount; FOffset := AtIndex; FOriginalLength := Length(Value); end; end.
unit ibSHSQLEditorActions; interface uses SysUtils, Classes, Dialogs, Menus, SHDesignIntf, ibSHDesignIntf; type TibSHSQLEditorPaletteAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHSQLEditorFormAction = class(TSHAction) private function GetCallString: string; function GetComponentFormClass: TSHComponentFormClass; public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; property CallString: string read GetCallString; property ComponentFormClass: TSHComponentFormClass read GetComponentFormClass; end; TibSHSQLEditorToolbarAction_ = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHSQLEditorEditorAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; // Forms TibSHSQLEditorFormAction_SQLText = class(TibSHSQLEditorFormAction) end; TibSHSQLEditorFormAction_QueryResults = class(TibSHSQLEditorFormAction) end; TibSHSQLEditorFormAction_BlobEditor = class(TibSHSQLEditorFormAction) end; TibSHSQLEditorFormAction_DataForm = class(TibSHSQLEditorFormAction) end; TibSHSQLEditorFormAction_QueryStatistics = class(TibSHSQLEditorFormAction) end; TibSHSQLEditorFormAction_DDLText = class(TibSHSQLEditorFormAction) end; //Toolbar TibSHSQLEditorToolbarAction_PrevQuery = class(TibSHSQLEditorToolbarAction_) end; TibSHSQLEditorToolbarAction_NextQuery = class(TibSHSQLEditorToolbarAction_) end; TibSHSQLEditorToolbarAction_Run = class(TibSHSQLEditorToolbarAction_) end; TibSHSQLEditorToolbarAction_RunAndFetchAll = class(TibSHSQLEditorToolbarAction_) end; TibSHSQLEditorToolbarAction_Prepare = class(TibSHSQLEditorToolbarAction_) end; TibSHSQLEditorToolbarAction_EndTransactionSeparator = class(TibSHSQLEditorToolbarAction_) end; TibSHSQLEditorToolbarAction_Commit = class(TibSHSQLEditorToolbarAction_) end; TibSHSQLEditorToolbarAction_Rollback = class(TibSHSQLEditorToolbarAction_) end; //Editors TibSHSQLEditorEditorAction_LoadLastContext = class(TibSHSQLEditorEditorAction) end; TibSHSQLEditorEditorAction_RecordCount = class(TibSHSQLEditorEditorAction) end; TibSHSQLEditorEditorAction_CreateNew = class(TibSHSQLEditorEditorAction) end; implementation uses ibSHConsts, ibSHDDLFrm, ibSHDataGridFrm, ibSHDataBlobFrm, ibSHDataVCLFrm, ibSHSQLEditorFrm, ibSHStatisticsFrm; { TibSHSQLEditorPaletteAction } constructor TibSHSQLEditorPaletteAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallPalette; Category := Format('%s', ['Tools']); Caption := Format('%s', ['SQL Editor']); ShortCut := TextToShortCut('Shift+Ctrl+F9'); end; function TibSHSQLEditorPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID); end; procedure TibSHSQLEditorPaletteAction.EventExecute(Sender: TObject); begin Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHSQLEditor, EmptyStr); end; procedure TibSHSQLEditorPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHSQLEditorPaletteAction.EventUpdate(Sender: TObject); begin Enabled := Assigned(Designer.CurrentDatabase) and (Designer.CurrentDatabase as ISHRegistration).Connected and SupportComponent(Designer.CurrentDatabase.BranchIID); end; { TibSHSQLEditorFormAction } constructor TibSHSQLEditorFormAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallForm; Caption := '-'; // separator Caption := CallString; SHRegisterComponentForm(IibSHSQLEditor, CallString, ComponentFormClass); end; function TibSHSQLEditorFormAction.GetCallString: string; begin Result := EmptyStr; if Self is TibSHSQLEditorFormAction_SQLText then Result := SCallSQLText else if Self is TibSHSQLEditorFormAction_QueryResults then Result := SCallQueryResults else if Self is TibSHSQLEditorFormAction_BlobEditor then Result := SCallDataBLOB else if Self is TibSHSQLEditorFormAction_DataForm then Result := SCallDataForm else if Self is TibSHSQLEditorFormAction_QueryStatistics then Result := SCallQueryStatistics else if Self is TibSHSQLEditorFormAction_DDLText then Result := SCallDDLText; end; function TibSHSQLEditorFormAction.GetComponentFormClass: TSHComponentFormClass; begin Result := nil; if AnsiSameText(CallString, SCallSQLText) then Result := TibSHSQLEditorForm else if AnsiSameText(CallString, SCallQueryResults) then Result := TibSHDataGridForm else if AnsiSameText(CallString, SCallDataBLOB) then Result := TibSHDataBlobForm else if AnsiSameText(CallString, SCallDataForm) then Result := TibSHDataVCLForm else if AnsiSameText(CallString, SCallQueryStatistics) then Result := TibBTStatisticsForm else if AnsiSameText(CallString, SCallDDLText) then Result := TibBTDDLForm; end; function TibSHSQLEditorFormAction.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHSQLEditor); end; procedure TibSHSQLEditorFormAction.EventExecute(Sender: TObject); begin Designer.ChangeNotification(Designer.CurrentComponent, CallString, opInsert); end; procedure TibSHSQLEditorFormAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHSQLEditorFormAction.EventUpdate(Sender: TObject); begin FDefault := Assigned(Designer.CurrentComponentForm) and AnsiSameText(CallString, Designer.CurrentComponentForm.CallString); end; { TibSHSQLEditorToolbarAction_ } constructor TibSHSQLEditorToolbarAction_.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallToolbar; Caption := '-'; if Self is TibSHSQLEditorToolbarAction_PrevQuery then Tag := 1; if Self is TibSHSQLEditorToolbarAction_NextQuery then Tag := 2; if Self is TibSHSQLEditorToolbarAction_Run then Tag := 3; if Self is TibSHSQLEditorToolbarAction_RunAndFetchAll then Tag := 4; if Self is TibSHSQLEditorToolbarAction_Prepare then Tag := 5; if Self is TibSHSQLEditorToolbarAction_EndTransactionSeparator then Tag := 6; if Self is TibSHSQLEditorToolbarAction_Commit then Tag := 7; if Self is TibSHSQLEditorToolbarAction_Rollback then Tag := 8; case Tag of 1: Caption := Format('%s', ['Previous Query']); 2: Caption := Format('%s', ['Next Query']); 3: begin Caption := Format('%s', ['Run']); ShortCut := TextToShortCut('F9'); // Buzz Ctrl+Enter задействован на клавиатурный переход по линку // SecondaryShortCuts.Add('F9'); end; 4: Caption := Format('%s', ['Run and Fetch All']); 5: begin Caption := Format('%s', ['Prepare']); ShortCut := TextToShortCut('Ctrl+F9'); end; 6: ; 7: begin Caption := Format('%s', ['Commit']); ShortCut := TextToShortCut('Shift+Ctrl+C'); end; 8: begin Caption := Format('%s', ['Rollback']); ShortCut := TextToShortCut('Shift+Ctrl+R'); end; end; if Tag <> 0 then Hint := Caption; end; function TibSHSQLEditorToolbarAction_.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHSQLEditor); end; procedure TibSHSQLEditorToolbarAction_.EventExecute(Sender: TObject); begin if Supports(Designer.CurrentComponentForm, IibSHSQLEditorForm) then case Tag of // PrevQuery 1: (Designer.CurrentComponentForm as IibSHSQLEditorForm).PreviousQuery; // NextQuery 2: (Designer.CurrentComponentForm as IibSHSQLEditorForm).NextQuery; // Run 3: (Designer.CurrentComponentForm as ISHRunCommands).Run; // RunAndFetchAll 4: (Designer.CurrentComponentForm as IibSHSQLEditorForm).RunAndFetchAll; // Prepare 5: (Designer.CurrentComponentForm as IibSHSQLEditorForm).Prepare; // CommitRollbackSeparator 6: ; // Commit 7: (Designer.CurrentComponentForm as ISHRunCommands).Commit; // Rollback 8: (Designer.CurrentComponentForm as ISHRunCommands).Rollback; end; end; procedure TibSHSQLEditorToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHSQLEditorToolbarAction_.EventUpdate(Sender: TObject); begin if Assigned(Designer.CurrentComponentForm) and AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSQLText) and Supports(Designer.CurrentComponentForm, IibSHSQLEditorForm) then begin case Tag of // Separator 0: begin Visible := True; end; // PrevQuery 1: begin Visible := True; Enabled := (Designer.CurrentComponentForm as IibSHSQLEditorForm).GetCanPreviousQuery; end; // NextQuery 2: begin Visible := True; Enabled := (Designer.CurrentComponentForm as IibSHSQLEditorForm).GetCanNextQuery; end; // Run 3: begin Visible := True; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).GetCanRun; end; // RunAndFetchAll 4: begin Visible := True; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).GetCanRun; end; // Prepare 5: begin Visible := True; Enabled := (Designer.CurrentComponentForm as IibSHSQLEditorForm).GetCanPrepare; end; // CommitRollbackSeparator 6: begin Visible := (Designer.CurrentComponentForm as IibSHSQLEditorForm).GetCanEndTransaction; end; // Commit 7: begin Visible := (Designer.CurrentComponentForm as IibSHSQLEditorForm).GetCanEndTransaction; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).GetCanCommit; end; // Rollback 8: begin Visible := (Designer.CurrentComponentForm as IibSHSQLEditorForm).GetCanEndTransaction; Enabled := (Designer.CurrentComponentForm as ISHRunCommands).GetCanRollback; end; end; end else Visible := False; end; { TibSHSQLEditorEditorAction } constructor TibSHSQLEditorEditorAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallEditor; if Self is TibSHSQLEditorEditorAction_LoadLastContext then Tag := 1; if Self is TibSHSQLEditorEditorAction_RecordCount then Tag := 2; if Self is TibSHSQLEditorEditorAction_CreateNew then Tag := 3; case Tag of 0: Caption := '-'; // separator 1: Caption := SCallLoadLastContext; 2: Caption := SCallRecordCount; 3: begin Caption := SCallCreateNew; ShortCut := TextToShortCut('Shift+F4'); end; end; end; function TibSHSQLEditorEditorAction.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHSQLEditor); end; procedure TibSHSQLEditorEditorAction.EventExecute(Sender: TObject); var vComponent: TSHComponent; begin if Supports(Designer.CurrentComponent, IibSHSQLEditor) then case Tag of // SCallLoadLastContext 1: begin if Assigned(Designer.CurrentComponentForm) and not AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSQLText) then Designer.ChangeNotification(Designer.CurrentComponent, SCallSQLText, opInsert); if Supports(Designer.CurrentComponentForm, IibSHSQLEditorForm) then (Designer.CurrentComponentForm as IibSHSQLEditorForm).LoadLastContext; end; // SCallRecordCount 2: begin (Designer.CurrentComponent as IibSHSQLEditor).SetRecordCount; if (Length((Designer.CurrentComponent as IibSHSQLEditor).RecordCountFrmt) > 0) then Designer.ShowMsg(Format('Record Count: %s', [(Designer.CurrentComponent as IibSHSQLEditor).RecordCountFrmt]), mtInformation); end; // SCallCreateNew 3: begin vComponent := Designer.CreateComponent( Designer.CurrentComponent.OwnerIID, Designer.CurrentComponent.ClassIID, EmptyStr); Designer.ChangeNotification(vComponent, opInsert); end; end; end; procedure TibSHSQLEditorEditorAction.EventHint(var HintStr: String; var CanShow: Boolean); begin CanShow := False; if Supports(Designer.CurrentComponent, IibSHSQLEditor) then case Tag of // SCallLoadLastContext 1: ; // SCallRecordCount 2: if (Length((Designer.CurrentComponent as IibSHSQLEditor).RecordCountFrmt) > 0) then begin HintStr := (Format('Last Record Count: %s', [(Designer.CurrentComponent as IibSHSQLEditor).RecordCountFrmt])); CanShow := True; end; 3: ; end; end; procedure TibSHSQLEditorEditorAction.EventUpdate(Sender: TObject); begin if Supports(Designer.CurrentComponent, IibSHSQLEditor) then case Tag of 1: Enabled := True; 2: Enabled := Assigned(Designer.CurrentComponentForm) and AnsiSameText(Designer.CurrentComponentForm.CallString, SCallSQLText); 3: begin if Assigned(Designer.CurrentComponent) then Caption := Format('%s %s...', [SCallCreateNew, 'Editor']); Enabled := True; end; end; end; end.
// // SpritePacks allow sprites to be grouped together and to have // procedures called on each element without the programmer needing // to maintain an array. // unit SpritePack; interface uses sgTypes, stringhash; type SpriteArray = array of Sprite; // The container for the SpritePacks, allowing it to be // stored in a HashTable // TSpritePack = class(TObject) private _sprites: SpriteArray; // Copy of _sprites for looping code to use // this allows _sprites to change due to // user actions on the callback without // it affecting the loop _spritesBk: SpriteArray; _name: String; _inLoop, _spritesChanged: Boolean; procedure EndLoop(); public constructor Create(const name: String); destructor Destroy; override; property Name: String read _name; procedure AddPackTo(ht: TStringHash); procedure AddSprite(s: Sprite); procedure RemoveSprite(s: Sprite); procedure CallForAllSprites(fn: SpriteFunction); procedure CallForAllSprites(fn: SpriteSingleFunction; val: Single); end; implementation uses sgSprites, sgShared; constructor TSpritePack.Create(const name: String); begin inherited Create(); _name := name; _inLoop := false; _spritesChanged := false; SetLength(_sprites, 0); SetLength(_spritesBk, 0); end; destructor TSpritePack.Destroy(); begin // At this point sprites are not owned by their SpritePack... maybe they should be SetLength(_sprites, 0); SetLength(_spritesBk, 0); inherited Destroy(); end; procedure TSpritePack.AddPackTo(ht: TStringHash); begin if ht.containsKey(_name) then begin RaiseWarning('Attempting to create duplicate SpritePack named ' + _name); exit; end; ht.SetValue(_name, self); end; procedure TSpritePack.AddSprite(s: Sprite); procedure AddOp(var arr: SpriteArray); begin SetLength(arr, Length(arr) + 1); arr[High(arr)] := s; end; begin AddOp(_sprites); AddOp(_spritesBk); // allow add in loops end; procedure TSpritePack.EndLoop(); var i: Integer; begin _inLoop := false; if _spritesChanged then begin SetLength(_spritesBk, Length(_sprites)); for i := 0 to High(_spritesBk) do begin _spritesBk[i] := _sprites[i]; end; _spritesChanged := false; end; end; procedure TSpritePack.RemoveSprite(s: Sprite); var removeIdx, i: Integer; begin removeIdx := -1; for i := 0 to High(_sprites) do begin if _sprites[i] = s then begin removeIdx := i; break; end; end; if removeIdx < 0 then begin RaiseWarning('Attempted to remove sprite from incorrect pack!'); exit; end; if _inLoop then _spritesChanged := true; for i := removeIdx to High(_sprites) - 1 do begin _sprites[i] := _sprites[i + 1]; if not _inLoop then _spritesBk[i] := _spritesBk[i + 1]; end; SetLength(_sprites, Length(_sprites) - 1); if not _inLoop then SetLength(_spritesBk, Length(_spritesBk) - 1); end; procedure TSpritePack.CallForAllSprites(fn: SpriteFunction); var i: Integer; begin _inLoop := true; for i := 0 to High(_spritesBk) do begin fn(_spritesBk[i]); end; EndLoop(); end; procedure TSpritePack.CallForAllSprites(fn: SpriteSingleFunction; val: Single); var i: Integer; begin _inLoop := true; for i := 0 to High(_spritesBk) do begin fn(_spritesBk[i], val); end; EndLoop(); end; end.
unit OTFEE4MStructures_U; // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, SysUtils, Windows; type EE4MError = Exception; EE4MNotConnected = EE4MError; EE4MExeNotFound = EE4MError; EE4MVxdNotFound = EE4MError; EE4MVxdBadStatus = EE4MError; EE4MDLLNotFound = EE4MError; EE4MBadDLL = EE4MError; EE4MDLLFailure = EE4MError; EE4MDLLBadSignature = EE4MDLLFailure; TDeviceIOControlRegisters = packed record reg_EBX : DWORD; reg_EDX : DWORD; reg_ECX : DWORD; reg_EAX : DWORD; reg_EDI : DWORD; reg_ESI : DWORD; reg_Flags : DWORD; end; TParamBlock = packed record Operation : Integer; NumLocks : Integer; end; const VWIN32_DIOC_DOS_IOCTL = 1; E_NOT_CONNECTED = 'E4M not connected - set Active to TRUE first'; E_BAD_STATUS = 'E4M driver returned bad status'; E_DRIVE_IN_USE = 'Close all windows and applications used by this drive first'; E_E4M_EXE_NOT_FOUND = 'The E4M executable could not be found'; E_E4M_DLL_NOT_FOUND = 'E4M DLL not found'; E_E4M_BAD_DLL = 'E4M DLL did not have correct facilities!'; E_E4M_DLL_FAILURE = 'E4M DLL returned unexpected value'; E_E4M_DLL_SIGNATURE_FAILURE = 'E4M DLL returned bad signature'; // SFS Volume File Packet IDs SFS_PACKET_NONE = 0; // Null packet SFS_PACKET_VOLUMEINFO = 1; // Volume information SFS_PACKET_ENCRINFO = 2; // Encryption information SFS_PACKET_DISK_BPB = 3; // Filesystem information SFS_PACKET_MULTIUSER = 4; // Multiuser access information SFS_PACKET_FASTACCESS = 5; // Direct disk access information SFS_PACKET_UNMOUNT = 6; // Volume unmount information SFS_PACKET_SMARTCARD = 7; // Smart card information type E4M_VOLUME_FILE_TYPE = (vtidUnknown, vtidSFS, vtidOldE4M, vtidE4M, vtidE4MSDSDevice, vtidScramDisk); E4M_CIPHER_TYPE = (cphrNone, cphrMDCSHA, cphrSQUARE, cphrTEA16, cphrTEA32, cphrMISTY1, cphrTRIPLEDES, cphrIDEA, cphrBLOWFISH, cphrDES56, cphrCAST, cphrUnknown); E4M_HASH_TYPE = (hashSHA1, hashMD5, hashUnknown); const E4M_OS_WIN_95 = $a; E4M_OS_WIN_98 = $b; E4M_OS_WIN_NT = $c; E4M_VOLUME_FILE_TYPE_NAMES: array [E4M_VOLUME_FILE_TYPE] of Ansistring = ('Unknown', 'SFS', 'OLD E4M', 'E4M', 'E4M/SFS partition', 'ScramDisk'); // ScramDisk is last E4M_VOLUME_SIGNATURES: array [E4M_VOLUME_FILE_TYPE] of string = ('<Unknown has no signature>', 'SFS1', 'CAV', 'E4M', '<E4M/SFS partition has no signature>', '<ScramDisk has no signature>'); // The encryption algorithm IDs E4M_CIPHER_IDS: array [E4M_CIPHER_TYPE] of integer = (0, 1, 32, 33, 34, 35, 36, 37, 38, 39, 40, $ffff); E4M_CIPHER_NAMES: array [E4M_CIPHER_TYPE] of Ansistring = ('None', 'MDCSHA', 'SQUARE', 'TEA16', 'TEA32', 'MISTY1', '3DES', 'IDEA', 'BLOWFISH', 'DES', 'CAST', 'Unknown'); E4M_HASH_IDS: array [E4M_HASH_TYPE] of integer = (0, 1, $ffff); E4M_HASH_NAMES: array [E4M_HASH_TYPE] of Ansistring = ('SHA1', 'MD5', 'Unknown'); const SFS_DISKKEY_SIZE = 128; const E4M_DISKKEY_SIZE = 288; // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- E4M_APP_NAME = 'E4M'; E4M_APP_EXE_NAME = 'volmount.exe'; //kE4MDriverName // setup when the component is created; depends on the OS E4M_SERVICE_NAME = 'E4M'; E4M_REGISTRY_ENTRY_PATH = '\e4m_volume\Shell\Open\command'; // E4M v2.00 driver name (NT only; 9x never supported) const E4M_NT_MOUNT_PREFIX_v200 = '\Device\E4MV200'; const E4M_NT_ROOT_PREFIX_v200 = '\Device\E4MRootV200'; const E4M_DOS_MOUNT_PREFIX_v200 = '\DosDevices\'; const E4M_DOS_ROOT_PREFIX_v200 = '\DosDevices\E4MRootV200'; const E4M_WIN32_ROOT_PREFIX_v200 = '\\.\E4MRootV200'; // E4M v2.01 driver name (NT only) const E4M_NT_MOUNT_PREFIX = '\Device\E4M'; const E4M_NT_ROOT_PREFIX = '\Device\E4MRoot'; const E4M_DOS_MOUNT_PREFIX = '\DosDevices\'; const E4M_DOS_ROOT_PREFIX = '\DosDevices\E4MRoot'; const E4M_WIN32_ROOT_PREFIX = '\\.\E4MRoot'; // E4M v2.01 driver name (9x only) const E4M_WIN9X_DRIVER_NAME = '\\.\E4M'; // E4M service const E4M_PIPE_SERVICE = '\\.\pipe\e4mservice'; const E4M_HDD_PARTITION_DEVICE_NAME_FORMAT = '\Device\Harddisk%d\Partition%d'; const MAX_HDD_MAX_PHYSICAL_DRIVES = 9; // E4M can only OPEN_TEST a drive with a // single digit number (0-9) const E4M_HDD_MAX_PARTITIONS = 9; // E4M can only OPEN_TEST a partition // with a single digit number (1-9) const E4M_SIZEOF_MRU_LIST = 8; // 0-7 const E4M_INI_FILE = 'e4m.ini'; const E4M_INI_SECTION_LASTRUN = 'LastRun'; const E4M_INI_KEY_NOMOUNTWARNING = 'no_mount_warning'; const E4M_INI_KEY_NEVERSAVEHISTORY = 'never_save_history'; const E4M_INI_KEY_CACHEINDRIVER = 'cache_in_driver'; const E4M_INI_KEY_DRIVELETTER = 'drive_letter'; const E4M_INI_KEY_LASTVOLUMEn = 'last_volume'; ///////////////////////////////////////////////////////////// // Application to driver (DeviceIoControl) packet definitions ///////////////////////////////////////////////////////////// const FILE_DEVICE_DISK = $00000007; const FILE_DEVICE_FILE_SYSTEM = $00000009; const IOCTL_DISK_BASE = FILE_DEVICE_DISK; const METHOD_BUFFERED = 0; const METHOD_IN_DIRECT = 1; const FILE_ANY_ACCESS = 0; const E4M_DWORD_TRUE = 1; const E4M_DWORD_FALSE = 0; // #const CTL_CODE( DeviceType, Function, Method, Access ) ( \ // ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ // Standard Windows values const FSCTL_LOCK_VOLUME = (((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((6) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, FILE_ANY_ACCESS) const FSCTL_UNLOCK_VOLUME = (((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((7) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 7, METHOD_BUFFERED, FILE_ANY_ACCESS) const FSCTL_DISMOUNT_VOLUME = (((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((8) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, FILE_ANY_ACCESS) const FSCTL_MOUNT_DBLS_VOLUME = (((FILE_DEVICE_FILE_SYSTEM) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR ((13) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(FILE_DEVICE_FILE_SYSTEM,13, METHOD_BUFFERED, FILE_ANY_ACCESS) // E4M values const E4M_MOUNT = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($800) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(IOCTL_DISK_BASE, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS) const E4M_MOUNT_LIST = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($801) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(IOCTL_DISK_BASE, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS) // E4M_9x_MOUNT_LIST_N introduced for E4M v2.01 const E4M_9x_MOUNT_LIST_N = 466976; // Get volume info from the device (only Win9x) const E4M_OPEN_TEST = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($802) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(IOCTL_DISK_BASE, 0x802, METHOD_BUFFERED, FILE_ANY_ACCESS) const E4M_UNMOUNT = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($803) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(IOCTL_DISK_BASE, 0x803, METHOD_BUFFERED, FILE_ANY_ACCESS) const E4M_WIPE_CACHE = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($804) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(IOCTL_DISK_BASE, 0x804, METHOD_BUFFERED, FILE_ANY_ACCESS) {$IFDEF Debug} const E4M_HALT_SYSTEM = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($805) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(IOCTL_DISK_BASE, 0x805, METHOD_BUFFERED, FILE_ANY_ACCESS) {$ENDIF} const E4M_UNMOUNT_PENDING = (((IOCTL_DISK_BASE) * $10000) OR ((FILE_ANY_ACCESS) * $4000) OR (($ffa) * $4) OR (METHOD_BUFFERED)); // = CTL_CODE(IOCTL_DISK_BASE, 0xffa, METHOD_BUFFERED, FILE_ANY_ACCESS) const RELEASE_TIME_SLICE = 466972; // Release time slice on apps behalf const E4M_DRIVER_VERSION = 466968; // Current driver version; introduced in // E4M v2.01 const ALLOW_FAST_SHUTDOWN = 466984; // Fast shutdown under win98 (only Win9x); // introduced in E4M v2.01 const E4M_MAX_PATH = 260; // Includes the null terminator const E4M_MAX_PASSWORD = 100; const E4M_ERR_OS_ERROR = $7000; const E4M_ERR_OUTOFMEMOR = $700e; const E4M_ERR_PASSWORD_WRONG = $8001; const E4M_ERR_VOLUME_FORMAT_BAD = $8002; const E4M_ERR_BAD_DRIVE_LETTER = $8003; const E4M_ERR_DRIVE_NOT_FOUND = $8004; const E4M_ERR_FILES_OPEN = $8005; const E4M_ERR_VOLUME_SIZE_WRONG = $8006; const E4M_ERR_COMPRESSION_NOT_SUPPORTED = $8007; const E4M_ERR_PASSWORD_CHANGE_VOL_TYPE = $8008; const E4M_ERR_PASSWORD_CHANGE_VOL_VERSION = $8009; const E4M_ERR_VOL_SEEKING = $800a; const E4M_ERR_VOL_WRITING = $800b; const E4M_ERR_FILES_OPEN_LOCK = $800c; type TOTFEE4M_200_MOUNT = packed record nReturnCode: integer; // Return code back from driver wszVolume: array [1..E4M_MAX_PATH] of WCHAR; // Volume to be mounted szPassword: array [1..(E4M_MAX_PASSWORD + 1)] of ansichar; // User password or SHA1 hash dummy1: array [1..3] of byte; // Needed to get the next item on a word boundry nPasswordLen: integer; // User password length bCache: boolean; // Cache passwords in driver dummy2: array [1..3] of byte; // Needed to get the next item on a word boundry bSD: boolean; // Set to TRUE for ScramDisk volumes, otherwise FALSE dummy3: array [1..3] of byte; // Needed to get the next item on a word boundry nDosDriveNo: integer; // Drive number to mount time: longint; // Time when this volume was mounted end; TOTFEE4M_201_MOUNT = packed record nReturnCode: integer; // Return code back from driver wszVolume: array [1..E4M_MAX_PATH] of short; // Volume to be mounted szPassword: array [1..(E4M_MAX_PASSWORD + 1)] of ansichar; // User password or SHA1 hash // it seems that we no longer need dummy1 // dummy1: array [1..3] of byte; // Needed to get the next item on a word boundry nPasswordLen: integer; // User password length bCache: boolean; // Cache passwords in driver dummy2: array [1..3] of byte; // Needed to get the next item on a word boundry nDosDriveNo: integer; // Drive number to mount time: longint; // Time when this volume was mounted end; TOTFEE4M_UNMOUNT = packed record nReturnCode: integer; nDosDriveNo: integer; // Drive letter to unmount end; TOTFEE4M_200_MOUNT_LIST = packed record ulMountedDrives: cardinal; // Bitfield of all mounted drive letters // Yes, it is 64 in the next line; it was hardcoded in the E4M source wszVolume: array [1..26] of array [1..64] of WCHAR; // Volume names of mounted volumes end; TOTFEE4M_201_MOUNT_LIST = packed record ulMountedDrives: cardinal; // Bitfield of all mounted drive letters // Yes, it is 64 in the next line; it was hardcoded in the E4M source wszVolume: array [1..26] of array [1..64] of short; // Volume names of mounted volumes end; TOTFEE4M_200_OPEN_TEST = packed record wszFileName: array [1..E4M_MAX_PATH] of WCHAR; // Volume to be "open tested" end; TOTFEE4M_201_OPEN_TEST = packed record wszFileName: array [1..E4M_MAX_PATH] of short; // Volume to be "open tested" nReturnCode: integer; // Win9x only secstart : cardinal; // Win9x only seclast : cardinal; // Win9x only device : cardinal; // Win9x only end; // Win9x only TOTFEE4M_9x_MOUNT_LIST_N_STRUCT = packed record nReturnCode: integer; // Return code back from driver nDosDriveNo: integer; // Drive letter to get info on wszVolume: array [1..E4M_MAX_PATH] of short; // Volume names of mounted volumes mountfilehandle: cardinal; // Device file handle or 0 end; // This one was introduced in E4M v2.01 TOTFEE4M_VERSION = packed record // This is not part of the E4M source; it's just a // DWORD, but is included for completeness version: DWORD; end; TOTFEE4MVolumeInfo = packed record // This is not part of the E4M source volumeFilename: AnsiString; mountedAs: ansichar; cipherID: E4M_CIPHER_TYPE; cipherName: AnsiString; hashID: E4M_HASH_TYPE; hashName: AnsiString; volumeTypeID: E4M_VOLUME_FILE_TYPE; volumeTypeName: AnsiString; readonly: boolean; end; pTOTFEE4MVolumeInfo = ^TOTFEE4MVolumeInfo; implementation END.
////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_STDLIB.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} {$O-} {$R-} unit PAXCOMP_STDLIB; interface {$I-} uses {$I uses.def} TypInfo, SysUtils, Classes, {$IFDEF DRTTI} Rtti, {$ENDIF} PaxInfos, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS, PAXCOMP_SYMBOL_REC, PAXCOMP_BASESYMBOL_TABLE, PAXCOMP_CLASSLST, PAXCOMP_CLASSFACT, {$IFDEF PAXARM} {$ELSE} PAXCOMP_SEH, {$ENDIF} {$IFNDEF INTERPRETER_ONLY} PAXCOMP_PROGLIB, {$ENDIF} PAXCOMP_MAP; type TExtraImportTableList = class(TTypedList) private function GetRecord(I: Integer): TBaseSymbolTable; public function Add(st: TBaseSymbolTable): Integer; procedure Remove(st: TBaseSymbolTable); function Import(CurrentTable: TBaseSymbolTable; const FullName: String; UpCase: Boolean; DoRaiseError: Boolean = true): Integer; property Records[I: Integer]: TBaseSymbolTable read GetRecord; default; end; var RUNNER_OWNER_OFFSET: IntPax; AvailUnitList: TStringList; AvailUnitList1: TStringList; AvailTypeList: TStringList; H_PascalNamespace: Integer; H_BasicNamespace: Integer; H_PaxCompilerSEH: Integer; H_PaxCompilerFramework: Integer; H_Writeln: Integer; H_WriteBool: Integer; H_WriteByteBool: Integer; H_WriteWordBool: Integer; H_WriteLongBool: Integer; H_WriteInteger: Integer; H_WriteInt64: Integer; H_WriteByte: Integer; H_WriteWord: Integer; H_WriteCardinal: Integer; H_WriteSmallInt: Integer; H_WriteShortInt: Integer; H_WriteAnsiString: Integer; H_WriteShortString: Integer; H_WriteAnsiChar: Integer; H_WriteWideChar: Integer; H_WriteWideString: Integer; H_WriteUnicString: Integer; H_WriteDouble: Integer; H_WriteSingle: Integer; H_WriteCurrency: Integer; H_WriteExtended: Integer; H_WriteVariant: Integer; H_WriteObject: Integer; H_TObject: Integer; H_TClass: Integer; H_TInterfacedObject: Integer; H_PInteger: Integer; H_PSmallInt: Integer; H_PShortInt: Integer; H_PCardinal: Integer; H_PWord: Integer; H_PByte: Integer; H_PInt64: Integer; H_PSingle: Integer; H_PDouble: Integer; H_PExtended: Integer; H_PCurrency: Integer; H_PVariant: Integer; H_PPointer: Integer; H_PBoolean: Integer; H_PWideChar: Integer; H_PAnsiChar: Integer; H_PShortString: Integer; H_PAnsiString: Integer; H_PWideString: Integer; H_PUnicString: Integer; H_PString: Integer; H_PPInteger: Integer; H_PPSmallInt: Integer; H_PPShortInt: Integer; H_PPCardinal: Integer; H_PPWord: Integer; H_PPByte: Integer; H_PPInt64: Integer; H_PPSingle: Integer; H_PPDouble: Integer; H_PPExtended: Integer; H_PPCurrency: Integer; H_PPVariant: Integer; H_PPPointer: Integer; H_PPBoolean: Integer; H_PPWideChar: Integer; H_PPAnsiChar: Integer; H_PPShortString: Integer; H_PPAnsiString: Integer; H_PPWideString: Integer; H_PPUnicString: Integer; H_PPString: Integer; H_QueryInterface, H_AddRef, H_Release, H_TGUID: Integer; H_PGUID: Integer; H_IUnknown: Integer; H_IDispatch: Integer; Id_ImplicitInt: Integer = -1; Id_CallJNIMethod: Integer = -1; H_TValue: Integer = -1; Id_VarFromTValue: Integer = -1; Id_GetDRTTIProperty: Integer = -1; Id_GetDRTTIIntegerProperty: Integer = -1; Id_GetDRTTIStringProperty: Integer = -1; Id_GetDRTTIExtendedProperty: Integer = -1; Id_GetDRTTIVariantProperty: Integer = -1; Id_GetDRTTIInt64Property: Integer = -1; Id_SetDRTTIProperty: Integer = -1; H_TVarRec: Integer; H_TFileRec: Integer; H_TTextRec: Integer; H_Dynarray_TVarRec: Integer; H_Dynarray_Integer: Integer; H_Dynarray_Byte: Integer; H_Dynarray_Word: Integer; H_Dynarray_ShortInt: Integer; H_Dynarray_SmallInt: Integer; H_Dynarray_Cardinal: Integer; H_Dynarray_Int64: Integer; H_Dynarray_UInt64: Integer; H_Dynarray_AnsiChar: Integer; H_Dynarray_WideChar: Integer; H_Dynarray_AnsiString: Integer; H_Dynarray_WideString: Integer; H_Dynarray_UnicodeString: Integer; H_Dynarray_ShortString: Integer; H_Dynarray_Double: Integer; H_Dynarray_Single: Integer; H_Dynarray_Extended: Integer; H_Dynarray_Currency: Integer; H_Dynarray_Boolean: Integer; H_Dynarray_ByteBool: Integer; H_Dynarray_WordBool: Integer; H_Dynarray_LongBool: Integer; H_Dynarray_Variant: Integer; H_Dynarray_OleVariant: Integer; H_Dynarray_Pointer: Integer; H_Unassigned: Integer; H_TMethod: Integer; H_DYN_VAR: Integer; Id_CallVirt: Integer; Id_PutVirt: Integer; Id_CondHalt: Integer; Id_ToParentClass: Integer; Id_UpdateInstance: Integer; Id_DestroyInherited: Integer; ID_Prog: Integer; Id_GetAddressGetCallerEIP: Integer; Id_WriteBool: Integer; Id_WriteByteBool: Integer; Id_WriteWordBool: Integer; Id_WriteLongBool: Integer; Id_WriteAnsiChar: Integer; Id_WriteByte: Integer; Id_WriteWord: Integer; Id_WriteCardinal: Integer; Id_WriteSmallInt: Integer; Id_WriteShortInt: Integer; Id_WriteInt: Integer; Id_WriteInt64: Integer; Id_WriteDouble: Integer; Id_WriteSingle: Integer; Id_WriteCurrency: Integer; Id_WriteExtended: Integer; Id_WriteString: Integer; Id_WriteShortString: Integer; Id_WriteWideChar: Integer; Id_WriteWideString: Integer; Id_WriteUnicString: Integer; Id_WriteVariant: Integer; Id_WriteObject: Integer; Id_PrintEx: Integer; Id_Is: Integer; Id_DynArrayLength: Integer; Id_VariantArrayLength: Integer; Id_AnsiStringLength: Integer; Id_SetVariantLength: Integer; Id_SetVariantLength2: Integer; Id_SetVariantLength3: Integer; Id_SetStringLength: Integer; Id_SetWideStringLength: Integer; Id_SetUnicStringLength: Integer; Id_SetShortStringLength: Integer; Id_LockVArray: Integer; Id_UnlockVArray: Integer; Id_LoadProc: Integer; Id_LoadSeg: Integer; Id_LoadClassRef: Integer; Id_TypeInfo, Id_GetDynamicMethodAddress, Id_AddMessage, Id_AnsiStringFromPAnsiChar: Integer; Id_AnsiStringFromPWideChar: Integer; Id_WideStringFromPAnsiChar: Integer; Id_WideStringFromPWideChar: Integer; Id_UnicStringFromPWideChar: Integer; Id_AnsiStringFromAnsiChar: Integer; Id_WideStringFromAnsiChar: Integer; Id_UnicStringFromAnsiChar: Integer; Id_WideStringFromWideChar: Integer; Id_UnicStringFromWideChar: Integer; Id_AnsiStringFromWideChar: Integer; Id_UnicStringFromPAnsiChar: Integer; Id_AnsiStringAssign: Integer; Id_AnsiStringAddition: Integer; Id_ShortStringAddition: Integer; Id_WideStringAddition: Integer; Id_UnicStringAddition: Integer; Id_ShortStringAssign: Integer; Id_WideStringAssign: Integer; Id_UnicStringAssign: Integer; Id_AnsiStringClr: Integer; Id_WideStringClr: Integer; Id_UnicStringClr: Integer; Id_InterfaceClr: Integer; Id_ClassClr: Integer = 0; Id_UniqueAnsiString: Integer = 0; Id_UniqueUnicString: Integer = 0; Id_StringAddRef: Integer; Id_WideStringAddRef: Integer; Id_UnicStringAddRef: Integer; Id_VariantAddRef: Integer; Id_DynarrayAddRef: Integer; Id_InterfaceAddRef: Integer; Id_ShortStringFromAnsiString: Integer; Id_ShortStringFromWideString: Integer; Id_ShortStringFromPWideChar: Integer; Id_ShortStringFromUnicString: Integer; Id_AnsiStringFromShortString: Integer; Id_UnicStringFromWideString: Integer; Id_WideStringFromShortString: Integer; Id_WideStringFromUnicString: Integer; Id_UnicStringFromShortString: Integer; Id_AnsiStringFromWideString: Integer; Id_AnsiStringFromUnicString: Integer; Id_WideStringFromAnsiString: Integer; Id_UnicStringFromAnsiString: Integer; Id_StrInt: Integer; Id_StrDouble: Integer; Id_StrSingle: Integer; Id_StrExtended: Integer; Id_DecStringCounter: Integer; Id_IncStringCounter: Integer; Id_AnsiStringEquality: Integer; Id_AnsiStringNotEquality: Integer; Id_ShortStringEquality: Integer; Id_ShortStringNotEquality: Integer; Id_WideStringEquality: Integer; Id_UnicStringEquality: Integer; Id_WideStringNotEquality: Integer; Id_UnicStringNotEquality: Integer; Id_ShortstringHigh: Integer; Id_AnsiStringGreaterThan: Integer; Id_AnsiStringGreaterThanOrEqual: Integer; Id_AnsiStringLessThan: Integer; Id_AnsiStringLessThanOrEqual: Integer; Id_ShortStringGreaterThan: Integer; Id_ShortStringGreaterThanOrEqual: Integer; Id_ShortStringLessThan: Integer; Id_ShortStringLessThanOrEqual: Integer; Id_WideStringGreaterThan: Integer; Id_UnicStringGreaterThan: Integer; Id_WideStringGreaterThanOrEqual: Integer; Id_UnicStringGreaterThanOrEqual: Integer; Id_WideStringLessThan: Integer; Id_UnicStringLessThan: Integer; Id_WideStringLessThanOrEqual: Integer; Id_UnicStringLessThanOrEqual: Integer; Id_Int64Multiplication: Integer; Id_Int64Division: Integer; Id_Int64Modulo: Integer; Id_Int64LeftShift: Integer; Id_Int64RightShift: Integer; Id_Int64LessThan: Integer; Id_Int64LessThanOrEqual: Integer; Id_Int64GreaterThan: Integer; Id_Int64GreaterThanOrEqual: Integer; Id_Int64Equality: Integer; Id_Int64NotEquality: Integer; Id_Int64Abs: Integer; Id_UInt64LessThan: Integer; Id_UInt64LessThanOrEqual: Integer; Id_UInt64GreaterThan: Integer; Id_UInt64GreaterThanOrEqual: Integer; Id_VariantClr: Integer; Id_VariantAssign: Integer; Id_VariantFromPAnsiChar: Integer; Id_VariantFromPWideChar: Integer; Id_VariantFromInterface: Integer; Id_OleVariantAssign: Integer; Id_ClassAssign: Integer; Id_VariantFromClass: Integer; // JS only Id_VariantFromPointer: Integer; // JS only Id_ClassFromVariant: Integer; // JS only Id_InterfaceFromClass, Id_InterfaceCast, Id_InterfaceAssign, Id_VariantFromAnsiString: Integer; Id_VariantFromWideString: Integer; Id_VariantFromUnicString: Integer; Id_VariantFromShortString: Integer; Id_VariantFromAnsiChar: Integer; Id_VariantFromWideChar: Integer; Id_VariantFromInt: Integer; Id_VariantFromInt64: Integer; Id_VariantFromByte: Integer; Id_VariantFromBool: Integer; Id_VariantFromWord: Integer; Id_VariantFromCardinal: Integer; Id_VariantFromSmallInt: Integer; Id_VariantFromShortInt: Integer; Id_VariantFromDouble: Integer; Id_VariantFromCurrency: Integer; Id_VariantFromSingle: Integer; Id_VariantFromExtended: Integer; Id_AnsiStringFromInt: Integer; // JS only Id_AnsiStringFromDouble: Integer; // JS only Id_AnsiStringFromSingle: Integer; // JS only Id_AnsiStringFromExtended: Integer; // JS only Id_AnsiStringFromBoolean: Integer; // JS only Id_UnicStringFromInt: Integer; // JS only Id_UnicStringFromDouble: Integer; // JS only Id_UnicStringFromSingle: Integer; // JS only Id_UnicStringFromExtended: Integer; // JS only Id_UnicStringFromBoolean: Integer; // JS only Id_FuncObjFromVariant: Integer; // JS only Id_PushContext: Integer; // JS only Id_PopContext: Integer; // JS only Id_FindContext: Integer; // JS only Id_AnsiCharFromVariant: Integer; Id_WideCharFromVariant: Integer; Id_AnsiStringFromVariant: Integer; Id_WideStringFromVariant: Integer; Id_UnicStringFromVariant: Integer; Id_ShortStringFromVariant: Integer; Id_DoubleFromVariant: Integer; Id_CurrencyFromVariant: Integer; Id_SingleFromVariant: Integer; Id_ExtendedFromVariant: Integer; Id_IntFromVariant: Integer; Id_Int64FromVariant: Integer; Id_ByteFromVariant: Integer; Id_WordFromVariant: Integer; Id_CardinalFromVariant: Integer; Id_SmallIntFromVariant: Integer; Id_ShortIntFromVariant: Integer; Id_BoolFromVariant: Integer; Id_ByteBoolFromVariant: Integer; Id_WordBoolFromVariant: Integer; Id_LongBoolFromVariant: Integer; Id_VariantAddition: Integer; Id_VariantSubtraction: Integer; Id_VariantMultiplication: Integer; Id_VariantDivision: Integer; Id_VariantIDivision: Integer; Id_VariantModulo: Integer; Id_VariantLeftShift: Integer; Id_VariantRightShift: Integer; Id_VariantAnd: Integer; Id_VariantOr: Integer; Id_VariantXor: Integer; Id_VariantLessThan: Integer; Id_VariantLessThanOrEqual: Integer; Id_VariantGreaterThan: Integer; Id_VariantGreaterThanOrEqual: Integer; Id_VariantEquality: Integer; Id_VariantNotEquality: Integer; Id_StructEquality: Integer; Id_StructNotEquality: Integer; Id_VariantNegation: Integer; Id_VariantAbs: Integer; Id_VariantNot: Integer; Id_VarArrayGet1: Integer; Id_VarArrayPut1: Integer; Id_VarArrayGet2: Integer; Id_VarArrayPut2: Integer; Id_VarArrayGet3: Integer; Id_VarArrayPut3: Integer; Id_DynarrayClr: Integer; Id_DynarrayAssign: Integer; Id_CreateEmptyDynarray: Integer; Id_DynarraySetLength: Integer; Id_DynarraySetLength2: Integer; Id_DynarraySetLength3: Integer; Id_DynarrayHigh: Integer; Id_DoubleMultiplication: Integer; Id_DoubleDivision: Integer; Id_DoubleAddition: Integer; Id_DoubleSubtraction: Integer; Id_DoubleNegation: Integer; Id_OleVariantFromVariant: Integer; Id_OleVariantFromPAnsiChar: Integer; Id_OleVariantFromPWideChar: Integer; Id_OleVariantFromAnsiString: Integer; Id_OleVariantFromWideString: Integer; Id_OleVariantFromUnicString: Integer; Id_OleVariantFromShortString: Integer; Id_OleVariantFromAnsiChar: Integer; Id_OleVariantFromWideChar: Integer; Id_OleVariantFromInt: Integer; Id_OleVariantFromInt64: Integer; Id_OleVariantFromByte: Integer; Id_OleVariantFromBool: Integer; Id_OleVariantFromWord: Integer; Id_OleVariantFromCardinal: Integer; Id_OleVariantFromSmallInt: Integer; Id_OleVariantFromShortInt: Integer; Id_OleVariantFromDouble: Integer; Id_OleVariantFromCurrency: Integer; Id_OleVariantFromSingle: Integer; Id_OleVariantFromExtended: Integer; Id_OleVariantFromInterface: Integer; Id_GetComponent: Integer; Id_SetInclude: Integer; Id_SetIncludeInterval: Integer; Id_SetExclude: Integer; Id_SetUnion: Integer; Id_SetDifference: Integer; Id_SetIntersection: Integer; Id_SetSubset: Integer; Id_SetSuperset: Integer; Id_SetEquality: Integer; Id_SetInequality: Integer; Id_SetMembership: Integer; Id_ClassName: Integer; Id_OnCreateObject: Integer; Id_OnAfterObjectCreation: Integer; Id_OnCreateHostObject: Integer; Id_OnDestroyHostObject: Integer; Id_BeforeCallHost: Integer; Id_AfterCallHost: Integer; Id_GetAnsiStrProp: Integer; Id_SetAnsiStrProp: Integer; Id_GetWideStrProp: Integer; Id_SetWideStrProp: Integer; Id_GetUnicStrProp: Integer; Id_SetUnicStrProp: Integer; Id_GetOrdProp: Integer; Id_SetOrdProp: Integer; Id_GetInterfaceProp: Integer; Id_SetInterfaceProp: Integer; Id_GetSetProp: Integer; Id_SetSetProp: Integer; Id_GetFloatProp: Integer; Id_SetFloatProp: Integer; Id_GetVariantProp: Integer; Id_SetVariantProp: Integer; Id_GetInt64Prop: Integer; Id_SetInt64Prop: Integer; Id_GetEventProp: Integer; Id_SetEventProp: Integer; Id_SetEventProp2: Integer; Id_CreateMethod: Integer; Id_CreateObject: Integer; Id_TryOn: Integer; Id_TryOff: Integer; Id_Raise: Integer; Id_Exit: Integer; Id_Finally: Integer; Id_CondRaise: Integer; Id_BeginExceptBlock: Integer; Id_EndExceptBlock: Integer; Id_Pause: Integer; Id_Halt: Integer; Id_GetClassByIndex: Integer; Id_CheckPause: Integer; Id_InitSub: Integer; Id_EndSub: Integer; Id_IntOver: Integer; Id_BoundError: Integer; Id_AssignTVarRec: Integer; Id_TObject_Destroy: Integer; Id_ErrAbstract: Integer; Id_RecordAssign: Integer; Id_TObject_Free: Integer; Id_TObject_GetInterface: Integer; CURR_FMUL_ID: Integer; Id_TDateTime: integer = 0; H_TFW_Object: Integer = 0; H_TFW_Boolean: Integer = 0; H_TFW_ByteBool: Integer = 0; H_TFW_WordBool: Integer = 0; H_TFW_LongBool: Integer = 0; H_TFW_Byte: Integer = 0; H_TFW_SmallInt: Integer = 0; H_TFW_ShortInt: Integer = 0; H_TFW_Word: Integer = 0; H_TFW_Cardinal: Integer = 0; H_TFW_Double: Integer = 0; H_TFW_Single: Integer = 0; H_TFW_Extended: Integer = 0; H_TFW_Currency: Integer = 0; H_TFW_AnsiChar: Integer = 0; H_TFW_WideChar: Integer = 0; H_TFW_Integer: Integer = 0; H_TFW_Int64: Integer = 0; H_TFW_Variant: Integer = 0; H_TFW_DateTime: Integer = 0; H_TFW_AnsiString: Integer = 0; H_TFW_UnicString: Integer = 0; H_TFW_Array: Integer = 0; FWArrayOffset: Integer = 0; Id_FWArray_Create: Integer = 0; Id_FWArray_GetLength: Integer = 0; Id_ToFWObject: Integer = 0; Id_PaxSEHHandler: Integer = 0; Id_InitFWArray: Integer = 0; {$IFDEF TRIAL} var strShowTrial: array[0..10] of Char; {$ENDIF} GlobalSymbolTable: TBaseSymbolTable; GlobalImportTable: TBaseSymbolTable; GlobalExtraImportTableList: TExtraImportTableList; List: TExtraImportTableList; type TMyInterfacedObject = class(TInterfacedObject); procedure TMyInterfacedObject_AddRef(Self: TObject); stdcall; procedure TMyInterfacedObject_Release(Self: TObject); stdcall; {$IFNDEF PAXARM} procedure _SetAnsiStrProp(PropInfo: PPropInfo; Instance: TObject; const value: AnsiString); stdcall; procedure _SetWideStrProp(PropInfo: PPropInfo; Instance: TObject; const value: WideString); stdcall; procedure _WideStringFromPWideChar(source: PWideChar; var dest: WideString); stdcall; {$ENDIF} procedure _SetUnicStrProp(PropInfo: PPropInfo; Instance: TObject; const value: UnicString); stdcall; procedure _DynarrayClr(var A: Pointer; FinalTypeID, TypeID, ElSize, FinalTypeID2, TypeID2, ElSize2: Integer); stdcall; procedure _DynarrayAssign(var Source, Dest: Pointer; FinalTypeID, TypeID, ElSize, FinalTypeID2, TypeID2, ElSize2: Integer); stdcall; procedure _DynarraySetLength(var A: Pointer; L: Integer; ElFinalTypeID, ElTypeID, ElSize: Integer); stdcall; procedure _DynarraySetLength2(var A: Pointer; L1, L2: Integer; ElFinalTypeID, ElTypeID, ElSize: Integer); stdcall; procedure _DynarraySetLength3(var A: Pointer; L1, L2, L3: Integer; ElFinalTypeID, ElTypeID, ElSize: Integer); stdcall; procedure _DynarrayClr1(var A: Pointer; FinalTypeID, TypeID, ElSize: Integer); stdcall; procedure _DynarrayClr2(var A: Pointer; FinalTypeID, TypeID, ElSize: Integer); stdcall; procedure _DynarrayClr3(var A: Pointer; FinalTypeID, TypeID, ElSize: Integer); stdcall; function _DynarrayLength(P: Pointer): Integer; procedure _ClearTVarRec(var Dest: TVarRec); procedure _SetVariantLength(var V: Variant; VType: Integer; L: Integer); stdcall; procedure _SetVariantLength2(var V: Variant; VType: Integer; L1, L2: Integer); stdcall; procedure _SetVariantLength3(var V: Variant; VType: Integer; L1, L2, L3: Integer); stdcall; procedure AddStdRoutines(st: TBaseSymbolTable); type DynarrayPointer = array of Pointer; var Import_TValue: procedure(Level: Integer; st: TBaseSymbolTable) = nil; procedure _InterfaceFromClass(Dest: PIUnknown; GUID: PGUID; SourceAddress: Pointer); stdcall; procedure _InterfaceCast(Dest: PIUnknown; GUID: PGUID; Source: PIUnknown); stdcall; function GetPaxInterface(Self: TObject; const GUID: TGUID; var obj: Pointer): Boolean; function UpdateSet(const S: TByteSet; L: Integer): TByteSet; procedure _PrintEx(PP: Pointer; Address: Pointer; Kind: Integer; FT: Integer; L1, L2: Integer); stdcall; procedure _AssignTVarRec(P: Pointer; Address: Pointer; var Dest: TVarRec; TypeID: Integer); stdcall; function _LoadProc(Runner: Pointer; ProcHandle: Integer; ProcName: PChar; DllName: PChar; OverCount: Integer): Pointer; stdcall; procedure _Halt(Runner: Pointer; ExitCode: Integer); stdcall; procedure _AddMessage(Runner: Pointer; msg_id: Integer; FullName: PChar); stdcall; procedure _OnAfterObjectCreation(Runner: Pointer; Instance: PObject); stdcall; procedure _TypeInfo(Prog: Pointer; FullTypeName: PChar; var result: PTypeInfo); stdcall; {$IFNDEF PAXARM} function _InitInstance(Self: TClass; Instance: Pointer): TObject; {$ENDIF} procedure _ToParentClass2(Instance: TObject); stdcall; procedure _UpdateInstance2(Instance: TObject; C: TClass); stdcall; procedure _SetInclude(S: PByteSet; value: Integer); stdcall; procedure _SetIncludeInterval(S: PByteSet; B1, B2: Integer); stdcall; procedure _ShortStringAssign(const source: ShortString; Ldest: Integer; dest: PShortString); stdcall; procedure _CreateEmptyDynarray(var A: Pointer); stdcall; procedure _GetComponent(X: TComponent; I: Integer; var Y: TComponent); stdcall; function GetPointerType(T: Integer): Integer; procedure FindAvailTypes; implementation uses {$IFDEF DRTTI} PAXCOMP_2010, PAXCOMP_2010Reg, {$ENDIF} PAXCOMP_BASERUNNER, PAXCOMP_JavaScript, PAXCOMP_Basic, PAXCOMP_GC, PAXCOMP_FRAMEWORK, PAXCOMP_TYPEINFO, Math; {$IFDEF TRIAL} procedure ShowTrial; var a: array[0..50] of ansichar; b: array[0..20] of ansichar; begin a[00] := 'T'; a[01] := 'h'; a[02] := 'i'; a[03] := 's'; a[04] := ' '; a[05] := 'i'; a[06] := 's'; a[07] := ' '; a[08] := 'a'; a[09] := 'n'; a[10] := ' '; a[11] := 'e'; a[12] := 'v'; a[13] := 'a'; a[14] := 'l'; a[15] := 'u'; a[16] := 'a'; a[17] := 't'; a[18] := 'i'; a[19] := 'o'; a[20] := 'n'; a[21] := ' '; a[22] := 'c'; a[23] := 'o'; a[24] := 'p'; a[25] := 'y'; a[26] := ' '; a[27] := 'o'; a[28] := 'f'; a[29] := ' '; a[30] := 'p'; a[31] := 'a'; a[32] := 'x'; a[33] := 'C'; a[34] := 'o'; a[35] := 'm'; a[36] := 'p'; a[37] := 'i'; a[38] := 'l'; a[39] := 'e'; a[40] := 'r'; a[41] := '.'; a[42] := #0; b[00] := 'p'; b[01] := 'a'; b[02] := 'x'; b[03] := 'C'; b[04] := 'o'; b[05] := 'm'; b[06] := 'p'; b[07] := 'i'; b[08] := 'l'; b[09] := 'e'; b[10] := 'r'; b[11] := #0; {$IFDEF LINUX} {$IFDEF FPC} // I will give you a better call for FPC/LINUX // {$ELSE} Application.MessageBox(PChar(S), 'paxCompiler', [smbOK]); {$ENDIF} {$ELSE} {$IFDEF UNIX} Writeln('Error '+S); {$ELSE} MessageBox(GetActiveWindow(), PChar(String(a)), PChar(String(b)), MB_ICONEXCLAMATION or MB_OK); {$ENDIF} {$ENDIF} end; {$ENDIF} procedure _BeginSub; begin end; procedure _Write; begin end; procedure _Writeln; begin writeln; end; procedure _WriteBool(value: Boolean); begin write(value); end; procedure _WriteByteBool(value: ByteBool); begin write(value); end; procedure _WriteWordBool(value: WordBool); begin write(value); end; procedure _WriteLongBool(value: LongBool); begin write(value); end; {$IFDEF VARIANTS} procedure _WriteWideChar(value: WideChar); begin write(value); end; {$ELSE} procedure _WriteWideChar(value: WideChar); var S: AnsiString; begin S := value; write(S); end; {$ENDIF} procedure _WriteByte(value: Byte; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteWord(value: Word; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteCardinal(value: Cardinal; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteSmallInt(value: SmallInt; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteShortInt(value: ShortInt; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteInt(value: Integer; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteInt64(value: Int64; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteDouble(value: Double; L1, L2: Integer); begin if L1 > 0 then begin if L2 > 0 then write(value:L1:L2) else write(value:L1); end else write(value); end; procedure _WriteSingle(value: Single; L1, L2: Integer); begin if L1 > 0 then begin if L2 > 0 then write(value:L1:L2) else write(value:L1); end else write(value); end; procedure _WriteCurrency(value: Currency; L1, L2: Integer); begin if L1 > 0 then begin if L2 > 0 then write(value:L1:L2) else write(value:L1); end else write(value); end; procedure _WriteExtended(value: Extended; L1, L2: Integer); begin if L1 > 0 then begin if L2 > 0 then write(value:L1:L2) else write(value:L1); end else write(value); end; {$IFNDEF PAXARM} procedure _WriteString(const value: AnsiString; L: Integer); begin if L = 0 then write(value) else write(value:L); end; procedure _WriteAnsiChar(value: AnsiChar); begin write(value); end; procedure _WriteShortString(const value: ShortString; L: Integer); begin if L = 0 then write(value) else write(value:L); end; {$ENDIF} {$IFDEF VARIANTS} {$IFNDEF PAXARM} procedure _WriteWideString(const value: WideString; L: Integer); begin if L = 0 then write(value) else write(value:L); end; {$ENDIF} {$ELSE} procedure _WriteWideString(const value: WideString; L: Integer); var S: AnsiString; begin S := value; if L = 0 then write(S) else write(S:L); end; {$ENDIF} {$IFDEF VARIANTS} procedure _WriteUnicString(const value: UnicString; L: Integer); begin if L = 0 then write(value) else write(value:L); end; {$ELSE} procedure _WriteUnicString(const value: UnicString; L: Integer); var S: AnsiString; begin S := value; if L = 0 then write(S) else write(S:L); end; {$ENDIF} procedure _WriteVariant(const value: Variant; L1, L2: Integer); var {$IFDEF PAXARM} S: String; {$ELSE} {$IFDEF FPC} S: String; {$ELSE} S: ShortString; {$ENDIF} {$ENDIF} begin if L1 > 0 then begin {$IFDEF PAXARM} S := VarToStr(value); {$ELSE} {$IFDEF FPC} S := VarToStr(value); {$ELSE} if L2 > 0 then STR(value:L1:L2, S) else STR(value:L1, S); write(S); {$ENDIF} {$ENDIF} end else begin if VarType(value) = varEmpty then write('undefined') else write(VarToStr(value)); end; end; procedure _WriteObject(const value: TObject); begin write('[' + value.ClassName + ']'); end; {$IFDEF DRTTI} function CheckField(t: TRTTIType; f: TRTTIField): Boolean; begin result := false; if not CheckType(f.FieldType) then Exit; if f.Parent <> t then Exit; result := true; end; {$ENDIF} type TStdPrintHandler = class public S: String; procedure DoPrintClassTypeField(Sender: TObject; const Infos: TPrintClassTypeFieldInfo); procedure DoPrintClassTypeProp(Sender: TObject; const Infos: TPrintClassTypePropInfo); end; procedure TStdPrintHandler.DoPrintClassTypeField(Sender: TObject; const Infos: TPrintClassTypeFieldInfo); begin if Infos.FieldIndex = 0 then begin if Infos.Started then S := '(' else S := S + '('; end; S := S + Infos.FieldName; S := S + ': '; S := S + ScalarValueToString(Infos.Address, Infos.TypeId); if Infos.FieldIndex = Infos.FieldCount - 1 then begin S := S + ')'; if Infos.Finished then Exit; end else S := S + '; '; end; procedure TStdPrintHandler.DoPrintClassTypeProp(Sender: TObject; const Infos: TPrintClassTypePropInfo); begin if Infos.PropIndex = 0 then begin if Infos.Started then S := '(' else S := S + '('; end; S := S + Infos.PropName; S := S + ': '; S := S + Infos.StrValue; if Infos.PropIndex = Infos.PropCount - 1 then begin S := S + ')'; if Infos.Finished then Exit; end else S := S + '; '; end; procedure _PrintEx(PP: Pointer; Address: Pointer; Kind: Integer; FT: Integer; L1, L2: Integer); stdcall; var S: String; {$IFDEF PAXARM} SS: String; type ShortString = string; var {$ELSE} SS: ShortString; {$ENDIF} {$IFDEF DRTTI} ClassTypeInfoContainer: TClassTypeInfoContainer; ClassTypeDataContainer: TClassTypeDataContainer; FieldInfos: TPrintClassTypeFieldInfo; PropInfos: TPrintClassTypePropInfo; f: TRTTIField; t: TRTTIType; K: Integer; ptd: PTypeData; I: Integer; pti: PTypeInfo; nProps: Integer; pProps: PPropList; ppi: PPropInfo; {$ENDIF} X: TObject; P: TBaseRunner; label ByRef; begin P := TBaseRunner(PP); if Assigned(P) then if Assigned(P.OnPrintEx) then begin P.OnPrintEx(P.Owner, Address, Kind, FT, L1, L2); Exit; end; try if Kind = KindCONST then begin {$IFNDEF PAXARM} if FT = typeANSICHAR then begin S := String(AnsiChar(Byte(Address))); end else {$ENDIF} if FT = typeWIDECHAR then begin S := String(WideChar(Word(Address))); end else if FT in UnsignedIntegerTypes then begin if L1 > 0 then STR(Cardinal(Address):L1, SS) else STR(Cardinal(Address), SS); S := String(SS); end else if FT in OrdinalTypes then begin if L1 > 0 then STR(Integer(Address):L1, SS) else STR(Integer(Address), SS); S := String(SS); end {$IFNDEF PAXARM} else if FT = typePANSICHAR then begin S := String(StrPas(PAnsiChar(Address))); end {$ENDIF} else if FT = typePWIDECHAR then begin S := String(UnicString(PWideChar(Address))); end else goto ByRef; end else // Kind = KindVAR begin ByRef: case FT of typeBOOLEAN: if Boolean(Address^) then S := 'true' else S := 'false'; typeBYTE, typeENUM: begin if L1 > 0 then STR(Byte(Address^):L1, SS) else STR(Byte(Address^), SS); S := String(SS); end; {$IFNDEF PAXARM} typeANSICHAR: S := String(AnsiChar(Address^)); typeANSISTRING: begin S := String(AnsiString(Address^)); while Length(S) < L1 do S := S + ' '; end; {$ENDIF} typeUNICSTRING: begin S := String(UnicString(Address^)); while Length(S) < L1 do S := S + ' '; end; {$IFNDEF PAXARM} typePANSICHAR: S := String(StrPas(PAnsiChar(Address^))); {$ENDIF} typePWIDECHAR: S := String(PWideChar(Address^)); typeWORD: begin if L1 > 0 then STR(Word(Address^):L1, SS) else STR(Word(Address^), SS); S := String(SS); end; typeINTEGER: begin if L1 > 0 then STR(Integer(Address^):L1, SS) else STR(Integer(Address^), SS); S := String(SS); end; typeDOUBLE: begin if (L1 > 0) and (L2 > 0) then STR(Double(Address^):L1:L2, SS) else if L1 > 0 then STR(Double(Address^):L1, SS) else STR(Double(Address^), SS); S := String(SS); end; typePOINTER: S := String(Format('%x', [Cardinal(Address^)])); typeRECORD: S := '[record]'; typeARRAY: S := '[array]'; typePROC: S := '[proc]'; typeSET: S := '[set]'; {$IFNDEF PAXARM} typeSHORTSTRING: begin S := String(ShortString(Address^)); while Length(S) < L1 do S := S + ' '; end; {$ENDIF} typeSINGLE: begin if (L1 > 0) and (L2 > 0) then STR(Single(Address^):L1:L2, SS) else if L1 > 0 then STR(Single(Address^):L1, SS) else STR(Single(Address^), SS); S := String(SS); end; typeEXTENDED: begin if (L1 > 0) and (L2 > 0) then begin STR(Extended(Address^):L1:L2, SS); end else if L1 > 0 then begin STR(Extended(Address^):L1, SS); end else SS := ShortString(FloatToStr(Extended(Address^))); S := String(SS); end; typeCLASS: if Integer(Address^) = 0 then S := 'nil' else if TObject(Address^).InheritsFrom(TFW_Object) then begin S := TFW_Object(Address^)._ToString; end else begin X := TObject(Address^); {$IFDEF DRTTI} ClassTypeInfoContainer := GetClassTypeInfoContainer(X); if ClassTypeInfoContainer <> nil then begin try ClassTypeDataContainer := ClassTypeInfoContainer.TypeDataContainer as TClassTypeDataContainer; with ClassTypeDataContainer.FieldListContainer do for I := 0 to Count - 1 do begin Address := ShiftPointer(Pointer(X), Records[I].Offset); if Records[I].FinalFieldTypeId = typeCLASS then begin _PrintEx(P, Address, KindTYPE_FIELD, Records[I].FinalFieldTypeId, 0, 0); end else begin FieldInfos.Host := false; FieldInfos.Started := false; FieldInfos.Finished := false; if I = 0 then if Kind = KindVAR then FieldInfos.Started := true; FieldInfos.Owner := X; FieldInfos.FieldIndex := I; FieldInfos.FieldCount := Count; FieldInfos.Address := Address; FieldInfos.FieldName := StringFromPShortString(@Records[I].Name); FieldInfos.TypeId := Records[I].FinalFieldTypeId; FieldInfos.Visibility := GetVisibility(Records[I].Vis); if I = Count - 1 then FieldInfos.Finished := true; if Assigned(P) then if Assigned(P.OnPrintClassTypeField) then begin P.OnPrintClassTypeField(P.Owner, FieldInfos); end; end; end; with ClassTypeDataContainer.AnotherFieldListContainer do for I := 0 to Count - 1 do begin Address := ShiftPointer(Pointer(X), Records[I].Offset); if Records[I].FinalFieldTypeId = typeCLASS then begin _PrintEx(P, Address, KindTYPE_FIELD, Records[I].FinalFieldTypeId, 0, 0); end else begin FieldInfos.Host := false; FieldInfos.Started := false; FieldInfos.Finished := false; if I = 0 then if Kind = KindVAR then FieldInfos.Started := true; FieldInfos.Owner := X; FieldInfos.FieldIndex := I; FieldInfos.FieldCount := Count; FieldInfos.Address := Address; FieldInfos.FieldName := StringFromPShortString(@Records[I].Name); FieldInfos.TypeId := Records[I].FinalFieldTypeId; FieldInfos.Visibility := GetVisibility(Records[I].Vis); if I = Count - 1 then FieldInfos.Finished := true; if Assigned(P) then if Assigned(P.OnPrintClassTypeField) then begin P.OnPrintClassTypeField(P.Owner, FieldInfos); end; end; end; // published properties pti := X.ClassInfo; if pti <> nil then begin ptd := GetTypeData(pti); nProps := ptd^.PropCount; GetMem(pProps, SizeOf(PPropInfo) * nProps); try GetPropInfos(pti, pProps); for I:=0 to nProps - 1 do begin {$ifdef fpc} ppi := pProps^[I]; {$else} ppi := pProps[I]; {$endif} case ppi^.PropType^.Kind of tkClass: begin IntPax(X) := GetOrdProp(X, ppi); _PrintEx(P, @X, KindTYPE_FIELD, typeCLASS, 0, 0); end; else begin PropInfos.Host := false; PropInfos.Started := false; PropInfos.Finished := false; if I = 0 then if Kind = KindVAR then PropInfos.Started := true; PropInfos.Owner := X; PropInfos.PropIndex := I; PropInfos.PropCount := nProps; PropInfos.StrValue := VarToStr(GetPropValue(X, ppi)); PropInfos.PropName := StringFromPShortString(@ppi^.Name); PropInfos.Visibility := mvPublished; if I = nProps - 1 then PropInfos.Finished := true; if Assigned(P) then if Assigned(P.OnPrintClassTypeProp) then begin P.OnPrintClassTypeProp(P.Owner, PropInfos); end; end; end; end; finally FreeMem(pProps, SizeOf(PPropInfo) * nProps); end; end; finally FreeAndNil(ClassTypeInfoContainer); end; end else // this is an object of host-defined class. begin t := PaxContext.GetType(X.ClassType); K := 0; for f in t.GetFields do if CheckField(t, f) then Inc(K); I := 0; for f in t.GetFields do if CheckField(t, f) then begin Inc(I); Address := ShiftPointer(Pointer(X), f.Offset); if f.FieldType is TRTTIRecordType then begin _PrintEx(P, Address, KindTYPE_FIELD, typeRECORD, 0, 0); end else if f.FieldType is TRTTIInstanceType then begin _PrintEx(P, Address, KindTYPE_FIELD, typeCLASS, 0, 0); end else begin FieldInfos.Host := true; FieldInfos.Started := false; FieldInfos.Finished := false; if I = 0 then if Kind = KindVAR then FieldInfos.Started := true; FieldInfos.Owner := X; FieldInfos.FieldIndex := I; FieldInfos.FieldCount := K; FieldInfos.Address := Address; FieldInfos.FieldName := f.Name; FieldInfos.FieldTypeName := f.FieldType.Name; FieldInfos.TypeId := PtiToFinType(f.FieldType.Handle); FieldInfos.Visibility := f.Visibility; if I = K - 1 then FieldInfos.Finished := true; if Assigned(P) then if Assigned(P.OnPrintClassTypeField) then begin P.OnPrintClassTypeField(P.Owner, FieldInfos); end; end; end; end; {$ELSE} S := '[Object: ' + X.ClassName + ']'; {$ENDIF} end; typeCLASSREF: if Integer(Address^) = 0 then S := 'nil' else S := '[Class ref: ' + TClass(Address^).ClassName + ']'; typeWIDECHAR: S := WideChar(Address^); {$IFNDEF PAXARM} typeWIDESTRING: S := WideString(Address^); {$ENDIF} typeVARIANT, typeOLEVARIANT: begin if TVarData(Variant(Address^)).VType = varDispatch then S := '[dispatch]' else if (L1 > 0) and (L2 > 0) then begin {$IFDEF FPC} S := VarToStr(Variant(Address^)); {$ELSE} STR(Variant(Address^):L1:L2, SS); S := String(SS); {$ENDIF} end else if L1 > 0 then begin {$IFDEF FPC} S := VarToStr(Variant(Address^)); {$ELSE} STR(Variant(Address^):L1, SS); S := String(SS); {$ENDIF} end else S := VarToStr(Variant(Address^)); end; typeDYNARRAY: S := '[dynarray]'; typeINT64: begin if L1 > 0 then STR(Int64(Address^):L1, SS) else STR(Int64(Address^), SS); S := String(SS); end; typeUINT64: begin if L1 > 0 then STR(UInt64(Address^):L1, SS) else STR(UInt64(Address^), SS); S := String(SS); end; typeINTERFACE: S := '[interface]'; typeCARDINAL: begin if L1 > 0 then STR(Cardinal(Address^):L1, SS) else STR(Cardinal(Address^), SS); S := String(SS); end; typeEVENT: S := '[event]'; typeCURRENCY: begin if (L1 > 0) and (L2 > 0) then STR(Currency(Address^):L1:L2, SS) else if L1 > 0 then STR(Currency(Address^):L1, SS) else STR(Currency(Address^), SS); S := String(SS); end; typeSMALLINT: begin if L1 > 0 then STR(SmallInt(Address^):L1, SS) else STR(SmallInt(Address^), SS); S := String(SS); end; typeSHORTINT: begin if L1 > 0 then STR(ShortInt(Address^):L1, SS) else STR(ShortInt(Address^), SS); S := String(SS); end; typeWORDBOOL: if WordBool(Address^) then S := 'true' else S := 'false'; typeLONGBOOL: if LongBool(Address^) then S := 'true' else S := 'false'; typeBYTEBOOL: if ByteBool(Address^) then S := 'true' else S := 'false'; else S := ''; end; end; except on E: Exception do begin S := E.Message; raise; end; end; if Assigned(P) then if Assigned(P.OnPrint) then begin P.OnPrint(P.Owner, S); Exit; end; {$IFDEF CONSOLE} write(S); Exit; {$ELSE} {$IFDEF PAXARM} {$IFDEF PAXARM_DEVICE} ShowMessage(S); {$ELSE} ShowMessage(S); {$ENDIF} {$ELSE} {$IFDEF LINUX} ShowMessage(S); {$ELSE} {$IFDEF MACOS32} ShowMessage(S); {$ELSE} MessageBox(GetActiveWindow(), PChar(String(S)), PChar('paxCompiler'), MB_ICONEXCLAMATION or MB_OK); {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} end; procedure _GetMem(var P: Pointer; Size: Integer); begin GetMem(P, Size); end; procedure _FreeMem(P: Pointer; Size: Integer); begin FreeMem(P, Size); end; // -------- ORDINAL FUNCTIONS -------------------------------------------------- function _Odd(X: Integer): Boolean; begin result := Odd(X); end; //--------- SET ROUTINES ------------------------------------------------------ type TSetBytes = array[1..SizeOf(TByteSet)] of Byte; function UpdateSet(const S: TByteSet; L: Integer): TByteSet; var I: Integer; begin FillChar(result, SizeOf(result), 0); for I := 1 to L do TSetBytes(result)[I] := TSetBytes(S)[I]; end; procedure _SetInclude(S: PByteSet; value: Integer); stdcall; begin if (value < 0) or (value > 255) then raise Exception.Create(errInvalidSet); Include(S^, value); end; procedure _SetIncludeInterval(S: PByteSet; B1, B2: Integer); stdcall; var value: Integer; begin if (B1 < 0) or (B1 > 255) then raise Exception.Create(errInvalidSet); if (B2 < 0) or (B2 > 255) then raise Exception.Create(errInvalidSet); for value:=B1 to B2 do Include(S^, value); end; procedure _SetExclude(var S: TByteSet; value: Integer); stdcall; begin if (value < 0) or (value > 255) then raise Exception.Create(errInvalidSet); Exclude(S, value); end; procedure _SetUnion(var S1: TByteSet; var S2: TByteSet; var R: TByteSet; SZ1, SZ2: Integer); stdcall; var L: Integer; Res: TByteSet; begin if SZ2 < SZ1 then L := SZ2 else L := SZ1; Res := UpdateSet(S1, L) + UpdateSet(S2, L); Move(Res, R, L); end; procedure _SetDifference(var S1: TByteSet; var S2: TByteSet; var R: TByteSet; SZ1, SZ2: Integer); stdcall; var L: Integer; Res: TByteSet; begin if SZ2 < SZ1 then L := SZ2 else L := SZ1; Res := UpdateSet(S1, L) - UpdateSet(S2, L); Move(Res, R, L); end; procedure _SetIntersection(var S1: TByteSet; var S2: TByteSet; var R: TByteSet; SZ1, SZ2: Integer); stdcall; var L: Integer; Res: TByteSet; begin if SZ2 < SZ1 then L := SZ2 else L := SZ1; Res := UpdateSet(S1, L) * UpdateSet(S2, L); Move(Res, R, L); end; function _SetSubset(var S1: TByteSet; var S2: TByteSet; SZ1, SZ2: Integer): Boolean; stdcall; var L: Integer; begin if SZ2 < SZ1 then L := SZ2 else L := SZ1; result := UpdateSet(S1, L) <= UpdateSet(S2, L); end; function _SetSuperset(var S1: TByteSet; var S2: TByteSet; SZ1, SZ2: Integer): Boolean; stdcall; var L: Integer; begin if SZ2 < SZ1 then L := SZ2 else L := SZ1; result := UpdateSet(S1, L) >= UpdateSet(S2, L); end; function _SetEquality(const S1: TByteSet; const S2: TByteSet; SZ1, SZ2: Integer): Boolean; stdcall; var L, I: Integer; begin if SZ2 < SZ1 then L := SZ2 else L := SZ1; result := true; for I := 1 to L do if TSetBytes(S1)[I] <> TSetBytes(S2)[I] then begin result := false; Exit; end; end; function _SetInequality(const S1: TByteSet; const S2: TByteSet; SZ1, SZ2: Integer): Boolean; stdcall; var L, I: Integer; begin if SZ2 < SZ1 then L := SZ2 else L := SZ1; result := false; for I := 1 to L do if TSetBytes(S1)[I] <> TSetBytes(S2)[I] then begin result := true; Exit; end; end; function _SetMembership(value: Integer; var S: TByteSet): Boolean; stdcall; begin result := value in S; end; //--------- AnsiString ROUTINES ---------------------------------------------------- type PStringRec = ^TStringRec; TStringRec = packed record RefCount: Longint; Length: Longint; end; {$IFNDEF PAXARM} {$IFDEF MACOS32} procedure _DecStringCounter(var S: AnsiString); var P: PStringRec; D: Pointer; begin D := Pointer(S); if D <> nil then begin P := PStringRec(Integer(D) - sizeof(TStringRec)); if P^.RefCount > 0 then begin Dec(P^.RefCount); if P^.refCount = 0 then FreeMem(P); end; end; end; {$ELSE} procedure _DecStringCounter(var S: AnsiString); var P: PStringRec; D: Pointer; begin D := Pointer(S); if D <> nil then begin P := PStringRec(Integer(D) - sizeof(TStringRec)); if P^.RefCount > 0 then if InterlockedDecrement(P^.refCount) = 0 then FreeMem(P); end; end; {$ENDIF} {$ENDIF} {$IFNDEF PAXARM} {$IFDEF MACOS32} procedure _IncStringCounter(var S: AnsiString); var P: PStringRec; D: Pointer; begin D := Pointer(S); if D <> nil then begin P := PStringRec(Integer(D) - sizeof(TStringRec)); Inc(P^.RefCount); end; end; {$ELSE} procedure _IncStringCounter(var S: AnsiString); var P: PStringRec; D: Pointer; begin D := Pointer(S); if D <> nil then begin P := PStringRec(Integer(D) - sizeof(TStringRec)); InterlockedIncrement(P^.refCount); end; end; {$ENDIF} {$ENDIF} procedure _LoadClassRef(P: TBaseRunner; C: TClass); stdcall; begin P.GetRootProg.PassedClassRef := C; end; function _LoadProc(Runner: Pointer; ProcHandle: Integer; ProcName: PChar; DllName: PChar; OverCount: Integer): Pointer; stdcall; var H: THandle; Address: Pointer; I: Integer; Ext: String; MR: TMapRec; AClassName: String; C: TClass; VarName: String; S, S1, S2: String; Offset: Integer; MapFieldRec: TMapFieldRec; P: TBaseRunner; label ProcessDll; begin P := TBaseRunner(Runner); Address := nil; result := nil; Ext := ExtractFileExt(DllName); if StrEql(Ext, '.' + PCU_FILE_EXT) then begin if Assigned(P.PausedPCU) then Address := P.PausedPCU.LoadAddressEx( DllName, ProcName, true, OverCount, MR, result) else Address := P.LoadAddressEx( DllName, ProcName, true, OverCount, MR, result); if Address = nil then begin if MR <> nil then if MR.SubDesc.DllName <> '' then begin DllName := PChar(MR.SubDesc.DllName); ProcName := PChar(MR.SubDesc.AliasName); goto ProcessDll; end; raise Exception.Create(Format(errProcNotFoundInPCU, [String(ProcName), String(DllName)])); end; P.SetAddress(ProcHandle, Address); if (PosCh('.', ProcName) > 0) and (result <> nil) then begin AClassName := ExtractOwner(DllName) + '.' + ExtractOwner(ProcName); Address := TBaseRunner(result).GetAddress(AClassName, MR); if Address <> nil then C := TClass(Address^) else Exit; if C = nil then Exit; Address := P.GetAddress(AClassName, MR); if Address <> nil then Pointer(Address^) := C; end; Exit; end else if (StrEql(Ext, '.' + PRM_FILE_EXT) or StrEql(Ext, '.' + PRR_FILE_EXT)) and (not StrEql(ProcName, 'Self')) then begin VarName := ProcName; S := ExtractFullOwner(DllName); S1 := ExtractOwner(S) + '.' + PCU_FILE_EXT; S2 := ExtractFullName(S); Address := P.PausedPCU.LoadAddressEx( S1, S2, true, OverCount, MR, result); if MR <> nil then begin I := MR.SubDesc.ParamList.IndexOf(VarName); if I >= 0 then begin Offset := MR.SubDesc.ParamList[I].ParamOffset; Address := P.PausedPCU.GetParamAddress(Offset); if StrEql(Ext, '.' + PRR_FILE_EXT) then Address := Pointer(Address^); P.SetAddress(ProcHandle, Address); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); Exit; end else if StrEql(Ext, '.' + LOC_FILE_EXT) or StrEql(Ext, '.' + LOR_FILE_EXT) then begin VarName := ProcName; S := ExtractFullOwner(DllName); S1 := ExtractOwner(S) + '.' + PCU_FILE_EXT; S2 := ExtractFullName(S); Address := P.PausedPCU.LoadAddressEx( S1, S2, true, OverCount, MR, result); if MR <> nil then begin I := MR.SubDesc.LocalVarList.IndexOf(VarName); if I >= 0 then begin Offset := MR.SubDesc.LocalVarList[I].LocalVarOffset; Address := P.PausedPCU.GetLocalAddress(Offset); if StrEql(Ext, '.' + LOR_FILE_EXT) then Address := Pointer(Address^); P.SetAddress(ProcHandle, Address); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); Exit; end else if StrEql(Ext, '.' + SLF_FILE_EXT) then begin VarName := ProcName; S := ExtractFullOwner(DllName); S1 := ExtractOwner(S) + '.' + PCU_FILE_EXT; S2 := ExtractFullName(S); Address := P.PausedPCU.LoadAddressEx( S1, S2, true, OverCount, MR, result); if MR <> nil then begin Offset := MR.SubDesc.SelfOffset; Address := P.PausedPCU.GetLocalAddress(Offset); P.SetAddress(ProcHandle, Address); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); Exit; end else if StrEql(Ext, '.' + FLD_FILE_EXT) then begin VarName := ProcName; S := ExtractFullOwner(DllName); S1 := ExtractOwner(S) + '.' + PCU_FILE_EXT; S2 := ExtractFullName(S); Address := P.PausedPCU.LoadAddressEx( S1, S2, true, OverCount, MR, result); if MR <> nil then begin Offset := MR.SubDesc.SelfOffset; Address := P.PausedPCU.GetLocalAddress(Offset); if Address <> nil then begin MR := TBaseRunner(result).ScriptMapTable.LookupType( ExtractFullOwner(S)); if MR <> nil then begin MapFieldRec := MR.FieldList.Lookup(VarName); if MapFieldRec <> nil then begin Address := ShiftPointer(Pointer(Address^), MapFieldRec.FieldOffset); P.SetAddress(ProcHandle, Address); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); end else P.RaiseError(errEntryPointNotFoundInPCU, [S2, S1]); end; Exit; end; ProcessDll: if Assigned(P.OnLoadProc) then begin P.OnLoadProc(P.Owner, ProcName, DllName, Address); if Address <> nil then begin P.SetAddress(ProcHandle, Address); Exit; end; end; I := P.DllList.IndexOf(DllName); if I = - 1 then begin {$IFDEF LINUX} H := HMODULE(dynlibs.LoadLibrary(DLLName)); Address := dynlibs.GetProcedureAddress(H, ProcName); {$ELSE} H := LoadLibrary(DllName); Address := GetProcAddress(H, ProcName); {$ENDIF} if Address <> nil then P.DllList.AddObject(DllName, TObject(H)); end else begin H := Cardinal(P.DllList.Objects[I]); {$IFDEF LINUX} Address := dynlibs.GetProcedureAddress(H, ProcName); {$ELSE} Address := GetProcAddress(H, PChar(ProcName)); {$ENDIF} end; if H = 0 then raise Exception.Create(Format(errDllNotFound, [String(DllName)])); if Address = nil then raise Exception.Create(Format(errProcNotFound, [String(ProcName), String(DllName)])); P.SetAddress(ProcHandle, Address); end; {$IFNDEF PAXARM} procedure _AnsiStringFromPAnsiChar(source: PAnsiChar; var dest: AnsiString); stdcall; begin dest := source; end; procedure _AnsiStringFromPWideChar(source: PWideChar; var dest: AnsiString); stdcall; begin dest := AnsiString(WideString(source)); end; procedure _AnsiStringFromAnsiChar(source: AnsiChar; var dest: AnsiString); stdcall; begin dest := source; end; procedure _WideStringFromAnsiChar(source: AnsiChar; var dest: WideString); stdcall; begin dest := WideString(source); end; procedure _UnicStringFromAnsiChar(source: AnsiChar; var dest: UnicString); stdcall; begin dest := UnicString(source); end; procedure _WideStringFromShortString(var Dest: WideString; Source: ShortString); stdcall; begin Dest := WideString(Source); end; procedure _ShortStringFromAnsiString(var Dest: ShortString; L: Integer; var Source: AnsiString); stdcall; begin Dest := Copy(Source, 1, L); end; procedure _ShortStringFromWideString(var Dest: ShortString; L: Integer; var Source: WideString); stdcall; begin Dest := ShortString(Copy(Source, 1, L)); end; procedure _ShortStringFromPWideChar(var Dest: ShortString; L: Integer; Source: PWideChar); stdcall; begin Dest := ShortString(Copy(WideString(Source), 1, L)); end; procedure _ShortStringFromUnicString(var Dest: ShortString; L: Integer; var Source: UnicString); stdcall; begin Dest := ShortString(Copy(Source, 1, L)); end; procedure _AnsiStringFromShortString(var Dest: AnsiString; Source: ShortString); stdcall; begin Dest := Source; end; procedure _UnicStringFromShortString(var Dest: UnicString; Source: ShortString); stdcall; begin Dest := UnicString(Source); end; procedure _AnsiStringFromWideString(var Dest: AnsiString; var Source: WideString); stdcall; begin Dest := AnsiString(Source); end; procedure _AnsiStringFromUnicString(var Dest: AnsiString; var Source: UnicString); stdcall; begin Dest := AnsiString(Source); end; procedure _WideStringFromAnsiString(var Dest: WideString; var Source: AnsiString); stdcall; begin Dest := WideString(Source); end; procedure _UnicStringFromAnsiString(var Dest: UnicString; var Source: AnsiString); stdcall; begin Dest := UnicString(Source); end; procedure _AnsiStringAddition(var s1: AnsiString; var s2: AnsiString; var dest: AnsiString); stdcall; begin dest := s1 + s2; end; procedure _ShortStringAddition(var s1, s2, dest: ShortString); stdcall; begin dest := s1 + s2; end; procedure _AnsiStringEquality(var s1: AnsiString; var s2: AnsiString; var dest: Boolean); stdcall; begin dest := s1 = s2; end; procedure _AnsiStringNotEquality(var s1: AnsiString; var s2: AnsiString; var dest: Boolean); stdcall; begin dest := s1 <> s2; end; procedure _ShortStringEquality(const s1: ShortString; const s2: ShortString; var dest: Boolean); stdcall; begin dest := s1 = s2; end; procedure _ShortStringNotEquality(const s1: ShortString; const s2: ShortString; var dest: Boolean); stdcall; begin dest := s1 <> s2; end; procedure _AnsiStringGreaterThan(var s1: AnsiString; var s2: AnsiString; var dest: Boolean); stdcall; begin dest := s1 > s2; end; procedure _AnsiStringGreaterThanOrEqual(var s1: AnsiString; var s2: AnsiString; var dest: Boolean); stdcall; begin dest := s1 >= s2; end; procedure _AnsiStringLessThan(var s1: AnsiString; var s2: AnsiString; var dest: Boolean); stdcall; begin dest := s1 < s2; end; procedure _AnsiStringLessThanOrEqual(var s1: AnsiString; var s2: AnsiString; var dest: Boolean); stdcall; begin dest := s1 <= s2; end; procedure _ShortStringGreaterThan(const s1: ShortString; const s2: ShortString; var dest: Boolean); stdcall; begin dest := s1 > s2; end; procedure _ShortStringGreaterThanOrEqual(const s1: ShortString; const s2: ShortString; var dest: Boolean); stdcall; begin dest := s1 >= s2; end; procedure _ShortStringLessThan(const s1: ShortString; const s2: ShortString; var dest: Boolean); stdcall; begin dest := s1 < s2; end; procedure _ShortStringLessThanOrEqual(const s1: ShortString; const s2: ShortString; var dest: Boolean); stdcall; begin dest := s1 <= s2; end; procedure _SetShortStringLength(var S: ShortString; L: Integer); stdcall; begin SetLength(S, L); end; procedure _SetWideStringLength(var S: WideString; L: Integer); stdcall; begin SetLength(S, L); end; procedure _WideStringFromPAnsiChar(source: PAnsiChar; var dest: WideString); stdcall; begin dest := WideString(AnsiString(source)); end; procedure _UnicStringFromPAnsiChar(source: PAnsiChar; var dest: UnicString); stdcall; begin dest := String(AnsiString(source)); end; procedure _WideStringFromPWideChar(source: PWideChar; var dest: WideString); stdcall; begin dest := WideString(source); end; procedure _WideStringFromWideChar(source: WideChar; var dest: WideString); stdcall; begin dest := source; end; procedure _AnsiStringFromWideChar(source: WideChar; var dest: AnsiString); stdcall; begin dest := AnsiString(source); end; procedure _AnsiStringAssign(var dest: AnsiString; var source: AnsiString); stdcall; begin dest := source; end; procedure _UnicStringFromWideString(var Dest: UnicString; var Source: WideString); stdcall; begin Dest := Source; end; procedure _WideStringFromUnicString(var Dest: WideString; var Source: UnicString); stdcall; begin Dest := Source; end; procedure _WideStringAssign(var dest: WideString; var source: WideString); stdcall; begin dest := source; end; procedure _WideStringAddition(var s1: WideString; var s2: WideString; var dest: WideString); stdcall; begin dest := s1 + s2; end; procedure _WideStringEquality(var s1: WideString; var s2: WideString; var dest: Boolean); stdcall; begin dest := s1 = s2; end; procedure _WideStringNotEquality(var s1: WideString; var s2: WideString; var dest: Boolean); stdcall; begin dest := s1 <> s2; end; function _Copy(const S: AnsiString; Index, Count:Integer): AnsiString; begin result := Copy(S, Index, Count); end; procedure _Insert(Source: AnsiString; var S: AnsiString; Index: Integer); begin Insert(Source, S, Index); end; function _PosString(const Substr: AnsiString; const S: AnsiString): Integer; begin result := Pos(Substr, S); end; function _PosChar(c: AnsiChar; const S: AnsiString): Integer; var I: Integer; begin for I:=SLow(s) to SHigh(s) do if s[I] = c then begin result := I; Exit; end; result := 0; end; procedure _StrInt(var S: AnsiString; L1, L2: Integer; value: Integer); stdcall; begin if L1 > 0 then Str(value:L1, S) else Str(value, S); end; procedure _StrDouble(var S: AnsiString; L2, L1: Integer; value: Double); stdcall; begin if L1 > 0 then begin if L2 > 0 then Str(value:L1:L2, S) else Str(value:L1, S); end else Str(value, S); end; procedure _StrSingle(var S: AnsiString; L2, L1: Integer; value: Single); stdcall; begin if L1 > 0 then begin if L2 > 0 then Str(value:L1:L2, S) else Str(value:L1, S); end else Str(value, S); end; procedure _StrExtended(var S: AnsiString; L2, L1: Integer; value: Extended); stdcall; begin if L1 > 0 then begin if L2 > 0 then Str(value:L1:L2, S) else Str(value:L1, S); end else Str(value, S); end; procedure _VariantFromShortString(var Dest: Variant; var Source: ShortString); stdcall; begin Dest := Source; end; procedure _OleVariantFromShortString(var Dest: OleVariant; var Source: ShortString); stdcall; begin Dest := Source; end; procedure _VariantFromAnsiChar(source: AnsiChar; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromAnsiChar(source: AnsiChar; var dest: OleVariant); stdcall; begin dest := source; end; procedure _ShortStringFromVariant(var Dest: ShortString; L: Integer; var Source: Variant); stdcall; begin Dest := Copy(ShortString(source), 1, L); end; procedure _WideStringGreaterThan(var s1: WideString; var s2: WideString; var dest: Boolean); stdcall; begin dest := s1 > s2; end; procedure _WideStringGreaterThanOrEqual(var s1: WideString; var s2: WideString; var dest: Boolean); stdcall; begin dest := s1 >= s2; end; procedure _WideStringLessThan(var s1: WideString; var s2: WideString; var dest: Boolean);stdcall; begin dest := s1 < s2; end; procedure _WideStringLessThanOrEqual(var s1: WideString; var s2: WideString; var dest: Boolean); stdcall; begin dest := s1 <= s2; end; procedure _SetStringLength(var S: AnsiString; L: Integer); stdcall; begin SetLength(S, L); end; procedure _AnsiStringClr(var S: AnsiString); stdcall; begin S := ''; end; procedure _WideStringClr(var S: WideString); stdcall; begin S := ''; end; procedure _UniqueAnsiString(var S: AnsiString); stdcall; begin UniqueString(S); end; function _LengthString(const S: AnsiString): Integer; begin result := Length(S); end; function _LengthWideString(const S: WideString): Integer; begin result := Length(S); end; procedure _Delete(var S: AnsiString; Index, Count:Integer); begin Delete(S, Index, Count); end; procedure _VariantFromPAnsiChar(source: PAnsiChar; var dest: Variant); stdcall; begin dest := AnsiString(Source); end; procedure _OleVariantFromPAnsiChar(source: PAnsiChar; var dest: OleVariant); stdcall; begin dest := AnsiString(Source); end; procedure _VariantFromAnsiString(var Dest: Variant; var Source: AnsiString); stdcall; begin Dest := Source; end; procedure _OleVariantFromAnsiString(var Dest: OleVariant; var Source: AnsiString); stdcall; begin Dest := Source; end; procedure _VariantFromWideString(var Dest: Variant; var Source: WideString); stdcall; begin Dest := Source; end; procedure _OleVariantFromWideString(var Dest: OleVariant; var Source: WideString); stdcall; begin Dest := Source; end; procedure _AnsiStringFromInt(var dest: AnsiString; var source: Integer); stdcall; //JS only begin dest := AnsiString(IntToStr(source)); end; procedure _AnsiStringFromDouble(var dest: AnsiString; var source: Double); stdcall; //JS only begin dest := AnsiString(FloatToStr(source)); end; procedure _AnsiStringFromSingle(var dest: AnsiString; var source: Single); stdcall; //JS only begin dest := AnsiString(FloatToStr(source)); end; procedure _AnsiStringFromExtended(var dest: AnsiString; var source: Extended); stdcall; //JS only begin dest := AnsiString(FloatToStr(source)); end; procedure _AnsiStringFromBoolean(var dest: AnsiString; var source: Boolean); stdcall; //JS only begin if source then dest := 'true' else dest := 'false'; end; procedure _AnsiCharFromVariant(var dest: AnsiChar; var source: Variant); stdcall; begin dest := AnsiChar(TVarData(Source).VInteger); end; procedure _AnsiStringFromVariant(var dest: AnsiString; var source: Variant); stdcall; begin dest := AnsiString(source); end; procedure _WideStringFromVariant(var dest: WideString; var source: Variant); stdcall; begin dest := source; end; //////////////////////////////////////// NOT PAXARM ///////////////// {$ENDIF} /////////////////////////////// NOT PAXARM ///////////////// //////////////////////////////////////// NOT PAXARM ///////////////// procedure _ShortStringAssign(const source: ShortString; Ldest: Integer; dest: PShortString); stdcall; var I, L: Integer; begin {$IFDEF ARC} L := Source[0]; {$ELSE} L := Length(Source); {$ENDIF} if L > Ldest then L := Ldest; {$IFDEF ARC} dest^[0] := L; {$ELSE} dest^[0] := AnsiChar(Chr(L)); {$ENDIF} for I := 1 to L do dest^[I] := Source[I]; end; procedure _UnicStringFromPWideChar(source: PWideChar; var dest: UnicString); stdcall; begin dest := UnicString(source); end; procedure _UnicStringFromWideChar(source: WideChar; var dest: UnicString); stdcall; begin dest := source; end; procedure _UnicStringAssign(var dest: UnicString; var source: UnicString); stdcall; begin dest := source; end; procedure _UnicStringAddition(var s1: UnicString; var s2: UnicString; var dest: UnicString); stdcall; begin dest := s1 + s2; end; procedure _UnicStringEquality(var s1: UnicString; var s2: UnicString; var dest: Boolean); stdcall; begin dest := s1 = s2; end; procedure _UnicStringNotEquality(var s1: UnicString; var s2: UnicString; var dest: Boolean); stdcall; begin dest := s1 <> s2; end; procedure _UnicStringGreaterThan(var s1: UnicString; var s2: UnicString; var dest: Boolean); stdcall; begin dest := s1 > s2; end; procedure _UnicStringGreaterThanOrEqual(var s1: UnicString; var s2: UnicString; var dest: Boolean); stdcall; begin dest := s1 >= s2; end; procedure _UnicStringLessThan(var s1: UnicString; var s2: UnicString; var dest: Boolean);stdcall; begin dest := s1 < s2; end; procedure _UnicStringLessThanOrEqual(var s1: UnicString; var s2: UnicString; var dest: Boolean); stdcall; begin dest := s1 <= s2; end; procedure _SetVariantLength(var V: Variant; VType: Integer; L: Integer); stdcall; begin V := VarArrayCreate([0, L - 1], VType); end; procedure _SetVariantLength2(var V: Variant; VType: Integer; L1, L2: Integer); stdcall; begin V := VarArrayCreate([0, L1 - 1, 0, L2 - 1], VType); end; procedure _SetVariantLength3(var V: Variant; VType: Integer; L1, L2, L3: Integer); stdcall; begin V := VarArrayCreate([0, L1 - 1, 0, L2 - 1, 0, L3 - 1], VType); end; procedure _SetUnicStringLength(var S: UnicString; L: Integer); stdcall; begin SetLength(S, L); end; procedure _UnicStringClr(var S: UnicString); stdcall; begin S := ''; end; procedure _InterfaceClr(var I: IUnknown); stdcall; begin I := nil; end; procedure _UniqueUnicString(var S: UnicString); stdcall; begin {$IFDEF VARIANTS} UniqueString(S); {$ENDIF} end; function _LengthShortString(const S: ShortString): Integer; begin result := Length(S); end; function _LengthUnicString(const S: UnicString): Integer; begin result := Length(S); end; procedure _ValInt(const S: String; var V: Integer; var Code: Integer); begin Val(S, V, Code); end; procedure _ValDouble(const S: String; var V: Double; var Code: Integer); begin Val(S, V, Code); end; procedure _ShortstringHigh(const P: Shortstring; var result: Integer); stdcall; begin result := Length(P) - 1; end; // unic string routines function _UnicLength(const S: UnicString): Integer; begin result := Length(S); end; procedure _UnicDelete(var S: UnicString; Index, Count: Integer); begin Delete(S, Index, Count); end; function _UnicCopy(const S: UnicString; Index, Count: Integer): UnicString; begin result := Copy(S, Index, Count); end; procedure _UnicInsert(Source: UnicString; var S: UnicString; Index: Integer); begin Insert(Source, S, Index); end; procedure _UnicValInt(const S: UnicString; var V: Integer; var Code: Integer); begin Val(S, V, Code); end; procedure _UnicValDouble(const S: UnicString; var V: Double; var Code: Integer); begin Val(S, V, Code); end; function _UnicPos(const Substr: UnicString; const S: UnicString): Integer; begin result := Pos(Substr, S); end; // INT64 ROUTINES /////////////////////////////////////// procedure _Int64Multiplication(var v1: Int64; var v2: Int64; var dest: Int64); stdcall; begin dest := v1 * v2; end; procedure _Int64Division(var v1: Int64; var v2: Int64; var dest: Int64); stdcall; begin dest := v1 div v2; end; procedure _Int64Modulo(var v1: Int64; var v2: Int64; var dest: Int64); stdcall; begin dest := v1 mod v2; end; procedure _Int64LeftShift(var v1: Int64; var v2: Int64; var dest: Int64); stdcall; begin dest := v1 shl v2; end; procedure _Int64RightShift(var v1: Int64; var v2: Int64; var dest: Int64); stdcall; begin dest := v1 shr v2; end; procedure _Int64LessThan(var v1: Int64; var v2: Int64; var dest: Boolean); stdcall; begin dest := v1 < v2; end; procedure _Int64LessThanOrEqual(var v1: Int64; var v2: Int64; var dest: Boolean); stdcall; begin dest := v1 <= v2; end; procedure _Int64GreaterThan(var v1: Int64; var v2: Int64; var dest: Boolean); stdcall; begin dest := v1 > v2; end; procedure _Int64GreaterThanOrEqual(var v1: Int64; var v2: Int64; var dest: Boolean); stdcall; begin dest := v1 >= v2; end; procedure _Int64Equality(var v1: Int64; var v2: Int64; var dest: Boolean); stdcall; begin dest := v1 = v2; end; procedure _Int64NotEquality(var v1: Int64; var v2: Int64; var dest: Boolean); stdcall; begin dest := v1 <> v2; end; procedure _Int64Abs(var v1: Int64; var dest: Int64); stdcall; begin dest := Abs(v1); end; procedure _UInt64LessThan(var v1: UInt64; var v2: UInt64; var dest: Boolean); stdcall; begin dest := v1 < v2; end; procedure _UInt64LessThanOrEqual(var v1: UInt64; var v2: UInt64; var dest: Boolean); stdcall; begin dest := v1 <= v2; end; procedure _UInt64GreaterThan(var v1: UInt64; var v2: UInt64; var dest: Boolean); stdcall; begin dest := v1 > v2; end; procedure _UInt64GreaterThanOrEqual(var v1: UInt64; var v2: UInt64; var dest: Boolean); stdcall; begin dest := v1 >= v2; end; procedure _VariantAssign(var dest: Variant; var source: Variant); stdcall; begin if VarIsNull(source) then VarClear(dest); dest := source; end; procedure _OleVariantAssign(var dest: OleVariant; var source: OleVariant); stdcall; begin dest := source; end; procedure _VariantFromInterface(const source: IDispatch; var dest: Variant); stdcall; begin dest := Source; end; procedure _OleVariantFromInterface(const source: IDispatch; var dest: OleVariant); stdcall; begin dest := Source; end; procedure _VariantFromPWideChar(source: PWideChar; var dest: Variant); stdcall; begin dest := UnicString(Source); end; procedure _OleVariantFromPWideChar(source: PWideChar; var dest: OleVariant); stdcall; begin dest := UnicString(Source); end; procedure _OleVariantFromVariant(var Dest: OleVariant; var Source: Variant); stdcall; begin Dest := Source; end; procedure _VariantFromUnicString(var Dest: Variant; var Source: UnicString); stdcall; begin Dest := Source; end; procedure _OleVariantFromUnicString(var Dest: OleVariant; var Source: UnicString); stdcall; begin Dest := Source; end; procedure _VariantFromWideChar(source: WideChar; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromWideChar(source: WideChar; var dest: OleVariant); stdcall; begin dest := source; end; procedure _VariantFromInt(source: Integer; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromInt(source: Integer; var dest: OleVariant); stdcall; begin dest := source; end; {$IFDEF VARIANTS} procedure _VariantFromInt64(var dest: Variant; var source: Int64); stdcall; begin dest := source; end; procedure _OleVariantFromInt64(var dest: OleVariant; var source: Int64); stdcall; begin dest := source; end; {$ELSE} procedure _VariantFromInt64(var dest: Variant; var source: Int64); stdcall; begin dest := Integer(source); end; procedure _OleVariantFromInt64(var dest: OleVariant; var source: Int64); stdcall; begin dest := Integer(source); end; {$ENDIF} procedure _VariantFromByte(source: Byte; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromByte(source: Byte; var dest: OleVariant); stdcall; begin dest := source; end; procedure _VariantFromBool(source: Boolean; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromBool(source: Boolean; var dest: OleVariant); stdcall; begin dest := source; end; procedure _VariantFromWord(source: Word; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromWord(source: Word; var dest: OleVariant); stdcall; begin dest := source; end; procedure _VariantFromCardinal(source: Cardinal; var dest: Variant); stdcall; begin {$IFDEF VARIANTS} dest := source; {$ELSE} dest := Integer(source); {$ENDIF} end; {$IFDEF VARIANTS} procedure _OleVariantFromCardinal(source: Cardinal; var dest: OleVariant); stdcall; begin dest := source; end; {$ELSE} procedure _OleVariantFromCardinal(source: Integer; var dest: OleVariant); stdcall; begin dest := source; end; {$ENDIF} procedure _VariantFromSmallInt(source: SmallInt; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromSmallInt(source: SmallInt; var dest: OleVariant); stdcall; begin dest := source; end; procedure _VariantFromShortInt(source: ShortInt; var dest: Variant); stdcall; begin dest := source; end; procedure _OleVariantFromShortInt(source: ShortInt; var dest: OleVariant); stdcall; begin dest := source; end; procedure _VariantFromDouble(var dest: Variant; var source: Double); stdcall; begin dest := source; end; procedure _OleVariantFromDouble(var dest: OleVariant; var source: Double); stdcall; begin dest := source; end; procedure _VariantFromCurrency(var dest: Variant; var source: Currency); stdcall; begin dest := source; end; procedure _OleVariantFromCurrency(var dest: OleVariant; var source: Currency); stdcall; begin dest := source; end; procedure _VariantFromSingle( var dest: Variant; var source: Single); stdcall; begin dest := source; end; procedure _OleVariantFromSingle(var dest: OleVariant; var source: Single); stdcall; begin dest := source; end; procedure _VariantFromExtended(var dest: Variant; var source: Extended); stdcall; begin dest := source; end; procedure _OleVariantFromExtended(var dest: OleVariant; var source: Extended); stdcall; begin dest := source; end; procedure _UnicStringFromInt(var dest: UnicString; var source: Integer); stdcall; //JS only begin dest := IntToStr(source); end; procedure _UnicStringFromDouble(var dest: UnicString; var source: Double); stdcall; //JS only begin dest := FloatToStr(source); end; procedure _UnicStringFromSingle(var dest: UnicString; var source: Single); stdcall; //JS only begin dest := FloatToStr(source); end; procedure _UnicStringFromExtended(var dest: UnicString; var source: Extended); stdcall; //JS only begin dest := FloatToStr(source); end; procedure _UnicStringFromBoolean(var dest: UnicString; var source: Boolean); stdcall; //JS only begin if source then dest := 'true' else dest := 'false'; end; procedure _WideCharFromVariant(var dest: WideChar; var source: Variant); stdcall; begin dest := WideChar(TVarData(Source).VInteger); end; procedure _UnicStringFromVariant(var dest: UnicString; var source: Variant); stdcall; begin dest := source; end; procedure _DoubleFromVariant(var dest: Double; var source: Variant); stdcall; begin dest := source; end; procedure _CurrencyFromVariant(var dest: Currency; var source: Variant); stdcall; begin dest := source; end; procedure _SingleFromVariant(var dest: Single; var source: Variant); stdcall; begin dest := source; end; procedure _ExtendedFromVariant(var dest: Extended; var source: Variant); stdcall; begin dest := source; end; procedure _IntFromVariant(var dest: Integer; var source: Variant); stdcall; begin dest := source; end; {$IFDEF VARIANTS} procedure _Int64FromVariant(var dest: Int64; var source: Variant); stdcall; begin dest := source; end; {$ELSE} procedure _Int64FromVariant(var dest: Int64; var source: Variant); stdcall; begin dest := Integer(source); end; {$ENDIF} procedure _ByteFromVariant(var dest: Byte; var source: Variant); stdcall; begin dest := source; end; procedure _WordFromVariant(var dest: Word; var source: Variant); stdcall; begin dest := source; end; procedure _CardinalFromVariant(var dest: Cardinal; var source: Variant); stdcall; begin dest := source; end; procedure _SmallIntFromVariant(var dest: SmallInt; var source: Variant); stdcall; begin dest := source; end; procedure _ShortIntFromVariant(var dest: ShortInt; var source: Variant); stdcall; begin dest := source; end; procedure _BoolFromVariant(var dest: Boolean; var source: Variant); stdcall; begin dest := source; end; procedure _ByteBoolFromVariant(var dest: ByteBool; var source: Variant); stdcall; begin {$IFDEF FPC} if source <> 0 then dest := true else dest := false; {$ELSE} dest := source; {$ENDIF} end; procedure _WordBoolFromVariant(var dest: WordBool; var source: Variant); stdcall; begin dest := source; end; procedure _LongBoolFromVariant(var dest: LongBool; var source: Variant); stdcall; begin dest := source; end; procedure _StructEquality(P1, P2: Pointer; SZ: Integer; var dest: Boolean); stdcall; begin dest := CompareMem(P1, P2, SZ); end; procedure _StructNotEquality(P1, P2: Pointer; SZ: Integer; var dest: Boolean); stdcall; begin dest := not CompareMem(P1, P2, SZ); end; procedure _VariantNot(var v1: Variant; var dest: Variant); stdcall; begin dest := not v1; end; procedure _VariantNegation(var v1: Variant; var dest: Variant); stdcall; begin dest := - v1; end; procedure _VariantAbs(var v1: Variant; var dest: Variant); stdcall; begin if v1 >= 0 then dest := v1 else dest := -v1; end; procedure _VarArrayPut1(var V: Variant; var value: Variant; const I1: Variant); stdcall; begin V[I1] := value; end; procedure _VarArrayGet1(var V: Variant; var result: Variant; const I1: Variant); stdcall; begin result := V[I1]; end; procedure _VarArrayPut2(var V: Variant; var value: Variant; const I2, I1: Variant); stdcall; begin V[I1, I2] := value; end; procedure _VarArrayGet2(var V: Variant; var result: Variant; const I2, I1: Variant); stdcall; begin result := V[I1, I2]; end; procedure _VarArrayPut3(var V: Variant; var value: Variant; const I3, I2, I1: Variant); stdcall; begin V[I1, I2, I3] := value; end; procedure _VarArrayGet3(var V: Variant; var result: Variant; const I3, I2, I1: Variant); stdcall; begin result := V[I1, I2, I3]; end; procedure _DoubleMultiplication(Language: Integer; var v1: Double; var v2: Double; var dest: Double); stdcall; begin dest := v1 * v2; end; procedure _DoubleDivision(Language: Integer; var v1: Double; var v2: Double; var dest: Double); stdcall; begin dest := v1 / v2; end; procedure _DoubleAddition(Language: Integer; var v1: Double; var v2: Double; var dest: Double); stdcall; begin dest := v1 + v2; end; procedure _DoubleSubtraction(Language: Integer; var v1: Double; var v2: Double; var dest: Double); stdcall; begin dest := v1 - v2; end; procedure _DoubleNegation(var v1: Double; var dest: Double); stdcall; begin dest := - v1; end; function GetPaxInterface(Self: TObject; const GUID: TGUID; var obj: Pointer): Boolean; var PaxInfo: PPaxInfo; P: TBaseRunner; ClassRec: TClassRec; IntfList: TIntfList; I, SZ: Integer; begin PaxInfo := GetPaxInfo(Self.ClassType); if PaxInfo = nil then raise Exception.Create(errInternalError); P := TBaseRunner(PaxInfo^.Prog); ClassRec := P.ClassList[PaxInfo^.ClassIndex]; IntfList := ClassRec.IntfList; I := IntfList.IndexOf(GUID); if I = -1 then result := false else begin SZ := Self.InstanceSize - IntfList.Count * SizeOf(Pointer); Obj := ShiftPointer(Self, SZ + I * SizeOf(Pointer)); result := true; end; end; { procedure _IntfCast(var Dest: IInterface; const Source: IInterface; const IID: TGUID); // PIC: EBX must be correct before calling QueryInterface var Temp: IInterface; begin if Source = nil then Dest := nil else begin Temp := nil; if Source.QueryInterface(IID, Temp) <> 0 then Error(reIntfCastError) else Dest := Temp; end; end; } {$IFNDEF PAXARM} {$IFNDEF PAX64} function TObject_GetScriptInterface(Self: TObject; const IID: TGUID; out Obj): Boolean; var InterfaceEntry: PInterfaceEntry; begin Pointer(Obj) := nil; InterfaceEntry := Self.GetInterfaceEntry(IID); if InterfaceEntry <> nil then begin if InterfaceEntry^.IOffset <> 0 then begin Pointer(Obj) := ShiftPointer(Pointer(Self), InterfaceEntry^.IOffset); asm push edi push esi push ebx end; if Pointer(Obj) <> nil then IInterface(Obj)._AddRef; asm pop ebx pop esi pop edi end; end; end; Result := Pointer(Obj) <> nil; end; {$ENDIF} {$ENDIF} procedure _InterfaceFromClass(Dest: PIUnknown; GUID: PGUID; SourceAddress: Pointer); stdcall; var Temp: IInterface; begin if Pointer(SourceAddress^) = nil then begin Dest^ := nil; Exit; end; Temp := nil; {$IFNDEF PAXARM} {$IFNDEF PAX64} if IsPaxObject(TObject(SourceAddress^)) then begin if not TObject_GetScriptInterface(TObject(SourceAddress^), GUID^, Temp) then raise Exception.Create(errIncompatibleTypesNoArgs); end else {$ENDIF} {$ENDIF} begin if not TMyInterfacedObject(SourceAddress^).GetInterface(GUID^, Temp) then raise Exception.Create(errIncompatibleTypesNoArgs); end; Dest^ := Temp; end; procedure _InterfaceCast(Dest: PIUnknown; GUID: PGUID; Source: PIUnknown); stdcall; var Temp: Pointer; begin if Source^ = nil then Dest^ := nil else begin Temp := nil; if Source.QueryInterface(GUID^, Temp) <> 0 then raise Exception.Create(errIncompatibleTypesNoArgs); if Assigned(Dest^) then Dest^._Release; Pointer(Dest^) := Temp; end; end; procedure _InterfaceAssign(var Dest: IUnknown; var Source: IUnknown); stdcall; begin Dest := Source; end; // PASCAL ARITHMETIC ROUTINES /////////////////////////////////////// function _ArcTan(const X: Extended): Extended; begin result := ArcTan(X); end; function _Cos(const X: Extended): Extended; begin result := Cos(X); end; function _Exp(X: Extended): Extended; begin result := Exp(X); end; function _Frac(X: Extended): Extended; begin result := Frac(X); end; function _Int(X: Extended): Extended; begin result := Int(X); end; function _Ln(X: Extended): Extended; begin result := Ln(X); end; function _Sin(X: Extended): Extended; begin result := Sin(X); end; function _Sqr(X: Extended): Extended; begin result := Sqr(X); end; function _Sqrt(X: Extended): Extended; begin result := Sqrt(X); end; function _Trunc(X: Extended): Integer; begin result := Trunc(X); end; function _Power(const Base, Exponent: Extended): Extended; begin result := Power(Base, Exponent); end; // PASCAL MISCELLANEOUS ROUTINES //////////////////////////////////// procedure _FillChar(var X; Count: Integer; Value: Byte); begin FillChar(X, Count, Value); end; function _Random: Double; begin result := Random; end; function _Random1(N: Integer): Integer; begin result := Random(N); end; function _HiInt(N: Integer): Byte; begin result := Hi(N); end; function _HiWord(N: Word): Byte; begin result := Hi(N); end; function _LoInt(N: Integer): Byte; begin result := Lo(N); end; function _LoWord(N: Word): Byte; begin result := Lo(N); end; {$IFDEF FPC} function _UpCase(Ch: AnsiChar): AnsiChar; begin result := Upcase(Ch); end; {$ENDIF} function GetClassByIndex(P: TBaseRunner; I: Integer): TClass; begin result := P.ClassList[I].PClass; end; procedure _Is(PClass: TClass; Instance: TObject; var result: Boolean); stdcall; begin result := Instance is PClass; end; procedure _ToParentClass2(Instance: TObject); stdcall; var C: TClass; begin C := Instance.ClassType; while IsPaxClass(C) do C := C.ClassParent; Move(C, Pointer(Instance)^, SizeOf(Pointer)); end; procedure _UpdateInstance2(Instance: TObject; C: TClass); stdcall; begin Move(C, Pointer(Instance)^, SizeOf(Pointer)); end; {$IFDEF NO_PARENT_CLASS} procedure _ToParentClass(P: TBaseRunner; Instance: TObject); stdcall; begin end; procedure _UpdateInstance(P: TBaseRunner; Instance: TObject); stdcall; begin end; {$ELSE} procedure _ToParentClass(P: TBaseRunner; Instance: TObject); stdcall; var C: TClass; begin {$IFNDEF PAXARM_DEVICE} {$IFNDEF FPC} if not (Instance is TCustomForm) then Exit; {$ENDIF} {$ENDIF} C := Instance.ClassType; P.SavedClass := C; while IsPaxClass(C) do C := C.ClassParent; if Instance is TComponent then TComponent(Instance).Tag := Integer(P.SavedClass); Move(C, Pointer(Instance)^, SizeOf(Pointer)); end; procedure _UpdateInstance(P: TBaseRunner; Instance: TObject); stdcall; var C: TClass; begin {$IFNDEF PAXARM_DEVICE} {$IFNDEF FPC} if not (Instance is TCustomForm) then Exit; {$ENDIF} {$ENDIF} C := P.SavedClass; Move(C, Pointer(Instance)^, SizeOf(Pointer)); P.SavedClass := nil; end; {$ENDIF} {$IFNDEF PAXARM} {$IFDEF PAX64} procedure _DestroyInherited(Instance: TObject); begin RaiseNotImpl; end; {$ELSE} procedure _DestroyInherited(Instance: TObject); var C, Temp: TClass; begin Temp := Instance.ClassType; C := Instance.ClassParent; Move(C, Pointer(Instance)^, 4); asm xor edx, edx mov eax, instance mov ecx, [eax] {$IFDEF FPC} mov ecx, [ecx + $30] {$ELSE} mov ecx, [ecx - $04] {$ENDIF} call ecx end; Move(Temp, Pointer(Instance)^, 4); end; {$ENDIF} {$ENDIF} { procedure _DestroyInherited(Instance: TObject); var C: TClass; begin C := Instance.ClassParent; asm xor edx, edx mov eax, instance mov ecx, C mov ecx, [ecx - $04] call ecx end; end; } {$IFDEF PAXARM} procedure _ClassName(P: Pointer; result: PString); stdcall; begin if IsDelphiClass(P) then result^ := TClass(P).ClassName else result^ := TObject(P).ClassName; end; {$ELSE} procedure _ClassName(P: Pointer; result: PShortString); stdcall; var ST: String; begin if IsDelphiClass(P) then ST := TClass(P).ClassName else ST := TObject(P).ClassName; result^ := ShortString(ST); end; {$ENDIF} procedure _OnCreateObject(P: TBaseRunner; Instance: TObject); stdcall; begin if Assigned(P.OnCreateObject) then P.OnCreateObject(P.Owner, Instance); end; procedure _BeforeCallHost(P: TBaseRunner; Id: Integer); stdcall; begin if Assigned(P.OnBeforeCallHost) then P.OnBeforeCallHost(P.Owner, Id); end; procedure _AfterCallHost(P: TBaseRunner; Id: Integer); stdcall; begin if Assigned(P.OnAfterCallHost) then P.OnAfterCallHost(P.Owner, Id); end; procedure _OnCreateHostObject(P: TBaseRunner; Instance: TObject); stdcall; begin if Instance is TFW_Object then (Instance as TFW_Object).prog := P; if Assigned(P.OnCreateHostObject) then P.OnCreateHostObject(P.Owner, Instance); end; procedure _OnDestroyHostObject(P: TBaseRunner; Instance: TObject); stdcall; begin if Assigned(P.OnDestroyHostObject) then P.OnDestroyHostObject(P.Owner, Instance); end; procedure _OnAfterObjectCreation(Runner: Pointer; Instance: PObject); stdcall; var P: TBaseRunner; begin P := TBaseRunner(Runner); Instance^.AfterConstruction; if Assigned(P.OnAfterObjectCreation) then P.OnAfterObjectCreation(P.Owner, Instance^); end; {$IFNDEF PAXARM} {$IFDEF PAX64} function _InitInstance(Self: TClass; Instance: Pointer): TObject; var IntfTable: PInterfaceTable; ClassPtr: TClass; I: Integer; begin with Self do begin ClassPtr := Self; while ClassPtr <> nil do begin IntfTable := ClassPtr.GetInterfaceTable; if IntfTable <> nil then for I := 0 to IntfTable.EntryCount-1 do with IntfTable.Entries[I] do begin if VTable <> nil then PPointer(@PByte(Instance)[IOffset])^ := VTable; end; ClassPtr := ClassPtr.ClassParent; end; end; Result := Instance; end; {$ELSE} function _InitInstance(Self: TClass; Instance: Pointer): TObject; var IntfTable: PInterfaceTable; ClassPtr: TClass; I: Integer; begin with Self do begin ClassPtr := Self; while ClassPtr <> nil do begin IntfTable := ClassPtr.GetInterfaceTable; if IntfTable <> nil then for I := 0 to IntfTable.EntryCount-1 do with IntfTable.Entries[I] do begin if VTable <> nil then PInteger(@PAnsiChar(Instance)[IOffset])^ := Integer(VTable); end; ClassPtr := ClassPtr.ClassParent; end; Result := Instance; end; end; {$ENDIF} {$ENDIF} {$IFDEF PAXARM} procedure _ErrAbstract(S: PWideChar); stdcall; begin raise Exception.Create(Format(ErrAbstractMethodCall, [S])); end; {$ELSE} procedure _ErrAbstract(S: PAnsiChar); stdcall; begin raise Exception.Create(Format(ErrAbstractMethodCall, [S])); end; {$ENDIF} procedure _Finally(P: TBaseRunner); stdcall; begin Inc(P.GetRootProg.FinallyCount); end; procedure _BeginExceptBlock(P: TBaseRunner); stdcall; begin P.ProcessingExceptBlock := true; end; procedure _EndExceptBlock(P: TBaseRunner); stdcall; begin P.ProcessingExceptBlock := false; if Assigned(P.CurrException) then {$IFDEF ARC} P.CurrException := nil; {$ELSE} P.CurrException.Free; {$ENDIF} P.CurrException := nil; end; // processing breakpoints procedure _CheckPause(P: TBaseRunner); var SourceLine, ModuleIndex: Integer; HasBreakpoint: Boolean; begin SourceLine := P.GetSourceLine; ModuleIndex := P.GetModuleIndex; HasBreakpoint := P.RunTimeModuleList.BreakpointList.IndexOf(ModuleIndex, SourceLine) >= 0; if HasBreakpoint then P.Pause else begin if P.RunMode = rmRUN then begin end else if P.RunMode = rmTRACE_INTO then P.Pause else if P.RunMode = rmNEXT_SOURCE_LINE then P.Pause else if P.RunMode = rmSTEP_OVER then begin if P.RootInitCallStackCount >= P.GetCallStackCount then P.Pause; end else if P.RunMode = rmRUN_TO_CURSOR then begin if P.RunTimeModuleList.TempBreakpoint.SourceLine = SourceLine then if P.RunTimeModuleList.TempBreakpoint.ModuleIndex = ModuleIndex then P.Pause; end; end; end; // processing halt procedure _Halt(Runner: Pointer; ExitCode: Integer); stdcall; var P: TBaseRunner; begin P := TBaseRunner(Runner); P.RootExceptionIsAvailableForHostApplication := false; P.ExitCode := ExitCode; raise THaltException.Create(ExitCode); end; // processing CondHalt procedure _CondHalt(P: TBaseRunner); stdcall; begin if P.IsHalted then begin P.RootExceptionIsAvailableForHostApplication := false; raise THaltException.Create(P.ExitCode); end; end; // processing of published properties {$IFNDEF PAXARM} procedure _GetAnsiStrProp(PropInfo: PPropInfo; Instance: TObject; var result: AnsiString); stdcall; begin {$IFDEF UNIC} Result := GetAnsiStrProp(Instance, PropInfo); {$ELSE} result := GetStrProp(Instance, PropInfo); {$ENDIF} end; procedure _SetAnsiStrProp(PropInfo: PPropInfo; Instance: TObject; const value: AnsiString); stdcall; begin {$IFDEF UNIC} SetAnsiStrProp(Instance, PropInfo, Value); {$ELSE} SetStrProp(Instance, PropInfo, Value); {$ENDIF} end; procedure _GetWideStrProp(PropInfo: PPropInfo; Instance: TObject; var result: WideString); stdcall; begin {$IFDEF VARIANTS} result := GetWideStrProp(Instance, PropInfo); {$ELSE} result := ''; {$ENDIF} end; procedure _SetWideStrProp(PropInfo: PPropInfo; Instance: TObject; const value: WideString); stdcall; begin {$IFDEF VARIANTS} SetWideStrProp(Instance, PropInfo, Value); {$ENDIF} end; {$ENDIF} procedure _GetUnicStrProp(PropInfo: PPropInfo; Instance: TObject; var result: UnicString); stdcall; begin {$IFDEF VARIANTS} {$IFDEF UNIC} {$IFDEF PAXARM} result := GetStrProp(Instance, PropInfo); {$ELSE} result := GetUnicodeStrProp(Instance, PropInfo); {$ENDIF} {$ELSE} result := GetWideStrProp(Instance, PropInfo); {$ENDIF} {$ELSE} result := ''; {$ENDIF} end; procedure _SetUnicStrProp(PropInfo: PPropInfo; Instance: TObject; const value: UnicString); stdcall; begin {$IFDEF VARIANTS} {$IFDEF UNIC} {$IFDEF PAXARM} SetStrProp(Instance, PropInfo, Value); {$ELSE} SetUnicodeStrProp(Instance, PropInfo, Value); {$ENDIF} {$ELSE} SetWideStrProp(Instance, PropInfo, Value); {$ENDIF} {$ENDIF} end; procedure _GetOrdProp(PropInfo: PPropInfo; Instance: TObject; var result: IntPax); stdcall; begin result := GetOrdProp(Instance, PropInfo); end; procedure _SetOrdProp(PropInfo: PPropInfo; Instance: TObject; value: Integer); stdcall; begin SetOrdProp(Instance, PropInfo, Value); end; {$IFDEF VARIANTS} procedure _GetInterfaceProp(PropInfo: PPropInfo; Instance: TObject; var result: IInterface); stdcall; begin {$IFDEF FPC} {$IFDEF LINUX} {$ELSE} result := GetInterfaceProp(Instance, PropInfo); {$ENDIF} {$ELSE} result := GetInterfaceProp(Instance, PropInfo); {$ENDIF} end; procedure _SetInterfaceProp(PropInfo: PPropInfo; Instance: TObject; value: IInterface); stdcall; begin {$IFDEF FPC} {$IFDEF LINUX} {$ELSE} SetInterfaceProp(Instance, PropInfo, Value); {$ENDIF} {$ELSE} SetInterfaceProp(Instance, PropInfo, Value); {$ENDIF} end; {$ELSE} procedure _GetInterfaceProp(PropInfo: PPropInfo; Instance: TObject; var result: IUnknown); stdcall; begin // result := GetInterfaceProp(Instance, PropInfo); end; procedure _SetInterfaceProp(PropInfo: PPropInfo; Instance: TObject; value: IUnknown); stdcall; begin // SetInterfaceProp(Instance, PropInfo, Value); end; {$ENDIF} procedure _GetSetProp(PropInfo: PPropInfo; Instance: TObject; var result: TByteSet); stdcall; var I: Integer; begin I := GetOrdProp(Instance, PropInfo); result := Int32ToByteSet(I); end; procedure _SetSetProp(PropInfo: PPropInfo; Instance: TObject; var value: TByteSet); stdcall; var I: Integer; begin I := ByteSetToInt32(value); SetOrdProp(Instance, PropInfo, I); end; procedure _GetFloatProp(PropInfo: PPropInfo; Instance: TObject; var result: Extended); stdcall; begin result := GetFloatProp(Instance, PropInfo); end; procedure _SetFloatProp(PropInfo: PPropInfo; Instance: TObject; var value: Extended); stdcall; begin SetFloatProp(Instance, PropInfo, Value); end; procedure _GetVariantProp(PropInfo: PPropInfo; Instance: TObject; var result: Variant); stdcall; begin result := GetVariantProp(Instance, PropInfo); end; procedure _SetVariantProp(PropInfo: PPropInfo; Instance: TObject; var value: Variant); stdcall; begin SetVariantProp(Instance, PropInfo, Value); end; procedure _GetInt64Prop(PropInfo: PPropInfo; Instance: TObject; var result: Int64); stdcall; begin result := GetInt64Prop(Instance, PropInfo); end; procedure _SetInt64Prop(PropInfo: PPropInfo; Instance: TObject; var value: Int64); stdcall; begin SetInt64Prop(Instance, PropInfo, Value); end; procedure _GetEventProp(PropInfo: PPropInfo; Instance: TObject; var N: TMethod); stdcall; begin N := GetMethodProp(Instance, PropInfo); end; procedure _CreateMethod(Data, Code: Pointer; var M: TMethod); stdcall; begin M.Code := Code; M.Data := Data; end; procedure _RecordAssign(dest, source: Pointer; Size: Integer); stdcall; begin Move(source^, dest^, Size); end; //------------------ Dynamic array support routines ---------------------------- procedure FreeDynarrayTVarRec(const A: DynarrayTVarRec); var I: Integer; begin for I:=0 to System.Length(A) - 1 do begin case A[I].VType of vtInt64: Dispose(PInt64(A[I].VInt64)); vtExtended: Dispose(PExtended(A[I].VExtended)); vtVariant: Dispose(PVariant(A[I].VVariant)); {$IFNDEF PAXARM} vtString: Dispose(PShortString(A[I].VString)); vtWideString: WideString(A[I].VWideString) := ''; {$ENDIF} {$IFDEF UNIC} vtUnicodeString: UnicString(A[I].VUnicodeString) := ''; {$ENDIF} end; end; end; procedure _ClearTVarRec(var Dest: TVarRec); begin case Dest.VType of vtInt64: if Assigned(Dest.VInt64) then begin Dispose(PInt64(Dest.VInt64)); end; vtExtended: if Assigned(Dest.VExtended) then begin Dispose(PExtended(Dest.VExtended)); end; {$IFNDEF PAXARM} vtString: if Assigned(Dest.VString) then begin Dispose(PShortString(Dest.VString)); end; {$ENDIF} vtVariant: if Assigned(Dest.VVariant) then begin Dispose(PVariant(Dest.VVariant)); end; {$IFNDEF PAXARM} vtWideString: if Assigned(Dest.VWideString) then begin WideString(Dest.VWideString) := ''; end; {$ENDIF} {$IFDEF UNIC} vtUnicodeString: if Assigned(Dest.VUnicodeString) then begin UnicString(Dest.VUnicodeString) := ''; end; {$ENDIF} end; FillChar(Dest, SizeOf(Dest), 0); end; procedure _AssignTVarRec(P: Pointer; Address: Pointer; var Dest: TVarRec; TypeID: Integer); stdcall; {$IFNDEF PAXARM} var WS: WideString; {$ENDIF} begin _ClearTVarRec(Dest); case TypeId of typeINTEGER: begin Dest.VType := vtInteger; Dest.VInteger := Integer(Address^); end; typeBYTE: begin Dest.VType := vtInteger; Dest.VInteger := Byte(Address^); end; typeWORD: begin Dest.VType := vtInteger; Dest.VInteger := Word(Address^); end; typeSHORTINT: begin Dest.VType := vtInteger; Dest.VInteger := ShortInt(Address^); end; typeSMALLINT: begin Dest.VType := vtInteger; Dest.VInteger := SmallInt(Address^); end; typeCARDINAL: begin Dest.VType := vtInt64; New(PInt64(Dest.VInt64)); Dest.VInt64^ := Cardinal(Address^); end; typeINT64, typeUINT64: begin Dest.VType := vtInt64; New(PInt64(Dest.VInt64)); Dest.VInt64^ := Int64(Address^); end; typeCURRENCY: begin Dest.VType := vtCurrency; New(PCurrency(Dest.VCurrency)); Dest.VCurrency^ := Currency(Address^); end; typeBOOLEAN: begin Dest.VType := vtBoolean; Dest.VBoolean := Boolean(Address^); end; {$IFNDEF PAXARM} typeANSICHAR: begin Dest.VType := vtChar; Dest.VChar := AnsiChar(Address^); end; typeSHORTSTRING: begin Dest.VType := vtString; New(PShortString(Dest.VString)); PShortString(Dest.VString)^ := PShortString(Address)^; end; typeANSISTRING: begin Dest.VType := vtAnsiString; AnsiString(Dest.VAnsiString) := PAnsiString(Address)^; end; typeWIDESTRING: begin {$IFDEF UNIC} Dest.VType := vtUnicodeString; UnicString(Dest.VUnicodeString) := PWideString(Address)^; {$ELSE} Dest.VType := vtString; New(PShortString(Dest.VString)); PShortString(Dest.VString)^ := PWideString(Address)^; {$ENDIF} end; {$ENDIF} typeDOUBLE, typeSINGLE, typeEXTENDED: begin Dest.VType := vtExtended; New(PExtended(Dest.VExtended)); case TypeId of typeDOUBLE: PExtended(Dest.VExtended)^ := PDouble(Address)^; typeSINGLE: PExtended(Dest.VExtended)^ := PSingle(Address)^; typeEXTENDED: PExtended(Dest.VExtended)^ := PExtended(Address)^; end; end; typePOINTER: begin Dest.VType := vtPointer; Dest.VPointer := Pointer(Address^); end; {$IFNDEF PAXARM} typePANSICHAR: begin Dest.VType := vtPChar; Dest.VPChar := Pointer(Address^); end; {$ENDIF} typeCLASS: begin Dest.VType := vtObject; Dest.VObject := TObject(Address^); end; typeCLASSREF: begin Dest.VType := vtClass; Dest.VClass := TClass(Address^); end; typeWIDECHAR: begin Dest.VType := vtWideChar; Dest.VWideChar := WideChar(Address^); end; typePWIDECHAR: begin {$IFDEF PAXARM} Dest.VType := vtUnicodeString; UnicString(Dest.VUnicodeString) := PWideChar(Pointer(Address^)); {$ELSE} {$IFDEF UNIC} Dest.VType := vtUnicodeString; _WideStringFromPWideChar(PWideChar(Pointer(Address^)), WS); UnicString(Dest.VUnicodeString) := WS; {$ELSE} Dest.VType := vtString; New(PShortString(Dest.VString)); _WideStringFromPWideChar(PWideChar(Pointer(Address^)), WS); PShortString(Dest.VString)^ := AnsiString(WS); {$ENDIF} {$ENDIF} end; typeVARIANT: begin Dest.VType := vtVariant; New(PVariant(Dest.VVariant)); PVariant(Dest.VVariant)^ := PVariant(Address)^; end; typeUNICSTRING: begin {$IFDEF UNIC} Dest.VType := vtUnicodeString; UnicString(Dest.VUnicodeString) := PUnicString(Address)^; {$ELSE} Dest.VType := vtString; New(PShortString(Dest.VString)); PShortString(Dest.VString)^ := PUnicString(Address)^; {$ENDIF} end; end; end; type PDynArrayRec = ^TDynArrayRec; TDynArrayRec = packed record {$IFDEF CPUX64} _Padding: LongInt; // Make 16 byte align for payload.. {$ENDIF} RefCnt: LongInt; Length: IntPax; end; procedure _CreateEmptyDynarray(var A: Pointer); stdcall; var P: Pointer; begin if A <> nil then begin P := ShiftPointer(A, - SizeOf(TDynArrayRec)); FreeMem(P, SizeOf(TDynArrayRec)); end; P := AllocMem(SizeOf(TDynArrayRec)); PDynArrayRec(P)^.RefCnt := 1; A := ShiftPointer(P, SizeOf(TDynArrayRec)); end; function _DynarrayRefCount(P: Pointer): Integer; begin if P = nil then result := -1 else begin P := ShiftPointer(P, - SizeOf(TDynArrayRec)); Result := PDynArrayRec(P)^.RefCnt; end; end; function _DynarrayLength(P: Pointer): Integer; var Q: Pointer; begin if P = nil then result := 0 else begin Q := ShiftPointer(P, - SizeOf(TDynArrayRec)); Result := PDynArrayRec(Q)^.Length; {$IFDEF FPC} Inc(result); {$ENDIF} end; end; procedure _DynarraySetLength(var A: Pointer; L: Integer; ElFinalTypeID, ElTypeID, ElSize: Integer); stdcall; var P: Pointer; begin case ElFinalTypeID of {$IFNDEF PAXARM} typeANSICHAR: SetLength(DynarrayChar(A), L); typeANSISTRING: SetLength(DynarrayString(A), L); typeSHORTSTRING: SetLength(DynarrayShortString(A), L); typeWIDESTRING: SetLength(DynarrayWideString(A), L); {$ENDIF} typeBOOLEAN: SetLength(DynarrayBoolean(A), L); typeBYTE: SetLength(DynarrayByte(A), L); typeWORD: SetLength(DynarrayWord(A), L); typeCARDINAL: SetLength(DynarrayCardinal(A), L); typeINTEGER: SetLength(DynarrayInteger(A), L); typeDOUBLE: SetLength(DynarrayDouble(A), L); typePOINTER: SetLength(DynarrayPointer(A), L); typeENUM: SetLength(DynarrayInteger(A), L); typePROC: SetLength(DynarrayPointer(A), L); typeSINGLE: SetLength(DynarraySingle(A), L); typeEXTENDED: SetLength(DynarrayExtended(A), L); typeCURRENCY: SetLength(DynarrayCurrency(A), L); typeCLASS: SetLength(DynarrayPointer(A), L); typeCLASSREF: SetLength(DynarrayPointer(A), L); typeWIDECHAR: SetLength(DynarrayWideChar(A), L); typeUNICSTRING: SetLength(DynarrayUnicString(A), L); typeVARIANT: SetLength(DynarrayVariant(A), L); typeDYNARRAY: SetLength(DynarrayPointer(A), L); else begin if ElTypeID = H_TVarRec then begin SetLength(DynarrayTVarRec(A), L); Exit; end; {$IFDEF FPC} Dec(L); {$ENDIF} if A <> nil then begin P := ShiftPointer(A, - SizeOf(TDynArrayRec)); ReallocMem(P, L * ElSize + SizeOf(TDynArrayRec)); PDynArrayRec(P)^.Length := L; A := ShiftPointer(P, SizeOf(TDynArrayRec)); Exit; end; A := AllocMem(SizeOf(TDynArrayRec) + L * ElSize); PDynArrayRec(A)^.RefCnt := 1; PDynArrayRec(A)^.Length := L; A := ShiftPointer(A, SizeOf(TDynArrayRec)); end; end; end; procedure _DynarraySetLength2(var A: Pointer; L1, L2: Integer; ElFinalTypeID, ElTypeID, ElSize: Integer); stdcall; var I: Integer; begin case ElFinalTypeID of {$IFNDEF PAXARM} typeANSICHAR: SetLength(DynarrayChar2(A), L1, L2); typeANSISTRING: SetLength(DynarrayString2(A), L1, L2); typeSHORTSTRING: SetLength(DynarrayShortString2(A), L1, L2); typeWIDESTRING: SetLength(DynarrayWideString2(A), L1, L2); {$ENDIF} typeBOOLEAN: SetLength(DynarrayBoolean2(A), L1, L2); typeBYTE: SetLength(DynarrayByte2(A), L1, L2); typeWORD: SetLength(DynarrayWord2(A), L1, L2); typeCARDINAL: SetLength(DynarrayCardinal2(A), L1, L2); typeINTEGER: SetLength(DynarrayInteger2(A), L1, L2); typeDOUBLE: SetLength(DynarrayDouble2(A), L1, L2); typePOINTER: SetLength(DynarrayPointer2(A), L1, L2); typeENUM: SetLength(DynarrayInteger2(A), L1, L2); typePROC: SetLength(DynarrayPointer2(A), L1, L2); typeSINGLE: SetLength(DynarraySingle2(A), L1, L2); typeEXTENDED: SetLength(DynarrayExtended2(A), L1, L2); typeCURRENCY: SetLength(DynarrayCurrency2(A), L1, L2); typeCLASS: SetLength(DynarrayPointer2(A), L1, L2); typeCLASSREF: SetLength(DynarrayPointer2(A), L1, L2); typeWIDECHAR: SetLength(DynarrayWideChar2(A), L1, L2); typeUNICSTRING: SetLength(DynarrayUnicString2(A), L1, L2); typeVARIANT: SetLength(DynarrayVariant2(A), L1, L2); typeDYNARRAY: SetLength(DynarrayPointer2(A), L1, L2); else begin _DynarraySetLength(A, L1, typePOINTER, 0, 0); for I := 0 to L1 - 1 do _DynarraySetLength(DynarrayPointer(A)[I], L2, ElFinalTypeId, ElTypeId, ElSize); end; end; end; procedure _DynarraySetLength3(var A: Pointer; L1, L2, L3: Integer; ElFinalTypeID, ElTypeID, ElSize: Integer); stdcall; type DynarrayPointer2 = array of array of Pointer; var I, J: Integer; begin case ElFinalTypeID of {$IFNDEF PAXARM} typeANSICHAR: SetLength(DynarrayChar3(A), L1, L2, L3); typeANSISTRING: SetLength(DynarrayString3(A), L1, L2, L3); typeSHORTSTRING: SetLength(DynarrayShortString3(A), L1, L2, L3); typeWIDESTRING: SetLength(DynarrayWideString3(A), L1, L2, L3); {$ENDIF} typeBOOLEAN: SetLength(DynarrayBoolean3(A), L1, L2, L3); typeBYTE: SetLength(DynarrayByte3(A), L1, L2, L3); typeWORD: SetLength(DynarrayWord3(A), L1, L2, L3); typeCARDINAL: SetLength(DynarrayCardinal3(A), L1, L2, L3); typeINTEGER: SetLength(DynarrayInteger3(A), L1, L2, L3); typeDOUBLE: SetLength(DynarrayDouble3(A), L1, L2, L3); typePOINTER: SetLength(DynarrayPointer3(A), L1, L2, L3); typeENUM: SetLength(DynarrayInteger3(A), L1, L2, L3); typePROC: SetLength(DynarrayPointer3(A), L1, L2, L3); typeSINGLE: SetLength(DynarraySingle3(A), L1, L2, L3); typeEXTENDED: SetLength(DynarrayExtended3(A), L1, L2, L3); typeCURRENCY: SetLength(DynarrayCurrency3(A), L1, L2, L3); typeCLASS: SetLength(DynarrayPointer3(A), L1, L2, L3); typeCLASSREF: SetLength(DynarrayPointer3(A), L1, L2, L3); typeWIDECHAR: SetLength(DynarrayWideChar3(A), L1, L2, L3); typeUNICSTRING: SetLength(DynarrayUnicString3(A), L1, L2, L3); typeVARIANT: SetLength(DynarrayVariant3(A), L1, L2, L3); typeDYNARRAY: SetLength(DynarrayPointer3(A), L1, L2, L3); else begin _DynarraySetLength2(A, L1, L2, typePOINTER, 0, 0); for I := 0 to L1 - 1 do for J := 0 to L2 - 1 do _DynarraySetLength(DynarrayPointer2(A)[I][J], L2, ElFinalTypeId, ElTypeId, ElSize); end; end; end; procedure _DynarrayHigh(var P: Pointer; var result: Integer); stdcall; begin result := _DynarrayLength(P) - 1; end; function _DynarrayIncRefCount(P: Pointer): Integer; var Q: Pointer; begin if P <> nil then begin Q := ShiftPointer(P, - SizeOf(TDynArrayRec)); Inc(PDynArrayRec(Q)^.RefCnt, 1); result := _DynarrayRefCount(P); end else result := 0; end; function _DynarrayDecRefCount(P: Pointer): Integer; var Q: Pointer; begin if P <> nil then begin Q := ShiftPointer(P, - SizeOf(TDynArrayRec)); Dec(PDynArrayRec(Q)^.RefCnt, 1); result := _DynarrayRefCount(P); end else result := 0; end; procedure _DynarrayClr(var A: Pointer; FinalTypeID, TypeID, ElSize, FinalTypeID2, TypeID2, ElSize2: Integer); stdcall; var P: Pointer; I, K, L: Integer; begin case FinalTypeID of {$IFNDEF PAXARM} typeANSISTRING: DynarrayString(A) := nil; typeWIDESTRING: DynarrayWideString(A) := nil; typeANSICHAR: DynarrayChar(A) := nil; typeSHORTSTRING: DynarrayShortString(A) := nil; {$ENDIF} typeUNICSTRING: DynarrayUnicString(A) := nil; typeVARIANT, typeOLEVARIANT: DynarrayVariant(A) := nil; typeBOOLEAN: DynarrayBoolean(A) := nil; typeBYTE: DynarrayByte(A) := nil; typeWORD: DynarrayWord(A) := nil; typeCARDINAL: DynarrayCardinal(A) := nil; typeINTEGER: DynarrayInteger(A) := nil; typeDOUBLE: DynarrayDouble(A) := nil; typePOINTER: DynarrayPointer(A) := nil; typeENUM: DynarrayInteger(A) := nil; typePROC: DynarrayPointer(A) := nil; typeSINGLE: DynarraySingle(A) := nil; typeEXTENDED: DynarrayExtended(A) := nil; typeCURRENCY: DynarrayCurrency(A) := nil; typeCLASS: DynarrayPointer(A) := nil; typeCLASSREF: DynarrayPointer(A) := nil; typeWIDECHAR: DynarrayWideChar(A) := nil; typeDYNARRAY: begin if A <> nil then begin for I := 0 to System.Length(DynarrayPointer(A)) - 1 do _DynarrayClr(DynarrayPointer(A)[I], FinalTypeID2, TypeID2, ElSize2, 0, 0, 0); DynarrayPointer(A) := nil; end; end else begin if A <> nil then begin if TypeID = H_TVarRec then begin K := _DynarrayRefCount(A); if K = 1 then begin {$ifdef GE_DXETOKYO} // XILINX, Tokyo mod FreeDynarrayTVarRec(DynarrayTVarRec(A)); {$else} FreeDynarrayTVarRec(A); {$endif} DynarrayTVarRec(A) := nil; Exit; end; end; K := _DynarrayRefCount(A); if K > 1 then begin _DynarrayDecRefCount(A); Exit; end; L := _DynarrayLength(A); P := ShiftPointer(A, - SizeOf(TDynArrayRec)); FreeMem(P, L * ElSize + SizeOf(TDynArrayRec)); A := nil; end; end; end; end; procedure _DynarrayClr1(var A: Pointer; FinalTypeID, TypeID, ElSize: Integer); stdcall; var P: Pointer; K, L: Integer; begin case FinalTypeID of {$IFNDEF PAXARM} typeANSISTRING: DynarrayString(A) := nil; typeWIDESTRING: DynarrayWideString(A) := nil; typeANSICHAR: DynarrayChar(A) := nil; typeSHORTSTRING: DynarrayShortString(A) := nil; {$ENDIF} typeUNICSTRING: DynarrayUnicString(A) := nil; typeVARIANT, typeOLEVARIANT: DynarrayVariant(A) := nil; typeBOOLEAN: DynarrayBoolean(A) := nil; typeBYTE: DynarrayByte(A) := nil; typeWORD: DynarrayWord(A) := nil; typeCARDINAL: DynarrayCardinal(A) := nil; typeINTEGER: DynarrayInteger(A) := nil; typeDOUBLE: DynarrayDouble(A) := nil; typePOINTER: DynarrayPointer(A) := nil; typeENUM: DynarrayInteger(A) := nil; typePROC: DynarrayPointer(A) := nil; typeSINGLE: DynarraySingle(A) := nil; typeEXTENDED: DynarrayExtended(A) := nil; typeCURRENCY: DynarrayCurrency(A) := nil; typeCLASS: DynarrayPointer(A) := nil; typeCLASSREF: DynarrayPointer(A) := nil; typeWIDECHAR: DynarrayWideChar(A) := nil; else begin if A <> nil then begin if TypeID = H_TVarRec then begin K := _DynarrayRefCount(A); if K = 1 then begin {$ifdef GE_DXETOKYO} // XILINX, Tokyo mod FreeDynarrayTVarRec(DynarrayTVarRec(A)); {$else} FreeDynarrayTVarRec(A); {$endif} DynarrayTVarRec(A) := nil; Exit; end; end; K := _DynarrayRefCount(A); if K > 1 then begin _DynarrayDecRefCount(A); Exit; end; L := _DynarrayLength(A); P := ShiftPointer(A, - SizeOf(TDynArrayRec)); FreeMem(P, L * ElSize + SizeOf(TDynArrayRec)); A := nil; end; end; end; end; procedure _DynarrayClr2(var A: Pointer; FinalTypeID, TypeID, ElSize: Integer); stdcall; var I: Integer; begin if A = nil then Exit; for I := 0 to System.Length(DynarrayPointer(A)) - 1 do _DynarrayClr1(DynarrayPointer(A)[I], FinalTypeID, TypeID, ElSize); DynarrayPointer(A) := nil; end; procedure _DynarrayClr3(var A: Pointer; FinalTypeID, TypeID, ElSize: Integer); stdcall; var I: Integer; begin if A = nil then Exit; for I := 0 to System.Length(DynarrayPointer(A)) - 1 do _DynarrayClr2(DynarrayPointer(A)[I], FinalTypeID, TypeID, ElSize); DynarrayPointer(A) := nil; end; procedure _DynarrayAssign(var Source, Dest: Pointer; FinalTypeID, TypeID, ElSize, FinalTypeID2, TypeID2, ElSize2: Integer); stdcall; var K: Integer; begin if Source = nil then begin _DynArrayClr(Dest, FinalTypeId, TypeId, ElSize, FinalTypeId2, TypeId2, ElSize2); Exit; end; _DynarrayIncRefCount(Source); if Dest <> nil then begin K := _DynarrayDecRefCount(Dest); if K = 0 then _DynArrayClr(Dest, FinalTypeId, TypeId, ElSize, FinalTypeId2, TypeId2, ElSize2); end; Dest := Source; end; function _VariantLength(const V: Variant): Integer; var VT: Word; I: Integer; begin VT := VarType(V); if VT < varArray then result := Length(V) else begin result := 1; for I := 1 to VarArrayDimCount(V) do result := result * (VarArrayHighBound(V, I) + 1); end; end; procedure _LockVArray(var V: Variant; var Result: Pointer); stdcall; begin result := VarArrayLock(V); end; procedure _UnlockVArray(var V: Variant); stdcall; begin VarArrayUnlock(V); end; procedure _IntOver; stdcall; begin raise EIntOverflow.Create(errIntegerOverflow); end; procedure _BoundError; stdcall; begin raise ERangeError.Create(errRangeCheckError); end; procedure _StringAddRef(var S: Pointer); stdcall; var P: PStringRec; begin if S <> nil then begin P := Pointer(Integer(S) - Sizeof(TStringRec)); Inc(P^.RefCount); end; end; procedure _DynarrayAddRef(P: Pointer); stdcall; begin _DynarrayIncRefCount(P); end; procedure _InterfaceAddRef(var I: Pointer); stdcall; begin IUnknown(I)._AddRef; end; procedure _VariantAddRef(var V: Variant); stdcall; var VT: Integer; begin VT := VarType(V); {$IFNDEF PAXARM} if VT = varString then _StringAddRef(TVarData(V).VString) else if VT = varOleStr then _StringAddRef(Pointer(TVarData(V).VOleStr)) else {$ENDIF} {$IFDEF UNIC} if VT = varUString then _StringAddRef(Pointer(TVarData(V).VUString)) else {$ENDIF} if VT = varDispatch then _InterfaceAddRef(TVarData(V).VDispatch); end; {$IFDEF PAXARM} function TObject_ClassName(IsClass: Integer; P: Pointer): String; stdcall; begin if IsClass = 1 then result := TClass(P).ClassName else result := TObject(P).ClassName; end; {$ELSE} function TObject_ClassName(IsClass: Integer; P: Pointer): ShortString; stdcall; var X: TObject; S: String; begin if IsClass = 1 then begin S := TClass(P).ClassName; result := ShortString(S); end else begin X := TObject(P); S := X.ClassName; result := ShortString(S); end; end; {$ENDIF} function _GetProgAddress: Pointer; begin result := @ CurrProg; end; function GetRefCount(Self: TInterfacedObject): Integer; begin result := Self.RefCount; end; function _Round(E: Extended): Int64; begin result := Round(E); end; procedure _GetComponent(X: TComponent; I: Integer; var Y: TComponent); stdcall; begin Y := X.Components[I]; end; procedure Dummy; begin end; // TExtraImportTableList ------------------------------------------------------- function TExtraImportTableList.GetRecord(I: Integer): TBaseSymbolTable; begin result := TBaseSymbolTable(L[I]); end; function TExtraImportTableList.Import(CurrentTable: TBaseSymbolTable; const FullName: String; UpCase: Boolean; DoRaiseError: Boolean = true): Integer; var I: Integer; begin result := 0; for I := 0 to Count - 1 do begin result := CurrentTable.ImportFromTable(Records[I], FullName, UpCase, DoRaiseError); if result <> 0 then Exit; end; end; function TExtraImportTableList.Add(st: TBaseSymbolTable): Integer; begin result := L.Add(st); end; procedure TExtraImportTableList.Remove(st: TBaseSymbolTable); var I: Integer; begin I := L.IndexOf(st); if I >= 0 then L.Delete(I); FreeAndNil(st); end; //------------------------------------------------------------------------------ procedure TMyInterfacedObject_AddRef(Self: TObject); stdcall; begin TMyInterfacedObject(Self)._AddRef; end; procedure TMyInterfacedObject_Release(Self: TObject); stdcall; begin TMyInterfacedObject(Self)._Release; end; function TObject_GetInterface(Self: TObject; const IID: TGUID; out Obj): Boolean; begin result := Self.GetInterface(IID, Obj); end; procedure Set_ExitCode(P: TBaseRunner; value: Integer); stdcall; begin P.ExitCode := value; end; function Get_ExitCode(P: TBaseRunner): Integer; stdcall; begin result := P.ExitCode; end; procedure _GetDynamicMethodAddress(AClass: TClass; Id: integer; var result: Pointer); stdcall; var Dmt: PDmtTable; DmtMethodList: PDmtMethodList; I: Integer; C: TClass; begin Result := nil; C := AClass; repeat Dmt := GetDmtFromClass(C); if Assigned(Dmt) then begin DmtMethodList := @Dmt^.IndexList[Dmt.Count]; for I := 0 to Dmt^.Count - 1 do if Dmt^.IndexList[I] = Id then begin Result := DmtMethodList[I]; Exit; end; end; C := C.ClassParent; if C = nil then break; until false; end; procedure _CallVirt(Runner: TBaseRunner; ObjectName, PropName: PChar; A: array of Variant; var Result: Variant); stdcall; begin if not Assigned(Runner.OnVirtualObjectMethodCall) then Runner.RaiseError(errVirtualObjectMethodCallEventNotAssigned, []); Runner.OnVirtualObjectMethodCall(Runner.Owner, String(ObjectName), String(PropName), A, result); end; procedure _PutVirt(Runner: TBaseRunner; ObjectName, PropName: PChar; A: array of Variant; const value: Variant); stdcall; begin if not Assigned(Runner.OnVirtualObjectPutProperty) then Runner.RaiseError(errVirtualObjectPutPropertyEventNotAssigned, []); Runner.OnVirtualObjectPutProperty(Runner.Owner, String(ObjectName), String(PropName), A, value); end; procedure _AddMessage(Runner: Pointer; msg_id: Integer; FullName: PChar); stdcall; var R: TMessageRec; I: Integer; P: TBaseRunner; begin P := TBaseRunner(Runner); I := P.MessageList.IndexOf(FullName); if I >= 0 then Exit; R := P.MessageList.AddRecord; R.msg_id := msg_id; R.FullName := FullName; end; procedure _TypeInfo(Prog: Pointer; FullTypeName: PChar; var result: PTypeInfo); stdcall; var R: TTypeInfoContainer; {$ifdef DRTTI} t: TRTTIType; PackageInfo: PPackageTypeInfo; lib: PLibModule; lp: PByte; i: integer; aName: String; aUnit: String; procedure PeekData(var P: PByte; var Data; Len: Integer); begin Move(P^, Data, Len); end; procedure ReadData(var P: PByte; var Data; Len: Integer); begin PeekData(P, Data, Len); Inc(P, Len); end; function ReadU8(var P: PByte): Byte; begin ReadData(P, Result, SizeOf(Result)); end; function ReadShortString(var P: PByte): string; var len: Integer; begin Result := UTF8ToString(PShortString(P)^); len := ReadU8(P); Inc(P, len); end; {$endif} var P: TBaseRunner; begin P := TBaseRunner(Prog); R := P.ProgTypeInfoList.LookupFullName(FullTypeName); if R = nil then begin {$ifdef DRTTI} t := PaxContext.FindType(FullTypeName); if t = nil then t := PaxContext.FindType(ExtractName(FullTypeName)); aName := ExtractName(FullTypeName); lib := LibModuleList; while lib <> nil do begin PackageInfo := lib^.TypeInfo; if PackageInfo <> nil then begin lp := Pointer(PackageInfo^.UnitNames); for i := 0 to PackageInfo^.UnitCount - 1 do begin aUnit := ReadShortString(lp); t := PaxContext.FindType(aUnit + '.' + aName); if t <> nil then break; end; end; if t <> nil then break; lib := lib.Next; end; if t = nil then result := nil else result := t.Handle; {$else} result := nil; {$endif} end else result := R.TypeInfoPtr; end; function GetPointerType(T: Integer): Integer; begin if T = typeINTEGER then result := H_PInteger else if T = typeSMALLINT then result := H_PSmallInt else if T = typeSHORTINT then result := H_PShortInt else if T = typeCARDINAL then result := H_PCardinal else if T = typeWORD then result := H_PWord else if T = typeBYTE then result := H_PByte else if T = typeINT64 then result := H_PInt64 else if T = typeSINGLE then result := H_PSingle else if T = typeDOUBLE then result := H_PDouble else if T = typeEXTENDED then result := H_PExtended else if T = typeCURRENCY then result := H_PCurrency else if T = typeVARIANT then result := H_PVariant else if T = typePOINTER then result := H_PPointer else if T = typeBOOLEAN then result := H_PBoolean else if T = typeWIDECHAR then result := H_PWideChar {$IFNDEF PAXARM} else if T = typeANSICHAR then result := H_PAnsiChar else if T = typeSHORTSTRING then result := H_PShortString else if T = typeANSISTRING then result := H_PAnsiString else if T = typeWIDESTRING then result := H_PWideString {$ENDIF} else if T = typeUNICSTRING then result := H_PUnicString else if T = H_PINTEGER then result := H_PPInteger else if T = H_PSMALLINT then result := H_PPSmallInt else if T = H_PSHORTINT then result := H_PPShortInt else if T = H_PCARDINAL then result := H_PPCardinal else if T = H_PWORD then result := H_PPWord else if T = H_PBYTE then result := H_PPByte else if T = H_PINT64 then result := H_PPInt64 else if T = H_PSINGLE then result := H_PPSingle else if T = H_PDOUBLE then result := H_PPDouble else if T = H_PEXTENDED then result := H_PPExtended else if T = H_PCURRENCY then result := H_PPCurrency else if T = H_PVARIANT then result := H_PPVariant else if T = H_PPOINTER then result := H_PPPointer else if T = H_PBOOLEAN then result := H_PPBoolean else if T = typeWIDECHAR then result := H_PWideChar {$IFNDEF PAXARM} else if T = H_PANSICHAR then result := H_PPAnsiChar else if T = H_PSHORTSTRING then result := H_PPShortString else if T = H_PANSISTRING then result := H_PPAnsiString else if T = H_PWIDESTRING then result := H_PPWideString {$ENDIF} else if T = H_PUNICSTRING then result := H_PPUnicString else result := 0; end; var Unassigned: Variant; procedure Register_TYPEINFO(H_Namespace: Integer; st: TBaseSymbolTable); var H_Sub: Integer; begin with st do begin H_Sub := RegisterRoutine(H_Namespace, 'TypeInfo', typeVOID, ccSTDCALL, nil); RegisterParameter(H_Sub, typePOINTER, Unassigned, false, 'X'); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _TypeInfo); Id_TypeInfo := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); end; end; procedure FindAvailTypes; begin if AvailTypeList.Count = 0 then begin {$IFDEF DRTTI} CreateAvailTypes; {$ENDIF} end; end; type TMyObject = class(TObject); const ByRef = true; procedure AddStdRoutines(st: TBaseSymbolTable); var H_Namespace, H_Sub, H, T1, T2, T3, T4, T5: Integer; H_R0_7, H_TGUID_D4, H_TEntries, H_TPOINT: Integer; begin with st do begin Reset; RegisterRoutine(0, strWrite, typeVOID, ccREGISTER, @_Write); H_Sub := RegisterRoutine(0, strWriteln, typeVOID, ccREGISTER, @_Writeln); H_Writeln := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteBool); Id_WriteBool := LastSubId; RegisterParameter(H_Sub, typeBOOLEAN, Unassigned); H_WriteBool := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteByteBool); Id_WriteByteBool := LastSubId; RegisterParameter(H_Sub, typeBYTEBOOL, Unassigned); H_WriteByteBool := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteWordBool); Id_WriteWordBool := LastSubId; RegisterParameter(H_Sub, typeWORDBOOL, Unassigned); H_WriteWordBool := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteLongBool); Id_WriteLongBool := LastSubId; RegisterParameter(H_Sub, typeLONGBOOL, Unassigned); H_WriteLongBool := H_Sub; {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteAnsiChar); Id_WriteAnsiChar := LastSubId; RegisterParameter(H_Sub, typeANSICHAR, Unassigned); H_WriteAnsiChar := H_Sub; {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteByte); Id_WriteByte := LastSubId; RegisterParameter(H_Sub, typeBYTE, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteByte := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteWord); Id_WriteWord := LastSubId; RegisterParameter(H_Sub, typeWORD, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteWord := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteCardinal); Id_WriteCardinal := LastSubId; RegisterParameter(H_Sub, typeCARDINAL, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteCardinal := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteSmallInt); Id_WriteSmallInt := LastSubId; RegisterParameter(H_Sub, typeSMALLINT, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteSmallInt := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteShortInt); Id_WriteShortInt := LastSubId; RegisterParameter(H_Sub, typeSHORTINT, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteShortInt := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteInt); Id_WriteInt := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteInteger := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteInt64); Id_WriteInt64 := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteInt64 := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteDouble); Id_WriteDouble := LastSubId; RegisterParameter(H_Sub, typeDOUBLE, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteDouble := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteSingle); Id_WriteSingle := LastSubId; RegisterParameter(H_Sub, typeSINGLE, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteSingle := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteCurrency); Id_WriteCurrency := LastSubId; RegisterParameter(H_Sub, typeCURRENCY, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteCurrency := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteExtended); Id_WriteExtended := LastSubId; RegisterParameter(H_Sub, typeEXTENDED, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteExtended := H_Sub; {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteString); Id_WriteString := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned); Records[Card].IsConst := true; RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteAnsiString := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteShortString); Id_WriteShortString := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteShortString := H_Sub; {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteWideChar); Id_WriteWideChar := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned); H_WriteWideChar := H_Sub; {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteWideString); Id_WriteWideString := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteWideString := H_Sub; {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteVariant); Id_WriteVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteVariant := H_Sub; H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteObject); Id_WriteObject := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); H_WriteObject := H_Sub; //--------- SET ROUTINES ------------------------------------------------------- H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetInclude); Id_SetInclude := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetIncludeInterval); Id_SetIncludeInterval := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetExclude); Id_SetExclude := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetUnion); Id_SetUnion := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetDifference); Id_SetDifference := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetIntersection); Id_SetIntersection := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeBOOLEAN, ccSTDCALL, @_SetSubset); Id_SetSubset := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeBOOLEAN, ccSTDCALL, @_SetSuperset); Id_SetSuperset := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeBOOLEAN, ccSTDCALL, @_SetEquality); Id_SetEquality := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeBOOLEAN, ccSTDCALL, @_SetInequality); Id_SetInequality := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeBOOLEAN, ccSTDCALL, @_SetMembership); Id_SetMembership := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typePOINTER, ccSTDCALL, @ _LoadProc); Id_LoadProc := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); //--------- String ROUTINES ---------------------------------------------------- {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _AnsiStringFromPAnsiChar); Id_AnsiStringFromPAnsiChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringFromPAnsiChar); Id_WideStringFromPAnsiChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringFromPWideChar); Id_WideStringFromPWideChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromAnsiChar); Id_AnsiStringFromAnsiChar := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringFromAnsiChar); Id_WideStringFromAnsiChar := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _WideStringFromWideChar); Id_WideStringFromWideChar := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _AnsiStringFromWideChar); Id_AnsiStringFromWideChar := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringAssign); Id_AnsiStringAssign := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringAssign); Id_WideStringAssign := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringAddition); Id_AnsiStringAddition := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringAddition); Id_WideStringAddition := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringAssign); Id_ShortStringAssign := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringAddition); Id_ShortStringAddition := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringClr); Id_AnsiStringClr := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringClr); Id_WideStringClr := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_InterfaceClr); Id_InterfaceClr := LastSubId; RegisterParameter(H_Sub, typeINTERFACE, Unassigned, ByRef); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_StringAddRef); Id_StringAddRef := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_StringAddRef); Id_WideStringAddRef := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_DynarrayAddRef); Id_DynarrayAddRef := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_InterfaceAddRef); Id_InterfaceAddRef := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantAddRef); Id_VariantAddRef := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringFromAnsiString); Id_ShortStringFromAnsiString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringFromWideString); Id_ShortStringFromWideString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromShortString); Id_AnsiStringFromShortString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringFromShortString); Id_WideStringFromShortString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromWideString); Id_AnsiStringFromWideString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringFromAnsiString); Id_WideStringFromAnsiString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_StrInt); Id_StrInt := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_StrDouble); Id_StrDouble := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeDOUBLE, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_StrSingle); Id_StrSingle := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeSINGLE, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_StrExtended); Id_StrExtended := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeEXTENDED, Unassigned); RegisterRoutine(0, '', typeVOID, ccREGISTER, @_DecStringCounter); Id_DecStringCounter := LastSubId; {$IFDEF FPC} RegisterRoutine(0, '', typeVOID, ccREGISTER, @_IncStringCounter); Id_IncStringCounter := LastSubId; {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringEquality); Id_AnsiStringEquality := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringNotEquality); Id_AnsiStringNotEquality := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringEquality); Id_ShortStringEquality := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringNotEquality); Id_ShortStringNotEquality := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringEquality); Id_WideStringEquality := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringNotEquality); Id_WideStringNotEquality := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeINTEGER, ccSTDCALL, @_ShortstringHigh); Id_ShortstringHigh := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _AnsiStringGreaterThan); Id_AnsiStringGreaterThan := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringGreaterThanOrEqual); Id_AnsiStringGreaterThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringLessThan); Id_AnsiStringLessThan := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringLessThanOrEqual); Id_AnsiStringLessThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _ShortStringGreaterThan); Id_ShortStringGreaterThan := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringGreaterThanOrEqual); Id_ShortStringGreaterThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringLessThan); Id_ShortStringLessThan := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringLessThanOrEqual); Id_ShortStringLessThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _WideStringGreaterThan); Id_WideStringGreaterThan := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringGreaterThanOrEqual); Id_WideStringGreaterThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringLessThan); Id_WideStringLessThan := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringLessThanOrEqual); Id_WideStringLessThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetStringLength); Id_SetStringLength := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetWideStringLength); Id_SetWideStringLength := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetShortStringLength); Id_SetShortStringLength := LastSubId; RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetVariantLength); Id_SetVariantLength := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); //--------- INT64 ROUTINES ----------------------------------------------------- H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64Multiplication); Id_Int64Multiplication := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64Division); Id_Int64Division := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64Modulo); Id_Int64Modulo := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64LeftShift); Id_Int64LeftShift := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64RightShift); Id_Int64RightShift := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64LessThan); Id_Int64LessThan := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64LessThanOrEqual); Id_Int64LessThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64GreaterThan); Id_Int64GreaterThan := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64GreaterThanOrEqual); Id_Int64GreaterThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64Equality); Id_Int64Equality := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64NotEquality); Id_Int64NotEquality := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _Int64Abs); Id_Int64Abs := LastSubId; RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); // uint64 H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _UInt64LessThan); Id_UInt64LessThan := LastSubId; RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _UInt64LessThanOrEqual); Id_UInt64LessThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _UInt64GreaterThan); Id_UInt64GreaterThan := LastSubId; RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _UInt64GreaterThanOrEqual); Id_UInt64GreaterThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeUINT64, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); //--------- VARIANT ROUTINES --------------------------------------------------- H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromVariant); Id_OleVariantFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantAssign); Id_VariantAssign := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _OleVariantAssign); Id_OleVariantAssign := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromPAnsiChar); Id_VariantFromPAnsiChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromPAnsiChar); Id_OleVariantFromPAnsiChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromInterface); Id_VariantFromInterface := LastSubId; RegisterParameter(H_Sub, typeINTERFACE, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromInterface); Id_OleVariantFromInterface := LastSubId; RegisterParameter(H_Sub, typeINTERFACE, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromAnsiString); Id_VariantFromAnsiString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromAnsiString); Id_OleVariantFromAnsiString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromWideString); Id_VariantFromWideString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromWideString); Id_OleVariantFromWideString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromShortString); Id_VariantFromShortString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromShortString); Id_OleVariantFromShortString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromAnsiChar); Id_VariantFromAnsiChar := LastSubId; RegisterParameter(H_Sub, typeANSICHAR, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromAnsiChar); Id_OleVariantFromAnsiChar := LastSubId; RegisterParameter(H_Sub, typeANSICHAR, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromWideChar); Id_VariantFromWideChar := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromWideChar); Id_OleVariantFromWideChar := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromInt); Id_VariantFromInt := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromInt); Id_OleVariantFromInt := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromInt64); Id_VariantFromInt64 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromInt64); Id_OleVariantFromInt64 := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantFromByte); Id_VariantFromByte := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBYTE, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _OleVariantFromByte); Id_OleVariantFromByte := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBYTE, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromBool); Id_VariantFromBool := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromBool); Id_OleVariantFromBool := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromWord); Id_VariantFromWord := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeWORD, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromWord); Id_OleVariantFromWord := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeWORD, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromCardinal); Id_VariantFromCardinal := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeCARDINAL, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromCardinal); Id_OleVariantFromCardinal := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeCARDINAL, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromSmallInt); Id_VariantFromSmallInt := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSMALLINT, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromSmallInt); Id_OleVariantFromSmallInt := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSMALLINT, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromShortInt); Id_VariantFromShortInt := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTINT, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromShortInt); Id_OleVariantFromShortInt := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTINT, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromDouble); Id_VariantFromDouble := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromDouble); Id_OleVariantFromDouble := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromCurrency); Id_VariantFromCurrency := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeCURRENCY, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromCurrency); Id_OleVariantFromCurrency := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeCURRENCY, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromSingle); Id_VariantFromSingle := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSINGLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromSingle); Id_OleVariantFromSingle := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSINGLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromExtended); Id_VariantFromExtended := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromExtended); Id_OleVariantFromExtended := LastSubId; RegisterParameter(H_Sub, typeOLEVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, ByRef); {$IFDEF UNIC} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromInt); Id_UnicStringFromInt := LastSubId; // js only RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromDouble); Id_UnicStringFromDouble := LastSubId; // js only RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromSingle); Id_UnicStringFromSingle := LastSubId; // js only RegisterParameter(H_Sub, typeSINGLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromExtended); Id_UnicStringFromExtended := LastSubId; // js only RegisterParameter(H_Sub, typeEXTENDED, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromBoolean); Id_UnicStringFromBoolean := LastSubId; // js only RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); {$ELSE} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromInt); Id_AnsiStringFromInt := LastSubId; // js only RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromDouble); Id_AnsiStringFromDouble := LastSubId; // js only RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromSingle); Id_AnsiStringFromSingle := LastSubId; // js only RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeSINGLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromExtended); Id_AnsiStringFromExtended := LastSubId; // js only RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromBoolean); Id_AnsiStringFromBoolean := LastSubId; // js only RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); {$ENDIF} // not unic H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideCharFromVariant); Id_WideCharFromVariant := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiCharFromVariant); Id_AnsiCharFromVariant := LastSubId; RegisterParameter(H_Sub, typeANSICHAR, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromVariant); Id_AnsiStringFromVariant := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringFromVariant); Id_WideStringFromVariant := LastSubId; RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringFromVariant); Id_ShortStringFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, ByRef); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_DoubleFromVariant); Id_DoubleFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_CurrencyFromVariant); Id_CurrencyFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeCURRENCY, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SingleFromVariant); Id_SingleFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ExtendedFromVariant); Id_ExtendedFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_IntFromVariant); Id_IntFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_Int64FromVariant); Id_Int64FromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeINT64, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ByteFromVariant); Id_ByteFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBYTE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WordFromVariant); Id_WordFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeWORD, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_CardinalFromVariant); Id_CardinalFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeCARDINAL, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SmallIntFromVariant); Id_SmallIntFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSMALLINT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortIntFromVariant); Id_ShortIntFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeSHORTINT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_BoolFromVariant); Id_BoolFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ByteBoolFromVariant); Id_ByteBoolFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBYTEBOOL, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WordBoolFromVariant); Id_WordBoolFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeWORDBOOL, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_LongBoolFromVariant); Id_LongBoolFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeLONGBOOL, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantAddition); Id_VariantAddition := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantSubtraction); Id_VariantSubtraction := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantMultiplication); Id_VariantMultiplication := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantDivision); Id_VariantDivision := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantIDivision); Id_VariantIDivision := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantModulo); Id_VariantModulo := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantLeftShift); Id_VariantLeftShift := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantRightShift); Id_VariantRightShift := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantAnd); Id_VariantAnd := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantOr); Id_VariantOr := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantXor); Id_VariantXor := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantLessThan); Id_VariantLessThan := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantLessThanOrEqual); Id_VariantLessThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantGreaterThan); Id_VariantGreaterThan := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantGreaterThanOrEqual); Id_VariantGreaterThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantEquality); Id_VariantEquality := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantNotEquality); Id_VariantNotEquality := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantNegation); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); Id_VariantNegation := LastSubId; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantAbs); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); Id_VariantAbs := LastSubId; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VariantNot); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); Id_VariantNot := LastSubId; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayGet1); Id_VarArrayGet1 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayPut1); Id_VarArrayPut1 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayGet2); Id_VarArrayGet2 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayPut2); Id_VarArrayPut2 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayGet3); Id_VarArrayGet3 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _VarArrayPut3); Id_VarArrayPut3 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _InterfaceFromClass); Id_InterfaceFromClass := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _InterfaceCast); Id_InterfaceCast := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _InterfaceAssign); Id_InterfaceAssign := LastSubId; RegisterParameter(H_Sub, typeINTERFACE, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTERFACE, Unassigned, ByRef); {$IFDEF PAX64} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DoubleMultiplication); Id_DoubleMultiplication := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DoubleDivision); Id_DoubleDivision := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DoubleAddition); Id_DoubleAddition := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DoubleSubtraction); Id_DoubleSubtraction := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DoubleNegation); Id_DoubleNegation := LastSubId; RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef); {$ENDIF} //------------------ Dynamic array support routines ---------------------------- RegisterRoutine(0, 'SetLength', typeVOID, ccSTDCALL, nil); RegisterRoutine(0, '', typeVOID, ccREGISTER, @_CondHalt); Id_CondHalt := LastSubId; H_Sub := RegisterRoutine(0, '_toParentClass', typeVOID, ccSTDCALL, @_ToParentClass); Id_ToParentClass := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); RegisterParameter(H_Sub, typeCLASS, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UpdateInstance); Id_UpdateInstance := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); RegisterParameter(H_Sub, typeCLASS, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_BeginExceptBlock); Id_BeginExceptBlock := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); // reserved // RegisterRoutine(0, '', typeVOID, ccSTDCALL, @Dummy); {$IFNDEF PAXARM} RegisterRoutine(0, '', typeVOID, ccREGISTER, @_DestroyInherited); Id_DestroyInherited := LastSubId; {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DynarraySetLength); Id_DynarraySetLength := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _CreateEmptyDynarray); Id_CreateEmptyDynarray := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DynarrayClr); Id_DynarrayClr := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _DynarrayAssign); Id_DynarrayAssign := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeINTEGER, ccSTDCALL, @_DynarrayHigh); Id_DynarrayHigh := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef); //------------------------------------------------------------------------------ {$IFDEF MSWINDOWS} RegisterRoutine(0, strGetTickCount, typeINTEGER, ccREGISTER, @GetTickCount); {$ELSE} RegisterRoutine(0, '', typeINTEGER, ccREGISTER, nil); {$ENDIF} RegisterRoutine(0, '', typePOINTER, ccREGISTER, @GetClassByIndex); Id_GetClassByIndex := LastSubId; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_PrintEx); Id_PrintEx := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); //runner RegisterParameter(H_Sub, typePOINTER, Unassigned); //address RegisterParameter(H_Sub, typeINTEGER, Unassigned); //kind RegisterParameter(H_Sub, typeINTEGER, Unassigned); //ft RegisterParameter(H_Sub, typeINTEGER, Unassigned); //L1 RegisterParameter(H_Sub, typeINTEGER, Unassigned); //L2 // processing IS H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_Is); Id_Is := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ClassName); Id_ClassName := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_BeforeCallHost); Id_BeforeCallHost := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AfterCallHost); Id_AfterCallHost := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OnCreateObject); Id_OnCreateObject := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OnCreateHostObject); Id_OnCreateHostObject := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OnDestroyHostObject); Id_OnDestroyHostObject := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OnAfterObjectCreation); Id_OnAfterObjectCreation := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); // processing of published properties {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetAnsiStrProp); Id_GetAnsiStrProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetAnsiStrProp); Id_SetAnsiStrProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetWideStrProp); Id_GetWideStrProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetWideStrProp); Id_SetWideStrProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetOrdProp); Id_GetOrdProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetOrdProp); Id_SetOrdProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetInterfaceProp); Id_GetInterfaceProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetInterfaceProp); Id_SetInterfaceProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetSetProp); Id_GetSetProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetSetProp); Id_SetSetProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetFloatProp); Id_GetFloatProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetFloatProp); Id_SetFloatProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetVariantProp); Id_GetVariantProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetVariantProp); Id_SetVariantProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetInt64Prop); Id_GetInt64Prop := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _SetInt64Prop); Id_SetInt64Prop := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _GetEventProp); Id_GetEventProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_SetEventProp); Id_SetEventProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_SetEventProp2); Id_SetEventProp2 := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _CreateMethod); Id_CreateMethod := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); // processing try-except-finally H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_TryOn); Id_TryOn := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_TryOff); Id_TryOff := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_Raise); Id_Raise := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_Exit); Id_Exit := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_Finally); Id_Finally := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_CondRaise); Id_CondRaise := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_EndExceptBlock); Id_EndExceptBlock := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); // processing pause H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_Pause); Id_Pause := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterRoutine(0, 'pause', typeVOID, ccSTDCALL, nil); H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, Address_InitSub); Id_InitSub := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, Address_EndSub); Id_EndSub := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); // processing halt H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_Halt); Id_Halt := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterRoutine(0, 'halt', typeVOID, ccSTDCALL, nil); RegisterRoutine(0, 'abort', typeVOID, ccSTDCALL, nil); RegisterRoutine(0, 'print', typeVOID, ccSTDCALL, nil); RegisterRoutine(0, 'println', typeVOID, ccSTDCALL, nil); // processing breakpoints H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_CheckPause); Id_CheckPause := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); // processing integer overflow RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_IntOver); Id_IntOver := LastSubId; // processing bound error RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_BoundError); Id_BoundError := LastSubId; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_CreateObject); Id_CreateObject := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _ErrAbstract); Id_ErrAbstract := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _RecordAssign); Id_RecordAssign := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterRoutine(0, '_GetProgAddress', typePOINTER, ccSTDCALL, @ _GetProgAddress); CURR_FMUL_ID := RegisterConstant(0, '_10000.0', typeSINGLE, 10000.0); ///////////////////////////////////////////////////////////////////// /// PASCAL NAMESPASCE /////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// H_Namespace := RegisterNamespace(0, StrPascalNamespace); H_PascalNamespace := H_Namespace; H_Sub := RegisterRoutine(H_Namespace, 'GetMem', typeVOID, ccREGISTER, @_GetMem); RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef, 'P'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Size'); H_Sub := RegisterRoutine(H_Namespace, 'FreeMem', typeVOID, ccREGISTER, @_FreeMem); RegisterParameter(H_Sub, typePOINTER, Unassigned, false, 'P'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Size'); H_Sub := RegisterRoutine(H_Namespace, 'AllocMem', typePOINTER, ccREGISTER, @AllocMem); RegisterParameter(H_Sub, typeCARDINAL, Unassigned, false, 'Size'); // PASCAL ARITHMETIC ROUTINES /////////////////////////////////////// H_Sub := RegisterRoutine(H_Namespace, 'Abs', typeVOID, ccSTDCALL, nil); RegisterParameter(H_Sub, typeVOID, Unassigned, ByRef, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'ArcTan', typeEXTENDED, ccREGISTER, @_ArcTan); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Cos', typeEXTENDED, ccREGISTER, @_Cos); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Exp', typeEXTENDED, ccREGISTER, @_Exp); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Frac', typeEXTENDED, ccREGISTER, @_Frac); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Int', typeEXTENDED, ccREGISTER, @_Int); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Ln', typeEXTENDED, ccREGISTER, @_Ln); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); RegisterConstant(H_Namespace, 'Pi', typeEXTENDED, Pi); H_Sub := RegisterRoutine(H_Namespace, 'Sin', typeEXTENDED, ccREGISTER, @_Sin); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Sqr', typeEXTENDED, ccREGISTER, @_Sqr); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Sqrt', typeEXTENDED, ccREGISTER, @_Sqrt); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Trunc', typeINTEGER, ccREGISTER, @_Trunc); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Power', typeEXTENDED, ccREGISTER, @_Power); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'Base'); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'Exponent'); ///////////////////////////////////////////////////////////////////// RegisterRoutine(H_Namespace, 'New', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Dispose', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Inc', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Dec', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Pred', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Succ', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Ord', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Chr', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'Low', typeVOID, ccSTDCALL, nil); RegisterRoutine(H_Namespace, 'High', typeVOID, ccSTDCALL, nil); RegisterRoutine(0, 'Assigned', typeVOID, ccSTDCALL, nil); H_Sub := RegisterRoutine(H_Namespace, 'Odd', typeBOOLEAN, ccREGISTER, @_Odd); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'X'); // PASCAL AnsiString ROUTINES /////////////////////////////////////// H_Sub := RegisterRoutine(0, 'Length', typeINTEGER, ccREGISTER, @_DynarrayLength); Id_DynArrayLength := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, false, 'X'); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, 'Length', typeINTEGER, ccREGISTER, @_LengthString); Id_AnsiStringLength := LastSubId; RegisterParameter(H_Sub, typeANSISTRING, Unassigned, false, 'S'); H_Sub := RegisterRoutine(0, 'Length', typeINTEGER, ccREGISTER, @ _LengthShortString); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, false, 'S'); H_Sub := RegisterRoutine(0, 'Length', typeINTEGER, ccREGISTER, @_LengthWideString); RegisterParameter(H_Sub, typeWIDESTRING, Unassigned, false, 'S'); {$ENDIF} H_Sub := RegisterRoutine(0, 'Length', typeINTEGER, ccREGISTER, @_LengthUnicString); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'S'); H_Sub := RegisterRoutine(0, 'Length', typeINTEGER, ccREGISTER, @_VariantLength); Id_VariantArrayLength := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, false, 'S'); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(H_Namespace, 'Delete', typeVOID, ccREGISTER, @_Delete); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef, 'S'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Index'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Count'); H_Sub := RegisterRoutine(H_Namespace, 'Insert', typeVOID, ccREGISTER, @_Insert); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, false, 'Substr'); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, ByRef, 'Dest'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Index'); {$ENDIF} RegisterRoutine(H_Namespace, 'Str', typeVOID, ccSTDCALL, nil); H_Sub := RegisterRoutine(H_Namespace, 'Val', typeVOID, ccREGISTER, @_ValInt); RegisterParameter(H_Sub, typeSTRING, Unassigned, false, 'S'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef, 'V'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef, 'Code'); H_Sub := RegisterRoutine(H_Namespace, 'Val', typeVOID, ccREGISTER, @_ValDouble); RegisterParameter(H_Sub, typeSTRING, Unassigned, false, 'X'); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef, 'V'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef, 'Code'); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(H_Namespace, 'Copy', typeANSISTRING, ccREGISTER, @_Copy); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, false, 'S'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Index'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Count'); H_Sub := RegisterRoutine(H_Namespace, 'Pos', typeINTEGER, ccREGISTER, @_PosString); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, false, 'Substr'); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, false, 'Str'); H_Sub := RegisterRoutine(H_Namespace, 'Pos', typeINTEGER, ccREGISTER, @_PosChar); RegisterParameter(H_Sub, typeANSICHAR, Unassigned, false, 'Ch'); RegisterParameter(H_Sub, typeANSISTRING, Unassigned, false, 'Str'); {$ENDIF} ///////////////////////////////////////////////////////////////////// // PASCAL MISCELLANEOUS ROUTINES //////////////////////////////////// H_Sub := RegisterRoutine(H_Namespace, 'SizeOf', typeVOID, ccSTDCALL, nil); RegisterParameter(H_Sub, typeVOID, Unassigned, ByRef, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Move', typeVOID, ccREGISTER, @Move); RegisterParameter(H_Sub, typePVOID, Unassigned, false, 'Source'); RegisterParameter(H_Sub, typePVOID, Unassigned, ByRef, 'Dest'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Count'); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(H_Namespace, 'FillChar', typeVOID, ccREGISTER, @_FillChar); RegisterParameter(H_Sub, typePVOID, Unassigned, ByRef, 'X'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Count'); RegisterParameter(H_Sub, typeANSICHAR, Unassigned, false, 'Value'); {$ENDIF} H_Sub := RegisterRoutine(H_Namespace, 'FillChar', typeVOID, ccREGISTER, @_FillChar); RegisterParameter(H_Sub, typePVOID, Unassigned, ByRef, 'X'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Count'); RegisterParameter(H_Sub, typeBYTE, Unassigned, false, 'Value'); {$IFNDEF PAXARM} {$IFDEF FPC} H_Sub := RegisterRoutine(H_Namespace, 'Upcase', typeANSICHAR, ccREGISTER, @_Upcase); {$ELSE} H_Sub := RegisterRoutine(H_Namespace, 'Upcase', typeANSICHAR, ccREGISTER, @ Upcase); {$ENDIF} RegisterParameter(H_Sub, typeANSICHAR, Unassigned, false, 'C'); {$ENDIF} RegisterRoutine(H_Namespace, 'Randomize', typeVOID, ccREGISTER, @Randomize); H_Sub := RegisterRoutine(H_Namespace, 'Random', typeINTEGER, ccREGISTER, @_Random1); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'X'); RegisterRoutine(H_Namespace, 'Random', typeDOUBLE, ccREGISTER, @_Random); H_Sub := RegisterRoutine(H_Namespace, 'Hi', typeBYTE, ccREGISTER, @_HiInt); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Hi', typeBYTE, ccREGISTER, @_HiWord); RegisterParameter(H_Sub, typeWORD, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Lo', typeBYTE, ccREGISTER, @_LoInt); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Lo', typeBYTE, ccREGISTER, @_LoWord); RegisterParameter(H_Sub, typeWORD, Unassigned, false, 'X'); H_Sub := RegisterRoutine(H_Namespace, 'Round', typeINT64, ccREGISTER, @_Round); RegisterParameter(H_Sub, typeEXTENDED, Unassigned, false, 'X'); {$IFDEF TRIAL} strShowTrial[0] := '_'; strShowTrial[1] := '_'; strShowTrial[2] := '_'; strShowTrial[3] := '9'; strShowTrial[4] := '^'; strShowTrial[5] := '*'; strShowTrial[6] := #0; RegisterRoutine(0, strShowTrial, typeVOID, ccREGISTER, @ ShowTrial); {$ENDIF} H_TPOINT := RegisterRecordType(0, 'TPoint', 1); RegisterTypeField(H_TPOINT, 'X', typeINTEGER); RegisterTypeField(H_TPOINT, 'Y', typeINTEGER); H := RegisterRecordType(0, 'TRect', 1); RegisterTypeField(H, 'Left', typeINTEGER); RegisterTypeField(H, 'Top', typeINTEGER); RegisterTypeField(H, 'Right', typeINTEGER); RegisterTypeField(H, 'Bottom', typeINTEGER); // PASCAL CLASSES ROUTINES ///////////////////////////////////////////////////// RegisterTypeAlias(H_Namespace, 'Real', typeDOUBLE); Id_TDateTime := RegisterTypeAlias(H_Namespace, 'TDateTime', typeDOUBLE); RegisterTypeAlias(H_Namespace, 'Longint', typeINTEGER); RegisterTypeAlias(H_Namespace, 'THandle', typeCARDINAL); RegisterTypeAlias(H_Namespace, 'LongWord', typeCARDINAL); RegisterTypeAlias(H_Namespace, 'HRESULT', typeINTEGER); RegisterTypeAlias(H_Namespace, 'HMODULE', typeINTEGER); H_PInteger := RegisterPointerType(H_Namespace, 'PInteger', typeINTEGER); H_PSmallInt := RegisterPointerType(H_Namespace, 'PSmallInt', typeSMALLINT); H_PShortInt := RegisterPointerType(H_Namespace, 'PShortInt', typeSHORTINT); H_PCardinal := RegisterPointerType(H_Namespace, 'PCardinal', typeCARDINAL); H_PWord := RegisterPointerType(H_Namespace, 'PWord', typeWORD); H_PByte := RegisterPointerType(H_Namespace, 'PByte', typeBYTE); H_PInt64 := RegisterPointerType(H_Namespace, 'PInt64', typeINT64); H_PSingle := RegisterPointerType(H_Namespace, 'PSingle', typeSINGLE); H_PDouble := RegisterPointerType(H_Namespace, 'PDouble', typeDOUBLE); H_PExtended := RegisterPointerType(H_Namespace, 'PExtended', typeEXTENDED); H_PCurrency := RegisterPointerType(H_Namespace, 'PCurrency', typeCURRENCY); H_PVariant := RegisterPointerType(H_Namespace, 'PVariant', typeVARIANT); H_PPointer := RegisterPointerType(H_Namespace, 'PPointer', typePOINTER); H_PBoolean := RegisterPointerType(H_Namespace, 'PBoolean', typeBOOLEAN); H_PWideChar := typePWIDECHAR; {$IFNDEF PAXARM} H_PAnsiChar := typePANSICHAR; H_PShortString := RegisterPointerType(0, 'PShortString', typeSHORTSTRING); H_PAnsiString := RegisterPointerType(0, 'PAnsiString', typeANSISTRING); H_PWideString := RegisterPointerType(0, 'PWideString', typeWIDESTRING); {$ENDIF} H_PUnicString := RegisterPointerType(0, 'PUnicString', typeUNICSTRING); {$IFDEF UNIC} H_PString := H_PUnicString; {$ELSE} H_PString := H_PAnsiString; {$ENDIF} RegisterTypeAlias(H_Namespace, 'PLongint', H_PINTEGER); RegisterTypeAlias(H_Namespace, 'PLongWord', H_PCARDINAL); RegisterTypeAlias(H_Namespace, 'PDate', H_PDOUBLE); {$IFNDEF PAXARM} RegisterTypeAlias(H_Namespace, 'PAnsiChar', typePANSICHAR); {$ENDIF} H_PPInteger := RegisterPointerType(H_Namespace, 'PPInteger', H_PINTEGER); H_PPSmallInt := RegisterPointerType(H_Namespace, 'PPSmallInt', H_PSMALLINT); H_PPShortInt := RegisterPointerType(H_Namespace, 'PPShortInt', H_PSHORTINT); H_PPCardinal := RegisterPointerType(H_Namespace, 'PPCardinal', H_PCARDINAL); H_PPWord := RegisterPointerType(H_Namespace, 'PPWord', H_PWORD); H_PPByte := RegisterPointerType(H_Namespace, 'PPByte', H_PBYTE); H_PPInt64 := RegisterPointerType(H_Namespace, 'PPInt64', H_PINT64); H_PPSingle := RegisterPointerType(H_Namespace, 'PPSingle', H_PSINGLE); H_PPDouble := RegisterPointerType(H_Namespace, 'PPDouble', H_PDOUBLE); H_PPExtended := RegisterPointerType(H_Namespace, 'PPExtended', H_PEXTENDED); H_PPCurrency := RegisterPointerType(H_Namespace, 'PPCurrency', H_PCURRENCY); H_PPVariant := RegisterPointerType(H_Namespace, 'PPVariant', H_PVARIANT); H_PPPointer := RegisterPointerType(H_Namespace, 'PPPointer', H_PPOINTER); H_PPBoolean := RegisterPointerType(H_Namespace, 'PPBoolean', H_PBOOLEAN); H_PPWideChar := RegisterPointerType(H_Namespace, 'PPWideChar', H_PWIDECHAR); {$IFNDEF PAXARM} H_PPAnsiChar := RegisterPointerType(H_Namespace, 'PPAnsiChar', H_PANSICHAR); H_PPShortString := RegisterPointerType(0, 'PPShortString', H_PSHORTSTRING); H_PPAnsiString := RegisterPointerType(0, 'PPAnsiString', H_PANSISTRING); H_PPWideString := RegisterPointerType(0, 'PPWideString', H_PWIDESTRING); {$ENDIF} H_PPUnicString := RegisterPointerType(0, 'PPUnicString', H_PUNICSTRING); H_R0_7 := RegisterSubrangeType(0, '%0-7', typeINTEGER, 0, 7); H_TGUID_D4 := RegisterArrayType(0, '%TGUID_D4', H_R0_7, typeBYTE, 1); H_TGUID := RegisterRecordType(0, 'TGUID', 1); RegisterTypeField(H_TGUID, 'D1', typeCARDINAL); RegisterTypeField(H_TGUID, 'D2', typeWORD); RegisterTypeField(H_TGUID, 'D3', typeWORD); RegisterTypeField(H_TGUID, 'D4', H_TGUID_D4); H_PGUID := RegisterPointerType(0, 'PGUID', H_TGUID); H_IUnknown := RegisterInterfaceType(0, 'IUnknown', IUnknown); RegisterHeader(H_IUnknown, 'function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;', nil, 1); H_QueryInterface := LastSubId; RegisterHeader(H_IUnknown, 'function _AddRef: Integer; stdcall;', nil, 2); H_AddRef := LastSubId; RegisterHeader(H_IUnknown, 'function _Release: Integer; stdcall;', nil, 3); H_Release := LastSubId; RegisterTypeAlias(0, 'IInterface', H_IUNKNOWN); H_IDispatch := RegisterInterfaceType(0, 'IDispatch', IDispatch); RegisterHeader(H_IDispatch, 'function GetTypeInfoCount(out Count: Integer): HResult; stdcall;', nil, 4); RegisterHeader(H_IDispatch, 'function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;', nil, 5); RegisterHeader(H_IDispatch, 'function GetIDsOfNames(const IID: TGUID; Names: Pointer;' + 'NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;', nil, 6); RegisterHeader(H_IDispatch, 'function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;' + 'Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;', nil, 7); // TObject H_TObject := RegisterClassType(0, TObject); H_TClass := RegisterClassReferenceType(0, 'TClass', H_TObject); RegisterConstructor(H_TObject, 'Create', @TObject.Create); RegisterDestructor(H_TObject, 'Destroy', @TMyObject.Destroy); Id_TObject_Destroy := LastSubId; RegisterMethod(H_TObject, 'Free', typeVOID, ccREGISTER, @TObject.Free); Id_TObject_Free := LastSubId; {$IFDEF PAXARM} RegisterMethod(H_TObject, 'ClassName', typeSTRING, ccSTDCALL, @TObject_ClassName); Id_TObject_ClassName := LastSubId; {$ELSE} RegisterMethod(H_TObject, 'ClassName', typeSHORTSTRING, ccSTDCALL, @TObject_ClassName); Id_TObject_ClassName := LastSubId; {$ENDIF} RegisterMethod(H_TObject, 'ClassType', H_TClass, ccREGISTER, @TObject.ClassType); RegisterMethod(H_TObject, 'ClassParent', H_TClass, ccREGISTER, @TObject.ClassParent, true); RegisterMethod(H_TObject, 'InstanceSize', typeINTEGER, ccREGISTER, @TObject.InstanceSize, true); RegisterHeader(H_TObject, 'function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; virtual;', @TObject.SafeCallException); RegisterHeader(H_TObject, 'procedure AfterConstruction; virtual;', @TObject.AfterConstruction); RegisterHeader(H_TObject, 'procedure BeforeDestruction; virtual;', @TObject.BeforeDestruction); RegisterHeader(H_TObject, 'procedure Dispatch(var Message); virtual;', @TObject.Dispatch); RegisterHeader(H_TObject, 'procedure DefaultHandler(var Message); virtual;', @TObject.DefaultHandler); RegisterHeader(H_TObject, 'class function NewInstance: TObject; virtual;', @TObject.NewInstance); RegisterHeader(H_TObject, 'procedure FreeInstance; virtual;', @TObject.FreeInstance); {$ifdef UNIC} RegisterHeader(H_TObject, 'function ToString: String; virtual;', @TObject.ToString); RegisterHeader(H_TObject, 'function Equals(Obj: TObject): Boolean; virtual;', @TObject.Equals); RegisterHeader(H_TObject, 'function GetHashCode: Integer; virtual;', @TObject.GetHashCode); {$endif} {$IFDEF PAXARM} H_Sub := RegisterMethod(H_TObject, 'FieldAddress', typePOINTER, ccREGISTER, @TObject.FieldAddress); RegisterParameter(H_Sub, typeSTRING, Unassigned, false, 'Name'); H_Sub := RegisterMethod(H_TObject, 'InheritsFrom', typeBOOLEAN, ccREGISTER, @TObject.InheritsFrom, true); RegisterParameter(H_Sub, H_TClass, Unassigned, false, 'AClass'); H_Sub := RegisterMethod(H_TObject, 'MethodAddress', typePOINTER, ccREGISTER, @TObject.MethodAddress, true); RegisterParameter(H_Sub, typeSTRING, Unassigned, false, 'Name'); H_Sub := RegisterMethod(H_TObject, 'MethodName', typeSTRING, ccREGISTER, @TObject.MethodName, true); RegisterParameter(H_Sub, typePOINTER, Unassigned, false, 'Address'); {$ELSE} H_Sub := RegisterMethod(H_TObject, 'FieldAddress', typePOINTER, ccREGISTER, @TObject.FieldAddress); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, false, 'Name'); H_Sub := RegisterMethod(H_TObject, 'InheritsFrom', typeBOOLEAN, ccREGISTER, @TObject.InheritsFrom, true); RegisterParameter(H_Sub, H_TClass, Unassigned, false, 'AClass'); H_Sub := RegisterMethod(H_TObject, 'MethodAddress', typePOINTER, ccREGISTER, @TObject.MethodAddress, true); RegisterParameter(H_Sub, typeSHORTSTRING, Unassigned, false, 'Name'); H_Sub := RegisterMethod(H_TObject, 'MethodName', typeSHORTSTRING, ccREGISTER, @TObject.MethodName, true); RegisterParameter(H_Sub, typePOINTER, Unassigned, false, 'Address'); {$ENDIF} RegisterHeader(H_TObject, 'function GetInterface(const IID: TGUID; out Obj): Boolean;', @ TObject_GetInterface); Id_TObject_GetInterface := LastSubId; // TInterfacedObject H_TInterfacedObject := RegisterClassType(0, TInterfacedObject); RegisterSupportedInterface(H_TInterfacedObject, 'IUnknown', IUnknown); RegisterConstructor(H_TInterfacedObject, 'Create', @TInterfacedObject.Create); RegisterHeader(H_TInterfacedObject, 'class function NewInstance: TObject; override;', @TInterfacedObject.NewInstance); RegisterHeader(H_TInterfacedObject, 'function __GetRefCount: Integer;', @GetRefCount); RegisterHeader(H_TInterfacedObject, 'property RefCount: Integer read __GetRefCount;', nil); RegisterHeader(H_TInterfacedObject, 'function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;', @TMyInterfacedObject.QueryInterface); RegisterHeader(H_TInterfacedObject, 'function _AddRef: Integer; stdcall;', @TMyInterfacedObject_AddRef); RegisterHeader(H_TInterfacedObject, 'function _Release: Integer; stdcall;', @TMyInterfacedObject_Release); // TInterfacedClass RegisterClassReferenceType(0, 'TInterfacedClass', H_TInterfacedObject); RegisterConstant(0, 'vtInteger', typeINTEGER, vtInteger); RegisterConstant(0, 'vtBoolean', typeINTEGER, vtBoolean); RegisterConstant(0, 'vtChar', typeINTEGER, vtChar); RegisterConstant(0, 'vtExtended', typeINTEGER, vtExtended); RegisterConstant(0, 'vtString', typeINTEGER, vtString); RegisterConstant(0, 'vtPointer', typeINTEGER, vtPointer); RegisterConstant(0, 'vtPChar', typeINTEGER, vtPChar); RegisterConstant(0, 'vtObject', typeINTEGER, vtObject); RegisterConstant(0, 'vtClass', typeINTEGER, vtClass); RegisterConstant(0, 'vtWideChar', typeINTEGER, vtWideChar); RegisterConstant(0, 'vtPWideChar', typeINTEGER, vtPWideChar); RegisterConstant(0, 'vtAnsiString', typeINTEGER, vtAnsiString); RegisterConstant(0, 'vtCurrency', typeINTEGER, vtCurrency); RegisterConstant(0, 'vtVariant', typeINTEGER, vtVariant); RegisterConstant(0, 'vtInterface', typeINTEGER, vtInterface); RegisterConstant(0, 'vtWideString', typeINTEGER, vtWideString); RegisterConstant(0, 'vtInt64', typeINTEGER, vtInt64); H_TVarRec := RegisterRecordType(0, 'TVarRec', 1); RegisterTypeField(H_TVarRec, 'VInteger', typeINTEGER, 0); RegisterTypeField(H_TVarRec, 'VBoolean', typeBOOLEAN, 0); {$IFNDEF PAXARM} RegisterTypeField(H_TVarRec, 'VChar', typeANSICHAR, 0); {$ENDIF} RegisterTypeField(H_TVarRec, 'VExtended', H_PExtended, 0); RegisterTypeField(H_TVarRec, 'VString', H_PShortString, 0); RegisterTypeField(H_TVarRec, 'VPointer', typePOINTER, 0); {$IFNDEF PAXARM} RegisterTypeField(H_TVarRec, 'VPChar', typePANSICHAR, 0); {$ENDIF} RegisterTypeField(H_TVarRec, 'VObject', H_TObject, 0); RegisterTypeField(H_TVarRec, 'VClass', H_TClass, 0); RegisterTypeField(H_TVarRec, 'VWideChar', typeWIDECHAR, 0); RegisterTypeField(H_TVarRec, 'VAnsiString', H_PSTRING, 0); RegisterTypeField(H_TVarRec, 'VCurrency', typePOINTER, 0); RegisterTypeField(H_TVarRec, 'VVariant', H_PVARIANT, 0); RegisterTypeField(H_TVarRec, 'VInterface', typePOINTER, 0); RegisterTypeField(H_TVarRec, 'VWideString', typePOINTER, 0); RegisterTypeField(H_TVarRec, 'VInt64', typePOINTER, 0); RegisterTypeField(H_TVarRec, 'VType', typeINTEGER, 4); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _AssignTVarRec); Id_AssignTVarRec := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Dynarray_TVarRec := RegisterDynamicArrayType(0, 'DYNARRAY_TVarRec', H_TVarRec); H_Dynarray_Integer := RegisterDynamicArrayType(0, 'DYNARRAY_Integer', typeINTEGER); H_Dynarray_Byte := RegisterDynamicArrayType(0, 'DYNARRAY_Byte', typeBYTE); H_Dynarray_Word := RegisterDynamicArrayType(0, 'DYNARRAY_Word', typeWORD); H_Dynarray_ShortInt := RegisterDynamicArrayType(0, 'DYNARRAY_ShortInt', typeSHORTINT); H_Dynarray_SmallInt := RegisterDynamicArrayType(0, 'DYNARRAY_SmallInt', typeSMALLINT); H_Dynarray_Cardinal := RegisterDynamicArrayType(0, 'DYNARRAY_Cardinal', typeCARDINAL); H_Dynarray_Int64 := RegisterDynamicArrayType(0, 'DYNARRAY_Int64', typeINT64); H_Dynarray_UInt64 := RegisterDynamicArrayType(0, 'DYNARRAY_UInt64', typeUINT64); {$IFNDEF PAXARM} H_Dynarray_AnsiChar := RegisterDynamicArrayType(0, 'DYNARRAY_AnsiChar', typeANSICHAR); H_Dynarray_WideChar := RegisterDynamicArrayType(0, 'DYNARRAY_WideChar', typeWIDECHAR); H_Dynarray_AnsiString := RegisterDynamicArrayType(0, 'DYNARRAY_AnsiString', typeANSISTRING); H_Dynarray_WideString := RegisterDynamicArrayType(0, 'DYNARRAY_WideString', typeWIDESTRING); H_Dynarray_ShortString := RegisterDynamicArrayType(0, 'DYNARRAY_ShortString', typeSHORTSTRING); {$ENDIF} H_Dynarray_UnicodeString := RegisterDynamicArrayType(0, 'DYNARRAY_UnicodeString', typeUNICSTRING); H_Dynarray_Double := RegisterDynamicArrayType(0, 'DYNARRAY_Double', typeDOUBLE); H_Dynarray_Single := RegisterDynamicArrayType(0, 'DYNARRAY_Single', typeSINGLE); H_Dynarray_Extended := RegisterDynamicArrayType(0, 'DYNARRAY_Extended', typeEXTENDED); H_Dynarray_Currency := RegisterDynamicArrayType(0, 'DYNARRAY_Currency', typeCURRENCY); H_Dynarray_Boolean := RegisterDynamicArrayType(0, 'DYNARRAY_Boolean', typeBOOLEAN); H_Dynarray_ByteBool := RegisterDynamicArrayType(0, 'DYNARRAY_ByteBool', typeBYTEBOOL); H_Dynarray_WordBool := RegisterDynamicArrayType(0, 'DYNARRAY_WordBool', typeWORDBOOL); H_Dynarray_LongBool := RegisterDynamicArrayType(0, 'DYNARRAY_LongBool', typeLONGBOOL); H_Dynarray_Variant := RegisterDynamicArrayType(0, 'DYNARRAY_Variant', typeVARIANT); H_Dynarray_OleVariant := RegisterDynamicArrayType(0, 'DYNARRAY_OleVariant', typeOLEVARIANT); H_Dynarray_Pointer := RegisterDynamicArrayType(0, 'DYNARRAY_Pointer', typePOINTER); RegisterConstant(0, 'Null', typeVARIANT, Null); H_Unassigned := RegisterConstant(0, strUnassigned, typeVARIANT, Unassigned); RegisterConstant(0, 'MaxInt', typeINTEGER, MaxInt); RegisterConstant(0, 'MaxLongint', typeINTEGER, MaxInt); H_TMethod := RegisterRecordType(0, 'TMethod', 1); RegisterTypeField(H_TMethod, 'Code', typePOINTER, 0); RegisterTypeField(H_TMethod, 'Data', typePOINTER, 4); // RegisterClassType(0, TPersistent); // RegisterClassType(0, TComponent); RegisterTypeAlias(H_Namespace, 'TVarType', typeWORD); {$IFNDEF PAXARM} RegisterPointerType(H_Namespace, 'PWideString', typeWIDESTRING); RegisterTypeAlias(0, 'DWORD', typeCARDINAL); RegisterTypeAlias(0, 'AnsiString', typeANSISTRING); RegisterTypeAlias(0, 'AnsiChar', typeANSICHAR); {$ENDIF} RegisterConstant (H_Namespace, 'MaxLongInt', typeINTEGER, MaxLongInt); RegisterTypeAlias (H_Namespace, 'IInvokable', H_IUNKNOWN); H_Sub := RegisterRecordType (H_Namespace, 'TDispatchMessage', 8); RegisterTypeField(H_Sub, 'MsgID', typeWORD, 0); {$IFNDEF PAXARM} RegisterPointerType (H_Namespace, 'PAnsiString', typeANSISTRING); H := RegisterTypeAlias (H_Namespace, 'UCS2Char', typeWIDECHAR); RegisterPointerType (H_Namespace, 'PUCS2Char', H); H := RegisterTypeAlias (H_Namespace, 'UCS4Char', typeINTEGER); // typeLONGWORD RegisterPointerType (H_Namespace, 'PUCS4Char', H); H_Sub := RegisterArrayType (H_Namespace, 'TUCS4CharArray', RegisterSubrangeType (0, '%TUCS4CharArray', typeINTEGER, 0, $effffff), H, 8 ); RegisterPointerType (H_Namespace, 'PUCS4CharArray', H_Sub); RegisterDynamicArrayType (H_Namespace, 'UCS4String', H); H_Sub := RegisterTypeAlias (H_Namespace, 'UTF8String', typeANSISTRING); RegisterPointerType (H_Namespace, 'PUTF8String', H_Sub); H_Sub := RegisterArrayType (H_Namespace, 'IntegerArray', RegisterSubrangeType (0, '%IntegerArray', typeINTEGER, 0, $effffff), typeINTEGER, 8 ); RegisterPointerType (H_Namespace, 'PIntegerArray', H_Sub); H_Sub := RegisterArrayType (H_Namespace, 'PointerArray', RegisterSubRangeType (0, '%PointerArray', typeINTEGER, 0, 512*1024*1024 - 2), typePOINTER, 8 ); RegisterPointerType (H_Namespace, 'PPointerArray', H_Sub); RegisterDynamicArrayType (H_Namespace, 'TBoundArray', typeINTEGER); H_Sub := RegisterArrayType (H_Namespace, 'TPCharArray', RegisterSubRangeType (0, '%TPCharArray', typeINTEGER, 0, (MaxLongint div SizeOf(PChar))-1), typePANSICHAR, 1 ); RegisterPointerType (H_Namespace, 'PPCharArray', H_Sub); {$ENDIF} RegisterPointerType (H_Namespace, 'PSmallInt', typeSMALLINT); RegisterPointerType (H_Namespace, 'PShortInt', typeSHORTINT); H := RegisterPointerType (H_Namespace, 'PDispatch', H_IDispatch); RegisterPointerType (H_Namespace, 'PPDispatch', H); RegisterPointerType (H_Namespace, 'PError', typeINTEGER); //typeLONGWORD RegisterPointerType (H_Namespace, 'PWordBool', typeWORDBOOL); H := RegisterPointerType (H_Namespace, 'PUnknown', H_IUnknown); RegisterPointerType (H_Namespace, 'PPUnknown', H); RegisterPointerType (H_Namespace, 'POleVariant', typeOLEVARIANT); RegisterPointerType (H_Namespace, 'PDateTime', typeDOUBLE); H_Sub := RegisterRecordType (H_Namespace, 'TVarArrayBound', 1); RegisterTypeField (H_Sub, 'ElementCount', typeINTEGER); RegisterTypeField (H_Sub, 'LowBound', typeINTEGER); H_Sub := RegisterArrayType (H_Namespace, 'TVarArrayBoundArray', RegisterSubRangeType (H_Namespace, '%TVarArrayBoundArray', typeBYTE, H_Namespace, H_Namespace), H_Sub, 8 ); RegisterPointerType (H_Namespace, 'PVarArrayBoundArray', H_Sub); H := RegisterArrayType (H_Namespace, 'TVarArrayCoorArray', RegisterSubRangeType (H_Namespace, '%TVarArrayCoorArray', typeBYTE, H_Namespace, H_Namespace), typeINTEGER, 8 ); RegisterPointerType (H_Namespace, 'PVarArrayCoorArray', H); H := RegisterRecordType (H_Namespace, 'TVarArray', 1); RegisterTypeField (H, 'DimCount', typeWORD); RegisterTypeField (H, 'Flags', typeWORD); RegisterTypeField (H, 'ElementSize', typeINTEGER); RegisterTypeField (H, 'LockCount', typeINTEGER); RegisterTypeField (H, 'Data', typePOINTER); RegisterTypeField (H, 'Bounds', H_Sub); RegisterPointerType (0, 'PVarArray', H); H_Sub := RegisterRecordType(0, 'TVarData', 1); RegisterVariantRecordTypeField(H_Sub, 'VType: TVarType', 01); RegisterVariantRecordTypeField(H_Sub, 'Reserved1: Word', 0101); RegisterVariantRecordTypeField(H_Sub, 'Reserved2: Word', 010101); RegisterVariantRecordTypeField(H_Sub, 'Reserved3: Word', 010101); RegisterVariantRecordTypeField(H_Sub, 'VSmallInt: SmallInt', 01010101); RegisterVariantRecordTypeField(H_Sub, 'VInteger: Integer', 02010101); RegisterVariantRecordTypeField(H_Sub, 'VSingle: Single', 03010101); RegisterVariantRecordTypeField(H_Sub, 'VDouble: Double', 04010101); RegisterVariantRecordTypeField(H_Sub, 'VCurrency: Currency', 05010101); RegisterVariantRecordTypeField(H_Sub, 'VDate: TDateTime', 06010101); RegisterVariantRecordTypeField(H_Sub, 'VOleStr: PWideChar', 07010101); RegisterVariantRecordTypeField(H_Sub, 'VDispatch: Pointer', 08010101); RegisterVariantRecordTypeField(H_Sub, 'VError: HRESULT', 09010101); RegisterVariantRecordTypeField(H_Sub, 'VBoolean: WordBool', 10010101); RegisterVariantRecordTypeField(H_Sub, 'VUnknown: Pointer', 11010101); RegisterVariantRecordTypeField(H_Sub, 'VShortInt: ShortInt', 12010101); RegisterVariantRecordTypeField(H_Sub, 'VByte: Byte', 13010101); RegisterVariantRecordTypeField(H_Sub, 'VWord: Word', 14010101); RegisterVariantRecordTypeField(H_Sub, 'VLongWord: LongWord', 15010101); RegisterVariantRecordTypeField(H_Sub, 'VInt64: Int64', 16010101); RegisterVariantRecordTypeField(H_Sub, 'VString: Pointer', 17010101); RegisterVariantRecordTypeField(H_Sub, 'VAny: Pointer', 18010101); RegisterVariantRecordTypeField(H_Sub, 'VArray: Pointer', 19010101); RegisterVariantRecordTypeField(H_Sub, 'VPointer: Pointer', 20010101); RegisterPointerType (H_Namespace, 'PVarData', H_Sub); RegisterTypeAlias (H_Namespace, 'TVarOp', typeINTEGER); H_Sub := RegisterRecordType (H_Namespace, 'TCallDesc', 1); RegisterTypeField (H_Sub, 'CallType', typeBYTE); RegisterTypeField (H_Sub, 'ArgCount', typeBYTE); RegisterTypeField (H_Sub, 'NamedArgCount', typeBYTE); H := RegisterDynamicArrayType (0, '%ArgTypes', RegisterSubRangeType (0, '%%ArgTypes', typeINTEGER, 0, 255) ); RegisterTypeField (H_Sub, 'ArgTypes', H); RegisterPointerType (H_Namespace, 'PCallDesc', H_Sub); H := RegisterRecordType (H_Namespace, 'TDispDesc', 1); RegisterTypeField (H, 'DispID', typeINTEGER); RegisterTypeField (H, 'ResType', typeBYTE); RegisterTypeField (H, 'CallDesc', H_Sub); RegisterPointerType (H_Namespace, 'PDispDesc', H); { TDynArrayTypeInfo PDynArrayTypeInfo } RegisterPointerType (H_Namespace, 'PVarRec', H_TVarRec); H := RegisterEnumType (H_Namespace, 'TTextLineBreakStyle', typeINTEGER); RegisterEnumValue (H, 'tlbsLF', H_Namespace); RegisterEnumValue (H, 'tlbsCRLF', 1); H := RegisterTypeAlias (H_Namespace, 'HRSRC', typeCARDINAL); // THandle RegisterTypeAlias (H_Namespace, 'TResourceHandle', H); H := RegisterTypeAlias (H_Namespace, 'HINST', typeCARDINAL); // THandle RegisterTypeAlias (H_Namespace, 'HGLOBAL', H); H := RegisterPointerType(H_Namespace, 'PCardinal', typeCARDINAL); // redefined H_Sub := RegisterRecordType (H_Namespace, 'TResStringRec', 1); RegisterTypeField (H_Sub, 'Module', H); RegisterTypeField (H_Sub, 'Identifier', typeINTEGER); RegisterPointerType (H_Namespace, 'PResStringRec', H_Sub); H := RegisterRoutine (H_Namespace, '%TThreadFunc', typeINTEGER, ccREGISTER, Nil); RegisterParameter (H, typePOINTER, Unassigned); H_Sub := RegisterProceduralType (H_Namespace, 'TThreadFunc', H); H := RegisterRoutine (H_Namespace, 'BeginThread', typeINTEGER, ccREGISTER, @BeginThread); RegisterParameter (H, typePointer, Unassigned); // SecurityAttributes: Pointer; RegisterParameter (H, typeCARDINAL, Unassigned); // StackSize: LongWord; RegisterParameter (H, H_Sub, Unassigned); //ThreadFunc: TThreadFunc; RegisterParameter (H, typePOINTER, Unassigned); //Parameter: Pointer; RegisterParameter (H, typeCARDINAL, Unassigned); //CreationFlags: LongWord; RegisterParameter (H, typeCARDINAL, Unassigned, ByRef); // var ThreadId: LongWord H := RegisterRoutine (H_Namespace, 'EndThread', typeVOID, ccREGISTER, @EndThread); RegisterParameter (H, typeINTEGER, Unassigned); // EndThread(ExitCode: Integer); { H_Sub := RegisterClass (H_Namespace, TAggregatedObject); H_Sub := RegisterClass (H_Namespace, TContainedObject); } RegisterConstant(H_Namespace, 'varEmpty', varEmpty); RegisterConstant(H_Namespace, 'varNull', varNull); RegisterConstant(H_Namespace, 'varSmallint', varSmallint); RegisterConstant(H_Namespace, 'varInteger', varInteger); RegisterConstant(H_Namespace, 'varSingle', varSingle); RegisterConstant(H_Namespace, 'varDouble', varDouble); RegisterConstant(H_Namespace, 'varCurrency', varCurrency); RegisterConstant(H_Namespace, 'varDate', varDate); RegisterConstant(H_Namespace, 'varOleStr', varOleStr); RegisterConstant(H_Namespace, 'varDispatch', varDispatch); RegisterConstant(H_Namespace, 'varError', varError); RegisterConstant(H_Namespace, 'varBoolean', varBoolean); RegisterConstant(H_Namespace, 'varVariant', varVariant); RegisterConstant(H_Namespace, 'varUnknown', varUnknown); {$IFDEF VARIANTS} RegisterConstant(H_Namespace, 'varShortInt', varShortInt); {$ENDIF} RegisterConstant(H_Namespace, 'varByte', varByte); {$IFDEF VARIANTS} RegisterConstant(H_Namespace, 'varWord', varWord); RegisterConstant(H_Namespace, 'varLongWord', varLongWord); RegisterConstant(H_Namespace, 'varInt64', varInt64); RegisterConstant(H_Namespace, 'varUInt64', $0015); {$ENDIF} RegisterConstant(H_Namespace, 'varStrArg', varStrArg); RegisterConstant(H_Namespace, 'varString', varString); RegisterConstant(H_Namespace, 'varAny', varAny); RegisterConstant(H_Namespace, 'varTypeMask', varTypeMask); RegisterConstant(H_Namespace, 'varArray', varArray); RegisterConstant(H_Namespace, 'varByRef', varByRef); {$IFDEF UNIC} RegisterConstant(H_Namespace, 'varUString', varUString); {$ENDIF} H := RegisterRecordType (H_Namespace, 'TInterfaceEntry', 1); RegisterTypeField(H, 'IID', H_TGUID); RegisterTypeField(H, 'VTable', typePOINTER); RegisterTypeField(H, 'IOffset', typeINTEGER); RegisterTypeField(H, 'ImplGetter', typeINTEGER); RegisterPointerType(H_Namespace, 'PInterfaceEntry', H); H_TEntries := RegisterArrayType(0, '', RegisterSubrangeType(0, '', typeINTEGER, 0, 9999), H, 1); H := RegisterRecordType (H_Namespace, 'TInterfaceTable', 1); RegisterTypeField(H, 'EntryCount', typeINTEGER); RegisterTypeField(H, 'Entries', H_TEntries); H_Sub := RegisterRoutine(0, '', typeVOID, ccREGISTER, @_WriteUnicString); Id_WriteUnicString := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_WriteUnicString := H_Sub; {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromPAnsiChar); Id_UnicStringFromPAnsiChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromAnsiChar); Id_UnicStringFromAnsiChar := LastSubId; RegisterParameter(H_Sub, typeANSICHAR, Unassigned); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringFromUnicString); Id_ShortStringFromUnicString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromShortString); Id_UnicStringFromShortString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AnsiStringFromUnicString); Id_AnsiStringFromUnicString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromAnsiString); Id_UnicStringFromAnsiString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_WideStringFromUnicString); Id_WideStringFromUnicString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromWideString); Id_UnicStringFromWideString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromPWideChar); Id_UnicStringFromPWideChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _UnicStringFromWideChar); Id_UnicStringFromWideChar := LastSubId; RegisterParameter(H_Sub, typeWIDECHAR, Unassigned); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromUnicString); Id_VariantFromUnicString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringFromVariant); Id_UnicStringFromVariant := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromUnicString); Id_OleVariantFromUnicString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringAddition); Id_UnicStringAddition := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringAssign); Id_UnicStringAssign := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringEquality); Id_UnicStringEquality := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringNotEquality); Id_UnicStringNotEquality := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _UnicStringGreaterThan); Id_UnicStringGreaterThan := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringGreaterThanOrEqual); Id_UnicStringGreaterThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringLessThan); Id_UnicStringLessThan := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringLessThanOrEqual); Id_UnicStringLessThanOrEqual := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeBOOLEAN, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnicStringClr); Id_UnicStringClr := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_StringAddRef); Id_UnicStringAddRef := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetUnicStringLength); Id_SetUnicStringLength := LastSubId; RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_VariantFromPWideChar); Id_VariantFromPWideChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_OleVariantFromPWideChar); Id_OleVariantFromPWideChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetUnicStrProp); Id_GetUnicStrProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetUnicStrProp); Id_SetUnicStrProp := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _AnsiStringFromPWideChar); Id_AnsiStringFromPWideChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_ShortStringFromPWideChar); Id_ShortStringFromPWideChar := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); {$ENDIF} {$IFDEF UNIC} // Length, Pos, Copy, Insert, Delete H_Sub := RegisterRoutine(H_Namespace, 'Length', typeINTEGER, ccREGISTER, @_UnicLength); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'S'); H_Sub := RegisterRoutine(H_Namespace, 'Delete', typeVOID, ccREGISTER, @_UnicDelete); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef, 'S'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Index'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Count'); H_Sub := RegisterRoutine(H_Namespace, 'Insert', typeVOID, ccREGISTER, @_UnicInsert); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'Substr'); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, ByRef, 'Dest'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Index'); H_Sub := RegisterRoutine(H_Namespace, 'Val', typeVOID, ccREGISTER, @_UnicValInt); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'S'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef, 'V'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef, 'Code'); H_Sub := RegisterRoutine(H_Namespace, 'Val', typeVOID, ccREGISTER, @_UnicValDouble); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'X'); RegisterParameter(H_Sub, typeDOUBLE, Unassigned, ByRef, 'V'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, ByRef, 'Code'); H_Sub := RegisterRoutine(H_Namespace, 'Copy', typeUNICSTRING, ccREGISTER, @_UnicCopy); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'S'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Index'); RegisterParameter(H_Sub, typeINTEGER, Unassigned, false, 'Count'); H_Sub := RegisterRoutine(H_Namespace, 'Pos', typeINTEGER, ccREGISTER, @_UnicPos); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'Substr'); RegisterParameter(H_Sub, typeUNICSTRING, Unassigned, false, 'Str'); {$ENDIF} //unic ID_Prog := RegisterClassType(0, TBaseRunner); RegisterHeader(ID_Prog, 'procedure __Set_ExitCode(value: Integer); stdcall;', @Set_ExitCode); RegisterHeader(ID_Prog, 'function __Get_ExitCode: Integer; stdcall;', @Get_ExitCode); RegisterHeader(ID_Prog, 'property ExitCode: Integer read __Get_ExitCode write __Set_ExitCode;', nil); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _StructEquality); Id_StructEquality := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _StructNotEquality); Id_StructNotEquality := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); Register_TYPEINFO(H_Namespace, st); RegisterRoutine(0, '', typeVOID, ccSTDCALL, Address_LoadSeg); Id_LoadSeg := LastSubId; RegisterRoutine(0, '', typeVOID, ccSTDCALL, @ _LoadClassRef); Id_LoadClassRef := LastSubId; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetVariantLength2); Id_SetVariantLength2 := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_SetVariantLength3); Id_SetVariantLength3 := LastSubId; RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_LockVArray); Id_LockVArray := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); RegisterParameter(H_Sub, typePOINTER, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UnlockVArray); Id_UnlockVArray := LastSubId; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_DynarraySetLength2); Id_DynarraySetLength2 := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_DynarraySetLength3); Id_DynarraySetLength3 := LastSubId; RegisterParameter(H_Sub, typeDYNARRAY, Unassigned, ByRef); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); H := RegisterRecordType(0, 'TMsg', 1); RegisterTypeField(H, 'hwnd', typeCARDINAL); RegisterTypeField(H, 'message', typeCARDINAL); RegisterTypeField(H, 'wParam', typeINTEGER); RegisterTypeField(H, 'lParam', typeINTEGER); RegisterTypeField(H, 'time', typeCARDINAL); RegisterTypeField(H, 'pt', H_TPOINT); RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetDynamicMethodAddress); Id_GetDynamicMethodAddress := LastSubId; H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_AddMessage); Id_AddMessage := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typePOINTER, Unassigned); if Assigned(RegisterSEH) then RegisterSEH(st); Register_StdJavaScript(st); Register_StdBasic(st); Register_Framework(st); if Assigned(Import_TValue) then Import_TValue(0, st); {$IFNDEF PAXARM} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UniqueAnsiString); Id_UniqueAnsiString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); {$ENDIF} H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_UniqueUnicString); Id_UniqueUnicString := LastSubId; RegisterParameter(H_Sub, typePOINTER, Unassigned); H_Sub := RegisterRoutine(0, '', typeVOID, ccSTDCALL, @_GetComponent); Id_GetComponent := LastSubId; RegisterParameter(H_Sub, typeCLASS, Unassigned); RegisterParameter(H_Sub, typeINTEGER, Unassigned); RegisterParameter(H_Sub, typeCLASS, Unassigned, ByRef); H_DYN_VAR := RegisterDynamicArrayType(0, '#DYN_VAR', typeVARIANT); H_SUB := RegisterRoutine(0, '#CallVirt', typeVOID, ccSTDCALL, @_CallVirt); Records[LastSubId].PushProgRequired := true; Id_CallVirt := LastSubId; RegisterParameter(H_Sub, typePCHAR, Unassigned, false, 'Obj'); RegisterParameter(H_Sub, typePCHAR, Unassigned, false, 'Prop'); RegisterParameter(H_Sub, H_DYN_VAR, Unassigned, false, 'A'); Records[Card].IsOpenArray := true; RegisterParameter(H_Sub, typeVARIANT, Unassigned, ByRef, 'Res'); H_SUB := RegisterRoutine(0, '#PutVirt', typeVOID, ccSTDCALL, @_PutVirt); Records[LastSubId].PushProgRequired := true; Id_PutVirt := LastSubId; RegisterParameter(H_Sub, typePCHAR, Unassigned, false, 'Obj'); RegisterParameter(H_Sub, typePCHAR, Unassigned, false, 'Prop'); RegisterParameter(H_Sub, H_DYN_VAR, Unassigned, false, 'A'); Records[Card].IsOpenArray := true; RegisterParameter(H_Sub, typeVARIANT, Unassigned, false, 'value'); Records[Card].IsConst := true; H_SUB := RegisterRoutine(0, 'FreeAndNil', typeVOID, ccREGISTER, @ FreeAndNil); RegisterParameter(H_SUB, typePVOID, Unassigned, true, 'X'); if SizeOf(Pointer) = SizeOf(Integer) then typeNATIVEINT := typeINTEGER else typeNATIVEINT := typeINT64; {$IFNDEF PAXARM} T1 := RegisterArrayType(H, '', RegisterSubrangeType(0, '', typeINTEGER, 1, 32), typeBYTE, 1); T2 := RegisterArrayType(H, '', RegisterSubrangeType(0, '', typeINTEGER, 0, 259), typeCHAR, 1); T3 := RegisterArrayType(H, '', RegisterSubrangeType(0, '', typeINTEGER, 0, 127), typeANSICHAR, 1); H := RegisterRecordType(H, 'TFileRec', 1); H_TFileRec := H; RegisterTypeField(H, 'Handle', typeNATIVEINT); RegisterTypeField(H, 'Mode', typeWORD); RegisterTypeField(H, 'Flags', typeWORD); RegisterVariantRecordTypeField(H, 'RecSize', typeCARDINAL, 1); RegisterVariantRecordTypeField(H, 'BufSize', typeCARDINAL, 2); RegisterVariantRecordTypeField(H, 'BufPos', typeCARDINAL, 2); RegisterVariantRecordTypeField(H, 'BufEnd', typeCARDINAL, 2); RegisterVariantRecordTypeField(H, 'BufPtr', typePANSICHAR, 2); RegisterVariantRecordTypeField(H, 'OpenFunc', typePOINTER, 2); RegisterVariantRecordTypeField(H, 'InOutFunc', typePOINTER, 2); RegisterVariantRecordTypeField(H, 'FlushFunc', typePOINTER, 2); RegisterVariantRecordTypeField(H, 'CloseFunc', typePOINTER, 2); RegisterVariantRecordTypeField(H, 'UserData', T1, 2); RegisterVariantRecordTypeField(H, 'Name', T2, 2); T4 := RegisterArrayType(H, '', RegisterSubrangeType(0, '', typeINTEGER, 0, 5), typeANSICHAR, 1); T5 := RegisterArrayType(H, '', RegisterSubrangeType(0, '', typeINTEGER, 0, 2), typeANSICHAR, 1); H := RegisterRecordType(H, 'TTextRec', 1); H_TTextRec := H; RegisterTypeField(H, 'Handle', typeNATIVEINT); RegisterTypeField(H, 'Mode', typeWORD); RegisterTypeField(H, 'Flags', typeWORD); RegisterTypeField(H, 'BufSize', typeCARDINAL); RegisterTypeField(H, 'BufPos', typeCARDINAL); RegisterTypeField(H, 'BufEnd', typeCARDINAL); RegisterTypeField(H, 'BufPtr', typePANSICHAR); RegisterTypeField(H, 'OpenFunc', typePOINTER); RegisterTypeField(H, 'InOutFunc', typePOINTER); RegisterTypeField(H, 'FlushFunc', typePOINTER); RegisterTypeField(H, 'CloseFunc', typePOINTER); RegisterTypeField(H, 'UserData', T1); RegisterTypeField(H, 'Name', T2); RegisterTypeField(H, 'Buffer', T3); {$IFDEF UNIC} RegisterTypeField(H, 'CodePage', typeWORD); RegisterTypeField(H, 'MBCSLength', typeSHORTINT); RegisterTypeField(H, 'MBCSBufPos', typeBYTE); RegisterVariantRecordTypeField(H, 'MBCSBuffer', T4, 1); RegisterVariantRecordTypeField(H, 'UTF16Buffer', T5, 2); {$ENDIF} {$ENDIF} //ndef paxarm RegisterRoutine(0, '', typeVOID, ccREGISTER, @ GetAddressGetCallerEIP); Id_GetAddressGetCallerEIP := LastSubId; end; end; initialization RUNNER_OWNER_OFFSET := IntPax(@TBaseRunner(nil).Owner); if Assigned(AssignRunnerLibProc) then AssignRunnerLibProc; {$IFDEF DRTTI} Initialize_paxcomp_2010; InitializePAXCOMP_2010Reg; {$ENDIF} GlobalSymbolTable := TBaseSymbolTable.Create; AddStdRoutines(GlobalSymbolTable); StdCard := GlobalSymbolTable.Card; StdSize := GlobalSymbolTable.GetDataSize; GlobalImportTable := GlobalSymbolTable; GlobalExtraImportTableList := TExtraImportTableList.Create; AvailUnitList := TStringList.Create; AvailUnitList1:= TStringList.Create; AvailTypeList := TStringList.Create; {$IFDEF DRTTI} AvailUnitList.Sorted := true; AvailUnitList.Duplicates := dupIgnore; AvailUnitList.CaseSensitive := false; AvailUnitList1.Sorted := true; AvailUnitList1.Duplicates := dupIgnore; AvailUnitList1.CaseSensitive := false; AvailTypeList.Sorted := true; AvailTypeList.Duplicates := dupIgnore; AvailTypeList.CaseSensitive := false; {$ENDIF} finalization AvailUnitList.Free; AvailUnitList1.Free; AvailTypeList.Free; GlobalSymbolTable.Free; GlobalExtraImportTableList.Free; {$IFDEF DRTTI} Finalize_paxcomp_2010; {$ENDIF} end.
unit Contador; interface uses System.Classes, System.Generics.Collections, // Aurelius.Mapping.Attributes, Aurelius.Types.Blob, Aurelius.Types.Nullable, Aurelius.Types.Proxy; type [Entity] [Table('CONTADOR')] [Id('Id', TIdGenerator.IdentityOrSequence)] TContador = class private FID: Integer; FNOME: string; public [Column('ID', [TColumnProp.Required, TColumnProp.NoInsert, TColumnProp.NoUpdate])] property Id: Integer read FID write FID; [Column('CNPJ', [], 100)] property Nome: string read FNOME write FNOME; end; implementation initialization RegisterEntity(TContador); end.
{ Double Commander ------------------------------------------------------------------------- Control like TButton which does not steal focus on click Copyright (C) 2021 Alexander Koblov (alexx2000@mail.ru) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser 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 KASButton; {$mode delphi} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, Themes; type { TKASButton } TKASButton = class(TPanel) private FState: TButtonState; FShowCaption: Boolean; FButtonGlyph: TButtonGlyph; function GetGlyph: TBitmap; function IsGlyphStored: Boolean; procedure SetGlyph(AValue: TBitmap); procedure SetShowCaption(AValue: Boolean); function GetDrawDetails: TThemedElementDetails; protected procedure Paint; override; procedure DoExit; override; procedure DoEnter; override; procedure MouseEnter; override; procedure MouseLeave; override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; protected procedure GlyphChanged(Sender: TObject); procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: Integer; WithThemeSpace: Boolean); override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; published property Action; property Glyph: TBitmap read GetGlyph write SetGlyph stored IsGlyphStored; property ShowCaption: Boolean read FShowCaption write SetShowCaption default True; end; procedure Register; implementation uses LCLType, LCLProc, LCLIntf, ActnList; procedure Register; begin RegisterComponents('KASComponents',[TKASButton]); end; { TKASButton } procedure TKASButton.DoEnter; begin inherited DoEnter; FState:= bsExclusive; Invalidate; end; procedure TKASButton.DoExit; begin inherited DoExit; FState:= bsUp; Invalidate; end; function TKASButton.GetDrawDetails: TThemedElementDetails; var Detail: TThemedButton; begin if not IsEnabled then Detail := tbPushButtonDisabled else if FState = bsDown then Detail := tbPushButtonPressed else if FState = bsHot then Detail := tbPushButtonHot else if FState = bsExclusive then Detail := tbPushButtonDefaulted else begin Detail := tbPushButtonNormal; end; Result := ThemeServices.GetElementDetails(Detail) end; procedure TKASButton.SetShowCaption(AValue: Boolean); begin if FShowCaption = AValue then Exit; FShowCaption:= AValue; Invalidate; end; function TKASButton.GetGlyph: TBitmap; begin Result:= FButtonGlyph.Glyph; end; function TKASButton.IsGlyphStored: Boolean; var Act: TCustomAction; begin if Action <> nil then begin Result:= True; Act:= TCustomAction(Action); if (Act.ActionList <> nil) and (Act.ActionList.Images <> nil) and (Act.ImageIndex >= 0) and (Act.ImageIndex < Act.ActionList.Images.Count) then Result := False; end else Result:= (FButtonGlyph.Glyph <> nil) and (not FButtonGlyph.Glyph.Empty) and (FButtonGlyph.Glyph.Width > 0) and (FButtonGlyph.Glyph.Height > 0); end; procedure TKASButton.SetGlyph(AValue: TBitmap); begin FButtonGlyph.Glyph := AValue; InvalidatePreferredSize; AdjustSize; end; procedure TKASButton.Paint; var APoint: TPoint; SysFont: TFont; PaintRect: TRect; TextFlags: Integer; Details: TThemedElementDetails; begin PaintRect:= ClientRect; Details:= GetDrawDetails; ThemeServices.DrawElement(Canvas.Handle, Details, PaintRect); PaintRect := ThemeServices.ContentRect(Canvas.Handle, Details, PaintRect); if FShowCaption and (Caption <> EmptyStr) then begin TextFlags := DT_CENTER or DT_VCENTER; if UseRightToLeftReading then begin TextFlags := TextFlags or DT_RTLREADING; end; SysFont := Screen.SystemFont; if (SysFont.Color = Font.Color) and ((SysFont.Name = Font.Name) or IsFontNameDefault(Font.Name)) and (SysFont.Pitch = Font.Pitch) and (SysFont.Style = Font.Style) then begin ThemeServices.DrawText(Canvas, Details, Caption, PaintRect, TextFlags, 0); end else begin Canvas.Brush.Style := bsClear; DrawText(Canvas.Handle, PChar(Caption), Length(Caption), PaintRect, TextFlags); end; end else if not FButtonGlyph.Glyph.Empty then begin APoint.X:= (PaintRect.Width - FButtonGlyph.Width) div 2; APoint.Y:= (PaintRect.Height - FButtonGlyph.Height) div 2; FButtonGlyph.Draw(Canvas, PaintRect, APoint, FState, True, 0); end; end; procedure TKASButton.MouseEnter; begin inherited MouseEnter; FState:= bsHot; Invalidate; end; procedure TKASButton.MouseLeave; begin inherited MouseLeave; FState:= bsUp; Invalidate; end; procedure TKASButton.KeyUp(var Key: Word; Shift: TShiftState); begin inherited KeyUp(Key, Shift); if (Key in [VK_SPACE, VK_RETURN]) and (Shift = []) then begin FState:= bsUp; Invalidate; Click; end; end; procedure TKASButton.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if (Key in [VK_SPACE, VK_RETURN]) and (Shift = []) then begin FState:= bsDown; Invalidate; end; end; procedure TKASButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); FState:= bsUp; Invalidate; end; procedure TKASButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); FState:= bsDown; Invalidate; end; procedure TKASButton.GlyphChanged(Sender: TObject); begin InvalidatePreferredSize; AdjustSize; end; procedure TKASButton.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin inherited ActionChange(Sender, CheckDefaults); if Sender is TCustomAction then begin with TCustomAction(Sender) do begin if (Glyph.Empty) and (ActionList <> nil) and (ActionList.Images <> nil) and (ImageIndex >= 0) and (ImageIndex < ActionList.Images.Count) then ActionList.Images.GetBitmap(ImageIndex, Glyph); end; end; end; procedure TKASButton.CalculatePreferredSize(var PreferredWidth, PreferredHeight: Integer; WithThemeSpace: Boolean); var PaintRect: TRect; ClientRect: TRect; Details: TThemedElementDetails; begin inherited CalculatePreferredSize(PreferredWidth, PreferredHeight, WithThemeSpace); if (not FButtonGlyph.Glyph.Empty) then begin Details:= GetDrawDetails; PaintRect:= TRect.Create(0, 0, 32, 32); ClientRect:= ThemeServices.ContentRect(Canvas.Handle, Details, PaintRect); PreferredWidth:= Abs(PaintRect.Width - ClientRect.Width) + FButtonGlyph.Width; PreferredHeight:= Abs(PaintRect.Height - ClientRect.Height) + FButtonGlyph.Height; end; end; constructor TKASButton.Create(TheOwner: TComponent); begin inherited Create(TheOwner); FButtonGlyph := TButtonGlyph.Create; FButtonGlyph.NumGlyphs := 1; FButtonGlyph.OnChange := GlyphChanged; FButtonGlyph.IsDesigning := csDesigning in ComponentState; FShowCaption:= True; TabStop:= True; end; destructor TKASButton.Destroy; begin FreeAndNil(FButtonGlyph); inherited Destroy; end; end.
unit Modules.Data; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TDBController = class(TDataModule) Connection: TFDConnection; QuCoordinates: TFDQuery; QuCounties: TFDQuery; QuStates: TFDQuery; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } public { Public declarations } end; var DBController: TDBController; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDBController.DataModuleCreate(Sender: TObject); begin QuStates.Open; QuCounties.Open; QuCoordinates.Open; end; procedure TDBController.DataModuleDestroy(Sender: TObject); begin QuCounties.Close; QuCoordinates.Close; QuStates.Close; Connection.Close; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit MV.Utils; interface uses FMX.Types3D, FMX.Types, System.UITypes, Classes, SysUtils, Types; const SHARED_PATH = '..\..\..\..\shared\'; IMAGES_PATH = SHARED_PATH + 'textures\'; TEXTURES_PATH = SHARED_PATH + 'textures\'; MODELS_PATH = SHARED_PATH + 'models\'; SHADERS_PATH = SHARED_PATH + 'shaders\'; function PointDistance2(const v1, v2: TPoint3D): Single; overload; function PointDistance2(const v1, v2: TPointF): Single; overload; function PointAdd(const v1: TPoint3D; const v2: TPoint3D): TPoint3D; function ColorToVector3D(const AColor: TColor):Tvector3D; function CreateTranslationMatrix3D(const AVec: TVector3D): TMatrix3D; function CreateScaleMatrix3D(const AScale: TVector3D): TMatrix3D; function Matrix3D(const m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44:Single): TMatrix3D; function Matrix3DA(const LArr: TSingleDynArray):TMatrix3D; function QuaternionRot(const R, P, Y: Single): TQuaternion3D; function CreateRotMatrix3D(const Y, P, R: Single): TMatrix3D; function SphericalToRect(const ARotation: TPointf; ARadius:Single) : TVector3D; function FloatStringsToSingleDynArray(const AStr: string): TSingleDynArray; function IntStringsToIntegerDynArray(const AStr: string): TIntegerDynArray; overload; function StringsToStringDynArray(const AStr: string): TStringDynArray; overload; implementation {------------------------------------------------------------------------------ Math } function SphericalToRect(const ARotation: TPointf; ARadius:Single) : TVector3D; var sinr: single; const DEG_TO_RAD = pi/180; begin sinr := ARadius * Sin(ARotation.y * DEG_TO_RAD); result.X := sinr * Cos(ARotation.x * DEG_TO_RAD); result.Y := sinr * Sin(ARotation.x * DEG_TO_RAD); result.Z := ARadius * Cos(ARotation.y * DEG_TO_RAD); end; function ColorToVector3D(const AColor: TColor):Tvector3D; var LColorRec: TColorRec; begin LColorRec.Color := AColor; result := Vector3D(LColorRec.R/128,LColorRec.G/128,LColorRec.B/128,1.0); end; function QuaternionRot(const R, P, Y: Single): TQuaternion3D; var qp, qy, qR: TQuaternion3D; begin qR := QuaternionFromAngleAxis(R, Vector3D(0, 0, 1)); qp := QuaternionFromAngleAxis(P, Vector3D(0, 1, 0)); qy := QuaternionFromAngleAxis(Y, Vector3D(1, 0, 0)); Result := QuaternionMultiply(qR, QuaternionMultiply(qp, qy)); end; function CreateRotMatrix3D(const Y, P, R: Single): TMatrix3D; var q: TQuaternion3D; begin q := QuaternionRot(R, P, Y); Result := QuaternionToMatrix(q); end; function Matrix3D(const m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 : Single): TMatrix3D; begin Result.m11 := m11; Result.m12 := m12; Result.m13 := m13; Result.m14 := m14; Result.m21 := m21; Result.m22 := m22; Result.m23 := m23; Result.m24 := m24; Result.m31 := m31; Result.m32 := m32; Result.m33 := m33; Result.m34 := m34; Result.m41 := m41; Result.m42 := m42; Result.m43 := m43; Result.m44 := m44; end; function Matrix3DA(const LArr: TSingleDynArray):TMatrix3d; begin result := Matrix3D( LArr[0],LArr[4],LArr[8],LArr[12], LArr[1],LArr[5],LArr[9],LArr[13], LArr[2],LArr[6],LArr[10],LArr[14], LArr[3],LArr[7],LArr[11],LArr[15]); end; function CreateTranslationMatrix3D(const AVec: TVector3D): TMatrix3D; begin { Result.m11 := 1; Result.m21 := 0; Result.m31 := 0; Result.m41 := 0; Result.m12 := 0; Result.m22 := 1; Result.m32 := 0; Result.m42 := 0; Result.m13 := 0; Result.m23 := 0; Result.m33 := 1; Result.m43 := 0; Result.m14 := AVec.x; Result.m24 := AVec.y; Result.m34 := AVec.z; Result.m44 := 1; } Result.m11 := 1; Result.m21 := 0; Result.m31 := 0; Result.m41 := AVec.x; Result.m12 := 0; Result.m22 := 1; Result.m32 := 0; Result.m42 := AVec.y; Result.m13 := 0; Result.m23 := 0; Result.m33 := 1; Result.m43 := AVec.z; Result.m14 := 0; Result.m24 := 0; Result.m34 := 0; Result.m44 := 1; end; function CreateScaleMatrix3D(const AScale: TVector3D): TMatrix3D; begin Result.M[0].V[0] := AScale.x; Result.M[0].V[1] := 0; Result.M[0].V[2] := 0; Result.M[0].V[3] := 0; Result.M[1].V[0] := 0; Result.M[1].V[1] := AScale.y; Result.M[1].V[2] := 0; Result.M[1].V[3] := 0; Result.M[2].V[0] := 0; Result.M[2].V[1] := 0; Result.M[2].V[2] := AScale.z; Result.M[2].V[3] := 0; Result.M[3].V[0] := 0; Result.M[3].V[1] := 0; Result.M[3].V[2] := 0; Result.M[3].V[3] := 1; end; function PointAdd(const v1: TPoint3D; const v2: TPoint3D): TPoint3D; begin Result.x := v1.x + v2.x; Result.y := v1.y + v2.y; Result.z := v1.z + v2.z; end; function PointDistance2(const v1, v2: TPoint3D): Single; begin Result := Sqr(v2.x - v1.x) + Sqr(v2.y - v1.y) + Sqr(v2.z - v1.z); end; function PointDistance2(const v1, v2: TPointF): Single; begin Result := Sqr(v2.x - v1.x) + Sqr(v2.y - v1.y); end; function FloatStringsToSingleDynArray(const AStr: string): TSingleDynArray; var str: string; c: PChar; LFormatSettings: TFormatSettings; procedure TryAdd; begin if str = '' then Exit; SetLength(Result, Length(Result) + 1); Result[High(Result)] := StrToFloat(str, LFormatSettings); str := ''; end; begin Result := nil; if AStr = '' then Exit; LFormatSettings := TFormatSettings.Create; c := @AStr[1]; while c^ <> #0 do begin case c^ of #1..#32: TryAdd; else case c^ of '.': LFormatSettings.DecimalSeparator := '.'; ',': LFormatSettings.DecimalSeparator := ','; end; str := str + c^; end; Inc(c); end; TryAdd; end; function IntStringsToIntegerDynArray(const AStr: string): TIntegerDynArray; var str: string; c: PChar; procedure TryAdd; begin if str = '' then Exit; SetLength(Result, Length(Result) + 1); Result[High(Result)] := StrToInt(str); str := ''; end; begin Result := nil; if AStr = '' then Exit; c := @AStr[1]; while c^ <> #0 do begin case c^ of #1..#32: TryAdd; else str := str + c^; end; Inc(c); end; TryAdd; end; function StringsToStringDynArray(const AStr: string): TStringDynArray; overload; var str: string; c: PChar; procedure TryAdd; begin if str = '' then Exit; SetLength(Result, Length(Result) + 1); Result[High(Result)] := str; str := ''; end; begin Result := nil; if AStr = '' then Exit; c := @AStr[1]; while c^ <> #0 do begin case c^ of #1..#32: TryAdd; else str := str + c^; end; Inc(c); end; TryAdd; end; end.
{ Unit criada por Vicente Barros Leonel Ultima Revisão - 30/04/2007 Por Vicente Barros Leonel } unit UCConsts; interface const // new consts version 2 a 5 ========================================= // Form Select Controls (design-time) Const_Contr_TitleLabel = 'Team of Components of the Form. :'; Const_Contr_GroupLabel = 'Group:'; Const_Contr_CompDispLabel = 'Available components:'; Const_Contr_CompSelLabel = 'Selected components:'; Const_Contr_BtOK = '&OK'; Const_Contr_BTCancel = '&Cancel'; Const_Contr_DescCol = 'Description'; Const_Contr_BtSellAllHint = 'Select All'; Const_Contr_BtSelHint = 'Select'; Const_Contr_BtUnSelHint = 'Unselect'; Const_Contr_BtUnSelAllHint = 'Unselect All'; //=================================================================== // group property Settins.AppMsgsForm Const_Msgs_BtNew = '&New Message'; Const_Msgs_BtReplay = '&Replay'; Const_Msgs_BtForward = 'F&orward'; Const_Msgs_BtDelete = '&Delete'; Const_Msgs_BtClose = '&Close'; Const_Msgs_WindowCaption = 'Messages of the System'; Const_Msgs_ColFrom = 'From'; Const_Msgs_ColSubject = 'Subject'; Const_Msgs_ColDate = 'Date'; Const_Msgs_PromptDelete = 'It confirms exclusion of the selected messages?'; Const_Msgs_PromptDelete_WindowCaption = 'Delete messages'; Const_Msgs_NoMessagesSelected = 'No Messages selected'; Const_Msgs_NoMessagesSelected_WindowCaption = 'Information'; // group property Settins.AppMsgsRec Const_MsgRec_BtClose = '&Close'; Const_MsgRec_WindowCaption = 'Message'; Const_MsgRec_Title = 'Received message'; Const_MsgRec_LabelFrom = 'From:'; Const_MsgRec_LabelDate = 'Date'; Const_MsgRec_LabelSubject = 'Subject'; Const_MsgRec_LabelMessage = 'Message'; // group property Settins.AppMsgsSend Const_MsgSend_BtSend = '&Send'; Const_MsgSend_BtCancel = '&Cancel'; Const_MsgSend_WindowCaption = 'Message'; Const_MsgSend_Title = 'Send New Message'; Const_MsgSend_GroupTo = 'To'; Const_MsgSend_RadioUser = 'User:'; Const_MsgSend_RadioAll = 'All'; Const_MsgSend_GroupMessage = 'Message'; Const_MsgSend_LabelSubject = 'Subject'; Const_MsgSend_LabelMessageText = 'Message text'; // Run errors MsgExceptConnection = 'Done not informed the Connection, Transaction or Database component %s'; MsgExceptTransaction = 'Done not informed the Transaction component %s'; MsgExceptDatabase = 'Done not informed the Database do component %s'; MsgExceptPropriedade = 'Inform the property %s'; MsgExceptUserMngMenu = 'Inform in the property UsersForm.MenuItem or UsersForm.Action the item responsible for the users control'; MsgExceptUserProfile = 'Inform in the property UsersProfile.MenuItem or UsersProfile.Action the Item responsible for the control of users Profile '; MsgExceptChagePassMenu = 'Inform in the property ChangePasswordForm.MenuItem or .Action the Item that allows to a user to alter his password'; MsgExceptAppID = 'In the property "ApplicationID" inform a name to identify the application in the chart of permissions'; MsgExceptUsersTable = 'In the property "TableUsers" inform the name of the chart that will be created to store the data of the users '; MsgExceptRightsTable = 'In the property "TableRights" inform the name of the chart that will be created to store the permissions of the users '; MsgExceptConnector = 'The property DataConnector not defined!'; // group property Settings.Mensagens Const_Men_AutoLogonError = 'Fault of Car Logon !' + #13 + #10 + 'Inform a valid user and password.'; Const_Men_SenhaDesabitada = 'Retired password of the Login %s'; Const_Men_SenhaAlterada = 'Password altered with success!'; Const_Men_MsgInicial = 'ATTENTION, Inicial Login :' + #13 + #10 + #13 + #10 + 'User: :user' + #13 + #10 + 'Password : :password' + #13 + #10 + #13 + #10 + 'Define the permissions for this user.'; Const_Men_MaxTentativas = '%d Attempts of login invalid. By reasons of segunça the system will be closed.'; Const_Men_LoginInvalido = 'User invalids or password !'; Const_Men_UsuarioExiste = 'The User "%s" is already set up in the system !!'; Const_Men_PasswordExpired = 'Attention, his sign died, favor exchanges it '; //group property Settings.Login Const_Log_BtCancelar = '&Cancel'; Const_Log_BtOK = '&OK'; Const_Log_LabelSenha = 'Password :'; Const_Log_LabelUsuario = 'User :'; Const_Log_WindowCaption = 'Login'; Const_Log_LbEsqueciSenha = 'I forgot the password'; Const_Log_MsgMailSend = 'The password was sent for his email .'; Const_Log_LabelTentativa = 'Attempt : '; Const_Log_LabelTentativas = 'Max of Attempts: '; //group property Settings.Log //new Const_LogC_WindowCaption = 'Security'; Const_LogC_LabelDescricao = 'Log of system'; Const_LogC_LabelUsuario = 'User :'; Const_LogC_LabelData = 'Date :'; Const_LogC_LabelNivel = 'Least level:'; Const_LogC_ColunaAppID = 'AppID'; Const_LogC_ColunaNivel = 'Level '; Const_LogC_ColunaMensagem = 'Message'; Const_LogC_ColunaUsuario = 'User'; Const_LogC_ColunaData = 'Date'; Const_LogC_BtFiltro = '&Apply Filter'; Const_LogC_BtExcluir = '&Erase Log'; Const_LogC_BtFechar = '&Close'; Const_LogC_ConfirmaExcluir = 'It confirms to exclude all the registers of log selected ?'; Const_LogC_ConfirmaDelete_WindowCaption = 'Delete confirmation'; Const_LogC_Todos = 'All'; Const_LogC_Low = 'Low'; Const_LogC_Normal = 'Normal'; Const_LogC_High = 'High'; Const_LogC_Critic = 'Critic'; Const_LogC_ExcluirEfectuada = 'Deletion of system log done: User = "%s" | Date = %s a %s | Level <= %s'; //group property Settings.CadastroUsuarios Const_Cad_WindowCaption = 'Security'; Const_Cad_LabelDescricao = 'Users register '; Const_Cad_ColunaNome = 'Name'; Const_Cad_ColunaLogin = 'Login'; Const_Cad_ColunaEmail = 'Email'; Const_Cad_BtAdicionar = '&Add'; Const_Cad_BtAlterar = 'A&lter'; Const_Cad_BtExcluir = '&Erase'; Const_Cad_BtPermissoes = 'A&ccesses'; Const_Cad_BtSenha = '&Password'; Const_Cad_BtFechar = '&Close'; Const_Cad_ConfirmaExcluir = 'Confirm erase the user "%s" ?'; Const_Cad_ConfirmaDelete_WindowCaption = 'Delete user'; //added by fduenas //group property Settings.PerfilUsuarios Const_Prof_WindowCaption = 'Security'; Const_Prof_LabelDescricao = 'Users profile '; Const_Prof_ColunaNome = 'Profile'; Const_Prof_BtAdicionar = '&Add'; Const_Prof_BtAlterar = 'A&lter'; Const_Prof_BtExcluir = '&Delete'; Const_Prof_BtPermissoes = 'A&ccesses'; Const_Prof_BtSenha = '&Password'; Const_Prof_BtFechar = '&Close'; Const_Prof_ConfirmaExcluir = 'There are users with the profile "%s". Confirm erase ?'; Const_Prof_ConfirmaDelete_WindowCaption = 'Delete profile'; //added by fduenas //group property Settings.IncAltUsuario Const_Inc_WindowCaption = 'Users register '; Const_Inc_LabelAdicionar = 'Add User'; Const_Inc_LabelAlterar = 'Change User'; Const_Inc_LabelNome = 'Name :'; Const_Inc_LabelLogin = 'Login :'; Const_Inc_LabelEmail = 'Email :'; Const_Inc_LabelPerfil = 'Profile :'; Const_Inc_CheckPrivilegiado = 'Privileged user '; Const_Inc_BtGravar = '&Save'; Const_Inc_BtCancelar = 'Cancel'; Const_Inc_CheckEspira = 'Password do not expired'; Const_Inc_Dia = 'Day'; Const_Inc_ExpiraEm = 'Expired in'; //group property Settings.IncAltPerfil Const_PInc_WindowCaption = 'Profile the Users'; Const_PInc_LabelAdicionar = 'Add Profile'; Const_PInc_LabelAlterar = 'Change Profile '; Const_PInc_LabelNome = 'Description :'; Const_PInc_BtGravar = '&Save'; Const_PInc_BtCancelar = 'Cancel'; //group property Settings.Permissao Const_Perm_WindowCaption = 'Security'; Const_Perm_LabelUsuario = 'Permissions of the User :'; Const_Perm_LabelPerfil = 'Permissions of the Profile :'; Const_Perm_PageMenu = 'Items of the Menu'; Const_Perm_PageActions = 'Actions'; Const_Perm_PageControls = 'Controls'; // by vicente barros leonel Const_Perm_BtLibera = '&Release'; Const_Perm_BtBloqueia = '&Block'; Const_Perm_BtGravar = '&Save'; Const_Perm_BtCancelar = '&Cancel'; //group property Settings.TrocaSenha do begin Const_Troc_WindowCaption = 'Security'; Const_Troc_LabelDescricao = 'Change Password'; Const_Troc_LabelSenhaAtual = 'Password :'; Const_Troc_LabelNovaSenha = 'New Password :'; Const_Troc_LabelConfirma = 'Confirmation :'; Const_Troc_BtGravar = '&Save'; Const_Troc_BtCancelar = 'Cancel'; //group property Settings.Mensagens.ErroTrocaSenha Const_ErrPass_SenhaAtualInvalida = 'Current password does not tally!'; Const_ErrPass_ErroNovaSenha = 'The Field: New Password and Confirmation must be the same.'; Const_ErrPass_NovaIgualAtual = 'New equal password to current password '; Const_ErrPass_SenhaObrigatoria = 'The password is compulsory '; Const_ErrPass_SenhaMinima = 'The password must contain at least %d characters '; Const_ErrPass_SenhaInvalida = 'When to use password was prohibited you obviate !'; Const_ErrPass_ForcaTrocaSenha = 'Compulsory change password'; //group property Settings.DefineSenha Const_DefPass_WindowCaption = 'Define Password of the user : "%s"'; Const_DefPass_LabelSenha = 'Password :'; //Group das tabelas do UC Const_TableUsers_FieldUserID = 'UCIdUser'; Const_TableUsers_FieldUserName = 'UCUserName'; Const_TableUsers_FieldLogin = 'UCLogin'; Const_TableUsers_FieldPassword = 'UCPassword'; Const_TableUsers_FieldEmail = 'UCEmail'; Const_TableUsers_FieldPrivileged = 'UCPrivileged'; Const_TableUsers_FieldTypeRec = 'UCTypeRec'; Const_TableUsers_FieldProfile = 'UCProfile'; Const_TableUsers_FieldKey = 'UCKey'; Const_TableUsers_TableName = 'UCTabUsers'; Const_TableUsers_FieldDateExpired = 'UCPassExpired'; Const_TableUser_FieldUserExpired = 'UCUserExpired'; Const_TableUser_FieldUserDaysSun = 'UCUserDaysSun'; Const_TableRights_FieldUserID = 'UCIdUser'; Const_TableRights_FieldModule = 'UCModule'; Const_TableRights_FieldComponentName = 'UCCompName'; Const_TableRights_FieldFormName = 'UCFormName'; Const_TableRights_FieldKey = 'UCKey'; Const_TableRights_TableName = 'UCTabRights'; Const_TableUsersLogged_FieldLogonID = 'UCIdLogon'; Const_TableUsersLogged_FieldUserID = 'UCIdUser'; Const_TableUsersLogged_FieldApplicationID = 'UCApplicationId'; Const_TableUsersLogged_FieldMachineName = 'UCMachineName'; Const_TableUsersLogged_FieldData = 'UCData'; Const_TableUsersLogged_TableName = 'UCTabUsersLogged'; implementation end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Media, FMX.Objects, FMX.ListBox, FMX.StdCtrls, FMX.Controls.Presentation, IdContext, IdCustomHTTPServer, IdBaseComponent, IdComponent, IdCustomTCPServer, IdHTTPServer, IdSync; type TMainForm = class(TForm) ToolBarMain: TToolBar; butStart: TButton; cmbDevices: TComboBox; imgContainer: TImage; StyleBook: TStyleBook; IdHTTPServer: TIdHTTPServer; butPlay: TButton; procedure FormCreate(Sender: TObject); procedure cmbDevicesChange(Sender: TObject); procedure butStartClick(Sender: TObject); procedure IdHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure butPlayClick(Sender: TObject); private { Private declarations } VideoCamera: TVideoCaptureDevice; procedure SampleBufferSync; procedure SampleBufferReady(Sender: TObject; const ATime: TMediaTime); public { Public declarations } end; type TGetImageStream = class(TIdSync) protected FStream: TStream; procedure DoSynchronize; override; public class procedure GetImage(aStream: TStream); end; var MainForm: TMainForm; implementation {$R *.fmx} {$R *.Macintosh.fmx MACOS} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.iPhone55in.fmx IOS} procedure TMainForm.butStartClick(Sender: TObject); begin if (VideoCamera <> nil) then begin if (VideoCamera.State = TCaptureDeviceState.Stopped) then begin VideoCamera.OnSampleBufferReady := SampleBufferReady; VideoCamera.Quality := TVideoCaptureQuality.LowQuality; VideoCamera.CaptureSettingPriority := TVideoCaptureSettingPriority.FrameRate; VideoCamera.StartCapture; butPlay.Enabled := True; end else begin VideoCamera.StopCapture; butPlay.Enabled := False; IdHTTPServer.Active := False; end; end else raise Exception.Create('Dispositivo de captura de vídeo não disponível!'); end; procedure TMainForm.butPlayClick(Sender: TObject); begin IdHTTPServer.DefaultPort := 8080; IdHTTPServer.Active := not IdHTTPServer.Active; end; procedure TMainForm.cmbDevicesChange(Sender: TObject); begin VideoCamera := TVideoCaptureDevice (TCaptureDeviceManager.Current.GetDevicesByName(cmbDevices.Selected.Text)); if (VideoCamera <> nil) then begin butStart.Enabled := True; end; end; procedure TMainForm.FormCreate(Sender: TObject); {$IF DEFINED(MSWINDOWS) OR DEFINED(MACOS)} var DeviceList: TCaptureDeviceList; i: integer; {$ENDIF} begin {$IF DEFINED(MSWINDOWS) OR DEFINED(MACOS)} DeviceList := TCaptureDeviceManager.Current.GetDevicesByMediaType (TMediaType.Video); for i := 0 to DeviceList.Count - 1 do begin cmbDevices.Items.Add(DeviceList[i].Name); end; cmbDevices.ItemIndex := 0; {$ELSE} VideoCamera := TCaptureDeviceManager.Current.DefaultVideoCaptureDevice; butStart.Enabled := True; {$ENDIF} end; procedure TMainForm.SampleBufferReady(Sender: TObject; const ATime: TMediaTime); begin TThread.Queue(TThread.CurrentThread, SampleBufferSync); end; procedure TMainForm.SampleBufferSync; begin VideoCamera.SampleBufferToBitmap(imgContainer.Bitmap, True); end; procedure TMainForm.IdHTTPServerCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var LStream: TMemoryStream; begin LStream := TMemoryStream.Create; try TGetImageStream.GetImage(LStream); LStream.Position := 0; except LStream.Free; raise; end; AResponseInfo.ResponseNo := 200; AResponseInfo.ContentType := 'image/bmp'; AResponseInfo.ContentStream := LStream; end; { TGetImageStream } procedure TGetImageStream.DoSynchronize; begin inherited; MainForm.imgContainer.Bitmap.SaveToStream(FStream); end; class procedure TGetImageStream.GetImage(aStream: TStream); begin with Create do try FStream := aStream; Synchronize; finally Free; end; end; end.
(* WLA: HDO, 2016-12-06 --- Wish list analyzer for the Christkind. ==========================================================*) PROGRAM WLA; (*$IFDEF WINDOWS*) USES WinCrt; (*$ENDIF*) TYPE WishNodePtr = ^WishNode; WishNode = RECORD next: WishNodePtr; name: STRING; item: STRING; END; (*RECORD*) WishListPtr = WishNodePtr; OrderNodePtr = ^OrderNode; OrderNode= RECORD next: OrderNodePtr; item: STRING; n: INTEGER; END; (*RECORD*) OrderList = OrderNode; ItemNodePrt = ^ItemNode; ItemNode = RECORD next : ItemNodePrt; item : STRING; END; DelivNodePtr = ^DelivNode; DelivNode = RECORD next: DelivNodePtr; name: STRING; items: ItemNodePrt; END; (*RECORD*) DelivListPtr = DelivNodePtr; (*#########*) (* Wishes *) (*#########*) (* New WishNode Function *) FUNCTION newWishNode(line : STRING): WishListPtr; VAR node : WishNodePtr; BEGIN New(node); node^.name := Copy(line,1,pos(':',line)-1); node^.item := Copy(line,pos(' ',line)+1,length(line)); node^.next := NIL; newWishNode := node; END; (* Append to a Wish List*) PROCEDURE appendToWishList(VAR list : WishNodePtr; node : WishNodePtr); VAR wishList : WishNodePtr; BEGIN IF list = NIL THEN list := node ELSE BEGIN wishList := list; WHILE (wishList^.next <> NIL) DO wishList := wishList^.next; wishList^.next := node; END; END; (*#########*) (* ORDER *) (*#########*) (* New Order Node*) FUNCTION newOrderNode(item : STRING; anz : INTEGER): OrderNodePtr; VAR node : OrderNodePtr; BEGIN New(node); node^.item := item; node^.n := anz; node^.next := NIL; NewOrderNode := node; END; (* Append to an Order List *) PROCEDURE appendToOrder(VAR list : OrderNodePtr; node : OrderNodePtr); VAR orderList : OrderNodePtr; BEGIN IF list = NIL THEN list := node ELSE BEGIN orderList := list; WHILE (orderList^.next <> NIL) DO orderList := orderList^.next; orderList^.next := node; END; END; (* Increase the number of items per order *) PROCEDURE increaseOrder(VAR list : OrderNodePtr; s_item : STRING); VAR temp_orderlist : OrderNodePtr; BEGIN IF list = NIL THEN appendToOrder(list, newOrderNode(s_item, 1)) ELSE BEGIN temp_orderlist := list; WHILE(temp_orderlist <> NIL) DO BEGIN IF(temp_orderlist^.item = s_item) THEN BEGIN temp_orderlist^.n := temp_orderlist^.n + 1; exit; END; temp_orderlist := temp_orderlist^.next; END; appendToOrder(list, newOrderNode(s_item, 1)); END; END; (* Generate Order List from Wish List*) FUNCTION orderListOf(wishlist : WishNodePtr): OrderNodePtr; VAR result : OrderNodePtr; BEGIN result := NIL; WHILE wishlist <> NIL DO BEGIN increaseOrder(result, wishlist^.item); wishlist := wishlist^.next; END; orderListOf := result; END; (*#########*) (* Items *) (*#########*) (* New Item Node *) FUNCTION newItemNode(item : STRING): ItemNodePrt; VAR node : ItemNodePrt; BEGIN New(node); node^.item := item; node^.next := NIL; newItemNode := node; END; (* Append To Item List *) PROCEDURE appendItem(VAR list : ItemNodePrt; element : ItemNodePrt); VAR tmp : ItemNodePrt; BEGIN IF list = NIL THEN list := element ELSE BEGIN tmp := list; WHILE (tmp^.next <> NIL) DO tmp := tmp^.next; tmp^.next := element; END; END; (*############*) (* Delivery *) (*############*) (* Get New DeliveryList *) FUNCTION newDelivNode(name,item : STRING): DelivNodePtr; VAR node : DelivNodePtr; BEGIN New(node); node^.name := name; node^.items := NewItemNode(item); node^.next := NIL; NewDelivNode := node; END; (* Append to a Deliverylist *) PROCEDURE appendToDelivery(VAR list : DelivNodePtr; element : DelivNodePtr); VAR tmp : DelivNodePtr; BEGIN IF list = NIL THEN list := element ELSE BEGIN tmp := list; WHILE (tmp^.next <> NIL) DO tmp := tmp^.next; tmp^.next := element; END; END; (* Append Item to Kids Item List *) PROCEDURE appendItemKid(VAR list : DelivNodePtr; name, item : STRING); VAR tmp : DelivNodePtr; BEGIN IF list = NIL THEN list := NewDelivNode(name, item) ELSE BEGIN tmp := list; WHILE tmp <> NIL DO BEGIN IF tmp^.name = name THEN BEGIN AppendItem(tmp^.items, NewItemNode(item)); exit; END; tmp := tmp^.next; END; appendToDelivery(list, NewDelivNode(name, item)); END; END; (* Genereate Delivery based on wish list *) FUNCTION DeliveryListOf(wishlist : WishNodePtr): DelivNodePtr; VAR result : DelivNodePtr; BEGIN result := NIL; WHILE wishlist <> NIL DO BEGIN AppendItemKid(result, wishlist^.name, wishlist^.item); wishlist := wishlist^.next; END; DeliveryListOf := result; END; (*#######################*) (* Printing to Console *) (*#######################*) (* Write Wish List to Console *) PROCEDURE writeWishList(wishList : WishNodePtr); BEGIN WriteLn(chr(205),chr(205),' Wish list ',chr(205),chr(205)); WHILE wishList <> NIL DO BEGIN Writeln(wishList^.name, ' : ' , wishList^.item); wishList := wishList^.next; END; WriteLn(chr(205),chr(205),' End Wish list ',chr(205),chr(205)); END; (* Write OrderList to Console *) PROCEDURE writeOrderList(list : OrderNodePtr); BEGIN WriteLn(chr(205),chr(205),' Order list ',chr(205),chr(205)); WHILE list <> NIL DO BEGIN Writeln(list^.item, ' : ' , list^.n); list := list^.next; END; WriteLn(chr(205),chr(205),' End Order list ',chr(205),chr(205)); END; (* Write Delivery List *) PROCEDURE writeDelivList(list : DelivListPtr); VAR citem: ItemNodePrt; BEGIN WriteLn(chr(205),chr(205),' Delv list ',chr(205),chr(205)); WHILE list <> NIL DO BEGIN Write(list^.name, ' : '); citem := list^.items; WHILE citem <> NIL DO BEGIN write(citem^.item, ' '); citem := citem^.next; END; writeln(); list := list^.next; END; WriteLn(chr(205),chr(205),' End Delv list ',chr(205),chr(205)); END; VAR wishesFile: TEXT; s: STRING; wish_list : WishNodePtr; order_list : OrderNodePtr; delv_list : DelivNodePtr; BEGIN (*WLA*) WriteLn(chr(205),chr(205),chr(185),' Lists for Xmas ',chr(204),chr(205),chr(205)); WriteLn; (* Read everyline from txt, appendtowishlist and close file *) Assign(wishesFile, 'Wishes.txt'); Reset(wishesFile); REPEAT ReadLn(wishesFile, s); appendToWishList(wish_list,newWishNode(s)); UNTIL Eof(wishesFile); Close(wishesFile); (* Write wishlist to console *) writeWishList(wish_list); WriteLn; (* Generating & Writing OrderList to Console *) order_list := orderListOf(wish_list); writeOrderList(order_list); WriteLn; (* Generating & Writing DeliveryList to Console *) delv_list := DeliveryListOf(wish_list); writeDelivList(delv_list); END. (*WLA*)
unit uEmailCheckerRes; // EMS Resource Module interface uses System.SysUtils, System.Classes, System.JSON, EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes; type [ResourceName('EmailChecker')] TEmailCheckerResource1 = class(TDataModule) published procedure Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); [ResourceSuffix('{item}')] procedure GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); end; implementation {%CLASSGROUP 'System.Classes.TPersistent'} uses RegExpressionsUtil; {$R *.dfm} procedure TEmailCheckerResource1.Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); begin // Sample code AResponse.Body.SetValue(TJSONString.Create('EmailChecker'), True) end; procedure TEmailCheckerResource1.GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); var LItem: string; begin LItem := ARequest.Params.Values['item']; if TRegularExpressionEngine.IsValidEmail(LItem) then AResponse.Body.SetValue(TJSONTrue.Create, True) else AResponse.Body.SetValue(TJSONFalse.Create, True); end; procedure Register; begin RegisterResource(TypeInfo(TEmailCheckerResource1)); end; initialization Register; end.
{================================================================================ Copyright (C) 1997-2001 Mills Enterprise Unit : rmDiffMap Purpose : This is a map component primarily used in showing where the differences are with in the mapping of the rmDiff Components. Date : 04-24-2000 Author : Ryan J. Mills Version : 1.92 Notes : This component originally came to me from Bernie Caudrey. I've only modified the original source to work with my rmDiff components. I would like to go back and rewrite the drawing and mapping algorithms because I think they are unnecessarily complex. It also doesn't use any resources where it should. ================================================================================} unit rmDiffMap; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TAByte = array of BYTE; pAByte = ^TAByte; TMapClickEvent = procedure(Sender:TObject; IndicatorPos : integer) of object; TrmDiffMap = class(TCustomControl) private { Private declarations } FColorDeleted : TColor; FColorInserted : TColor; FColorModified : TColor; FShowIndicator : Boolean; FIndicatorPos : integer; FRows : integer; FIndicator : TBitmap; FData : TAByte; FOnMapClick : TMapClickEvent; procedure DrawIndicator; procedure SetIndicatorPos(Value : integer); function MapHeight : integer; protected { Protected declarations } procedure Paint; override; public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure SetData(Value : TAByte; Size : integer); procedure MouseDown(Button : TMouseButton; Shift : TShiftState; X, Y : Integer); override; property Data : TAByte read FData; published { Published declarations } property Color; property Caption; property Align; property BevelInner; property BevelOuter; property BevelWidth; property ColorDeleted : TColor read FColorDeleted write FColorDeleted; property ColorInserted : TColor read FColorInserted write FColorInserted; property ColorModified : TColor read FColorModified write FColorModified; property ShowIndicator : Boolean read FShowIndicator write FShowIndicator; property IndicatorPos : integer read FIndicatorPos write SetIndicatorPos; property IndicatorRange : integer read FRows; property OnMapClick : TMapClickEvent read FOnMapClick write FOnMapClick; end; implementation const TOP_MARGIN = 5; BOTTOM_MARGIN = 5; INDICATOR_WIDTH = 4; // These constants are reproduced here from IntfDifferenceEngine.pas RECORD_SAME = 0; RECORD_DELETED = 1; RECORD_INSERTED = 2; RECORD_MODIFIED = 3; constructor TrmDiffMap.Create(AOwner : TComponent); begin inherited; FShowIndicator := True; FColorDeleted := clRed; FColorInserted := clLime; FColorModified := clYellow; Caption := ''; FData := nil; FRows := 0; IndicatorPos := 0; FIndicator := TBitmap.Create; FIndicator.Width := 4; FIndicator.Height := 6; FIndicator.Canvas.Pixels[0,0] := clBlack; FIndicator.Canvas.Pixels[0,1] := clBlack; FIndicator.Canvas.Pixels[0,2] := clBlack; FIndicator.Canvas.Pixels[0,3] := clBlack; FIndicator.Canvas.Pixels[0,4] := clBlack; FIndicator.Canvas.Pixels[1,1] := clBlack; FIndicator.Canvas.Pixels[1,2] := clBlack; FIndicator.Canvas.Pixels[1,3] := clBlack; FIndicator.Canvas.Pixels[2,2] := clBlack; FIndicator.Canvas.Pixels[1,0] := clFuchsia; FIndicator.Canvas.Pixels[2,0] := clFuchsia; FIndicator.Canvas.Pixels[2,1] := clFuchsia; FIndicator.Canvas.Pixels[3,2] := clFuchsia; FIndicator.Canvas.Pixels[1,4] := clFuchsia; FIndicator.Canvas.Pixels[2,4] := clFuchsia; FIndicator.TransparentMode := tmFixed; FIndicator.TransparentColor := clFuchsia; FIndicator.Transparent := True; fIndicator.SaveToFile('c:\indicator.bmp'); end; destructor TrmDiffMap.Destroy; begin if FData <> nil then begin FData := nil; end; FIndicator.Free; inherited; end; procedure TrmDiffMap.SetData(Value : TAByte; Size : integer); begin if FData <> nil then begin FData := nil; end; FData := Value; if FData <> nil then begin FRows := Size; end else begin FRows := 0; end; end; procedure TrmDiffMap.SetIndicatorPos(Value : integer); begin FIndicatorPos := Value; Refresh; end; procedure TrmDiffMap.Paint; var i : Integer; j : Integer; NrOfDataRows : Integer; Ht : Integer; Ct : Integer; CurrIndex : Integer; PixelPos : Integer; PixelHt : Double; // amount of pixel height for each row - could be a rather small number PixelFrac : Double; // Faction part of pixel - left over from previous PixelPrevHt : Double; // logical height of previous mapped pixel (eg. .92) NrOfPixelRows : Double; // Number of rows that the current pixel is to represent. ExtraPixel : Double; // Left over pixel from when calculating number of rows for the next pixel. // eg. 1/.3 = 3 rows, .1 remaining, next 1.1/.3 = 3 rows, .2 remain, next 1.2/.3 = 4 rows. DrawIt : Boolean; // Drawing flag for each column RowModified : Boolean; RowDeleted : Boolean; RowInserted : Boolean; ExitLoop : Boolean; // loop control // Draws the line between two points on the horizonatal line of i. procedure DrawLine(X1, X2 : integer); var k : integer; begin // What colour? Black or Background? if DrawIt then begin if RowModified then begin Canvas.Pen.Color := ColorModified; end else begin if RowInserted then begin Canvas.Pen.Color := ColorInserted; end else begin if RowDeleted then begin Canvas.Pen.Color := ColorDeleted; end; end; end; end else begin Canvas.Pen.Color := Color; end; // Draw the pixels for the map here for k := 0 to Round(NrOfPixelRows) - 1 do begin Canvas.MoveTo(X1, PixelPos + k); Canvas.LineTo(X2, PixelPos + k); end; end; begin inherited; if csDesigning in ComponentState then begin exit; end; Ht := MapHeight; Ct := FRows; if Ct < 1 then begin Ct := 1; end; PixelHt := Ht / Ct; CurrIndex := 1; NrOfPixelRows := 0.0; PixelPrevHt := 0.0; PixelPos := 5; i := 1; ExtraPixel := 0.0; J := CurrIndex; while J < Ct do begin NrOfDataRows := 0; PixelPrevHt := PixelPrevHt - NrOfPixelRows; // remainder from prevous pixel row (+ or -) PixelFrac := frac(PixelPrevHt); // We want just the fractional part! // Calculate how high the pixel line is to be if PixelHt < 1.0 then begin NrOfPixelRows := 1.0; // Each Pixel line represents one or more rows of data end else begin NrOfPixelRows := Int(PixelHt + ExtraPixel); // We have several pixel lines for each row of data. ExtraPixel := frac(PixelHt + ExtraPixel);// save frac part for next time end; // Calculate the nr of data rows to be represented by the Pixel Line about to be drawn. ExitLoop := False; repeat // the '.../2.0' checks if half a Pixel Ht will fit, else leave remainder for next row. if (PixelFrac + PixelHt <= NrOfPixelRows) or (PixelFrac + PixelHt / 2.0 <= NrOfPixelRows) then begin PixelFrac := PixelFrac + PixelHt; inc(NrOfDataRows); end else begin ExitLoop := True; end; until (PixelFrac >= NrOfPixelRows) or (ExitLoop); // go through each data row, check if a file has been modified. // if any file has been modified then we add to the Mapping. if NrOfDataRows > 0 then begin DrawIt := False; end; RowModified := False; RowInserted := False; RowDeleted := False; for j := j to j + NrOfDataRows - 1 do begin if j < ct then begin case Data[j] of RECORD_MODIFIED : begin DrawIt := True; RowModified := True; end; RECORD_INSERTED : begin DrawIt := True; RowInserted := True; end; RECORD_DELETED : begin DrawIt := True; RowDeleted := True; end; end; end else begin i := i; end; end; // Mapping is drawn here if ShowIndicator then begin DrawLine(INDICATOR_WIDTH, Width - INDICATOR_WIDTH); end else begin DrawLine(0, Width); end; inc(PixelPos, Trunc(NrOfPixelRows)); // the pixel pos on the map. PixelPrevHt := int(PixelPrevHt) + PixelFrac; end; if ShowIndicator then begin DrawIndicator; end; end; procedure TrmDiffMap.DrawIndicator; var Y : integer; begin Canvas.Pen.Color := clBlack; if FRows <> 0 then begin Y := TOP_MARGIN + Trunc((IndicatorPos / FRows) * MapHeight); Canvas.Draw(0, Y - (FIndicator.Height div 2), FIndicator); end; end; function TrmDiffMap.MapHeight : integer; begin Result := Height - TOP_MARGIN - BOTTOM_MARGIN; end; procedure TrmDiffMap.MouseDown(Button : TMouseButton; Shift : TShiftState; X, Y : Integer); var NewRow : Integer; NewTopRow : Integer; PixelHt : Double; begin inherited; if Assigned(OnMapClick) then begin PixelHt := MapHeight / IndicatorRange; // This is how much of a pixel (or how many pixels), each row represents. // (the pixel clicked) + Half the Pixel Height + 1.0 / the pixel height // eg. Of 1000 rows, in the pixel area height of 500, then pixelHt = .5 (500/1000) // Therefore, if pixel 100 is clicked we get - (100 + .25 + 1) / .5 = 51 // Y-5, we subtract 5 as we start 5 pixels from the top of lblQuickPickArea. NewRow := Round(((Y - TOP_MARGIN) * 1.0 + PixelHt / 2.0 + 1.0) / PixelHt); if NewRow > IndicatorRange - 1 then begin NewRow := IndicatorRange - 1 end else begin if NewRow < 1 then begin NewRow := 1; end; end; OnMapClick(self, NewRow); end; end; end.
unit LrTextPainter; interface uses Windows, Classes, Graphics, LrGraphics; type TLrTextPainter = class(TPersistent) private FCanvas: TCanvas; FHAlign: TLrHAlign; FTransparent: Boolean; FVAlign: TLrVAlign; FWordWrap: Boolean; FOnChange: TNotifyEvent; protected function GetDC: HDC; function GetFlags: Integer; procedure AlignRect(const inText: string; var ioR: TRect); procedure Change; procedure SetHAlign(const Value: TLrHAlign); procedure SetTransparent(const Value: Boolean); procedure SetVAlign(const Value: TLrVAlign); procedure SetWordWrap(const Value: Boolean); public function Height(const inText: string; inR: TRect): Integer; function Width(const inText: string): Integer; procedure PaintText(const inText: string; inR: TRect; inCanvas: TCanvas = nil); public property Canvas: TCanvas read FCanvas write FCanvas; property Flags: Integer read GetFlags; property DC: HDC read GetDC; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property HAlign: TLrHAlign read FHAlign write SetHAlign; property Transparent: Boolean read FTransparent write SetTransparent; property VAlign: TLrVAlign read FVAlign write SetVAlign; property WordWrap: Boolean read FWordWrap write SetWordWrap; end; function TextPainter: TLrTextPainter; implementation uses LrVclUtils; const cLrAlignFlags: array[TLrHAlign] of Integer = ( DT_LEFT, DT_LEFT, DT_CENTER, DT_RIGHT ); cLrWrapFlags: array[Boolean] of Integer = ( 0, DT_WORDBREAK ); cLrTxFlags: array[Boolean] of Integer = ( Windows.OPAQUE, Windows.TRANSPARENT ); var SingletonTextPainter: TLrTextPainter; function TextPainter: TLrTextPainter; begin if SingletonTextPainter = nil then SingletonTextPainter := TLrTextPainter.Create; Result := SingletonTextPainter; end; { TLrTextPainter } function TLrTextPainter.GetDC: HDC; begin Result := Canvas.Handle; end; function TLrTextPainter.GetFlags: Integer; begin Result := cLrAlignFlags[HAlign] + cLrWrapFlags[WordWrap] + DT_NOPREFIX; end; function TLrTextPainter.Height(const inText: string; inR: TRect): Integer; begin if Canvas <> nil then Result := DrawText(DC, PChar(inText), Length(inText), inR, Flags + DT_CALCRECT) else Result := 0; end; function TLrTextPainter.Width(const inText: string): Integer; begin if Canvas <> nil then Result := Canvas.TextWidth(inText) else Result := 0; end; procedure TLrTextPainter.AlignRect(const inText: string; var ioR: TRect); var y: Integer; begin y := (ioR.Bottom - ioR.Top) - Height(inText, ioR); case VAlign of vaBottom: ; vaMiddle: y := y div 2; else y := 0; end; Inc(ioR.Top, LrMax(0, y)); end; procedure TLrTextPainter.PaintText(const inText: string; inR: TRect; inCanvas: TCanvas); begin if inCanvas <> nil then Canvas := inCanvas; if Canvas <> nil then begin AlignRect(inText, inR); SetBkMode(DC, cLrtxFlags[Transparent]); DrawText(DC, PChar(inText), Length(inText), inR, Flags); end; end; procedure TLrTextPainter.Change; begin if Assigned(OnChange) then OnChange(Self); end; procedure TLrTextPainter.SetHAlign(const Value: TLrHAlign); begin FHAlign := Value; Change; end; procedure TLrTextPainter.SetTransparent(const Value: Boolean); begin FTransparent := Value; Change; end; procedure TLrTextPainter.SetVAlign(const Value: TLrVAlign); begin FVAlign := Value; Change; end; procedure TLrTextPainter.SetWordWrap(const Value: Boolean); begin FWordWrap := Value; Change; end; end.
unit ufrmCostCenter; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterBrowse, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, cxClasses, ufraFooter4Button, Vcl.StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, DBClient, ufrmDialogCostCenter, dxBarBuiltInMenu, cxPC; type TfrmCostCenter = class(TfrmMasterBrowse) procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); private FCDS: TClientDataSet; { Private declarations } protected procedure RefreshData; override; public { Public declarations } end; var frmCostCenter: TfrmCostCenter; implementation uses System.DateUtils, uDMClient,uDBUtils, uDXUtils; {$R *.dfm} procedure TfrmCostCenter.actAddExecute(Sender: TObject); begin inherited; frmDialogCostCenter := TfrmDialogCostCenter.Create(nil); try frmDialogCostCenter.LoadData('00000000-0000-0000-0000-000000000000'); frmDialogCostCenter.ShowModal; if frmDialogCostCenter.ModalResult = mrOk then actRefreshExecute(Sender); finally frmDialogCostCenter.Free; end; end; procedure TfrmCostCenter.actEditExecute(Sender: TObject); begin inherited; frmDialogCostCenter := TfrmDialogCostCenter.Create(nil); try frmDialogCostCenter.LoadData(FCDS.FieldByName('COST_CENTER_ID').AsString); frmDialogCostCenter.ShowModal; if frmDialogCostCenter.ModalResult =mrOk then actRefreshExecute(Sender); finally frmDialogCostCenter.Free; end; end; procedure TfrmCostCenter.RefreshData; begin if Assigned(FCDS) then FreeAndNil(FCDS); FCDS := TDBUtils.DSToCDS(DMClient.DSProviderClient.CostCenter_GetDSLookup(),Self ); cxGridView.LoadFromCDS(FCDS); cxGridView.SetVisibleColumns(['COST_CENTER_ID'],False); end; end.
{* 멀티 스레드에서 사용 되는 변수가 있을 경우 사용하기 위해서 임계영역과 세트로 작성돤 데이터 래핑 클래스이다. 단 번에 참조하지 않고 참조되는 동안 프로세스가 진행되는 경우, 멀티 스레드 상에서 경합을 피하기 위해서 사용한다. } unit SyncValues; interface uses Classes, SysUtils, SyncObjs; type TSyncValue = class private FCS : TCriticalSection; public constructor Create; virtual; destructor Destroy; override; procedure Lock; procedure Unlock; end; TSyncInteger = class (TSyncValue) private FValue: integer; public procedure SetValue(AValue:integer); public property Value : integer read FValue write FValue; end; TSyncInt64 = class (TSyncValue) private FValue: int64; public function GetValue:int64; procedure SetValue(AValue:int64); public property Value : int64 read FValue write FValue; end; TSyncString = class (TSyncValue) private FValue: string; public function GetValue:string; procedure SetValue(AValue:string); public property Value : string read FValue write FValue; end; TSyncShortString = class (TSyncValue) private FValue: ShortString; public function GetValue:ShortString; procedure SetValue(AValue:ShortString); public property Value : ShortString read FValue write FValue; end; TSyncBoolean = class (TSyncValue) private FValue: boolean; public procedure SetValue(AValue:boolean); public property Value : boolean read FValue write FValue; end; TSyncSize = class (TSyncValue) private FX: integer; FY: integer; public procedure GetValue(var AX,AY:integer); procedure SetValue(AX,AY:integer); public property X : integer read FX write FX; property Y : integer read FY write FY; end; TSyncStringList = class (TSyncValue) private FStringList : TStringList; public constructor Create; override; destructor Destroy; override; public property StringList : TStringList read FStringList; end; implementation { TSyncValue } constructor TSyncValue.Create; begin inherited; FCS := TCriticalSection.Create; end; destructor TSyncValue.Destroy; begin FCS.Free; inherited; end; procedure TSyncValue.Lock; begin FCS.Acquire; end; procedure TSyncValue.Unlock; begin FCS.Release; end; { TSyncSize } procedure TSyncSize.GetValue(var AX, AY: integer); begin Lock; try AX := FX; AY := FY; finally Unlock; end; end; procedure TSyncSize.SetValue(AX, AY: integer); begin Lock; try FX := AX; FY := AY; finally Unlock; end; end; { TSyncInteger } procedure TSyncInteger.SetValue(AValue: integer); begin Lock; try FValue := AValue; finally Unlock; end; end; { TSyncInt64 } function TSyncInt64.GetValue: int64; begin Lock; try Result := FValue; finally Unlock; end; end; procedure TSyncInt64.SetValue(AValue: int64); begin Lock; try FValue := AValue; finally Unlock; end; end; { TSyncString } function TSyncString.GetValue: string; begin Lock; try Result := FValue; finally Unlock; end; end; procedure TSyncString.SetValue(AValue: string); begin Lock; try FValue := AValue; finally Unlock; end; end; { TSyncShortString } function TSyncShortString.GetValue: ShortString; begin Lock; try Result := FValue; finally Unlock; end; end; procedure TSyncShortString.SetValue(AValue: ShortString); begin Lock; try FValue := AValue; finally Unlock; end; end; { TSyncBoolean } procedure TSyncBoolean.SetValue(AValue: boolean); begin Lock; try FValue := AValue; finally Unlock; end; end; { TSyncStringList } constructor TSyncStringList.Create; begin inherited; FStringList := TStringList.Create; end; destructor TSyncStringList.Destroy; begin FreeAndNil(FStringList); inherited; end; end.
program fre_resourcetest; {$mode objfpc}{$H+} uses {$IFDEF UNIX} BaseUnix, {$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp { you can add units after this }; type { TFREResourcetestApplication } TFREResourcetestApplication = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; procedure TestMemory (const blocksize:integer=1024); procedure TestFileHandles; procedure TestProcessFork; end; { TMyApplication } procedure TFREResourcetestApplication.DoRun; var ErrorMsg: String; s : string; begin // quick check parameters ErrorMsg:=CheckOptions('hfpm:',['help','file','process','memory']); if ErrorMsg<>'' then begin Writeln('Invalid option: ',Errormsg); Terminate; Exit; end; // parse parameters if HasOption('h','help') then begin WriteHelp; Terminate; Exit; end; if HasOption('m','memory') then begin s:=GetOptionValue('m','memory'); TestMemory(strtoint(s)); Terminate; Exit; end; if HasOption('f','file') then begin TestFileHandles; Terminate; Exit; end; if HasOption('p','process') then begin TestProcessFork; Terminate; Exit; end; { add your program here } // stop program loop Terminate; end; constructor TFREResourcetestApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TFREResourcetestApplication.Destroy; begin inherited Destroy; end; procedure TFREResourcetestApplication.WriteHelp; begin { add your help code here } writeln('Usage: ',ExeName); writeln(' OPTIONS'); writeln(' -h | --help : print this help'); writeln(' -m <size> | --memory <size> : getmem allocation in <size> blocks'); writeln(' -f | --file : file handles'); writeln(' -p | --process : process fork'); end; procedure TFREResourcetestApplication.TestMemory(const blocksize: integer); var total_alloc : QWord; success_getmems : QWord; p : pointer; begin total_alloc := 0; success_getmems := 0; while true do begin try p:=GetMem(blocksize); if p=nil then begin writeln('GetMem resultet nil'); writeln('Total Allocated:',total_alloc,' Successfull Getmem Calls:',success_getmems); end else begin inc(total_alloc,blocksize); inc(success_getmems); if (success_getmems mod 1000)=0 then writeln('Total Allocated:',total_alloc,' Successfull Getmem Calls:',success_getmems); end; except on E:Exception do begin writeln('EXCEPTION:',E.Message); sleep(100); end;end; end; end; procedure TFREResourcetestApplication.TestFileHandles; var total_fh : QWord; sl : TStringlist; begin sl := TstringList.Create; try sl.Add('TEST'); sl.SaveToFile('testfile'); finally sl.Free; end; while true do begin if FileOpen('testfile',fmOpenRead+fmShareDenyNone)=-1 then begin writeln('Filehandle -1'); writeln('Total fh:',total_fh); end else begin inc(total_fh); if (total_fh mod 1000)=0 then writeln('Total fh:',total_fh); end; end; end; procedure TFREResourcetestApplication.TestProcessFork; begin end; var Application: TFREResourcetestApplication; begin Application:=TFREResourcetestApplication.Create(nil); Application.Title:='Resourcetest'; Application.Run; Application.Free; end.
unit ibSHDDLGrantorEditors; interface uses SysUtils, Classes, DesignIntf, TypInfo, SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors; type // -> Property Editors TibSHDDLGrantorPropEditor = class(TibBTPropertyEditor) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; procedure Edit; override; end; IibSHDDLGrantorPrivilegesForPropEditor = interface ['{13851CEB-3890-43A2-9AA5-92A4D7F6455D}'] end; IibSHDDLGrantorGrantsOnPropEditor = interface ['{CE03EE87-4D51-42EB-9B91-FDC1BFC76F79}'] end; IibSHDDLGrantorDisplayPropEditor = interface ['{E12D36F9-66FF-40E1-9B7F-8E35677CBB9B}'] end; TibSHDDLGrantorPrivilegesForPropEditor = class(TibSHDDLGrantorPropEditor, IibSHDDLGrantorPrivilegesForPropEditor); TibSHDDLGrantorGrantsOnPropEditor = class(TibSHDDLGrantorPropEditor, IibSHDDLGrantorGrantsOnPropEditor); TibSHDDLGrantorDisplayPropEditor = class(TibSHDDLGrantorPropEditor, IibSHDDLGrantorDisplayPropEditor); implementation uses ibSHConsts, ibSHValues; { TibSHDDLGrantorPropEditor } function TibSHDDLGrantorPropEditor.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes; if Supports(Self, IibSHDDLGrantorPrivilegesForPropEditor) then Result := [paValueList]; if Supports(Self, IibSHDDLGrantorGrantsOnPropEditor) then Result := [paValueList]; if Supports(Self, IibSHDDLGrantorDisplayPropEditor) then Result := [paValueList]; end; function TibSHDDLGrantorPropEditor.GetValue: string; begin Result := inherited GetValue; if Supports(Self, IibSHDDLGrantorPrivilegesForPropEditor) then ; if Supports(Self, IibSHDDLGrantorGrantsOnPropEditor) then ; if Supports(Self, IibSHDDLGrantorDisplayPropEditor) then ; end; procedure TibSHDDLGrantorPropEditor.GetValues(AValues: TStrings); begin inherited GetValues(AValues); if Supports(Self, IibSHDDLGrantorPrivilegesForPropEditor) then AValues.Text := GetPrivilegesFor; if Supports(Self, IibSHDDLGrantorGrantsOnPropEditor) then AValues.Text := GetGrantsOn; if Supports(Self, IibSHDDLGrantorDisplayPropEditor) then AValues.Text := GetDisplayGrants; end; procedure TibSHDDLGrantorPropEditor.SetValue(const Value: string); begin inherited SetValue(Value); if Supports(Self, IibSHDDLGrantorPrivilegesForPropEditor) then if Designer.CheckPropValue(Value, GetPrivilegesFor) then inherited SetStrValue(Value); if Supports(Self, IibSHDDLGrantorGrantsOnPropEditor) then if Designer.CheckPropValue(Value, GetGrantsOn) then inherited SetStrValue(Value); if Supports(Self, IibSHDDLGrantorDisplayPropEditor) then if Designer.CheckPropValue(Value, GetDisplayGrants) then inherited SetStrValue(Value); end; procedure TibSHDDLGrantorPropEditor.Edit; begin inherited Edit; if Supports(Self, IibSHDDLGrantorPrivilegesForPropEditor) then ; if Supports(Self, IibSHDDLGrantorGrantsOnPropEditor) then ; if Supports(Self, IibSHDDLGrantorDisplayPropEditor) then ; end; end.
unit ThWebVariable; interface uses Classes, ThRegExpr; type TThValidator = class; // TThCustomDatum = class(TPersistent) private FWebValue: string; FWebName: string; FDisplayName: string; protected procedure SetDisplayName(const Value: string); procedure SetWebName(const Value: string); procedure SetWebValue(const Value: string); virtual; published property DisplayName: string read FDisplayName write SetDisplayName; property WebName: string read FWebName write SetWebName; property WebValue: string read FWebValue write SetWebValue; end; // TThDatum = class(TThCustomDatum) private FValidator: TThValidator; procedure SetValidator(const Value: TThValidator); protected procedure SetWebValue(const Value: string); override; public property Validator: TThValidator read FValidator write SetValidator; end; // TThValidator = class(TComponent) private FWebDatum: TThDatum; FWebValue: string; FOnFailValidate: TNotifyEvent; protected procedure SetOnFailValidate(const Value: TNotifyEvent); protected procedure DoFailValidate; function ValidateString(var ioString: string): Boolean; virtual; abstract; public function Validate(inDatum: TThDatum): Boolean; virtual; property WebDatum: TThDatum read FWebDatum; property WebValue: string read FWebValue write FWebValue; published property OnFailValidate: TNotifyEvent read FOnFailValidate write SetOnFailValidate; end; // TThCustomWebVariable = class(TComponent) private FDatum: TThDatum; protected function GetDisplayName: string; function GetValidator: TThValidator; function GetWebName: string; function GetWebValue: string; virtual; procedure SetDisplayName(const Value: string); procedure SetValidator(const Value: TThValidator); procedure SetWebName(const Value: string); procedure SetWebValue(const Value: string); protected function DoMacroReplace(ARegExpr: TRegExpr): string; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function MacroReplace(const inValue: string): string; protected property DisplayName: string read GetDisplayName write SetDisplayName; property Validator: TThValidator read GetValidator write SetValidator; public property WebName: string read GetWebName write SetWebName; property WebValue: string read GetWebValue write SetWebValue; end; // TThWebVariable = class(TThCustomWebVariable) published property DisplayName; property Validator; property WebName; property WebValue; end; implementation { TThCustomDatum } procedure TThCustomDatum.SetDisplayName(const Value: string); begin FDisplayName := Value; end; procedure TThCustomDatum.SetWebName(const Value: string); begin if FWebName = FDisplayName then FDisplayName := Value; FWebName := Value; end; procedure TThCustomDatum.SetWebValue(const Value: string); begin FWebValue := Value; end; { TThDatum } procedure TThDatum.SetValidator(const Value: TThValidator); begin FValidator := Value; end; procedure TThDatum.SetWebValue(const Value: string); begin inherited; if FValidator <> nil then if not FValidator.Validate(Self) then FWebValue := FValidator.WebValue; end; { TThCustomWebVariable } constructor TThCustomWebVariable.Create(AOwner: TComponent); begin inherited; FDatum := TThDatum.Create; end; destructor TThCustomWebVariable.Destroy; begin FDatum.Free; inherited; end; function TThCustomWebVariable.GetValidator: TThValidator; begin Result := FDatum.FValidator; end; procedure TThCustomWebVariable.SetValidator(const Value: TThValidator); begin if Validator <> nil then Validator.RemoveFreeNotification(Self); FDatum.FValidator := Value; if Validator <> nil then Validator.FreeNotification(Self); end; procedure TThCustomWebVariable.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = Validator) then FDatum.FValidator := nil; end; function TThCustomWebVariable.GetWebName: string; begin Result := FDatum.WebName; end; function TThCustomWebVariable.GetWebValue: string; begin Result := MacroReplace(FDatum.WebValue); end; procedure TThCustomWebVariable.SetWebName(const Value: string); begin FDatum.WebName := Value; end; procedure TThCustomWebVariable.SetWebValue(const Value: string); begin FDatum.WebValue := Value; end; function TThCustomWebVariable.GetDisplayName: string; begin Result := FDatum.DisplayName; end; procedure TThCustomWebVariable.SetDisplayName(const Value: string); begin FDatum.DisplayName := Value; end; function TThCustomWebVariable.DoMacroReplace(ARegExpr: TRegExpr): string; var i: Integer; begin Result := ''; if Owner <> nil then for i := 0 to Pred(Owner.ComponentCount) do if Owner.Components[i] is TThCustomWebVariable then with TThCustomWebVariable(Owner.Components[i]) do if ARegExpr.Match[1] = WebName then begin Result := WebValue; break; end; end; function TThCustomWebVariable.MacroReplace(const inValue: string): string; begin with TRegExpr.Create do try Expression := '\{%([^}]*)\}'; Result := ReplaceEx(inValue, DoMacroReplace); finally Free; end; end; { TThValidator } procedure TThValidator.SetOnFailValidate(const Value: TNotifyEvent); begin FOnFailValidate := Value; end; procedure TThValidator.DoFailValidate; begin if Assigned(OnFailValidate) then OnFailValidate(Self); end; function TThValidator.Validate(inDatum: TThDatum): Boolean; begin FWebDatum := inDatum; FWebValue := inDatum.WebValue; Result := ValidateString(FWebValue); if not Result then DoFailValidate; end; end.
unit ColorToolUnit; interface uses System.Math, System.SysUtils, System.Classes, Winapi.Windows, Vcl.Controls, Vcl.Graphics, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Dmitry.Controls.WebLink, ToolsUnit, ImageHistoryUnit, Effects, uDBGraphicTypes, uMemory; type TColorToolPanelClass = class(TToolsPanelClass) private { Private declarations } NewImage: TBitmap; CloseLink: TWebLink; MakeItLink: TWebLink; ContrastLabel: TStaticText; ContrastTrackBar: TTrackBar; BrightnessLabel: TStaticText; BrightnessTrackBar: TTrackBar; RLabel: TStaticText; RTrackBar: TTrackBar; GLabel: TStaticText; GTrackBar: TTrackBar; BLabel: TStaticText; BTrackBar: TTrackBar; Loading: Boolean; ApplyOnDone: Boolean; FOnDone: TNotifyEvent; PImage, PNewImage: TArPARGB; FOverageContrast: Integer; protected function LangID: string; override; public { Public declarations } procedure Init; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ClosePanel; override; procedure MakeTransform; override; procedure ClosePanelEvent(Sender: TObject); procedure DoMakeImage(Sender: TObject); procedure SetLocalProperties(Sender: TObject); procedure RefreshInfo; function GetProperties: string; override; class function ID: string; override; procedure ExecuteProperties(Properties: string; OnDone: TNotifyEvent); override; procedure SetProperties(Properties: string); override; end; implementation { TColorToolPanelClass } procedure TColorToolPanelClass.ClosePanel; begin if Assigned(OnClosePanel) then OnClosePanel(Self); if not ApplyOnDone then inherited; end; procedure TColorToolPanelClass.ClosePanelEvent(Sender: TObject); begin CancelTempImage(True); ClosePanel; end; constructor TColorToolPanelClass.Create(AOwner: TComponent); begin inherited; ApplyOnDone := False; NewImage := nil; Loading := True; Align := AlClient; ContrastLabel := TStaticText.Create(Self); ContrastLabel.Top := 8; ContrastLabel.Left := 8; ContrastLabel.Caption := L('Contract: [%d]'); ContrastLabel.Parent := AOwner as TWinControl; ContrastTrackBar := TTrackBar.Create(Self); ContrastTrackBar.Top := ContrastLabel.Top + ContrastLabel.Height + 5; ContrastTrackBar.Left := 8; ContrastTrackBar.Width := 161; ContrastTrackBar.Min := -100; ContrastTrackBar.Max := 100; ContrastTrackBar.Position := 0; ContrastTrackBar.OnChange := SetLocalProperties; ContrastTrackBar.Parent := AOwner as TWinControl; BrightnessLabel := TStaticText.Create(Self); BrightnessLabel.Top := ContrastTrackBar.Top + ContrastTrackBar.Height + 5; BrightnessLabel.Left := 8; BrightnessLabel.Caption := L('Brightness : [%d]'); BrightnessLabel.Parent := AOwner as TWinControl; BrightnessTrackBar := TTrackBar.Create(Self); BrightnessTrackBar.Top := BrightnessLabel.Top + BrightnessLabel.Height + 5; BrightnessTrackBar.Left := 8; BrightnessTrackBar.Width := 161; BrightnessTrackBar.Min := -255; BrightnessTrackBar.Max := 255; BrightnessTrackBar.Position := 0; BrightnessTrackBar.OnChange := SetLocalProperties; BrightnessTrackBar.Parent := AOwner as TWinControl; RLabel := TStaticText.Create(Self); RLabel.Top := BrightnessTrackBar.Top + BrightnessTrackBar.Height + 5; RLabel.Caption := 'R'; RTrackBar := TTrackBar.Create(Self); RTrackBar.Orientation := TrVertical; RTrackBar.Top := RLabel.Top + RLabel.Height + 5; RTrackBar.Left := 15; RTrackBar.Min := -100; RTrackBar.Max := 100; RTrackBar.Position := 0; RTrackBar.OnChange := SetLocalProperties; RTrackBar.Parent := AOwner as TWinControl; RLabel.Left := RTrackBar.Left; RLabel.Parent := AOwner as TWinControl; GLabel := TStaticText.Create(Self); GLabel.Top := BrightnessTrackBar.Top + BrightnessTrackBar.Height + 5; GLabel.Caption := 'G'; GTrackBar := TTrackBar.Create(Self); GTrackBar.Orientation := TrVertical; GTrackBar.Top := RLabel.Top + RLabel.Height + 5; GTrackBar.Left := RTrackBar.Left + RTrackBar.Width + 5; GTrackBar.Min := -100; GTrackBar.Max := 100; GTrackBar.Position := 0; GTrackBar.OnChange := SetLocalProperties; GTrackBar.Parent := AOwner as TWinControl; GLabel.Left := GTrackBar.Left; GLabel.Parent := AOwner as TWinControl; BLabel := TStaticText.Create(Self); BLabel.Top := BrightnessTrackBar.Top + BrightnessTrackBar.Height + 5; BLabel.Caption := 'B'; BTrackBar := TTrackBar.Create(Self); BTrackBar.Orientation := TrVertical; BTrackBar.Top := RLabel.Top + RLabel.Height + 5; BTrackBar.Left := GTrackBar.Left + GTrackBar.Width + 5; BTrackBar.Min := -100; BTrackBar.Max := 100; BTrackBar.Position := 0; BTrackBar.OnChange := SetLocalProperties; BTrackBar.Parent := AOwner as TWinControl; BLabel.Left := BTrackBar.Left; BLabel.Parent := AOwner as TWinControl; MakeItLink := TWebLink.Create(Self); MakeItLink.Parent := AOwner as TWinControl; MakeItLink.Text := L('Apply'); MakeItLink.Top := BTrackBar.Top + BTrackBar.Height + 5; MakeItLink.Left := 10; MakeItLink.Visible := True; MakeItLink.Color := ClBtnface; MakeItLink.OnClick := DoMakeImage; MakeItLink.LoadFromResource('DOIT'); MakeItLink.RefreshBuffer(True); CloseLink := TWebLink.Create(Self); CloseLink.Parent := AOwner as TWinControl; CloseLink.Text := L('Close tool'); CloseLink.Top := MakeItLink.Top + MakeItLink.Height + 5; CloseLink.Left := 10; CloseLink.Visible := True; CloseLink.Color := ClBtnface; CloseLink.OnClick := ClosePanelEvent; CloseLink.LoadFromResource('CANCELACTION'); CloseLink.RefreshBuffer(True); Loading := False; RefreshInfo; FOverageContrast := -1; end; procedure TColorToolPanelClass.Init; var I: Integer; begin NewImage := TBitmap.Create; NewImage.Assign(Image); SetLength(PImage, NewImage.Height); SetLength(PNewImage, Image.Height); for I := 0 to Image.Height - 1 do PImage[I] := Image.ScanLine[I]; for I := 0 to NewImage.Height - 1 do PNewImage[I] := NewImage.ScanLine[I]; SetTempImage(NewImage); end; destructor TColorToolPanelClass.Destroy; begin F(ContrastLabel); F(ContrastTrackBar); F(BrightnessLabel); F(BrightnessTrackBar); F(RTrackBar); F(GTrackBar); F(BTrackBar); F(CloseLink); F(MakeItLink); F(RLabel); F(GLabel); F(BLabel); inherited; end; procedure TColorToolPanelClass.DoMakeImage(Sender: TObject); begin MakeTransform; end; procedure TColorToolPanelClass.ExecuteProperties(Properties: string; OnDone: TNotifyEvent); begin FOnDone := OnDone; ApplyOnDone := True; Loading := True; ContrastTrackBar.Position := StrToIntDef(GetValueByName(Properties, 'Contrast'), 0); BrightnessTrackBar.Position := StrToIntDef(GetValueByName(Properties, 'Brightness'), 0); RTrackBar.Position := StrToIntDef(GetValueByName(Properties, 'RValue'), 0); GTrackBar.Position := StrToIntDef(GetValueByName(Properties, 'GValue'), 0); BTrackBar.Position := StrToIntDef(GetValueByName(Properties, 'BValue'), 0); Loading := False; SetLocalProperties(Self); MakeTransform; if Assigned(FOnDone) then FOnDone(Self); end; function TColorToolPanelClass.GetProperties: string; begin Result := 'Contrast=' + IntToStr(ContrastTrackBar.Position) + ';'; Result := Result + 'Brightness=' + IntToStr(BrightnessTrackBar.Position) + ';'; Result := Result + 'RValue=' + IntToStr(RTrackBar.Position) + ';'; Result := Result + 'GValue=' + IntToStr(GTrackBar.Position) + ';'; Result := Result + 'BValue=' + IntToStr(BTrackBar.Position) + ';'; end; class function TColorToolPanelClass.ID: string; begin Result := '{E20DDD6C-0E5F-4A69-A689-978763DE8A0A}'; end; function TColorToolPanelClass.LangID: string; begin Result := 'ColorTool'; end; procedure TColorToolPanelClass.MakeTransform; begin inherited; if NewImage <> nil then begin ImageHistory.Add(NewImage, '{' + ID + '}[' + GetProperties + ']'); SetImagePointer(NewImage); end; ClosePanel; end; procedure TColorToolPanelClass.RefreshInfo; begin ContrastLabel.Caption := Format(L('Contrast: [%d]'), [ContrastTrackBar.Position]); BrightnessLabel.Caption := Format(L('Brightness : [%d]'), [BrightnessTrackBar.Position]); RLabel.Caption := Format(L('R [%d]'), [RTrackBar.Position]); GLabel.Caption := Format(L('G [%d]'), [GTrackBar.Position]); BLabel.Caption := Format(L('B [%d]'), [BTrackBar.Position]); end; procedure TColorToolPanelClass.SetLocalProperties(Sender: TObject); var Width, Height: Integer; ContrastValue: Extended; function Znak(X: Extended): Extended; begin if X >= 0 then Result := 1 else Result := -1; end; begin if Loading then Exit; Height := NewImage.Height; Width := NewImage.Width; ContrastValue := Znak(ContrastTrackBar.Position) * 100 * Power(Abs(ContrastTrackBar.Position) / 100, 2); SetContractBrightnessRGBChannelValue(PImage, PNewImage, Width, Height, ContrastValue, FOverageContrast, BrightnessTrackBar.Position, RTrackBar.Position, GTrackBar.Position, BTrackBar.Position); Editor.MakeImage; Editor.DoPaint; RefreshInfo; end; procedure TColorToolPanelClass.SetProperties(Properties: String); begin end; end.
unit n_LogThreads; interface uses SysUtils, Classes, Forms, DateUtils, IBDataBase, IBQuery, IBSQL, SyncObjs, IdTCPServer, n_free_functions, v_constants, n_constants; type TlmText = record // для хранения последнего набора сообщений каждого типа lmCODE : integer; // код последней записи в LOGMESSAGES MyText : String; EMessageText: String; CommentText : String; end; TThreadData = class public thCommand: integer; ID : integer; IDuser : integer; pProcess : Pointer; thParams : String; // текст параметра потока lmTexts : array [lgmsInfo..lgmsSysMess] of TlmText; // сообщения по типам constructor Create; destructor Destroy; override; end; var ServerID: integer; // код данного экземпляра сервера из таблицы LOGSERVERLIST MainThreadData: TThreadData; // Данные для логирования главного потока программы manycntsTime: TDateTime; // время последнего сообщения "many connections" CSlog: TCriticalSection; // защита от одновременного срабатывания fnCreateThread WorkThreadDataIDs: TIntegerList; strDelim1_45, strDelim2_45: String; //---------------------- новые функции function fnGetServerID: integer; procedure prSetThLogParams(ThreadData: TThreadData; COMMAND: integer=0; // записывает/добавляет параметры потока pUSERID: integer=0; FIRMID: integer=0; PARAMS: string=''; plus: Boolean=True); function fnWriteMessageToLog(ThreadData: TThreadData; MessType: integer; // записывает/добавляет сообщение ProcName, MyText, EMessageText, CommentText: string; plus: Boolean=false): boolean; //---------------------- доработанные функции ВЧ function fnCreateThread(ThreadType: integer; Command: Integer=0): TThreadData; // Создает поток и возвращает его ID и открытое Query procedure prDestroyThreadData(ThreadData: TThreadData; ProcName: string); // записывает в лог время завершения потока и освобождает память ThreadData function fnSignatureToThreadType(Signature: integer): integer; // Переводит сигнатуру в тип потока procedure fnWriteToLog(ThreadData: TThreadData; MessType: integer; ProcName, MyText, EMessageText, CommentText: string); // запись в лог //---------------------- доработанные функции НК procedure fnWriteToLogPlus(ThreadData: TThreadData; MessType: integer; ProcName: string; MyText: string=''; EMess: string=''; CommText: string=''; plus: Boolean=True; logf: string='error'); procedure TestConnections(flZero: boolean=False; flDSlist: boolean=False; NameLog: String=''); // проверка соединений с БД implementation uses n_server_common, n_DataSetsManager, n_DataCacheInMemory; //====================================================== function fnGetServerID: integer; // логирование в ib_css const nmProc = 'fnGetServerID'; // имя процедуры/функции var ibs: TIBSQL; ibd: TIBDatabase; begin Result:= 0; if not cntsLog.BaseConnected then Exit; ibd:= nil; ibs:= nil; try try ibd:= cntsLog.GetFreeCnt; ibs:= fnCreateNewIBSQL(ibd, 'ibs_'+nmProc, -1, tpWrite, true); ibs.SQL.Text:= 'select NewSELLCODE from GetLogServerID(:pSELLSERVER, :pSELLPATH)'; ibs.ParamByName('pSELLSERVER').AsString:= fnGetComputerName; ibs.ParamByName('pSELLPATH').AsString:= AnsiUpperCase(ParamStr(0)); ibs.ExecQuery; if not (ibs.Bof and ibs.Eof) then begin Result:= ibs.FieldByName('NewSELLCODE').AsInteger; if ibs.Transaction.InTransaction then ibs.Transaction.Commit; end; except on E:Exception do begin prMessageLOGS(nmProc+': '+E.Message); Result:= 0; end; end; finally prFreeIBSQL(ibs); cntsLog.SetFreeCnt(ibd); end; end; //================================================== constructor TThreadData.Create; var i: Integer; tmt: TlmText; begin inherited Create; ID:= 0; IDuser:= 0; pProcess:= nil; thCommand:= 0; thParams:= ''; // текст параметра потока for i:= Low(lmTexts) to High(lmTexts) do begin // сообщения по типам tmt:= lmTexts[i]; tmt.lmCODE:= 0; tmt.MyText:= ''; tmt.EMessageText:= ''; tmt.CommentText:= ''; end; end; //================================================== destructor TThreadData.Destroy; begin inherited Destroy; end; //************************* логирование в ib_css ******************************* //======================================= Создает и возвращает поток логирования function fnCreateThread(ThreadType: integer; Command: Integer=0): TThreadData; const nmProc = 'fnCreateThread'; // имя процедуры/функции var i, newID: integer; ibd: TIBDatabase; ibs: TIBSQL; begin // ibd:= nil; ibs:= nil; newID:= 0; Result:= TThreadData.Create; if not cntsLog.BaseConnected or (ServerID<1) then Exit; try ibd:= cntsLog.GetFreeCnt; // логирование в ib_css try ibs:= fnCreateNewIBSQL(ibd, 'TD_ibs', -1, tpWrite, True); ibs.SQL.Text:= 'select NewTHLGCODE from CreateThreadLog('+IntToStr(ThreadType)+ ', '+IntToStr(Command)+', :pTIME, '+IntToStr(ServerID)+')'; ibs.ParamByName('pTIME').AsDateTime:= Now; for i:= 1 to RepeatCount do try ibs.Close; if not ibs.Transaction.InTransaction then ibs.Transaction.StartTransaction; ibs.ExecQuery; if (ibs.Bof and ibs.Eof) or (ibs.Fields[0].AsInteger<1) then raise Exception.Create('Empty NewTHLGCODE'); newID:= ibs.FieldByName('NewTHLGCODE').AsInteger; if (newID>0) and (WorkThreadDataIDs.IndexOf(newID)>-1) then raise Exception.Create('Duplicate NewTHLGCODE'); if ibs.Transaction.InTransaction then ibs.Transaction.Commit; break; except on E:Exception do begin if ibs.Transaction.InTransaction then ibs.Transaction.RollbackRetaining; prMessageLOGS(nmProc+': CreateThreadLog error, try '+IntToStr(i)+#13#10+E.Message); if (i<RepeatCount) then sleep(101) else newID:= -1; end; end; finally prFreeIBSQL(ibs); cntsLog.SetFreeCnt(ibd); end; CSlog.Enter; try if (newID>0) and (WorkThreadDataIDs.IndexOf(newID)<0) then WorkThreadDataIDs.Add(newID) else newID:= -1; Result.ID:= newID; if (Command<>0) then Result.thCommand:= COMMAND; finally CSlog.Leave; end; except on E:Exception do prMessageLOGS(nmProc+': '+E.Message); end; end; //============================================================================== // записывает в лог время завершения потока и освобождает память ThreadData procedure prDestroyThreadData(ThreadData: TThreadData; ProcName: string); const nmProc = 'prDestroyThreadData'; // имя процедуры/функции var nq: string; i, tdID: integer; ibd: TIBDatabase; ibs: TIBSQL; begin if not Assigned(ThreadData) then Exit; // ibd:= nil; ibs:= nil; try tdID:= ThreadData.ID; CSlog.Enter; try if (tdID>0) then WorkThreadDataIDs.Remove(tdID); prFree(ThreadData); finally CSlog.Leave; end; if not cntsLog.BaseConnected or (tdID<1) then Exit; ibd:= cntsLog.GetFreeCnt; try ibs:= fnCreateNewIBSQL(ibd, 'TD_ibs', -1, tpWrite); if Assigned(ibs) then begin ibs.Transaction.StartTransaction; ibs.SQL.Text:= 'execute procedure SetThreadLogEnd(:THLGCODE, :THLGENDTIME)'; ibs.ParamByName('THLGCODE').asInteger:= tdID; ibs.ParamByName('THLGENDTIME').AsDateTime:= Now(); nq:= ibs.Name; for i:= 1 to RepeatCount do try // RepeatCount попыток if not ibs.Transaction.InTransaction then ibs.Transaction.StartTransaction; ibs.ExecQuery; ibs.Transaction.Commit; break; except on E:Exception do begin if ibs.Transaction.InTransaction then ibs.Transaction.RollbackRetaining; prMessageLOGS(nmProc+': '+ProcName+': error save THLGENDTIME, '+nq+', try '+IntToStr(i)); if i<RepeatCount then sleep(101); // если сбой - пробуем повторить end; end; end; finally prFreeIBSQL(ibs); cntsLog.SetFreeCnt(ibd); end; except on E:Exception do prMessageLOGS(nmProc+': '+E.Message); end; end; //=============================== записывает/добавляет параметры потока в ib_css procedure prSetThLogParams(ThreadData: TThreadData; COMMAND: integer=0; pUSERID: integer=0; FIRMID: integer=0; PARAMS: string=''; plus: Boolean=True); const nmProc = 'prSetThLogParams'; // имя процедуры/функции var i: Integer; s, sID, sCommand, sFirm, sUser: String; ibd: TIBDatabase; ibQuery: TIBQuery; // для AsMemo begin ibQuery:= nil; ibd:= nil; if (FIRMID=isWe) then FIRMID:= 0; if not cntsLog.BaseConnected or not Assigned(ThreadData) or (ThreadData.ID<1) or ((COMMAND=0) and (pUSERID=0) and (FIRMID=0) and (PARAMS='')) then Exit; try //----------------------------------------------------------- пишем в базу sID:= IntToStr(ThreadData.ID); sCommand:= IntToStr(COMMAND); sFirm:= IntToStr(FIRMID); sUser:= IntToStr(pUSERID); if (COMMAND<>0) then ThreadData.thCommand:= COMMAND; try try ibd:= cntsLog.GetFreeCnt; except Exit; end; ibQuery:= fnCreateNewIBQuery(ibd, 'TD_ibQuery', -1, tpWrite); s:= ''; if (PARAMS<>'') then begin if plus then s:= ThreadData.thParams; // если дописывать s:= s+fnIfStr(s<>'', #13#10, '')+PARAMS; end; if ibQuery.Active then ibQuery.Close; if (ibQuery.ParamCount>0) then ibQuery.Params.Clear; ibQuery.SQL.Text:= 'select rTHLGPARAMS from SetThreadLogParamsR('+sID+', '+ fnIfStr(s<>'', ':PARAMS,', 'null,')+' '+sCommand+', '+sUser+', '+sFirm+')'; if (s<>'') then ibQuery.ParamByName('PARAMS').AsMemo:= s; for i:= 1 to RepeatCount do try ibQuery.Open; s:= ibQuery.FieldByName('rTHLGPARAMS').AsString; if ibQuery.Transaction.InTransaction then ibQuery.Transaction.Commit; ThreadData.thParams:= s; break; except on E:Exception do begin if ibQuery.Transaction.InTransaction then ibQuery.Transaction.RollbackRetaining; if (i<RepeatCount) then sleep(101) else begin prMessageLOGS(nmProc+': ExecSQL Error: '+E.Message); prMessageLOGS(nmProc+': COMMAND='+sCommand+', FIRMID='+sFirm+ ', USERID='+sUser+fnIfStr(s<>'', ': Params='+s, '')); end; end; // on E:Exception end; // except (for) if ibQuery.Active then ibQuery.Close; finally prFreeIBQuery(ibQuery); cntsLog.SetFreeCnt(ibd); end; //------------------------------------------------------------ счетчик коннектов if (ThreadData.IDuser>0) or (pUSERID<1) or not Cache.ClientExist(pUSERID) then Exit; if (FIRMID<1) or (FIRMID=isWe) then Exit; if (ThreadData.thCommand<1) or (ThreadData.thCommand=csWebAutentication) or (ThreadData.thCommand=csBackJobAutentication) then Exit; ThreadData.IDuser:= pUSERID; Cache.arClientInfo[pUSERID].CheckConnectCount; except on E:Exception do prMessageLOGS(nmProc+': Alert! - '+E.Message); end; end; //====================================== записывает/добавляет сообщение в ib_css function fnWriteMessageToLog(ThreadData: TThreadData; MessType: integer; ProcName, MyText, EMessageText, CommentText: string; plus: Boolean=false): boolean; const nmProc = 'fnWriteMessageToLog'; // имя процедуры/функции var i, SCODE: Integer; s1, s2, s3, ss: String; fl1, fl2, fl3: Boolean; tmt: TlmText; ibd: TIBDatabase; ibQuery: TIBQuery; // для AsMemo begin Result:= false; if not cntsLog.BaseConnected or not Assigned(ThreadData) or (ThreadData.ID<1) then Exit; SCODE:= 0; fl1:= MyText<>''; fl2:= EMessageText<>''; fl3:= CommentText<>''; if not (fl1 or fl2 or fl3) then Exit; // если нечего писать - выходим ibQuery:= nil; ibd:= nil; with ThreadData do try try try ibd:= cntsLog.GetFreeCnt; except Exit; end; s1:= ''; s2:= ''; s3:= ''; tmt:= lmTexts[MessType]; if plus then begin // если дописывать SCODE:= tmt.lmCODE; if fl1 then s1:= tmt.MyText; if fl2 then s2:= tmt.EMessageText; if fl3 then s3:= tmt.CommentText; end; if fl1 then s1:= s1+fnIfStr(s1<>'', #13#10, '')+MyText; if fl2 then s2:= s2+fnIfStr(s2<>'', #13#10, '')+EMessageText; if fl3 then s3:= s3+fnIfStr(s3<>'', #13#10, '')+CommentText; ibQuery:= fnCreateNewIBQuery(ibd, 'TD_ibQuery', ID, tpWrite); if not Assigned(ibQuery) then Exit; ss:= 'select NewLGMSCODE from SaveMessageToLog(:id, :idth, :TIME, :PROC,'+ fnIfStr(fl1, ' :MYMES,', ' null,')+fnIfStr(fl2, ' :EMESS,', ' null,')+ fnIfStr(fl3, ' :COMM,', ' null,')+' :TYPE)'; ibQuery.SQL.Text:= ss; ibQuery.ParamByName('id').AsInteger:= SCODE; // код строки (если 0 - создается новая запись) ibQuery.ParamByName('idth').AsInteger:= ID; // код потока ibQuery.ParamByName('TIME').AsDateTime:= Now; // дата и время сообщения ibQuery.ParamByName('PROC').asString:= ProcName; // Имя процедуры if fl1 then ibQuery.ParamByName('MYMES').AsMemo:= s1; // Наш текст if fl2 then ibQuery.ParamByName('EMESS').AsMemo:= s2; // Текст ошибки из E.Message if fl3 then ibQuery.ParamByName('COMM').AsMemo:= s3; // Примечание (например, текст SQL) ibQuery.ParamByName('TYPE').AsInteger:= MessType; // Код типа сообщения for i:= 1 to RepeatCount do try if ibQuery.Active then ibQuery.Close; ibQuery.Open; if not (ibQuery.Bof and ibQuery.Eof) and (SCODE<>ibQuery.FieldByName('NewLGMSCODE').AsInteger) then SCODE:= ibQuery.FieldByName('NewLGMSCODE').AsInteger; if ibQuery.Transaction.InTransaction then ibQuery.Transaction.Commit; Result:= true; if (lmTexts[MessType].lmCODE<>SCODE) then lmTexts[MessType].lmCODE:= SCODE; if fl1 then tmt.MyText := s1; if fl2 then tmt.EMessageText:= s2; if fl3 then tmt.CommentText := s3; break; except on E:Exception do begin if ibQuery.Transaction.InTransaction then ibQuery.Transaction.RollbackRetaining; prMessageLOGS(nmProc+': error save message, try '+IntToStr(i)+': '+E.Message); if (i<RepeatCount) then sleep(101); end; end; finally prFreeIBQuery(ibQuery); cntsLog.SetFreeCnt(ibd); end; except on E:Exception do prMessageLOGS(nmProc+': Alert! - '+E.Message); end; end; //****************************************************************************** //================================================================= запись в лог procedure fnWriteToLog(ThreadData: TThreadData; MessType: integer; ProcName, MyText, EMessageText, CommentText: string); const nmProc = 'fnWriteToLog'; // имя процедуры/функции var s, mess: String; ch: Char; begin if fnWriteMessageToLog(ThreadData, MessType, ProcName, MyText, EMessageText, CommentText) // логирование в ib_css and not (MessType in [lgmsSysError, lgmsSysMess, lgmsCryticalSysError]) then Exit; if ((AppStatus in [stSuspending, stSuspended]) // если остановлены и сообщение из Server*Connect - не пишем в текст.лог and ((pos('Server', ProcName)>0) and (pos('Connect', ProcName)>0))) or // если Сервер перегружен - не пишем в текст.лог ((AppStatus=stWork) and (pos('Сервер перегружен', EMessageText)>0)) then Exit; try mess:= fnIfStr(MyText='', '', 'MyText: '+MyText); if EMessageText<>'' then begin ch:= EMessageText[1]; // length(EMessageText) if not SysUtils.CharInSet(ch, [#13, #10]) then s:= #13#10 else s:= ''; mess:= mess+fnIfStr(mess='', '', s)+'error: '+EMessageText; end; if CommentText<>'' then mess:= mess+fnIfStr(mess='', '', #13#10)+'Comment: '+CommentText; prMessageLOGS(ProcName+': '+mess); except end; end; //============================================================================== function fnSignatureToThreadType(Signature: integer): integer; begin case Signature of csOldAutorizeSignature: Result:= thtpOldAutorize; csAutorizeSignature : Result:= thtpAutorize; csPingSignature : Result:= thtpPing; csCommonSignature : Result:= thtpArm; csOnlineOrder : Result:= thtpWeb; csWebArm : Result:= thtpWebArm; else Result:= thtpUnknown; end; end; //============================= добавляет тексты к последней записи LOG-а потока procedure fnWriteToLogPlus(ThreadData: TThreadData; MessType: integer; ProcName: string; MyText: string=''; EMess: string=''; CommText: string=''; plus: Boolean=True; logf: string='error'); var err: boolean; begin err:= not fnWriteMessageToLog(ThreadData, MessType, ProcName, MyText, EMess, CommText, plus); // логирование в ib_css if not (err or (MessType in [lgmsSysError, lgmsSysMess, lgmsCryticalSysError])) then Exit; prMessageLOGS(fnIfStr(ProcName='', '', ProcName+': ')+MyText+ fnIfStr(EMess='', '', #10+EMess)+fnIfStr(CommText='', '', #10+CommText), logf); end; //============================================================================== procedure TestConnections(flZero: boolean=False; flDSlist: boolean=False; NameLog: String=''); // проверка соединений с БД // flZero=True - выводить DataSetCount=0, flDSlist=True - выводить список DataSets var i, j, ii: integer; s, cm, ss: string; p: Pointer; Body: TStringList; begin s:= ''; Body:= nil; ii:= 100; // число коннектов, после которого отсылать сообщение админу if NameLog='' then NameLog:= 'TestConns'; try with DataSetsManager do for j:= Low(Cnts) to High(Cnts) do try p:= GetCntsItemPointer(j); if not Assigned(p) then Continue; cm:= TComponent(p).Name; if (TComponent(p) is TIDTCPServer) and not flDSlist then begin // TIDTCPServer i:= fnGetThreadsCount(TIDTCPServer(p)); if cm='' then cm:= 'TIDTCPServer'; if i>ii then begin if not Assigned(Body) then Body:= TStringList.Create; Body.Add('many Contexts: '+cm+'.Contexts.Count = '+IntToStr(i)); end; if flZero or (i>0) then s:= s+fnIfStr(s='', ' ', #13#10+StringOfChar(' ', 18))+cm+'.Contexts.Count = '+IntToStr(i); end; except on E: Exception do prMessageLOGS('TestConnections: '+cm+' '+E.Message, NameLog); end; cntsGRB.TestCntsState(s, ii, Body); // формируем строку по cntsGRB cntsORD.TestCntsState(s, ii, Body); // формируем строку по cntsORD cntsLOG.TestCntsState(s, ii, Body); // формируем строку по cntsLOG cntsTDT.TestCntsState(s, ii, Body); // формируем строку по cntsTDT cntsSUF.TestCntsState(s, ii, Body); // формируем строку по cntsSUF cntsSUFORD.TestCntsState(s, ii, Body); // формируем строку по cntsSUFORD cntsSUFLOG.TestCntsState(s, ii, Body); // формируем строку по cntsSUFLOG if Assigned(Body) and (Body.Count>0) and ((manycntsTime=DateNull) or (Now>IncMinute(manycntsTime, 5))) then begin manycntsTime:= Now; // отправить сообщение админу prMessageLOGS('many connections:'#13#10+ss, NameLog); Body.Insert(0, FormatDateTime(' '+cDateTimeFormatY2S+' ', manycntsTime)+ ' - many connections ('+fnGetComputerName+', '+Application.Name+')'); ss:= Cache.GetConstEmails(pcEmplORDERAUTO); if ss='' then ss:= fnGetSysAdresVlad(caeOnlyDayLess); Body.Insert(0, GetMessageFromSelf); ss:= n_SysMailSend(ss, 'many connections', Body, nil, '', '', true); if (ss<>'') then prMessageLOGS('Ошибка отправки письма о коннектах: '#13#10+ss, NameLog) else prMessageLOGS('send mail to admin', NameLog); end; finally prFree(Body); end; if s<>'' then begin // выводим в лог prMessageLOGS(strDelim1_45, NameLog, false); prMessageLOGS(s, NameLog, false); prMessageLOGS(strDelim1_45, NameLog, false); end; end; //****************************************************************************** initialization begin manycntsTime:= DateNull; CSlog:= TCriticalSection.Create; WorkThreadDataIDs:= TIntegerList.Create; strDelim1_45:= StringOfChar('-', 45); strDelim2_45:= StringOfChar('=', 45); end; finalization begin prFree(CSlog); prFree(WorkThreadDataIDs); end; //****************************************************************************** end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmDataStoragePropEdit Purpose : The property and component editors for the rmDataStorage components Date : 12-29-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmDataStoragePropEdit; interface {$I CompilerDefines.INC} {$ifdef D6_or_higher} uses DesignIntf, DesignEditors, TypInfo; {$else} uses DsgnIntf, TypInfo; {$endif} type TrmDataLongintProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; end; TrmDataStorageEditor = class(TComponentEditor) private procedure SaveToFile; procedure LoadFromFile; procedure ClearData; public function GetVerb(index:integer):string; override; function GetVerbCount:integer; override; procedure ExecuteVerb(index:integer); override; end; implementation uses rmDataStorage, dialogs; { TrmDataLongintProperty } function TrmDataLongintProperty.GetAttributes: TPropertyAttributes; begin Result := [paReadOnly]; end; { TrmDataStorageEditor } procedure TrmDataStorageEditor.ClearData; begin if assigned(Component) then begin TrmCustomDataStorage(Component).ClearData; designer.modified; end; end; procedure TrmDataStorageEditor.ExecuteVerb(index: integer); begin case index of 0:LoadFromFile; 1:SaveToFile; 2:ClearData; end; end; function TrmDataStorageEditor.GetVerb(index: integer): string; begin case index of 0:result := 'Load data from file...'; 1:result := 'Save data to file...'; 2:result := 'Clear data'; end; end; function TrmDataStorageEditor.GetVerbCount: integer; begin result := 3; end; procedure TrmDataStorageEditor.LoadFromFile; begin if assigned(Component) then begin with TOpenDialog.create(nil) do try Title := 'Load file...'; Filter := 'All Files|*.*'; FilterIndex := 1; if execute then begin TrmCustomDataStorage(Component).LoadFromFile(filename); designer.modified; end; finally free; end end; end; procedure TrmDataStorageEditor.SaveToFile; begin if assigned(Component) then begin if TrmCustomDataStorage(Component).DataSize = 0 then begin ShowMessage('Component contains no data.'); exit; end; with TSaveDialog.create(nil) do try Title := 'Save to...'; Filter := 'All Files|*.*'; FilterIndex := 1; if execute then TrmCustomDataStorage(Component).WriteToFile(filename); finally free; end end; end; end.
(* Category: SWAG Title: OOP/TURBO VISION ROUTINES Original name: 0053.PAS Description: TV Broadcast Message Author: SWAG SUPPORT TEAM Date: 02-28-95 09:53 *) { This program will create two modaless dialog boxes and will allow only one Dialog2 dialog to be created at any time. Additionally, it will demonstrate how to broadcast messages to background windows and update information without changing the selected dialog. } {$X+} Program DialogCommunication; uses Objects, Drivers, Views, Menus, Dialogs, App, Crt; const cmDialog1 = 100; cmDialog2 = 101; cmDialog1Button = 200; cmDialog2Button = 201; type PHelloApp = ^THelloApp; THelloApp = object(TApplication) procedure MakeDialog; procedure HandleEvent(var Event: TEvent); virtual; procedure InitMenuBar; virtual; procedure InitStatusLine; virtual; end; PMyDialog1 = ^TMyDialog1; TMyDialog1 = object(TDialog) procedure MakeDialog2; procedure HandleEvent(var Event:TEvent); virtual; end; PMyDialog2 = ^TMyDialog2; TMyDialog2 = object(TMyDialog1) procedure HandleEvent(var Event:TEvent); virtual; end; procedure TMyDialog1.HandleEvent(var Event: TEvent); var AreYouThere: PView; begin TDialog.HandleEvent(Event); if Event.What = evCommand then begin case Event.Command of cmDialog1Button: begin AreYouThere:= Message(DeskTop, evBroadcast, cmDialog2, nil); if AreYouThere = nil then MakeDialog2 else ClearEvent(Event); end else Exit; end; ClearEvent(Event); end; end; procedure TMyDialog1.MakeDialog2; var Dialog2: PMyDialog2; R: TRect; Button: PButton; begin R.Assign(1,1,40,20); Dialog2:= New(PMyDialog2, init(R,'Dialog2')); R.Assign(10,10,20,12); Button:= New(PButton,Init(R,'Beep', cmDialog2Button, bfdefault)); Dialog2^.Insert(Button); DeskTop^.Insert(Dialog2); end; procedure TMyDialog2.HandleEvent(var Event: TEvent); begin case Event.Command of cmDialog2: begin sound(2000); delay(10); nosound; Title:=newstr('Hello world'); ReDraw; ClearEvent(Event); end; end; TDialog.HandleEvent(Event); if Event.What = evCommand then begin case Event.Command of cmDialog2Button: begin Sound(1000); delay(100); NoSound; end; else Exit; end; ClearEvent(Event); end; end; { THelloApp } procedure THelloApp.MakeDialog; var R:TRect; Button1: PButton; Dialog1: PMyDialog1; begin R.Assign(25, 5, 65, 16); Dialog1:= New(PMyDialog1, init(R,'Dialog1')); R.Assign(16, 8, 38, 10); Button1:= New(PButton, Init(R,'Call Dialog2', cmDialog1Button, bfDefault)); Dialog1^.Insert(Button1); DeskTop^.Insert(Dialog1); end; procedure THelloApp.HandleEvent(var Event: TEvent); begin TApplication.HandleEvent(Event); if Event.What = evCommand then begin case Event.Command of cmDialog1:begin MakeDialog; end; else Exit; end; ClearEvent(Event); end; end; procedure THelloApp.InitMenuBar; var R: TRect; begin GetExtent(R); R.B.Y := R.A.Y + 1; MenuBar := New(PMenuBar, Init(R, NewMenu( NewSubMenu('~O~pen Dialogs', hcNoContext, NewMenu( NewItem('~D~ialog1','', 0, cmDialog1, hcNoContext, NewLine( NewItem('E~x~it', 'Alt-X', kbAltX, cmQuit, hcNoContext, nil)))), nil)))); end; procedure THelloApp.InitStatusLine; var R: TRect; begin GetExtent(R); R.A.Y := R.B.Y-1; StatusLine := New(PStatusLine, Init(R, NewStatusDef(0, $FFFF, NewStatusKey('', kbF10, cmMenu, NewStatusKey('~Alt-X~ Exit', kbAltX, cmQuit, nil)), nil))); end; var HelloWorld: THelloApp; begin HelloWorld.Init; HelloWorld.Run; HelloWorld.Done; end.
unit DisplayFrame1; { TdispFrame permet d'afficher une trace avec un minimum d'instructions. Il faut placer un frame dans une fenêtre et l'initialiser avec InstallArray. On peut aussi initialiser les paramètres de visu. On dispose du menu Coordonnées/BK color avec le clic droit. On pourrait perfectionner afin d'avoir les commandes FastCOO. } interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses {$IFDEF FPC} Lresources, {$ELSE} {$ENDIF} Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, util1,Dgraphic,dtf0,visu0, BMex1,cood0, Menus, debug0; type TDispFrame = class(TFrame) PaintBox1: TPaintBox; PopupMenu1: TPopupMenu; Coordinates1: TMenuItem; ColorDialog1: TColorDialog; Backgroundcolor1: TMenuItem; procedure PaintBox1Paint(Sender: TObject); procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Coordinates1Click(Sender: TObject); procedure Backgroundcolor1Click(Sender: TObject); private { Déclarations privées } BMfen:TbitmapEx; Fvalid:boolean; visu0:^TvisuInfo; procedure resizeBM; procedure BMpaint(forcer:boolean); procedure DrawBM; procedure cadrerX(sender:Tobject); procedure cadrerY(sender:Tobject); procedure initVisu0; procedure doneVisu0; public { Déclarations publiques } data:typedataB; visu:TvisuInfo; color0:integer; constructor create(Aowner:Tcomponent);override; destructor destroy;override; procedure InstallArray(p:pointer;tp:typetypeG;n1,n2:integer); procedure invalidate;override; function Coo:boolean; end; implementation {$IFNDEF FPC} {$R *.DFM} {$ENDIF} { TDispFrame } constructor TDispFrame.create(Aowner:Tcomponent); begin inherited create(Aowner); BMfen:=TbitmapEx.create; visu.init; color0:=clWhite; end; destructor TDispFrame.destroy; begin BMfen.free; visu.done; inherited; end; procedure TDispFrame.resizeBM; begin if (BMfen.width<>paintbox1.width) or (BMfen.height<>paintbox1.height) then begin BMfen.width:=paintbox1.width; BMfen.height:=paintbox1.height; Fvalid:=false; end; end; procedure TDispFrame.DrawBM; begin paintbox1.canvas.draw(0,0,BMfen); end; procedure TDispFrame.BMpaint(forcer: boolean); begin if not assigned(data) then exit; if not Fvalid or forcer then with BMfen do begin initGraphic(canvas,0,0,width,height); clearWindow(color0); visu.displayTrace(data,nil,0); doneGraphic; end; end; procedure TDispFrame.InstallArray(p: pointer; tp: typetypeG; n1,n2: integer); begin data.free; data:=nil; case tp of G_smallint: data:=typedataI.create(p,1,n1,n1,n2); G_longint: data:=typedataL.create(p,1,n1,n1,n2); G_single: data:=typedataS.create(p,1,n1,n1,n2); G_extended:data:=typedataE.create(p,1,n1,n1,n2); end; Fvalid:=false; end; procedure TDispFrame.PaintBox1Paint(Sender: TObject); begin resizeBM; BMpaint(false); DrawBM; Fvalid:=true; end; procedure TDispFrame.invalidate; begin Fvalid:=false; invalidateRect(handle,nil,false); {le invalidate de Delphi doit appeler invalidateRect(handle,nil,true), ce qui efface d'abord la fenêtre avant de réafficher } end; procedure TDispFrame.cadrerX(sender:Tobject); begin visu0^.cadrerX(data); end; procedure TDispFrame.cadrerY(sender:Tobject); begin visu0^.cadrerY(data); end; procedure TDispFrame.initVisu0; begin new(visu0); visu0^.init; visu0^.assign(visu); end; procedure TDispFrame.doneVisu0; begin visu0^.done; dispose(visu0); visu0:=nil; end; function TDispFrame.coo:boolean; var chg:boolean; title0:AnsiString; begin InitVisu0; title0:=''; if cood.choose(title0,visu0^,cadrerX,cadrerY) then begin chg:= not visu.compare(visu0^); visu.assign(visu0^); end else chg:=false; DoneVisu0; result:=chg; if result then invalidate; end; procedure TDispFrame.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var p:Tpoint; begin p:=paintBox1.clientToScreen(point(x,y)); if button=mbRight then popupMenu1.popup(p.x,p.y); end; procedure TDispFrame.Coordinates1Click(Sender: TObject); begin coo; end; procedure TDispFrame.Backgroundcolor1Click(Sender: TObject); begin ColorDialog1.Color:=color0; if ColorDialog1.execute then begin color0:=ColorDialog1.Color; invalidate; end; end; Initialization AffDebug('Initialization DisplayFrame1',0); {$IFDEF FPC} {$I DisplayFrame1.lrs} {$ENDIF} end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Base classes } unit VXS.BaseClasses; interface uses System.Classes, System.SysUtils, VXS.Strings, VXS.PersistentClasses; type TVXProgressTimes = record deltaTime, newTime: Double end; { Progression event for time-base animations/simulations. deltaTime is the time delta since last progress and newTime is the new time after the progress event is completed. } TVXProgressEvent = procedure(Sender: TObject; const deltaTime, newTime: Double) of object; IVXNotifyAble = interface(IInterface) ['{00079A6C-D46E-4126-86EE-F9E2951B4593}'] procedure NotifyChange(Sender: TObject); end; IVXProgessAble = interface(IInterface) ['{95E44548-B0FE-4607-98D0-CA51169AF8B5}'] procedure DoProgress(const progressTime: TVXProgressTimes); end; { An abstract class describing the "update" interface. } TVXUpdateAbleObject = class(TVXInterfacedPersistent, IVXNotifyAble) private FOwner: TPersistent; FUpdating: Integer; FOnNotifyChange: TNotifyEvent; protected function GetOwner: TPersistent; override; final; public constructor Create(AOwner: TPersistent); virtual; procedure NotifyChange(Sender: TObject); virtual; procedure Notification(Sender: TObject; Operation: TOperation); virtual; property Updating: Integer read FUpdating; procedure BeginUpdate; procedure EndUpdate; property Owner: TPersistent read FOwner; property OnNotifyChange: TNotifyEvent read FOnNotifyChange write FOnNotifyChange; end; { A base class describing the "cadenceing" interface. } TVXCadenceAbleComponent = class(TComponent, IVXProgessAble) public procedure DoProgress(const progressTime: TVXProgressTimes); virtual; end; { A base class describing the "update" interface. } TVXUpdateAbleComponent = class(TVXCadenceAbleComponent, IVXNotifyAble) public procedure NotifyChange(Sender: TObject); virtual; end; TVXNotifyCollection = class(TOwnedCollection) strict private FOnNotifyChange: TNotifyEvent; strict protected procedure Update(item: TCollectionItem); override; public constructor Create(AOwner: TPersistent; AItemClass: TCollectionItemClass); property OnNotifyChange: TNotifyEvent read FOnNotifyChange write FOnNotifyChange; end; //------------------------------------------------------------------------- implementation //------------------------------------------------------------------------- //---------------------- TVXUpdateAbleObject ----------------------------------------- constructor TVXUpdateAbleObject.Create(AOwner: TPersistent); begin inherited Create; FOwner := AOwner; end; procedure TVXUpdateAbleObject.NotifyChange(Sender: TObject); begin if FUpdating = 0 then begin if Assigned(Owner) then begin if Owner is TVXUpdateAbleObject then TVXUpdateAbleObject(Owner).NotifyChange(Self) else if Owner is TVXUpdateAbleComponent then TVXUpdateAbleComponent(Owner).NotifyChange(Self); end; if Assigned(FOnNotifyChange) then FOnNotifyChange(Self); end; end; procedure TVXUpdateAbleObject.Notification(Sender: TObject; Operation: TOperation); begin end; function TVXUpdateAbleObject.GetOwner: TPersistent; begin Result := FOwner; end; procedure TVXUpdateAbleObject.BeginUpdate; begin Inc(FUpdating); end; procedure TVXUpdateAbleObject.EndUpdate; begin Dec(FUpdating); if FUpdating <= 0 then begin Assert(FUpdating = 0); NotifyChange(Self); end; end; // ------------------ // ------------------ TVXCadenceAbleComponent ------------------ // ------------------ procedure TVXCadenceAbleComponent.DoProgress(const progressTime: TVXProgressTimes); begin // nothing end; // ------------------ // ------------------ TVXUpdateAbleObject ------------------ // ------------------ procedure TVXUpdateAbleComponent.NotifyChange(Sender: TObject); begin if Assigned(Owner) then if (Owner is TVXUpdateAbleComponent) then (Owner as TVXUpdateAbleComponent).NotifyChange(Self); end; // ------------------ // ------------------ TVXNotifyCollection ------------------ // ------------------ constructor TVXNotifyCollection.Create(AOwner: TPersistent; AItemClass: TCollectionItemClass); begin inherited Create(AOwner, AItemClass); if Assigned(AOwner) and (AOwner is TVXUpdateAbleComponent) then OnNotifyChange := TVXUpdateAbleComponent(AOwner).NotifyChange; end; procedure TVXNotifyCollection.Update(Item: TCollectionItem); begin inherited; if Assigned(FOnNotifyChange) then FOnNotifyChange(Self); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFSE_CABECALHO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfseCabecalhoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, NFSeDetalheVO, NFSeIntermediarioVO; type TNfseCabecalhoVO = class(TVO) private FID: Integer; FID_OS_ABERTURA: Integer; FID_CLIENTE: Integer; FID_EMPRESA: Integer; FNUMERO: String; FCODIGO_VERIFICACAO: String; FDATA_HORA_EMISSAO: TDateTime; FCOMPETENCIA: String; FNUMERO_SUBSTITUIDA: String; FNATUREZA_OPERACAO: Integer; FREGIME_ESPECIAL_TRIBUTACAO: Integer; FOPTANTE_SIMPLES_NACIONAL: String; FINCENTIVADOR_CULTURAL: String; FNUMERO_RPS: String; FSERIE_RPS: String; FTIPO_RPS: Integer; FDATA_EMISSAO_RPS: TDateTime; FOUTRAS_INFORMACOES: String; FCODIGO_OBRA: String; FNUMERO_ART: String; //Transientes FListaNFSeDetalheVO: TListaNFSeDetalheVO; FListaNFSeIntermediarioVO: TListaNFSeIntermediarioVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdOsAbertura: Integer read FID_OS_ABERTURA write FID_OS_ABERTURA; property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property Numero: String read FNUMERO write FNUMERO; property CodigoVerificacao: String read FCODIGO_VERIFICACAO write FCODIGO_VERIFICACAO; property DataHoraEmissao: TDateTime read FDATA_HORA_EMISSAO write FDATA_HORA_EMISSAO; property Competencia: String read FCOMPETENCIA write FCOMPETENCIA; property NumeroSubstituida: String read FNUMERO_SUBSTITUIDA write FNUMERO_SUBSTITUIDA; property NaturezaOperacao: Integer read FNATUREZA_OPERACAO write FNATUREZA_OPERACAO; property RegimeEspecialTributacao: Integer read FREGIME_ESPECIAL_TRIBUTACAO write FREGIME_ESPECIAL_TRIBUTACAO; property OptanteSimplesNacional: String read FOPTANTE_SIMPLES_NACIONAL write FOPTANTE_SIMPLES_NACIONAL; property IncentivadorCultural: String read FINCENTIVADOR_CULTURAL write FINCENTIVADOR_CULTURAL; property NumeroRps: String read FNUMERO_RPS write FNUMERO_RPS; property SerieRps: String read FSERIE_RPS write FSERIE_RPS; property TipoRps: Integer read FTIPO_RPS write FTIPO_RPS; property DataEmissaoRps: TDateTime read FDATA_EMISSAO_RPS write FDATA_EMISSAO_RPS; property OutrasInformacoes: String read FOUTRAS_INFORMACOES write FOUTRAS_INFORMACOES; property CodigoObra: String read FCODIGO_OBRA write FCODIGO_OBRA; property NumeroArt: String read FNUMERO_ART write FNUMERO_ART; //Transientes property ListaNFSeDetalheVO: TListaNFSeDetalheVO read FListaNfseDetalheVO write FListaNfseDetalheVO; //Transientes property ListaNFSeIntermediarioVO: TListaNFSeIntermediarioVO read FListaNFSeIntermediarioVO write FListaNFSeIntermediarioVO; end; TListaNfseCabecalhoVO = specialize TFPGObjectList<TNfseCabecalhoVO>; implementation constructor TNfseCabecalhoVO.Create; begin inherited; FListaNfseDetalheVO := TListaNFSeDetalheVO.Create; FListaNFSeIntermediarioVO := TListaNFSeIntermediarioVO.Create; end; destructor TNfseCabecalhoVO.Destroy; begin FreeAndNil(FListaNfseDetalheVO); FreeAndNil(FListaNFSeIntermediarioVO); inherited; end; initialization Classes.RegisterClass(TNfseCabecalhoVO); finalization Classes.UnRegisterClass(TNfseCabecalhoVO); end.
unit uTEFTypes; interface type TVinculadoInfo = class CupomVinculado: String; FormaPagamento: String; IDMeioPag: Integer; ValorAprovado: Currency; NumeroParcelas : Integer; PreDatado: TDateTime; PreDatadoComGarantia : Boolean; end; TTEFCallInfo = class PostDate : Boolean; IsMagnetico : Boolean; UsaCDC : Boolean; UsaPreAutorizacao : Boolean; Bandeira : Integer; TipoTEF : Integer; end; TTEFDialMessageType = (mtOperador, mtCliente, mtPendencia, mtAtividade, mtInatividade); TTEFPrintEvent = procedure(Sender: TObject; var Printed: Boolean) of object; TTEFDialMessageEvent = procedure(Sender: TObject; MessageType: TTEFDialMessageType = mtOperador; NeedUserOK: Boolean = True) of object; TTEFNeedOpenPrintVinculado = procedure(Sender: TObject; AVinculadoInfo: TVinculadoInfo; var Opened: Boolean) of object; TTEFNeedOpenPrint = procedure(Sender: TObject; var Opened: Boolean) of object; TTEFNeedClosePrint = procedure(Sender: TObject; var Closed: Boolean) of object; TTEFNeedPrintLine = procedure(Sender: TObject; LineToPrint: String; var LinePrinted: Boolean) of object; TTEFTryAgainDialog = procedure(Sender: TObject; var TryAgain: Boolean) of object; TTEFStatusPrinter = procedure(Sender: TObject; var Online: Boolean) of object; TTEFPerguntaCupom = procedure(Sender: TObject; var TemCupom: Boolean) of object; TExecutaComandoMsg = procedure(Sender: TObject; Msg: String) of Object; TExecutaComando = procedure(Sender: TObject) of Object; implementation end.
unit uPrintInventory; // QuickReport simple list // - Connect a datasource to the QuickReport component // - Put QRDBText components on the Detail band interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, DB, DBTables, quickrpt, Qrctrls; type TInventoryReport = class(TForm) Report: TQuickRep; Title: TQRBand; PageHeader: TQRBand; Detail: TQRBand; PageNumber: TQRSysData; PageFooter: TQRBand; QRDateTime: TQRSysData; QRSysData1: TQRSysData; dsInventory: TDataSource; quInventory: TQuery; quInventoryIDModel: TIntegerField; quInventoryModel: TStringField; quInventoryDescription: TStringField; quInventoryCurrentCost: TFloatField; quInventorySellingPrice: TFloatField; quInventoryMarkUp: TFloatField; quInventoryVendorCost: TFloatField; quInventoryOtherCost: TFloatField; quInventoryWeight: TFloatField; quInventoryGroupName: TStringField; quInventoryQtyOnHold: TIntegerField; quInventoryQtyOnHand: TIntegerField; quInventoryQtyOnOrder: TIntegerField; QRDBText2: TQRDBText; QRDBText3: TQRDBText; QRDBText4: TQRDBText; QRDBText6: TQRDBText; QRDBText5: TQRDBText; QRDBText7: TQRDBText; QRDBText8: TQRDBText; QRDBText9: TQRDBText; QRLabel4: TQRLabel; QRLabel2: TQRLabel; QRLabel5: TQRLabel; QRLabel6: TQRLabel; QRLabel7: TQRLabel; QRLabel8: TQRLabel; QRLabel1: TQRLabel; QRLabel10: TQRLabel; private { Private declarations } public { Public declarations } end; implementation {$R *.DFM} end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: HDRFormatsUnit.pas,v 1.13 2007/02/05 22:21:07 clootie Exp $ *----------------------------------------------------------------------------*) //----------------------------------------------------------------------------- // File: HDRFormats.cpp // // Desc: This sample shows how to do a single pass motion blur effect using // floating point textures and multiple render targets. // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- {$I DirectX.inc} unit HDRFormatsUnit; interface uses Windows, Messages, SysUtils, Math, DXTypes, Direct3D9, D3DX9, DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTmesh, DXUTSettingsDlg, Skybox; const NUM_TONEMAP_TEXTURES = 5; // Number of stages in the 3x3 down-scaling // of average luminance textures NUM_BLOOM_TEXTURES = 2; RGB16_MAX = 100; type TEncodingMode = (FP16, FP32, RGB16, RGBE8); // , NUM_ENCODING_MODES); TRenderMode = (DECODED, RGB_ENCODED, ALPHA_ENCODED); // , NUM_RENDER_MODES); PTechHandles = ^TTechHandles; TTechHandles = record Scene: TD3DXHandle; DownScale2x2_Lum: TD3DXHandle; DownScale3x3: TD3DXHandle; DownScale3x3_BrightPass: TD3DXHandle; FinalPass: TD3DXHandle; end; TScreenVertex = packed record pos: TD3DXVector4; tex: TD3DXVector2; end; const TScreenVertex_FVF = D3DFVF_XYZRHW or D3DFVF_TEX1; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_pd3dDevice: IDirect3DDevice9; // Direct3D device g_pFont: ID3DXFont; // Font for drawing text g_Camera: CModelViewerCamera; g_pEffect: ID3DXEffect; g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog g_HUD: CDXUTDialog; // manages the 3D UI g_SampleUI: CDXUTDialog; // Sample specific controls g_aSkybox: array[TEncodingMode] of CSkybox; g_pMSRT: IDirect3DSurface9; // Multi-Sample float render target g_pMSDS: IDirect3DSurface9; // Depth Stencil surface for the float RT g_pTexRender: IDirect3DTexture9; // Render target texture g_pTexBrightPass: IDirect3DTexture9; // Bright pass filter g_pMesh: ID3DXMesh; g_apTexToneMap: array[0..NUM_TONEMAP_TEXTURES-1] of IDirect3DTexture9; // Tone mapping calculation textures g_apTexBloom: array[0..NUM_BLOOM_TEXTURES-1] of IDirect3DTexture9; // Blooming effect intermediate texture g_bBloom: Boolean; // Bloom effect on/off g_eEncodingMode: TEncodingMode; g_eRenderMode: TRenderMode; g_aTechHandles: array[TEncodingMode] of TTechHandles; g_pCurTechnique: PTechHandles; g_bShowHelp: Boolean; g_bShowText: Boolean; g_aPowsOfTwo: array[0..256] of Double; // Lookup table for log calculations g_bSupportsR16F: Boolean = False; g_bSupportsR32F: Boolean = False; g_bSupportsD16: Boolean = False; g_bSupportsD32: Boolean = False; g_bSupportsD24X8: Boolean = False; g_bUseMultiSample: Boolean = False; // True when using multisampling on a supported back buffer g_MaxMultiSampleType: TD3DMultiSampleType = D3DMULTISAMPLE_NONE; // Non-Zero when g_bUseMultiSample is true g_dwMultiSampleQuality: DWORD = 0; // Used when we have multisampling on a backbuffer //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- const IDC_STATIC = -1; IDC_TOGGLEFULLSCREEN = 1; IDC_TOGGLEREF = 3; IDC_CHANGEDEVICE = 4; IDC_ENCODING_MODE = 5; IDC_RENDER_MODE = 6; IDC_BLOOM = 7; //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; procedure OnLostDevice(pUserContext: Pointer); stdcall; procedure OnDestroyDevice(pUserContext: Pointer); stdcall; procedure InitApp; //todo: report bug report to MS //function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT; overload; function LoadMesh(strFileName: WideString; out ppMesh: ID3DXMesh): HRESULT; overload; procedure RenderText(fTime: Double); procedure DrawFullScreenQuad(fLeftU: Single = 0.0; fTopV: Single = 0.0; fRightU: Single = 1.0; fBottomV: Single = 1.0); function RenderModel: HRESULT; function RetrieveTechHandles: HRESULT; function GetSampleOffsets_DownScale3x3(dwWidth, dwHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; function GetSampleOffsets_DownScale2x2_Lum(dwSrcWidth, dwSrcHeight, dwDestWidth, dwDestHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; function GetSampleOffsets_Bloom(dwD3DTexSize: DWORD; var afTexCoordOffset: array of Single; var avColorWeight: array of TD3DXVector4; fDeviation: Single; fMultiplier: Single = 1.0): HRESULT; function RenderBloom: HRESULT; function MeasureLuminance: HRESULT; function BrightPassFilter: HRESULT; function CreateEncodedTexture(const pTexSrc: IDirect3DCubeTexture9; out ppTexDest: IDirect3DCubeTexture9; eTarget: TEncodingMode): HRESULT; procedure CreateCustomDXUTobjects; procedure DestroyCustomDXUTobjects; implementation //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- procedure InitApp; const RENDER_MODE_NAMES: array[TRenderMode] of PWideChar = ( 'Decoded scene', 'RGB channels', 'Alpha channel' ); var i: Integer; iY: Integer; pElement: CDXUTElement; pComboBox: CDXUTComboBox; rm: TRenderMode; pMultiSampleTypeList: TD3DMultiSampleTypeArray; begin g_pFont := nil; g_pEffect := nil; g_bShowHelp := False; g_bShowText := True; g_pMesh := nil; g_pTexRender := nil; g_bBloom := True; g_eEncodingMode := RGBE8; g_eRenderMode := DECODED; g_pCurTechnique := @g_aTechHandles[g_eEncodingMode]; for i := 0 to 255 do g_aPowsOfTwo[i] := Power(2.0, (i - 128)); ZeroMemory(@g_apTexToneMap, SizeOf(g_apTexToneMap)); ZeroMemory(@g_apTexBloom, SizeOf(g_apTexBloom)); ZeroMemory(@g_aTechHandles, SizeOf(g_aTechHandles)); // Initialize dialogs g_SettingsDlg.Init(g_DialogResourceManager); g_HUD.Init(g_DialogResourceManager); g_SampleUI.Init(g_DialogResourceManager); g_HUD.SetFont(0, 'Arial', 14, 400); g_HUD.SetCallback(OnGUIEvent); iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); g_SampleUI.SetCallback(OnGUIEvent); // Title font for comboboxes g_SampleUI.SetFont(1, 'Arial', 14, FW_BOLD); pElement := g_SampleUI.GetDefaultElement(DXUT_CONTROL_STATIC, 0); if Assigned(pElement) then begin pElement.iFont := 1; pElement.dwTextFormat := DT_LEFT or DT_BOTTOM; end; pComboBox := nil; g_SampleUI.AddStatic(IDC_STATIC, '(E)ncoding mode', 0, 0, 105, 25); g_SampleUI.AddComboBox(IDC_ENCODING_MODE, 0, 25, 140, 24, Ord('E'), False, @pComboBox); if Assigned(pComboBox) then pComboBox.SetDropHeight(50); g_SampleUI.AddStatic(IDC_STATIC, '(R)ender mode', 0, 45, 105, 25 ); g_SampleUI.AddComboBox(IDC_RENDER_MODE, 0, 70, 140, 24, Ord('R'), False, @pComboBox); if Assigned(pComboBox) then pComboBox.SetDropHeight(30); for rm := Low(TRenderMode) to High(TRenderMode) do pComboBox.AddItem(RENDER_MODE_NAMES[rm], {IntToPtr}Pointer(rm)); g_SampleUI.AddCheckBox(IDC_BLOOM, 'Show (B)loom', 0, 110, 140, 18, g_bBloom, Ord('B')); // Although multisampling is supported for render target surfaces, those surfaces // exist without a parent texture, and must therefore be copied to a texture // surface if they're to be used as a source texture. This sample relies upon // several render targets being used as source textures, and therefore it makes // sense to disable multisampling altogether. // pMultiSampleTypeList.Add(D3DMULTISAMPLE_NONE); SetLength(pMultiSampleTypeList, 1); pMultiSampleTypeList[0]:= D3DMULTISAMPLE_NONE; DXUTGetEnumeration.PossibleMultisampleTypeList:= pMultiSampleTypeList; DXUTGetEnumeration.SetMultisampleQualityMax(0); end; //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning E_FAIL. //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; var pD3D: IDirect3D9; begin Result:= False; // No fallback, so need ps2.0 if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit; // Skip backbuffer formats that don't support alpha blending pD3D := DXUTGetD3DObject; if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- {static} var s_bFirstTime: Boolean = True; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; begin // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or (pCaps.VertexShaderVersion < D3DVS_VERSION(1,1)) then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. {$IFDEF DEBUG_VS} if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then with pDeviceSettings do begin BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING; BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE; BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING; end; {$ENDIF} {$IFDEF DEBUG_PS} pDeviceSettings.DeviceType := D3DDEVTYPE_REF; {$ENDIF} // For the first device created if its a REF device, optionally display a warning dialog box if s_bFirstTime then begin s_bFirstTime := False; if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning; end; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var str: array[0..MAX_PATH-1] of WideChar; strPath: array [0..MAX_PATH-1] of WideChar; vecEye, vecAt: TD3DXVector3; dwShaderFlags: DWORD; pD3D: IDirect3D9; settings: TDXUTDeviceSettings; //bCreatedTexture: Boolean; pCubeTexture: IDirect3DCubeTexture9; pEncodedTexture: IDirect3DCubeTexture9; bSupports128FCube: Boolean; begin Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; // Initialize the font Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFont); if V_Failed(Result) then Exit; g_pd3dDevice := pd3dDevice; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; {$ENDIF} Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, 'HDRFormats.fx'); if FAILED(Result) then Exit; Result := D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil); // If this fails, there should be debug output if FAILED(Result) then Exit; RetrieveTechHandles; // Determine which encoding modes this device can support pD3D := DXUTGetD3DObject; settings := DXUTGetDeviceSettings; //bCreatedTexture := False; Result:= DXUTFindDXSDKMediaFile(strPath, MAX_PATH, 'Light Probes\uffizi_cross.dds'); if V_Failed(Result) then Exit; g_SampleUI.GetComboBox(IDC_ENCODING_MODE).RemoveAllItems; g_bSupportsR16F := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R16F)) then g_bSupportsR16F := True; g_bSupportsR32F := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R32F)) then g_bSupportsR32F := True; bSupports128FCube := false; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, 0, D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F)) then bSupports128FCube := True; // FP16 if (g_bSupportsR16F and bSupports128FCube) then begin // Device supports floating-point textures. Result:= D3DXCreateCubeTextureFromFileExW(pd3dDevice, strPath, D3DX_DEFAULT, 1, 0, D3DFMT_A16B16G16R16F, D3DPOOL_MANAGED, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, nil, nil, pCubeTexture); if V_Failed(Result) then Exit; Result:= g_aSkybox[FP16].OnCreateDevice(pd3dDevice, 50, pCubeTexture, 'skybox.fx'); if V_Failed(Result) then Exit; g_SampleUI.GetComboBox(IDC_ENCODING_MODE).AddItem('FP16', Pointer(FP16)); end; // FP32 if (g_bSupportsR32F and bSupports128FCube) then begin // Device supports floating-point textures. Result:= D3DXCreateCubeTextureFromFileExW(pd3dDevice, strPath, D3DX_DEFAULT, 1, 0, D3DFMT_A16B16G16R16F, D3DPOOL_MANAGED, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, nil, nil, pCubeTexture); if V_Failed(Result) then Exit; Result:= g_aSkybox[FP32].OnCreateDevice(pd3dDevice, 50, pCubeTexture, 'skybox.fx'); if V_Failed(Result) then Exit; g_SampleUI.GetComboBox(IDC_ENCODING_MODE).AddItem('FP32', Pointer(FP32)); end; if ((not g_bSupportsR32F and not g_bSupportsR16F) or not bSupports128FCube) then begin // Device doesn't support floating-point textures. Use the scratch pool to load it temporarily // in order to create encoded textures from it. //bCreatedTexture := True; Result:= D3DXCreateCubeTextureFromFileExW(pd3dDevice, strPath, D3DX_DEFAULT, 1, 0, D3DFMT_A16B16G16R16F, D3DPOOL_SCRATCH, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, nil, nil, pCubeTexture); if V_Failed(Result) then Exit; end; // RGB16 if (D3D_OK = pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, 0, D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16)) then begin Result:= CreateEncodedTexture(pCubeTexture, pEncodedTexture, RGB16); if V_Failed(Result) then Exit; Result:= g_aSkybox[RGB16].OnCreateDevice(pd3dDevice, 50, pEncodedTexture, 'skybox.fx'); if V_Failed(Result) then Exit; g_SampleUI.GetComboBox(IDC_ENCODING_MODE).AddItem('RGB16', Pointer(RGB16)); end; // RGBE8 Result:= CreateEncodedTexture(pCubeTexture, pEncodedTexture, RGBE8); if V_Failed(Result) then Exit; Result:= g_aSkybox[RGBE8].OnCreateDevice(pd3dDevice, 50, pEncodedTexture, 'skybox.fx'); if V_Failed(Result) then Exit; g_SampleUI.GetComboBox(IDC_ENCODING_MODE).AddItem('RGBE8', Pointer(RGBE8)); g_SampleUI.GetComboBox(IDC_ENCODING_MODE).SetSelectedByText('RGBE8'); //Clootie: not needed in Delphi // if bCreatedTexture then pCubeTexture:= nil; Result := LoadMesh('misc\teapot.x', g_pMesh); if Failed(Result) then Exit; vecEye := D3DXVector3(0.0, 0.0, -5.0); vecAt := D3DXVector3(0.0, 0.0, 0.0); g_Camera.SetViewParams(vecEye, vecAt); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var fAspectRatio: Single; i: TEncodingMode; fmt: TD3DFormat; nSampleLen: Integer; t: Integer; pCheckBox: CDXUTCheckBox; pComboBox: CDXUTComboBox; pD3D: IDirect3D9; settings: TDXUTDeviceSettings; dfmt: TD3DFormat; Caps: TD3DCaps9; imst: TD3DMultiSampleType; msQuality: DWORD; pBackBufferDesc: PD3DSurfaceDesc; begin Result:= g_DialogResourceManager.OnResetDevice; if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnResetDevice; if V_Failed(Result) then Exit; Result := S_OK; if (pd3dDevice = nil) then Exit; for i:= Low(i) to High(i) do g_aSkybox[i].OnResetDevice(pBackBufferSurfaceDesc); if Assigned(g_pFont) then g_pFont.OnResetDevice; if Assigned(g_pEffect) then g_pEffect.OnResetDevice; fmt := D3DFMT_UNKNOWN; case g_eEncodingMode of FP16: fmt := D3DFMT_A16B16G16R16F; FP32: fmt := D3DFMT_A16B16G16R16F; RGBE8: fmt := D3DFMT_A8R8G8B8; RGB16: fmt := D3DFMT_A16B16G16R16; end; Result := pd3dDevice.CreateTexture(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height, 1, D3DUSAGE_RENDERTARGET, fmt, D3DPOOL_DEFAULT, g_pTexRender, nil); if Failed(Result) then Exit; Result := pd3dDevice.CreateTexture(pBackBufferSurfaceDesc.Width div 8, pBackBufferSurfaceDesc.Height div 8, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_pTexBrightPass, nil); if Failed(Result) then Exit; // Determine whether we can and should support a multisampling on the HDR render target g_bUseMultiSample := False; pD3D := DXUTGetD3DObject; if not Assigned(pD3D) then begin Result:= E_FAIL; Exit; end; settings := DXUTGetDeviceSettings; g_bSupportsD16 := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D16)) then begin if SUCCEEDED(pD3D.CheckDepthStencilMatch(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, fmt, D3DFMT_D16)) then begin g_bSupportsD16 := True; end; end; g_bSupportsD32 := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D32)) then begin if SUCCEEDED(pD3D.CheckDepthStencilMatch(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, fmt, D3DFMT_D32)) then begin g_bSupportsD32 := True; end; end; g_bSupportsD24X8 := False; if SUCCEEDED(pD3D.CheckDeviceFormat(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D24X8)) then begin if SUCCEEDED(pD3D.CheckDepthStencilMatch(settings.AdapterOrdinal, settings.DeviceType, settings.AdapterFormat, fmt, D3DFMT_D24X8)) then begin g_bSupportsD24X8 := True; end; end; dfmt := D3DFMT_UNKNOWN; if g_bSupportsD16 then dfmt := D3DFMT_D16 else if g_bSupportsD32 then dfmt := D3DFMT_D32 else if g_bSupportsD24X8 then dfmt := D3DFMT_D24X8; if (dfmt <> D3DFMT_UNKNOWN) then begin pd3dDevice.GetDeviceCaps(Caps); g_MaxMultiSampleType := D3DMULTISAMPLE_NONE; for imst := D3DMULTISAMPLE_2_SAMPLES to D3DMULTISAMPLE_16_SAMPLES do begin msQuality := 0; if SUCCEEDED(pD3D.CheckDeviceMultiSampleType(Caps.AdapterOrdinal, Caps.DeviceType, fmt, settings.pp.Windowed, imst, @msQuality)) then begin g_bUseMultiSample := True; g_MaxMultiSampleType := imst; if (msQuality > 0) then g_dwMultiSampleQuality := msQuality-1 else g_dwMultiSampleQuality := msQuality; end; end; // Create the Multi-Sample floating point render target if g_bUseMultiSample then begin pBackBufferDesc := DXUTGetBackBufferSurfaceDesc; Result := g_pd3dDevice.CreateRenderTarget(pBackBufferDesc.Width, pBackBufferDesc.Height, fmt, g_MaxMultiSampleType, g_dwMultiSampleQuality, False, g_pMSRT, nil); if FAILED(Result) then g_bUseMultiSample := False else begin Result := g_pd3dDevice.CreateDepthStencilSurface(pBackBufferDesc.Width, pBackBufferDesc.Height, dfmt, g_MaxMultiSampleType, g_dwMultiSampleQuality, True, g_pMSDS, nil); if FAILED(Result) then begin g_bUseMultiSample := False; SAFE_RELEASE(g_pMSRT); end; end; end; end; // For each scale stage, create a texture to hold the intermediate results // of the luminance calculation nSampleLen := 1; for t := 0 to NUM_TONEMAP_TEXTURES - 1 do begin fmt := D3DFMT_UNKNOWN; case g_eEncodingMode of FP16: fmt := D3DFMT_R16F; FP32: fmt := D3DFMT_R32F; RGBE8: fmt := D3DFMT_A8R8G8B8; RGB16: fmt := D3DFMT_A16B16G16R16; end; Result := pd3dDevice.CreateTexture(nSampleLen, nSampleLen, 1, D3DUSAGE_RENDERTARGET, fmt, D3DPOOL_DEFAULT, g_apTexToneMap[t], nil); if Failed(Result) then Exit; nSampleLen := nSampleLen * 3; end; // Create the temporary blooming effect textures for t := 0 to NUM_BLOOM_TEXTURES - 1 do begin Result := pd3dDevice.CreateTexture(pBackBufferSurfaceDesc.Width div 8, pBackBufferSurfaceDesc.Height div 8, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_apTexBloom[t], nil); if Failed(Result) then Exit; end; g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0); g_HUD.SetSize(170, 170); g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width - 150, pBackBufferSurfaceDesc.Height - 150); g_SampleUI.SetSize(150, 110); pCheckBox := g_SampleUI.GetCheckBox(IDC_BLOOM); pCheckBox.Checked := g_bBloom; pComboBox := g_SampleUI.GetComboBox(IDC_ENCODING_MODE); pComboBox.SetSelectedByData(Pointer(g_eEncodingMode)); pComboBox := g_SampleUI.GetComboBox(IDC_RENDER_MODE); pComboBox.SetSelectedByData(Pointer(g_eRenderMode)); // Setup the camera's projection parameters fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height; g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 5000.0); g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; begin // Update the camera's position based on user input g_Camera.FrameMove(fElapsedTime); g_pEffect.SetValue('g_vEyePt', g_Camera.GetEyePt, SizeOf(TD3DXVector3)); end; //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var pSurfBackBuffer: IDirect3DSurface9; pSurfDS: IDirect3DSurface9; pSurfRenderTarget: IDirect3DSurface9; mWorldViewProj: TD3DXMatrixA16; iPass: Integer; uiNumPasses: LongWord; begin // If the settings dialog is being shown, then // render it instead of rendering the app's scene if g_SettingsDlg.Active then begin g_SettingsDlg.OnRender(fElapsedTime); Exit; end; pd3dDevice.GetRenderTarget(0, pSurfBackBuffer); pd3dDevice.GetDepthStencilSurface(pSurfDS); g_pTexRender.GetSurfaceLevel(0, pSurfRenderTarget); // Setup the HDR render target if g_bUseMultiSample then begin pd3dDevice.SetRenderTarget(0, g_pMSRT); pd3dDevice.SetDepthStencilSurface( g_pMSDS); end else begin pd3dDevice.SetRenderTarget(0, pSurfRenderTarget); end; // Clear the render target pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, $000000FF, 1.0, 0); // Update matrices D3DXMatrixMultiply(mWorldViewProj, g_Camera.GetViewMatrix^, g_Camera.GetProjMatrix^); g_pEffect.SetMatrix('g_mWorldViewProj', mWorldViewProj); // For the first pass we'll draw the screen to the full screen render target // and to update the velocity render target with the velocity of each pixel if SUCCEEDED(pd3dDevice.BeginScene) then begin // Draw the skybox g_aSkybox[g_eEncodingMode].Render(mWorldViewProj); RenderModel; // If using floating point multi sampling, stretchrect to the rendertarget if g_bUseMultiSample then begin pd3dDevice.StretchRect(g_pMSRT, nil, pSurfRenderTarget, nil, D3DTEXF_NONE); pd3dDevice.SetRenderTarget(0, pSurfRenderTarget); pd3dDevice.SetDepthStencilSurface(pSurfDS); pd3dDevice.Clear(0, nil, D3DCLEAR_ZBUFFER, 0, 1.0, 0); end; MeasureLuminance; BrightPassFilter; if g_bBloom then RenderBloom; //--------------------------------------------------------------------- // Final pass pd3dDevice.SetRenderTarget(0, pSurfBackBuffer); pd3dDevice.SetTexture(0, g_pTexRender); pd3dDevice.SetTexture(1, g_apTexToneMap[0]); if g_bBloom then pd3dDevice.SetTexture(2, g_apTexBloom[0]) else pd3dDevice.SetTexture(2, nil); pd3dDevice.SetSamplerState(2, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); pd3dDevice.SetSamplerState(2, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); case g_eRenderMode of DECODED: g_pEffect.SetTechnique(g_pCurTechnique.FinalPass); RGB_ENCODED: g_pEffect.SetTechnique('FinalPassEncoded_RGB'); ALPHA_ENCODED: g_pEffect.SetTechnique('FinalPassEncoded_A'); end; g_pEffect._Begin(@uiNumPasses, 0); for iPass:= 0 to uiNumPasses - 1 do begin g_pEffect.BeginPass(iPass); DrawFullScreenQuad; g_pEffect.EndPass; end; g_pEffect._End; pd3dDevice.SetTexture(0, nil); pd3dDevice.SetTexture(1, nil); pd3dDevice.SetTexture(2, nil); if g_bShowText then RenderText(fTime); g_HUD.OnRender(fElapsedTime); g_SampleUI.OnRender(fElapsedTime); pd3dDevice.EndScene; end; pSurfRenderTarget := nil; pSurfBackBuffer := nil; pSurfDS := nil; end; //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- procedure RenderText(fTime: Double); var txtHelper: CDXUTTextHelper; pd3dsdBackBuffer: PD3DSurfaceDesc; const ENCODING_MODE_NAMES: array[TEncodingMode] of PWideChar = ( '16-Bit floating-point (FP16)', '32-Bit floating-point (FP32)', '16-Bit integer (RGB16)', '8-Bit integer w/ shared exponent (RGBE8)' ); RENDER_MODE_NAMES: array[TRenderMode] of PWideChar = ( 'Decoded scene', 'RGB channels of encoded textures', 'Alpha channel of encoded textures' ); begin // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr ); // If NULL is passed in as the sprite object, then it will work fine however the // pFont->DrawText() will not be batched together. Batching calls will improves perf. // TODO: Add sprite txtHelper := CDXUTTextHelper.Create(g_pFont, nil, 15); // Output statistics txtHelper._Begin; txtHelper.SetInsertionPos(2, 0); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine(DXUTGetFrameStats); txtHelper.DrawTextLine(DXUTGetDeviceStats); txtHelper.SetForegroundColor(D3DXColor( 0.90, 0.90, 1.0, 1.0)); txtHelper.DrawFormattedTextLine(ENCODING_MODE_NAMES[g_eEncodingMode], []); txtHelper.DrawFormattedTextLine(RENDER_MODE_NAMES[g_eRenderMode], []); if g_bUseMultiSample then begin txtHelper.DrawTextLine('Using MultiSample Render Target'); txtHelper.DrawFormattedTextLine('Number of Samples: %d', [Integer(g_MaxMultiSampleType)]); txtHelper.DrawFormattedTextLine('Quality: %d', [g_dwMultiSampleQuality]); end; // Draw help if g_bShowHelp then begin pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; txtHelper.SetInsertionPos(2, pd3dsdBackBuffer.Height-15*6); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0)); txtHelper.DrawTextLine('Controls:'); txtHelper.SetInsertionPos(20, pd3dsdBackBuffer.Height-15*5); txtHelper.DrawTextLine('Rotate model: Left mouse button'#10 + 'Rotate camera: Right mouse button'#10 + 'Zoom camera: Mouse wheel scroll'#10 + 'Quit: ESC'); txtHelper.SetInsertionPos(250, pd3dsdBackBuffer.Height-15*5); txtHelper.DrawTextLine('Cycle encoding: E'#10 + 'Cycle render mode: R'#10 + 'Toggle bloom: B'#10 + 'Hide text: T'#10); txtHelper.SetInsertionPos(410, pd3dsdBackBuffer.Height-15*5); txtHelper.DrawTextLine('Hide help: F1'#10 + 'Change Device: F2'#10 + 'Toggle HAL/REF: F3'#10 + 'View readme: F9'#10); end else begin txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Press F1 for help'); end; txtHelper._End; txtHelper.Free; end; //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; begin Result:= 0; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; if g_SettingsDlg.IsActive then begin g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); Exit; end; // Give the dialogs a chance to handle the message first pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); end; //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; begin if bKeyDown then begin case nChar of VK_F1: g_bShowHelp := not g_bShowHelp; Ord('T'): g_bShowText := not g_bShowText; end; end; end; //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; var pComboBox: CDXUTComboBox; pCheckBox: CDXUTCheckBox; pBackBufDesc: PD3DSurfaceDesc; begin case nControlID of IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen; IDC_TOGGLEREF: DXUTToggleREF; IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active; IDC_BLOOM: g_bBloom := not g_bBloom; IDC_RENDER_MODE: begin pComboBox := CDXUTComboBox(pControl); g_eRenderMode := TRenderMode({PtrToInt}(pComboBox.GetSelectedData)); end; IDC_ENCODING_MODE: begin pComboBox := CDXUTComboBox(pControl); g_eEncodingMode := TEncodingMode({PtrToInt}(pComboBox.GetSelectedData)); g_pCurTechnique := @g_aTechHandles[ g_eEncodingMode ]; // Refresh resources pBackBufDesc := DXUTGetBackBufferSurfaceDesc; OnLostDevice(nil); OnResetDevice(g_pd3dDevice, pBackBufDesc^, nil); end; end; // Update the bloom checkbox based on new state pCheckBox := g_SampleUI.GetCheckBox(IDC_BLOOM); pCheckBox.Enabled := (g_eRenderMode = DECODED); pCheckBox.Checked := (g_eRenderMode = DECODED) and g_bBloom; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- procedure OnLostDevice; stdcall; var i: TEncodingMode; j: Integer; begin g_DialogResourceManager.OnLostDevice; g_SettingsDlg.OnLostDevice; for i:= Low(i) to High(i) do g_aSkybox[i].OnLostDevice; if Assigned(g_pFont) then g_pFont.OnLostDevice; if Assigned(g_pEffect) then g_pEffect.OnLostDevice; g_pMSRT := nil; g_pMSDS := nil; g_pTexRender := nil; g_pTexBrightPass := nil; for j:= 0 to NUM_TONEMAP_TEXTURES - 1 do g_apTexToneMap[j] := nil; for j:= 0 to NUM_BLOOM_TEXTURES - 1 do g_apTexBloom[j] := nil; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- procedure OnDestroyDevice; stdcall; var i: TEncodingMode; begin g_DialogResourceManager.OnDestroyDevice; g_SettingsDlg.OnDestroyDevice; for i:= Low(i) to High(i) do g_aSkybox[i].OnDestroyDevice; g_pFont := nil; g_pEffect := nil; g_pMesh := nil; g_pd3dDevice:= nil; end; //-------------------------------------------------------------------------------------- function GaussianDistribution(x, y, rho: Single): Single;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF} var g: Single; begin g := 1.0 / Sqrt(2.0 * D3DX_PI * rho * rho); g := g * Exp(-(x*x + y*y)/(2*rho*rho)); Result:= g; end; //-------------------------------------------------------------------------------------- function log2_ceiling(val: Single): Integer;{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF} var iMax, iMin, iMiddle: Integer; begin iMax := 256; iMin := 0; while (iMax - iMin > 1) do begin iMiddle := (iMax + iMin) div 2; if (val > g_aPowsOfTwo[iMiddle]) then iMin := iMiddle else iMax := iMiddle; end; Result:= iMax - 128; end; //-------------------------------------------------------------------------------------- procedure EncodeRGBE8(pSrc: PD3DXFloat16; out ppDest: PByte);{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF} var r, g, b: Single; maxComponent: Single; nExp: Integer; fDivisor: Single; pDestColor: PD3DColor; begin r := D3DXFloat16ToFloat((pSrc{+0})^); g := D3DXFloat16ToFloat(PD3DXFloat16(PWideChar(pSrc)+1)^); b := D3DXFloat16ToFloat(PD3DXFloat16(PWideChar(pSrc)+2)^); // Determine the largest color component maxComponent := max(max(r, g), b); // Round to the nearest integer exponent nExp := log2_ceiling(maxComponent); // Divide the components by the shared exponent fDivisor := g_aPowsOfTwo[ nExp+128 ]; r := r / fDivisor; g := g / fDivisor; b := b / fDivisor; // Constrain the color components r := max(0, min(1, r)); g := max(0, min(1, g)); b := max(0, min(1, b)); // Store the shared exponent in the alpha channel pDestColor := PD3DColor(ppDest); pDestColor^ := D3DCOLOR_RGBA(Trunc(r*255), Trunc(g*255), Trunc(b*255), nExp+128); Inc(ppDest, SizeOf(TD3DColor)); end; //-------------------------------------------------------------------------------------- procedure EncodeRGB16(pSrc: PD3DXFloat16; out ppDest: PByte);{$IFDEF SUPPORTS_INLINE} inline;{$ENDIF} var r, g, b: Single; pDestColor: PWord; begin r := D3DXFloat16ToFloat((pSrc{+0})^); g := D3DXFloat16ToFloat(PD3DXFloat16(PWideChar(pSrc)+1)^); b := D3DXFloat16ToFloat(PD3DXFloat16(PWideChar(pSrc)+2)^); // Divide the components by the multiplier r := r / RGB16_MAX; g := g / RGB16_MAX; b := b / RGB16_MAX; // Constrain the color components r := max( 0, min(1, r)); g := max( 0, min(1, g)); b := max( 0, min(1, b)); // Store pDestColor := PWord(ppDest); pDestColor^ := Trunc(r*65535); Inc(pDestColor); pDestColor^ := Trunc(g*65535); Inc(pDestColor); pDestColor^ := Trunc(b*65535); //Inc(pDestColor); Inc(ppDest, SizeOf(Int64)); end; //----------------------------------------------------------------------------- // Name: RetrieveTechHandles() // Desc: //----------------------------------------------------------------------------- function RetrieveTechHandles: HRESULT; const modes: array[TEncodingMode] of PChar = ('FP16', 'FP16', 'RGB16', 'RGBE8'); techniques: array[0..4] of PChar = ('Scene', 'DownScale2x2_Lum', 'DownScale3x3', 'DownScale3x3_BrightPass', 'FinalPass'); var dwNumTechniques: DWORD; str: String; pHandle: PD3DXHandle; m: TEncodingMode; t: LongWord; begin dwNumTechniques := SizeOf(TTechHandles) div SizeOf(TD3DXHandle); pHandle := PD3DXHandle(@g_aTechHandles); for m := Low(m) to High(m) do begin for t := 0 to dwNumTechniques - 1 do begin str:= Format('%s_%s', [techniques[t], modes[m]]); pHandle^ := g_pEffect.GetTechniqueByName(PAnsiChar(str)); Inc(pHandle); end; end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: LoadMesh() // Desc: //----------------------------------------------------------------------------- function LoadMesh(strFileName: WideString; out ppMesh: ID3DXMesh): HRESULT; overload; var pMesh: ID3DXMesh; str: array[0..MAX_PATH-1] of WideChar; rgdwAdjacency: PDWORD; pTempMesh: ID3DXMesh; begin DXUTFindDXSDKMediaFile(str, MAX_PATH, PWideChar(strFileName)); Result := D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, g_pd3dDevice, nil, nil, nil, nil, pMesh); if FAILED(Result) or (pMesh = nil) then Exit; // Make sure there are normals which are required for lighting if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then begin Result := pMesh.CloneMeshFVF(pMesh.GetOptions, pMesh.GetFVF or D3DFVF_NORMAL, g_pd3dDevice, pTempMesh); if FAILED(Result) then Exit; D3DXComputeNormals(pTempMesh, nil); pMesh := nil; pMesh := pTempMesh; end; // Optimze the mesh to make it fast for the user's graphics card try GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3); except Result:= E_OUTOFMEMORY; Exit; end; V(pMesh.GenerateAdjacency(1e-6, rgdwAdjacency)); pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil); FreeMem(rgdwAdjacency); ppMesh := pMesh; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: MeasureLuminance() // Desc: Measure the average log luminance in the scene. //----------------------------------------------------------------------------- function MeasureLuminance: HRESULT; var uiNumPasses: LongWord; iPass: Integer; avSampleOffsets: array[0..15] of TD3DXVector2; pTexSrc: IDirect3DTexture9; pTexDest: IDirect3DTexture9; pSurfDest: IDirect3DSurface9; descSrc: TD3DSurfaceDesc; descDest: TD3DSurfaceDesc; pd3dDevice: IDirect3DDevice9; i: Integer; desc: TD3DSurfaceDesc; begin //------------------------------------------------------------------------- // Initial sampling pass to convert the image to the log of the grayscale //------------------------------------------------------------------------- pTexSrc := g_pTexRender; pTexDest := g_apTexToneMap[NUM_TONEMAP_TEXTURES-1]; pTexSrc.GetLevelDesc(0, descSrc); pTexDest.GetLevelDesc(0, descDest); GetSampleOffsets_DownScale2x2_Lum(descSrc.Width, descSrc.Height, descDest.Width, descDest.Height, avSampleOffsets); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetTechnique(g_pCurTechnique.DownScale2x2_Lum); Result := pTexDest.GetSurfaceLevel(0, pSurfDest); if FAILED(Result) then Exit; pd3dDevice := DXUTGetD3DDevice; pd3dDevice.SetRenderTarget(0, pSurfDest); pd3dDevice.SetTexture(0, pTexSrc); pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@uiNumPasses, 0); if FAILED(Result) then Exit; for iPass := 0 to uiNumPasses - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad; g_pEffect.EndPass; end; g_pEffect._End; pd3dDevice.SetTexture(0, nil); pSurfDest := nil; //------------------------------------------------------------------------- // Iterate through the remaining tone map textures //------------------------------------------------------------------------- for i := NUM_TONEMAP_TEXTURES-1 downto 1 do begin // Cycle the textures pTexSrc := g_apTexToneMap[i]; pTexDest := g_apTexToneMap[i-1]; Result := pTexDest.GetSurfaceLevel(0, pSurfDest); if FAILED(Result) then Exit; pTexSrc.GetLevelDesc(0, desc); GetSampleOffsets_DownScale3x3(desc.Width, desc.Height, avSampleOffsets); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetTechnique(g_pCurTechnique.DownScale3x3); pd3dDevice.SetRenderTarget(0, pSurfDest); pd3dDevice.SetTexture(0, pTexSrc); pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@uiNumPasses, 0); if FAILED(Result) then Exit; for iPass := 0 to uiNumPasses - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad; g_pEffect.EndPass; end; g_pEffect._End; pd3dDevice.SetTexture(0, nil); pSurfDest := nil; end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_DownScale3x3 // Desc: Get the texture coordinate offsets to be used inside the DownScale3x3 // pixel shader. //----------------------------------------------------------------------------- function GetSampleOffsets_DownScale3x3(dwWidth, dwHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; var tU, tV: Single; index: Integer; x, y: Integer; begin tU := 1.0 / dwWidth; tV := 1.0 / dwHeight; // Sample from the 9 surrounding points. index := 0; for y := -1 to 1 do for x := -1 to 1 do begin avSampleOffsets[ index ].x := x * tU; avSampleOffsets[ index ].y := y * tV; Inc(index); end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_DownScale2x2_Lum // Desc: Get the texture coordinate offsets to be used inside the DownScale2x2_Lum // pixel shader. //----------------------------------------------------------------------------- function GetSampleOffsets_DownScale2x2_Lum(dwSrcWidth, dwSrcHeight, dwDestWidth, dwDestHeight: DWORD; var avSampleOffsets: array of TD3DXVector2): HRESULT; var tU, tV, deltaU, deltaV: Single; index: Integer; x, y: Integer; begin tU := 1.0 / dwSrcWidth; tV := 1.0 / dwSrcHeight; deltaU := dwSrcWidth / dwDestWidth / 2.0; deltaV := dwSrcHeight / dwDestHeight / 2.0; // Sample from 4 surrounding points. index := 0; for y := 0 to 1 do for x := 0 to 1 do begin avSampleOffsets[ index ].x := (x - 0.5) * deltaU * tU; avSampleOffsets[ index ].y := (y - 0.5) * deltaV * tV; Inc(index); end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: GetSampleOffsets_Bloom() // Desc: //----------------------------------------------------------------------------- function GetSampleOffsets_Bloom(dwD3DTexSize: DWORD; var afTexCoordOffset: array of Single; var avColorWeight: array of TD3DXVector4; fDeviation: Single; fMultiplier: Single = 1.0): HRESULT; var i: Integer; tu: Single; weight: Single; begin tu := 1.0 / dwD3DTexSize; // Fill the center texel weight := 1.0 * GaussianDistribution(0, 0, fDeviation); avColorWeight[0] := D3DXVector4(weight, weight, weight, 1.0); afTexCoordOffset[0] := 0.0; // Fill the right side for i := 1 to 7 do begin weight := fMultiplier * GaussianDistribution(i, 0, fDeviation); afTexCoordOffset[i] := i * tu; avColorWeight[i] := D3DXVector4(weight, weight, weight, 1.0); end; // Copy to the left side for i := 8 to 14 do begin avColorWeight[i] := avColorWeight[i-7]; afTexCoordOffset[i] := -afTexCoordOffset[i-7]; end; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: RenderModel() // Desc: Render the model //----------------------------------------------------------------------------- function RenderModel: HRESULT; var mWorldViewProj: TD3DXMatrixA16; iPass: Integer; uiNumPasses: LongWord; begin // Set the transforms D3DXMatrixMultiply(mWorldViewProj, g_Camera.GetWorldMatrix^, g_Camera.GetViewMatrix^); D3DXMatrixMultiply(mWorldViewProj, mWorldViewProj, g_Camera.GetProjMatrix^); g_pEffect.SetMatrix('g_mWorld', g_Camera.GetWorldMatrix^); g_pEffect.SetMatrix('g_mWorldViewProj', mWorldViewProj); // Draw the mesh g_pEffect.SetTechnique(g_pCurTechnique.Scene); g_pEffect.SetTexture('g_tCube', g_aSkybox[g_eEncodingMode].EnvironmentMap); Result := g_pEffect._Begin(@uiNumPasses, 0); if FAILED(Result) then Exit; for iPass:=0 to uiNumPasses - 1 do begin g_pEffect.BeginPass(iPass); g_pMesh.DrawSubset(0); g_pEffect.EndPass; end; g_pEffect._End; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: BrightPassFilter // Desc: Prepare for the bloom pass by removing dark information from the scene //----------------------------------------------------------------------------- function BrightPassFilter: HRESULT; var pBackBufDesc: PD3DSurfaceDesc; avSampleOffsets: array[0..15] of TD3DXVector2; pSurfBrightPass: IDirect3DSurface9; iPass: Integer; uiNumPasses: LongWord; begin pBackBufDesc := DXUTGetBackBufferSurfaceDesc; GetSampleOffsets_DownScale3x3(pBackBufDesc.Width div 2, pBackBufDesc.Height div 2, avSampleOffsets); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); Result := g_pTexBrightPass.GetSurfaceLevel(0, pSurfBrightPass); if FAILED(Result) then Exit; g_pEffect.SetTechnique(g_pCurTechnique.DownScale3x3_BrightPass); g_pd3dDevice.SetRenderTarget(0, pSurfBrightPass); g_pd3dDevice.SetTexture(0, g_pTexRender); g_pd3dDevice.SetTexture(1, g_apTexToneMap[0]); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); Result := g_pEffect._Begin(@uiNumPasses, 0); if FAILED(Result) then Exit; for iPass := 0 to uiNumPasses - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad; g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetTexture(0, nil); g_pd3dDevice.SetTexture(1, nil); pSurfBrightPass := nil; Result:= S_OK; end; //----------------------------------------------------------------------------- // Name: RenderBloom() // Desc: Render the blooming effect //----------------------------------------------------------------------------- function RenderBloom: HRESULT; var iPass: Integer; uiPassCount: LongWord; i: Integer; avSampleOffsets: array[0..15] of TD3DXVector2; afSampleOffsets: array[0..15] of Single; avSampleWeights: array[0..15] of TD3DXVector4; pSurfDest: IDirect3DSurface9; desc: TD3DSurfaceDesc; begin Result := g_apTexBloom[1].GetSurfaceLevel(0, pSurfDest); if FAILED(Result) then Exit; Result := g_pTexBrightPass.GetLevelDesc(0, desc); if FAILED(Result) then Exit; {Result := }GetSampleOffsets_Bloom(desc.Width, afSampleOffsets, avSampleWeights, 3.0, 1.25); for i := 0 to 15 do avSampleOffsets[i] := D3DXVector2(afSampleOffsets[i], 0.0); g_pEffect.SetTechnique('Bloom'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetValue('g_avSampleWeights', @avSampleWeights, SizeOf(avSampleWeights)); g_pd3dDevice.SetRenderTarget(0, pSurfDest); g_pd3dDevice.SetTexture(0, g_pTexBrightPass); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pEffect._Begin(@uiPassCount, 0); for iPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad; g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetTexture(0, nil); pSurfDest := nil; Result := g_apTexBloom[0].GetSurfaceLevel(0, pSurfDest); if FAILED(Result) then Exit; Result := GetSampleOffsets_Bloom(desc.Height, afSampleOffsets, avSampleWeights, 3.0, 1.25); for i:= 0 to 15 do avSampleOffsets[i] := D3DXVector2(0.0, afSampleOffsets[i]); g_pEffect.SetTechnique('Bloom'); g_pEffect.SetValue('g_avSampleOffsets', @avSampleOffsets, SizeOf(avSampleOffsets)); g_pEffect.SetValue('g_avSampleWeights', @avSampleWeights, SizeOf(avSampleWeights)); g_pd3dDevice.SetRenderTarget(0, pSurfDest); g_pd3dDevice.SetTexture(0, g_apTexBloom[1]); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); g_pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); g_pEffect._Begin(@uiPassCount, 0); for iPass := 0 to uiPassCount - 1 do begin g_pEffect.BeginPass(iPass); // Draw a fullscreen quad to sample the RT DrawFullScreenQuad; g_pEffect.EndPass; end; g_pEffect._End; g_pd3dDevice.SetTexture(0, nil); pSurfDest := nil; end; //----------------------------------------------------------------------------- // Name: DrawFullScreenQuad // Desc: Draw a properly aligned quad covering the entire render target //----------------------------------------------------------------------------- procedure DrawFullScreenQuad(fLeftU: Single = 0.0; fTopV: Single = 0.0; fRightU: Single = 1.0; fBottomV: Single = 1.0); var dtdsdRT: TD3DSurfaceDesc; pSurfRT: IDirect3DSurface9; fWidth5: Single; fHeight5: Single; svQuad: array[0..3] of TScreenVertex; begin // Acquire render target width and height g_pd3dDevice.GetRenderTarget(0, pSurfRT); pSurfRT.GetDesc(dtdsdRT); pSurfRT := nil; // Ensure that we're directly mapping texels to pixels by offset by 0.5 // For more info see the doc page titled "Directly Mapping Texels to Pixels" fWidth5 := dtdsdRT.Width - 0.5; fHeight5 := dtdsdRT.Height - 0.5; // Draw the quad svQuad[0].pos := D3DXVector4(-0.5, -0.5, 0.5, 1.0); svQuad[0].tex := D3DXVector2(fLeftU, fTopV); svQuad[1].pos := D3DXVector4(fWidth5, -0.5, 0.5, 1.0); svQuad[1].tex := D3DXVector2(fRightU, fTopV); svQuad[2].pos := D3DXVector4(-0.5, fHeight5, 0.5, 1.0); svQuad[2].tex := D3DXVector2(fLeftU, fBottomV); svQuad[3].pos := D3DXVector4(fWidth5, fHeight5, 0.5, 1.0); svQuad[3].tex := D3DXVector2(fRightU, fBottomV); g_pd3dDevice.SetRenderState(D3DRS_ZENABLE, iFalse); g_pd3dDevice.SetFVF(TScreenVertex_FVF); g_pd3dDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, svQuad, SizeOf(TScreenVertex)); g_pd3dDevice.SetRenderState(D3DRS_ZENABLE, iTrue); end; //----------------------------------------------------------------------------- // Name: CreateEncodedTexture // Desc: Create a copy of the input floating-point texture with RGBE8 or RGB16 // encoding //----------------------------------------------------------------------------- function CreateEncodedTexture(const pTexSrc: IDirect3DCubeTexture9; out ppTexDest: IDirect3DCubeTexture9; eTarget: TEncodingMode): HRESULT; var desc: TD3DSurfaceDesc; fmt: TD3DFormat; iFace: TD3DCubemapFaces; rcSrc, rcDest: TD3DLockedRect; pSrcBytes, pDestBytes: PByte; x, y: LongWord; pSrc: PD3DXFloat16; pDest: PByte; begin Result:= pTexSrc.GetLevelDesc(0, desc); if V_Failed(Result) then Exit; // Create a texture with equal dimensions to store the encoded texture case eTarget of RGBE8: fmt := D3DFMT_A8R8G8B8; RGB16: fmt := D3DFMT_A16B16G16R16; else fmt := D3DFMT_UNKNOWN; end; Result:= g_pd3dDevice.CreateCubeTexture(desc.Width, 1, 0, fmt, D3DPOOL_MANAGED, ppTexDest, nil); if V_Failed(Result) then Exit; for iFace := Low(iFace) to High(iFace) do begin // Lock the source texture for reading Result:= pTexSrc.LockRect(iFace, 0, rcSrc, nil, D3DLOCK_READONLY); if V_Failed(Result) then Exit; // Lock the destination texture for writing Result:= ppTexDest.LockRect(iFace, 0, rcDest, nil, 0); if V_Failed(Result) then Exit; pSrcBytes := PByte(rcSrc.pBits); pDestBytes := PByte(rcDest.pBits); for y := 0 to desc.Height - 1 do begin pSrc := PD3DXFloat16(pSrcBytes); pDest := pDestBytes; for x := 0 to desc.Width - 1 do begin case eTarget of RGBE8: EncodeRGBE8(pSrc, pDest); RGB16: EncodeRGB16(pSrc, pDest); else Result:= E_FAIL; Exit; end; Inc(pSrc, 4); end; Inc(pSrcBytes, rcSrc.Pitch); Inc(pDestBytes, rcDest.Pitch); end; // Release the locks ppTexDest.UnlockRect(iFace, 0); pTexSrc.UnlockRect(iFace, 0); end; Result:= S_OK; end; procedure CreateCustomDXUTobjects; var i: TEncodingMode; begin g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog g_Camera := CModelViewerCamera.Create; // A model viewing camera g_HUD := CDXUTDialog.Create; // dialog for standard controls g_SampleUI := CDXUTDialog.Create; // dialog for sample specific controls for i:= Low(i) to High(i) do g_aSkybox[i]:= CSkybox.Create; end; procedure DestroyCustomDXUTobjects; var i: TEncodingMode; begin FreeAndNil(g_DialogResourceManager); FreeAndNil(g_SettingsDlg); FreeAndNil(g_Camera); FreeAndNil(g_HUD); FreeAndNil(g_SampleUI); for i:= Low(i) to High(i) do FreeAndNil(g_aSkybox[i]); end; end.
unit SHOptionsIntf; interface uses SysUtils, Classes, Graphics, StdCtrls, // SQLHammer SHDesignIntf; type // System -> ISHSystemOptions = interface(ISHComponentOptions) ['{8F0FFA69-1AC6-4132-BF3B-452EB24C2B7F}'] function GetStartBranch: Integer; procedure SetStartBranch(Value: Integer); function GetShowSplashWindow: Boolean; procedure SetShowSplashWindow(Value: Boolean); function GetUseWorkspaces: Boolean; procedure SetUseWorkspaces(Value: Boolean); function GetExternalDiffPath: string; procedure SetExternalDiffPath(Value: string); function GetExternalDiffParams: string; procedure SetExternalDiffParams(Value: string); function GetWarningOnExit: Boolean; procedure SetWarningOnExit(Value: Boolean); function GetLeftWidth: Integer; procedure SetLeftWidth(Value: Integer); function GetRightWidth: Integer; procedure SetRightWidth(Value: Integer); function GetIDE1Height: Integer; procedure SetIDE1Height(Value: Integer); function GetIDE2Height: Integer; procedure SetIDE2Height(Value: Integer); function GetIDE3Height: Integer; procedure SetIDE3Height(Value: Integer); function GetNavigatorLeft: Boolean; procedure SetNavigatorLeft(Value: Boolean); function GetToolboxTop: Boolean; procedure SetToolboxTop(Value: Boolean); function GetStartPage: Integer; procedure SetStartPage(Value: Integer); function GetMultilineMode: Boolean; procedure SetMultilineMode(Value: Boolean); function GetFilterMode: Boolean; procedure SetFilterMode(Value: Boolean); property ShowSplashWindow: Boolean read GetShowSplashWindow write SetShowSplashWindow; property UseWorkspaces: Boolean read GetUseWorkspaces write SetUseWorkspaces; property ExternalDiffPath: string read GetExternalDiffPath write SetExternalDiffPath; property ExternalDiffParams: string read GetExternalDiffParams write SetExternalDiffParams; property WarningOnExit: Boolean read GetWarningOnExit write SetWarningOnExit; {Invisible} property StartBranch: Integer read GetStartBranch write SetStartBranch; property LeftWidth: Integer read GetLeftWidth write SetLeftWidth; property RightWidth: Integer read GetRightWidth write SetRightWidth; property IDE1Height: Integer read GetIDE1Height write SetIDE1Height; property IDE2Height: Integer read GetIDE2Height write SetIDE2Height; property IDE3Height: Integer read GetIDE3Height write SetIDE3Height; property NavigatorLeft: Boolean read GetNavigatorLeft write SetNavigatorLeft; property ToolboxTop: Boolean read GetToolboxTop write SetToolboxTop; property StartPage: Integer read GetStartPage write SetStartPage; property MultilineMode: Boolean read GetMultilineMode write SetMultilineMode; property FilterMode: Boolean read GetFilterMode write SetFilterMode; end; // Editor -> TSHEditorCaretType = (VerticalLine, HorizontalLine, HalfBlock, Block); TSHEditorLinkOption = (SingleClick, CtrlClick, DblClick); TSHEditorScrollHintFormat = (TopLineOnly, TopToBottom); TSHEditorSelectionMode = (Normal, Line, Column); ISHEditorOptions = interface; ISHEditorGeneralOptions = interface(ISHComponentOptions) ['{8B111A9D-394D-4F8F-A014-BCA6D817BD61}'] function GetHideSelection: Boolean; procedure SetHideSelection(Value: Boolean); function GetUseHighlight: Boolean; procedure SetUseHighlight(Value: Boolean); function GetInsertCaret: TSHEditorCaretType; procedure SetInsertCaret(Value: TSHEditorCaretType); function GetInsertMode: Boolean; procedure SetInsertMode(Value: Boolean); function GetMaxLineWidth: Integer; procedure SetMaxLineWidth(Value: Integer); function GetMaxUndo: Integer; procedure SetMaxUndo(Value: Integer); function GetOpenLink: TSHEditorLinkOption; procedure SetOpenLink(Value: TSHEditorLinkOption); function GetOptions: ISHEditorOptions; function GetOverwriteCaret: TSHEditorCaretType; procedure SetOverwriteCaret(Value: TSHEditorCaretType); function GetScrollHintFormat: TSHEditorScrollHintFormat; procedure SetScrollHintFormat(Value: TSHEditorScrollHintFormat); function GetScrollBars: TScrollStyle; procedure SetScrollBars(Value: TScrollStyle); function GetSelectionMode: TSHEditorSelectionMode; procedure SetSelectionMode(Value: TSHEditorSelectionMode); function GetTabWidth: Integer; procedure SetTabWidth(Value: Integer); function GetWantReturns: Boolean; procedure SetWantReturns(Value: Boolean); function GetWantTabs: Boolean; procedure SetWantTabs(Value: Boolean); function GetWordWrap: Boolean; procedure SetWordWrap(Value: Boolean); function GetOpenedFilesHistory: TStrings; function GetFindTextHistory: TStrings; function GetReplaceTextHistory: TStrings; function GetLineNumberHistory: TStrings; function GetDemoLines: TStrings; function GetPromtOnReplace: Boolean; procedure SetPromtOnReplace(Value: Boolean); property HideSelection: Boolean read GetHideSelection write SetHideSelection; property UseHighlight: Boolean read GetUseHighlight write SetUseHighlight; property InsertCaret: TSHEditorCaretType read GetInsertCaret write SetInsertCaret; property InsertMode: Boolean read GetInsertMode write SetInsertMode; property MaxLineWidth: Integer read GetMaxLineWidth write SetMaxLineWidth; property MaxUndo: Integer read GetMaxUndo write SetMaxUndo; property OpenLink: TSHEditorLinkOption read GetOpenLink write SetOpenLink; property Options: ISHEditorOptions read GetOptions; property OverwriteCaret: TSHEditorCaretType read GetOverwriteCaret write SetOverwriteCaret; property ScrollHintFormat: TSHEditorScrollHintFormat read GetScrollHintFormat write SetScrollHintFormat; property ScrollBars: TScrollStyle read GetScrollBars write SetScrollBars; property SelectionMode: TSHEditorSelectionMode read GetSelectionMode write SetSelectionMode; property TabWidth: Integer read GetTabWidth write SetTabWidth; property WantReturns: Boolean read GetWantReturns write SetWantReturns; property WantTabs: Boolean read GetWantTabs write SetWantTabs; property WordWrap: Boolean read GetWordWrap write SetWordWrap; { Invisible } property OpenedFilesHistory: TStrings read GetOpenedFilesHistory; property FindTextHistory: TStrings read GetFindTextHistory; property ReplaceTextHistory: TStrings read GetReplaceTextHistory; property LineNumberHistory: TStrings read GetLineNumberHistory; property DemoLines: TStrings read GetDemoLines; property PromtOnReplace: Boolean read GetPromtOnReplace write SetPromtOnReplace; end; ISHEditorOptions = interface ['{6C086418-9B91-4DD8-A9A8-8F8DCEAFA6E5}'] function GetAltSetsColumnMode: Boolean; procedure SetAltSetsColumnMode(Value: Boolean); function GetAutoIndent: Boolean; procedure SetAutoIndent(Value: Boolean); function GetAutoSizeMaxLeftChar: Boolean; procedure SetAutoSizeMaxLeftChar(Value: Boolean); function GetDisableScrollArrows: Boolean; procedure SetDisableScrollArrows(Value: Boolean); function GetDragDropEditing: Boolean; procedure SetDragDropEditing(Value: Boolean); function GetEnhanceHomeKey: Boolean; procedure SetEnhanceHomeKey(Value: Boolean); function GetGroupUndo: Boolean; procedure SetGroupUndo(Value: Boolean); function GetHalfPageScroll: Boolean; procedure SetHalfPageScroll(Value: Boolean); function GetHideShowScrollbars: Boolean; procedure SetHideShowScrollbars(Value: Boolean); function GetKeepCaretX: Boolean; procedure SetKeepCaretX(Value: Boolean); function GetNoCaret: Boolean; procedure SetNoCaret(Value: Boolean); function GetNoSelection: Boolean; procedure SetNoSelection(Value: Boolean); function GetScrollByOneLess: Boolean; procedure SetScrollByOneLess(Value: Boolean); function GetScrollHintFollows: Boolean; procedure SetScrollHintFollows(Value: Boolean); function GetScrollPastEof: Boolean; procedure SetScrollPastEof(Value: Boolean); function GetScrollPastEol: Boolean; procedure SetScrollPastEol(Value: Boolean); function GetShowScrollHint: Boolean; procedure SetShowScrollHint(Value: Boolean); function GetSmartTabDelete: Boolean; procedure SetSmartTabDelete(Value: Boolean); function GetSmartTabs: Boolean; procedure SetSmartTabs(Value: Boolean); function GetTabIndent: Boolean; procedure SetTabIndent(Value: Boolean); function GetTabsToSpaces: Boolean; procedure SetTabsToSpaces(Value: Boolean); function GetTrimTrailingSpaces: Boolean; procedure SetTrimTrailingSpaces(Value: Boolean); property AltSetsColumnMode: Boolean read GetAltSetsColumnMode write SetAltSetsColumnMode; property AutoIndent: Boolean read GetAutoIndent write SetAutoIndent; property AutoSizeMaxLeftChar: Boolean read GetAutoSizeMaxLeftChar write SetAutoSizeMaxLeftChar; property DisableScrollArrows: Boolean read GetDisableScrollArrows write SetDisableScrollArrows; property DragDropEditing: Boolean read GetDragDropEditing write SetDragDropEditing; property EnhanceHomeKey: Boolean read GetEnhanceHomeKey write SetEnhanceHomeKey; property GroupUndo: Boolean read GetGroupUndo write SetGroupUndo; property HalfPageScroll: Boolean read GetHalfPageScroll write SetHalfPageScroll; property HideShowScrollbars: Boolean read GetHideShowScrollbars write SetHideShowScrollbars; property KeepCaretX: Boolean read GetKeepCaretX write SetKeepCaretX; property NoCaret: Boolean read GetNoCaret write SetNoCaret; property NoSelection: Boolean read GetNoSelection write SetNoSelection; property ScrollByOneLess: Boolean read GetScrollByOneLess write SetScrollByOneLess; property ScrollHintFollows: Boolean read GetScrollHintFollows write SetScrollHintFollows; property ScrollPastEof: Boolean read GetScrollPastEof write SetScrollPastEof; property ScrollPastEol: Boolean read GetScrollPastEol write SetScrollPastEol; property ShowScrollHint: Boolean read GetShowScrollHint write SetShowScrollHint; property SmartTabDelete: Boolean read GetSmartTabDelete write SetSmartTabDelete; property SmartTabs: Boolean read GetSmartTabs write SetSmartTabs; property TabIndent: Boolean read GetTabIndent write SetTabIndent; property TabsToSpaces: Boolean read GetTabsToSpaces write SetTabsToSpaces; property TrimTrailingSpaces: Boolean read GetTrimTrailingSpaces write SetTrimTrailingSpaces; end; ISHEditorGutter = interface; ISHEditorMargin = interface; ISHEditorDisplayOptions = interface(ISHComponentOptions) ['{B0C98531-C37F-4A62-8690-1AD57607858B}'] function GetFont: TFont; procedure SetFont(Value: TFont); function GetGutter: ISHEditorGutter; function GetMargin: ISHEditorMargin; property Font: TFont read GetFont write SetFont; property Gutter: ISHEditorGutter read GetGutter; property Margin: ISHEditorMargin read GetMargin; end; ISHEditorGutter = interface ['{50E59981-2292-457B-8A25-81E4D6C733D1}'] function GetAutoSize: Boolean; procedure SetAutoSize(Value: Boolean); function GetDigitCount: Integer; procedure SetDigitCount(Value: Integer); function GetFont: TFont; procedure SetFont(Value: TFont); function GetLeadingZeros: Boolean; procedure SetLeadingZeros(Value: Boolean); function GetLeftOffset: Integer; procedure SetLeftOffset(Value: Integer); function GetRightOffset: Integer; procedure SetRightOffset(Value: Integer); function GetShowLineNumbers: Boolean; procedure SetShowLineNumbers(Value: Boolean); function GetUseFontStyle: Boolean; procedure SetUseFontStyle(Value: Boolean); function GetVisible: Boolean; procedure SetVisible(Value: Boolean); function GetWidth: Integer; procedure SetWidth(Value: Integer); function GetZeroStart: Boolean; procedure SetZeroStart(Value: Boolean); property AutoSize: Boolean read GetAutoSize write SetAutoSize; property DigitCount: Integer read GetDigitCount write SetDigitCount; property Font: TFont read GetFont write SetFont; property LeadingZeros: Boolean read GetLeadingZeros write SetLeadingZeros; property LeftOffset: Integer read GetLeftOffset write SetLeftOffset; property RightOffset: Integer read GetRightOffset write SetRightOffset; property ShowLineNumbers: Boolean read GetShowLineNumbers write SetShowLineNumbers; property UseFontStyle: Boolean read GetUseFontStyle write SetUseFontStyle; property Visible: Boolean read GetVisible write SetVisible; property Width: Integer read GetWidth write SetWidth; property ZeroStart: Boolean read GetZeroStart write SetZeroStart; end; ISHEditorMargin = interface ['{923EEB68-AF96-4099-8429-6C5B018E2A83}'] function GetRightEdgeVisible: Boolean; procedure SetRightEdgeVisible(Value: Boolean); function GetRightEdgeWidth: Integer; procedure SetRightEdgeWidth(Value: Integer); function GetBottomEdgeVisible: Boolean; procedure SetBottomEdgeVisible(Value: Boolean); property RightEdgeVisible: Boolean read GetRightEdgeVisible write SetRightEdgeVisible; property RightEdgeWidth: Integer read GetRightEdgeWidth write SetRightEdgeWidth; property BottomEdgeVisible: Boolean read GetBottomEdgeVisible write SetBottomEdgeVisible; end; ISHEditorColor = interface; ISHEditorColorAttr = interface; ISHEditorColorOptions = interface(ISHComponentOptions) ['{58B3B67F-C65F-4404-A74F-6F82F4F18F86}'] function GetBackground: TColor; procedure SetBackground(Value: TColor); function GetGutter: TColor; procedure SetGutter(Value: TColor); function GetRightEdge: TColor; procedure SetRightEdge(Value: TColor); function GetBottomEdge: TColor; procedure SetBottomEdge(Value: TColor); function GetCurrentLine: TColor; procedure SetCurrentLine(Value: TColor); function GetErrorLine: TColor; procedure SetErrorLine(Value: TColor); function GetScrollHint: TColor; procedure SetScrollHint(Value: TColor); function GetSelected: ISHEditorColor; function GetCommentAttr: ISHEditorColorAttr; function GetCustomStringAttr: ISHEditorColorAttr; function GetDataTypeAttr: ISHEditorColorAttr; function GetIdentifierAttr: ISHEditorColorAttr; function GetFunctionAttr: ISHEditorColorAttr; function GetLinkAttr: ISHEditorColorAttr; function GetNumberAttr: ISHEditorColorAttr; function GetSQLKeywordAttr: ISHEditorColorAttr; function GetStringAttr: ISHEditorColorAttr; function GetStringDblQuotedAttr: ISHEditorColorAttr; function GetSymbolAttr: ISHEditorColorAttr; function GetVariableAttr: ISHEditorColorAttr; function GetWrongSymbolAttr: ISHEditorColorAttr; property Background: TColor read GetBackground write SetBackground; property Gutter: TColor read GetGutter write SetGutter; property RightEdge: TColor read GetRightEdge write SetRightEdge; property BottomEdge: TColor read GetBottomEdge write SetBottomEdge; property CurrentLine: TColor read GetCurrentLine write SetCurrentLine; property ErrorLine: TColor read GetErrorLine write SetErrorLine; property ScrollHint: TColor read GetScrollHint write SetScrollHint; property Selected: ISHEditorColor read GetSelected; property CommentAttr: ISHEditorColorAttr read GetCommentAttr; property CustomStringAttr: ISHEditorColorAttr read GetCustomStringAttr; property DataTypeAttr: ISHEditorColorAttr read GetDataTypeAttr; property IdentifierAttr: ISHEditorColorAttr read GetIdentifierAttr; property FunctionAttr: ISHEditorColorAttr read GetFunctionAttr; property LinkAttr: ISHEditorColorAttr read GetLinkAttr; property NumberAttr: ISHEditorColorAttr read GetNumberAttr; property SQLKeywordAttr: ISHEditorColorAttr read GetSQLKeywordAttr; property StringAttr: ISHEditorColorAttr read GetStringAttr; property StringDblQuotedAttr: ISHEditorColorAttr read GetStringDblQuotedAttr; property SymbolAttr: ISHEditorColorAttr read GetSymbolAttr; property VariableAttr: ISHEditorColorAttr read GetVariableAttr; property WrongSymbolAttr: ISHEditorColorAttr read GetWrongSymbolAttr; end; ISHEditorColor = interface ['{7D4BFE88-C414-4A8F-A903-D4DE6623EBE6}'] function GetForeground: TColor; procedure SetForeground(Value: TColor); function GetBackground: TColor; procedure SetBackground(Value: TColor); property Foreground: TColor read GetForeground write SetForeground; property Background: TColor read GetBackground write SetBackground; end; ISHEditorColorAttr = interface(ISHEditorColor) ['{13D4A45B-151D-4B5A-896F-B5DBBAAB3AB7}'] function GetStyle: TFontStyles; procedure SetStyle(Value: TFontStyles); property Style: TFontStyles read GetStyle write SetStyle; end; TSHEditorCaseCode = (Lower, Upper, NameCase, FirstUpper, None, Invert, Toggle); ISHEditorCodeInsightOptions = interface(ISHComponentOptions) ['{5ED7677A-0ACA-4718-A15C-E95C0228A9B6}'] function GetCodeCompletion: Boolean; procedure SetCodeCompletion(Value: Boolean); function GetCodeParameters: Boolean; procedure SetCodeParameters(Value: Boolean); function GetCaseCode: TSHEditorCaseCode; procedure SetCaseCode(Value: TSHEditorCaseCode); function GetCaseSQLKeywords: TSHEditorCaseCode; procedure SetCaseSQLKeywords(Value: TSHEditorCaseCode); function GetCustomStrings: TStrings; function GetDelay: Integer; procedure SetDelay(Value: Integer); function GetWindowLineCount: Integer; procedure SetWindowLineCount(Value: Integer); function GetWindowWidth: Integer; procedure SetWindowWidth(Value: Integer); property CodeCompletion: Boolean read GetCodeCompletion write SetCodeCompletion; property CodeParameters: Boolean read GetCodeParameters write SetCodeParameters; property CaseCode: TSHEditorCaseCode read GetCaseCode write SetCaseCode; property CaseSQLKeywords: TSHEditorCaseCode read GetCaseSQLKeywords write SetCaseSQLKeywords; property CustomStrings: TStrings read GetCustomStrings; property Delay: Integer read GetDelay write SetDelay; { Invisible } property WindowLineCount: Integer read GetWindowLineCount write SetWindowLineCount; property WindowWidth: Integer read GetWindowWidth write SetWindowWidth; end; IEditorCodeInsightOptionsExt =interface ['{26AA3F44-F109-486B-BAC7-D152CA3F07B8}'] function GetShowBeginEndRegions:boolean; procedure SetShowBeginEndRegions(const Value:boolean); end; // DBGrid -> ISHDBGridAllowedOperations = interface; ISHDBGridAllowedSelections = interface; ISHDBGridScrollBar = interface; ISHDBGridOptions = interface; ISHDBGridGeneralOptions = interface(ISHComponentOptions) ['{40F3DF8D-976B-4840-B8D7-1F1A4A711E63}'] function GetAllowedOperations: ISHDBGridAllowedOperations; function GetAllowedSelections: ISHDBGridAllowedSelections; function GetAutoFitColWidths: Boolean; procedure SetAutoFitColWidths(Value: Boolean); function GetDrawMemoText: Boolean; procedure SetDrawMemoText(Value: Boolean); function GetFrozenCols: Integer; procedure SetFrozenCols(Value: Integer); function GetHorzScrollBar: ISHDBGridScrollBar; function GetMinAutoFitWidth: Integer; procedure SetMinAutoFitWidth(Value: Integer); function GetOptions: ISHDBGridOptions; function GetRowHeight: Integer; procedure SetRowHeight(Value: Integer); function GetRowLines: Integer; procedure SetRowLines(Value: Integer); function GetRowSizingAllowed: Boolean; procedure SetRowSizingAllowed(Value: Boolean); function GetTitleHeight: Integer; procedure SetTitleHeight(Value: Integer); function GetToolTips: Boolean; procedure SetToolTips(Value: Boolean); function GetVertScrollBar: ISHDBGridScrollBar; property AllowedOperations: ISHDBGridAllowedOperations read GetAllowedOperations; property AllowedSelections: ISHDBGridAllowedSelections read GetAllowedSelections; property AutoFitColWidths: Boolean read GetAutoFitColWidths write SetAutoFitColWidths; property DrawMemoText: Boolean read GetDrawMemoText write SetDrawMemoText; property FrozenCols: Integer read GetFrozenCols write SetFrozenCols; property HorzScrollBar: ISHDBGridScrollBar read GetHorzScrollBar; property MinAutoFitWidth: Integer read GetMinAutoFitWidth write SetMinAutoFitWidth; property Options: ISHDBGridOptions read GetOptions; property RowHeight: Integer read GetRowHeight write SetRowHeight; property RowLines: Integer read GetRowLines write SetRowLines; property RowSizingAllowed: Boolean read GetRowSizingAllowed write SetRowSizingAllowed; property TitleHeight: Integer read GetTitleHeight write SetTitleHeight; property ToolTips: Boolean read GetToolTips write SetToolTips; property VertScrollBar: ISHDBGridScrollBar read GetVertScrollBar; end; ISHDBGridAllowedOperations = interface ['{31B0A303-BEB1-4A27-9AAD-5B526B2C8498}'] function GetInsert: Boolean; procedure SetInsert(Value: Boolean); function GetUpdate: Boolean; procedure SetUpdate(Value: Boolean); function GetDelete: Boolean; procedure SetDelete(Value: Boolean); function GetAppend: Boolean; procedure SetAppend(Value: Boolean); property Insert: Boolean read GetInsert write SetInsert; property Update: Boolean read GetUpdate write SetUpdate; property Delete: Boolean read GetDelete write SetDelete; property Append: Boolean read GetAppend write SetAppend; end; ISHDBGridAllowedSelections = interface ['{A6FB56C7-E843-484F-B555-2FA61AAD9030}'] function GetRecordBookmarks: Boolean; procedure SetRecordBookmarks(Value: Boolean); function GetRectangle: Boolean; procedure SetRectangle(Value: Boolean); function GetColumns: Boolean; procedure SetColumns(Value: Boolean); function GetAll: Boolean; procedure SetAll(Value: Boolean); property RecordBookmarks: Boolean read GetRecordBookmarks write SetRecordBookmarks; property Rectangle: Boolean read GetRectangle write SetRectangle; property Columns: Boolean read GetColumns write SetColumns; property All: Boolean read GetAll write SetAll; end; TSHDBGridScrollBarVisibleMode = (Always, Never, Auto); ISHDBGridScrollBar = interface ['{2D9E677A-DBAC-4032-AA56-9698F4CD0C85}'] function GetTracking: Boolean; procedure SetTracking(Value: Boolean); function GetVisible: Boolean; procedure SetVisible(Value: Boolean); function GetVisibleMode: TSHDBGridScrollBarVisibleMode; procedure SetVisibleMode(Value: TSHDBGridScrollBarVisibleMode); property Tracking: Boolean read GetTracking write SetTracking; property Visible: Boolean read GetVisible write SetVisible; property VisibleMode: TSHDBGridScrollBarVisibleMode read GetVisibleMode write SetVisibleMode; end; ISHDBGridOptions = interface ['{C7181E03-C0BC-4BE5-BAAB-794FC10366E8}'] function GetAlwaysShowEditor: Boolean; procedure SetAlwaysShowEditor(Value: Boolean); function GetAlwaysShowSelection: Boolean; procedure SetAlwaysShowSelection(Value: Boolean); function GetCancelOnExit: Boolean; procedure SetCancelOnExit(Value: Boolean); function GetClearSelection: Boolean; procedure SetClearSelection(Value: Boolean); function GetColLines: Boolean; procedure SetColLines(Value: Boolean); function GetColumnResize: Boolean; procedure SetColumnResize(Value: Boolean); function GetConfirmDelete: Boolean; procedure SetConfirmDelete(Value: Boolean); function GetData3D: Boolean; procedure SetData3D(Value: Boolean); function GetEditing: Boolean; procedure SetEditing(Value: Boolean); function GetEnterAsTab: Boolean; procedure SetEnterAsTab(Value: Boolean); function GetIncSearch: Boolean; procedure SetIncSearch(Value: Boolean); function GetIndicator: Boolean; procedure SetIndicator(Value: Boolean); function GetFitRowHeightToText: Boolean; procedure SetFitRowHeightToText(Value: Boolean); function GetFixed3D: Boolean; procedure SetFixed3D(Value: Boolean); function GetFrozen3D: Boolean; procedure SetFrozen3D(Value: Boolean); function GetHighlightFocus: Boolean; procedure SetHighlightFocus(Value: Boolean); function GetMultiSelect: Boolean; procedure SetMultiSelect(Value: Boolean); function GetPreferIncSearch: Boolean; procedure SetPreferIncSearch(Value: Boolean); function GetResizeWholeRightPart: Boolean; procedure SetResizeWholeRightPart(Value: Boolean); function GetRowHighlight: Boolean; procedure SetRowHighlight(Value: Boolean); function GetRowLines: Boolean; procedure SetRowLines(Value: Boolean); function GetRowSelect: Boolean; procedure SetRowSelect(Value: Boolean); function GetTabs: Boolean; procedure SetTabs(Value: Boolean); function GetTitles: Boolean; procedure SetTitles(Value: Boolean); function GetTraceColSizing: Boolean; procedure SetTraceColSizing(Value: Boolean); property AlwaysShowEditor: Boolean read GetAlwaysShowEditor write SetAlwaysShowEditor; property AlwaysShowSelection: Boolean read GetAlwaysShowSelection write SetAlwaysShowSelection; property CancelOnExit: Boolean read GetCancelOnExit write SetCancelOnExit; property ClearSelection: Boolean read GetClearSelection write SetClearSelection; property ColLines: Boolean read GetColLines write SetColLines; property ColumnResize: Boolean read GetColumnResize write SetColumnResize; property ConfirmDelete: Boolean read GetConfirmDelete write SetConfirmDelete; property Data3D: Boolean read GetData3D write SetData3D; property Editing: Boolean read GetEditing write SetEditing; property EnterAsTab: Boolean read GetEnterAsTab write SetEnterAsTab; property IncSearch: Boolean read GetIncSearch write SetIncSearch; property Indicator: Boolean read GetIndicator write SetIndicator; property FitRowHeightToText: Boolean read GetFitRowHeightToText write SetFitRowHeightToText; property Fixed3D: Boolean read GetFixed3D write SetFixed3D; property Frozen3D: Boolean read GetFrozen3D write SetFrozen3D; property HighlightFocus: Boolean read GetHighlightFocus write SetHighlightFocus; property MultiSelect: Boolean read GetMultiSelect write SetMultiSelect; property PreferIncSearch: Boolean read GetPreferIncSearch write SetPreferIncSearch; property ResizeWholeRightPart: Boolean read GetResizeWholeRightPart write SetResizeWholeRightPart; property RowHighlight: Boolean read GetRowHighlight write SetRowHighlight; property RowLines: Boolean read GetRowLines write SetRowLines; property RowSelect: Boolean read GetRowSelect write SetRowSelect; property Tabs: Boolean read GetTabs write SetTabs; property Titles: Boolean read GetTitles write SetTitles; property TraceColSizing: Boolean read GetTraceColSizing write SetTraceColSizing; end; ISHDBGridDisplayOptions = interface(ISHComponentOptions) ['{15BC2CAB-7B77-4568-B2E3-A9072B32B479}'] function GetLuminateSelection: Boolean; procedure SetLuminateSelection(Value: Boolean); function GetStriped: Boolean; procedure SetStriped(Value: Boolean); function GetFont: TFont; procedure SetFont(Value: TFont); function GetTitleFont: TFont; procedure SetTitleFont(Value: TFont); property LuminateSelection: Boolean read GetLuminateSelection write SetLuminateSelection; property Striped: Boolean read GetStriped write SetStriped; property Font: TFont read GetFont write SetFont; property TitleFont: TFont read GetTitleFont write SetTitleFont; end; ISHDBGridColorOptions = interface(ISHComponentOptions) ['{DE1AB5C8-B795-4A32-9B15-B489363AABCC}'] function GetBackground: TColor; procedure SetBackground(Value: TColor); function GetFixed: TColor; procedure SetFixed(Value: TColor); function GetCurrentRow: TColor; procedure SetCurrentRow(Value: TColor); function GetOddRow: TColor; procedure SetOddRow(Value: TColor); function GetNullValue: TColor; procedure SetNullValue(Value: TColor); property Background: TColor read GetBackground write SetBackground; property Fixed: TColor read GetFixed write SetFixed; property CurrentRow: TColor read GetCurrentRow write SetCurrentRow; property OddRow: TColor read GetOddRow write SetOddRow; property NullValue: TColor read GetNullValue write SetNullValue; end; ISHDBGridDisplayFormats = interface; ISHDBGridEditFormats = interface; ISHDBGridFormatOptions = interface(ISHComponentOptions) ['{ADEE178C-054C-444A-9F40-A03141DB7CB5}'] function GetDisplayFormats: ISHDBGridDisplayFormats; function GetEditFormats: ISHDBGridEditFormats; property DisplayFormats: ISHDBGridDisplayFormats read GetDisplayFormats; property EditFormats: ISHDBGridEditFormats read GetEditFormats; end; ISHDBGridDisplayFormats = interface ['{BBBFC0A3-C87D-44E5-972A-695FADCFC918}'] function GetStringFieldWidth: Integer; procedure SetStringFieldWidth(Value: Integer); function GetIntegerField: string; procedure SetIntegerField(Value: string); function GetFloatField: string; procedure SetFloatField(Value: string); function GetDateTimeField: string; procedure SetDateTimeField(Value: string); function GetDateField: string; procedure SetDateField(Value: string); function GetTimeField: string; procedure SetTimeField(Value: string); function GetNullValue: string; procedure SetNullValue(Value: string); property StringFieldWidth: Integer read GetStringFieldWidth write SetStringFieldWidth; property IntegerField: string read GetIntegerField write SetIntegerField; property FloatField: string read GetFloatField write SetFloatField; property DateTimeField: string read GetDateTimeField write SetDateTimeField; property DateField: string read GetDateField write SetDateField; property TimeField: string read GetTimeField write SetTimeField; property NullValue: string read GetNullValue write SetNullValue; end; ISHDBGridEditFormats = interface ['{0A2C1361-1901-47DE-B1B7-567409F69B5F}'] function GetIntegerField: string; procedure SetIntegerField(Value: string); function GetFloatField: string; procedure SetFloatField(Value: string); property IntegerField: string read GetIntegerField write SetIntegerField; property FloatField: string read GetFloatField write SetFloatField; end; implementation end.
unit CCJS_PartsPosition; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, DB, ADODB, ActnList, Grids, DBGrids; type TfrmCCJS_PartsPosition = class(TForm) pnlTop: TPanel; pnlTop_Order: TPanel; pnlTop_Price: TPanel; pnlTop_Client: TPanel; dsParts: TDataSource; qrspJSOParts: TADOStoredProc; pnlTop_ArtCode: TPanel; pnlTop_ArtName: TPanel; ActionMain: TActionList; aMain_Exit: TAction; pnlGrid: TPanel; DBGrid: TDBGrid; pnlControl: TPanel; pnlControl_Show: TPanel; pnlControl_Tool: TPanel; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aMain_ExitExecute(Sender: TObject); procedure dsPartsDataChange(Sender: TObject; Field: TField); private { Private declarations } ISignActive : integer; ModeParts : integer; OrderID : integer; { Номер интернет-заказа или звонка} NRN : integer; { Родительская ссылка } NUSER : integer; OrderPrice : real; OrderClient : string; ArtCode : integer; ArtName : string; qrspADO : TADOStoredProc; procedure ShowGets; procedure ExecCondition(QRSP : TADOStoredProc); procedure CreateCondition(QRSP : TADOStoredProc); public { Public declarations } procedure SetModeParts(Mode : integer); procedure SetOrder(Order : integer); procedure SetRN(RN : integer); procedure SetPrice(Price : real); procedure SetClient(Client : string); procedure SetUser(IDUSER : integer); procedure SetArtCode(Code : integer); procedure SetArtName(Name : string); end; const cFModeParts_JSO = 0; { Журнал интернет-заказов } var frmCCJS_PartsPosition: TfrmCCJS_PartsPosition; implementation uses Util, UMain, UCCenterJournalNetZkz; {$R *.dfm} procedure TfrmCCJS_PartsPosition.FormCreate(Sender: TObject); begin ISignActive := 0; end; procedure TfrmCCJS_PartsPosition.FormActivate(Sender: TObject); var SCaption : string; begin if ISignActive = 0 then begin { Иконка окна } FCCenterJournalNetZkz.imgMain.GetIcon(183,self.Icon); { Отображаем реквизиты заказа } SCaption := 'Заказ № ' + VarToStr(OrderID); pnlTop_Order.Caption := SCaption; pnlTop_Order.Width := TextPixWidth(SCaption, pnlTop_Order.Font) + 20; SCaption := 'Сумма ' + VarToStr(OrderPrice); pnlTop_Price.Caption := SCaption; pnlTop_Price.Width := TextPixWidth(SCaption, pnlTop_Price.Font) + 20; SCaption := OrderClient; pnlTop_Client.Caption := SCaption; pnlTop_Client.Width := TextPixWidth(SCaption, pnlTop_Client.Font) + 20; SCaption := 'АртКод ' + VarToStr(ArtCode); pnlTop_ArtCode.Caption := SCaption; pnlTop_ArtCode.Width := TextPixWidth(SCaption, pnlTop_ArtCode.Font) + 20; SCaption := ArtName; pnlTop_ArtName.Caption := SCaption; pnlTop_ArtName.Width := TextPixWidth(SCaption, pnlTop_ArtName.Font) + 20; ISignActive := 1; { Подставляем набор данных } case ModeParts of cFModeParts_JSO: begin self.Caption := 'Интернет заказы. Товар по частям'; dsParts.DataSet := qrspJSOParts; qrspADO := qrspJSOParts; ExecCondition(qrspADO); end; end; end; end; procedure TfrmCCJS_PartsPosition.ShowGets; var SCaption : string; begin if ISignActive = 1 then begin SCaption := 'В одном чеке не может быть больше ' + DBGrid.DataSource.DataSet.FieldByName('NCheckKol').AsString + ' шт.'; pnlControl_Show.Caption := SCaption; pnlControl_Show.Width := TextPixWidth(SCaption, pnlControl_Show.Font) + 20 end; end; procedure TfrmCCJS_PartsPosition.SetModeParts(Mode : integer); begin ModeParts := Mode; end; procedure TfrmCCJS_PartsPosition.SetOrder(Order : integer); begin OrderID := Order; end; procedure TfrmCCJS_PartsPosition.SetRN(RN : integer); begin NRN := RN; end; procedure TfrmCCJS_PartsPosition.SetPrice(Price : real); begin OrderPrice := Price; end; procedure TfrmCCJS_PartsPosition.SetClient(Client : string); begin OrderClient := Client; end; procedure TfrmCCJS_PartsPosition.SetUser(IDUSER : integer); begin NUSER := IDUSER; end; procedure TfrmCCJS_PartsPosition.SetArtCode(Code : integer); begin ArtCode := Code; end; procedure TfrmCCJS_PartsPosition.SetArtName(Name : string); begin ArtName := Name; end; procedure TfrmCCJS_PartsPosition.ExecCondition(QRSP : TADOStoredProc); var RNOrderID: Integer; begin if not QRSP.IsEmpty then RNOrderID := QRSP.FieldByName('NRN').AsInteger else RNOrderID := -1; if QRSP.Active then QRSP.Active := false; CreateCondition(QRSP); QRSP.Active := true; QRSP.Locate('NRN', RNOrderID, []); ShowGets; end; procedure TfrmCCJS_PartsPosition.CreateCondition(QRSP : TADOStoredProc); begin QRSP.Parameters.ParamValues['@NRN'] := NRN; end; procedure TfrmCCJS_PartsPosition.aMain_ExitExecute(Sender: TObject); begin Self.Close; end; procedure TfrmCCJS_PartsPosition.dsPartsDataChange(Sender: TObject; Field: TField); begin ShowGets; end; end.
program SmallestPrimeFactor; uses SysUtils; function IsPrime(Prime: Integer): Boolean; // Determine if a number is prime by brute force. // Test if any number from 2 up to a half of it is a factor. // If a factor exists it is prime. var Factor: Integer; begin IsPrime := True; for Factor := 2 to Integer(Prime DIV 2) do if (Prime MOD Factor) = 0 then IsPrime := False; end; var Number: Integer; PrimeFactor: Integer = 2; // 2 is smallest prime begin Write('Please enter a positive integer: '); Read(Number); if (Number = 1) or (Number = -1) then begin // All prime numbers are, by definition, greater than one. // So 1 and -1 do not have any prime factors. Writeln('Smallest Prime Factor: N/A'); // Exit here to not run into factor finding code. // As no prime factors of 1 or -1 exist. Readln(); Exit(); end; while (Number MOD PrimeFactor) <> 0 do // While prime is not factor of number. begin // Get next prime. PrimeFactor := PrimeFactor + 1; while not IsPrime(PrimeFactor) do PrimeFactor := PrimeFactor + 1; end; Writeln('Smallest Prime Factor: ', PrimeFactor); Readln end.
{------------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: uHighlighterProcs.pas, released 2000-06-23. The Initial Author of the Original Code is Michael Hieke. All Rights Reserved. Contributors to the SynEdit project are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. $Id: uHighlighterProcs.pas,v 1.3 2002/06/15 06:57:24 etrusco Exp $ You may retrieve the latest version of this file at the SynEdit home page, located at http://SynEdit.SourceForge.net Known Issues: -------------------------------------------------------------------------------} unit uHighlighterProcs; interface uses Classes, SynEditHighlighter; procedure GetHighlighters(AOwner: TComponent; AHighlighters: TStrings; AppendToList: boolean); function GetHighlightersFilter(AHighlighters: TStrings): string; function GetHighlighterFromFileExt(AHighlighters: TStrings; Extension: string): TSynCustomHighlighter; function GetHighlighterFromLanguageName(LanguageName : String; AHighlighters: TStrings) : TSynCustomHighlighter; implementation uses SysUtils; procedure GetHighlighters(AOwner: TComponent; AHighlighters: TStrings; AppendToList: boolean); var i: integer; Highlighter: TSynCustomHighlighter; begin if Assigned(AOwner) and Assigned(AHighlighters) then begin if not AppendToList then AHighlighters.Clear; for i := AOwner.ComponentCount - 1 downto 0 do begin if not (AOwner.Components[i] is TSynCustomHighlighter) then continue; Highlighter := AOwner.Components[i] as TSynCustomHighlighter; // only one highlighter for each language if AHighlighters.IndexOf(Highlighter.GetLanguageName) = -1 then AHighlighters.AddObject(Highlighter.GetLanguageName, Highlighter); end; end; end; function GetHighlightersFilter(AHighlighters: TStrings): string; var i: integer; Highlighter: TSynCustomHighlighter; begin Result := ''; if Assigned(AHighlighters) then for i := 0 to AHighlighters.Count - 1 do begin if not (AHighlighters.Objects[i] is TSynCustomHighlighter) then continue; Highlighter := TSynCustomHighlighter(AHighlighters.Objects[i]); if Highlighter.DefaultFilter = '' then continue; Result := Result + Highlighter.DefaultFilter; if Result[Length(Result)] <> '|' then Result := Result + '|'; end; end; function GetHighlighterFromFileExt(AHighlighters: TStrings; Extension: string): TSynCustomHighlighter; var ExtLen: integer; i, j: integer; Highlighter: TSynCustomHighlighter; Filter: string; begin Extension := LowerCase(Extension); ExtLen := Length(Extension); if Assigned(AHighlighters) and (ExtLen > 0) then begin for i := 0 to AHighlighters.Count - 1 do begin if not (AHighlighters.Objects[i] is TSynCustomHighlighter) then continue; Highlighter := TSynCustomHighlighter(AHighlighters.Objects[i]); Filter := LowerCase(Highlighter.DefaultFilter); j := Pos('|', Filter); if j > 0 then begin Delete(Filter, 1, j); j := Pos(Extension, Filter); if (j > 0) and ((j + ExtLen > Length(Filter)) or (Filter[j + ExtLen] = ';')) then begin Result := Highlighter; exit; end; end; end; end; Result := nil; end; function GetHighlighterFromLanguageName(LanguageName : String; AHighlighters: TStrings) : TSynCustomHighlighter; Var Index : integer; begin Result := nil; Index := AHighlighters.IndexOf(LanguageName); if Index >= 0 then Result := AHighlighters.Objects[Index] as TSynCustomHighlighter end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXFAXOD0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {* Shows how to use the Fax On Demand. *} {*********************************************************} unit ExFaxOD0; interface uses WinTypes, WinProcs, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AdFax, AdFStat, AdTapi, AdPort, AdTUtil, ExtCtrls, OoMisc; type TForm1 = class(TForm) ApdTapiDevice1: TApdTapiDevice; ApdSendFax1: TApdSendFax; ApdFaxStatus1: TApdFaxStatus; ApdComPort1: TApdComPort; Button1: TButton; AnswerButton: TButton; GroupBox1: TGroupBox; Label1: TLabel; Edit1: TEdit; Label2: TLabel; Edit2: TEdit; Label3: TLabel; Edit3: TEdit; Timer1: TTimer; procedure Button1Click(Sender: TObject); procedure AnswerButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ApdTapiDevice1TapiDTMF(CP: TObject; Digit: Char; ErrorCode: Longint); procedure ApdTapiDevice1TapiConnect(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure ApdTapiDevice1TapiPortOpen(Sender: TObject); procedure ApdSendFax1FaxFinish(CP: TObject; ErrorCode: Integer); procedure ApdTapiDevice1TapiWaveNotify(CP: TObject; Msg: TWaveMessage); private { Private declarations } public { Public declarations } end; const CurrentState: Integer = 0; StateIdle = 0; StateGreeting = 1; StateEndCall = 2; StateGettingNumber = 3; StatePlayBack = 4; StateWaitReply = 5; var Form1: TForm1; WaveFileDir: String; SendTheFax: Boolean; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin ApdTapiDevice1.SelectDevice; ApdTapiDevice1.EnableVoice := True; end; procedure TForm1.AnswerButtonClick(Sender: TObject); begin if not ApdTapiDevice1.EnableVoice then ApdTapiDevice1.EnableVoice := True; if ApdTapiDevice1.EnableVoice then begin ApdTapiDevice1.AutoAnswer; end else MessageDlg('The Selected device does not support Voice Extensions.', mtInformation, [mbOk], 0); end; procedure TForm1.FormCreate(Sender: TObject); begin SendTheFax := False; WaveFileDir := ExtractFilePath(ParamStr(0)); WaveFileDir := Copy(WaveFileDir, 1, Pos('EXAMPLES',UpperCase(WaveFileDir))+8); ApdSendFax1.FaxFile := WaveFileDir+'aprologo.apf'; if (FileGetAttr(ApdSendFax1.FaxFile) and faReadOnly) > 0 then begin MessageDlg('The AProLogo.APF fax file is designated Read-Only and may not be used in this ' + ' example until this attribute is changed to Read/Write.', mtInformation, [mbOK], 0); Halt; end; end; procedure TForm1.ApdTapiDevice1TapiDTMF(CP: TObject; Digit: Char; ErrorCode: Longint); var i: Integer; begin case CurrentState of StateIdle : begin Edit1.Text := 'StateIdle'; end; StateGreeting : begin Edit1.Text := 'StateGreeting'; case Digit of '5': begin CurrentState := StateGettingNumber; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'enter.wav'); end; '*': begin CurrentState := StateEndCall; ApdTapiDevice1.InterruptWave := False; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'goodbye.wav'); end; else begin ApdTapiDevice1.PlayWaveFile(WaveFileDir+'Play'+Digit+'.wav'); while ApdTapiDevice1.WaveState = wsPlaying do Application.ProcessMessages; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'invalid.wav'); end; end; end; StateEndCall : begin {nothing to do here...} end; StateGettingNumber : begin Edit1.Text := 'StateGettingNumber'; case Digit of '*': begin Edit3.Text := ''; ApdTapiDevice1TapiConnect(Self); end; '#': begin if Edit3.Text = '' then ApdTapiDevice1TapiConnect(Self) else begin CurrentState := StatePlayBack; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'uentered.wav'); for i := 1 to Length(Edit3.Text) do begin while ApdTapiDevice1.WaveState = wsPlaying do Application.ProcessMessages; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'play'+Copy(Edit3.Text, i, 1)+'.wav'); end; while ApdTapiDevice1.WaveState = wsPlaying do Application.ProcessMessages; CurrentState := StateWaitReply; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'correct.wav'); end; end; else begin Edit3.Text := Edit3.Text+Digit; end; end; end; StateWaitReply : begin Edit1.Text := 'StateWaitReply'; case Digit of '*': begin Edit3.Text := ''; CurrentState := StateGettingNumber; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'enter.wav'); end; '#': begin {wait for previous message to conclude then play final message} while ApdTapiDevice1.WaveState = wsPlaying do Application.ProcessMessages; SendTheFax := True; ApdTapiDevice1.InterruptWave := False; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'hangup.wav'); CurrentState := StateEndCall; end; end; end; end; end; procedure TForm1.ApdTapiDevice1TapiConnect(Sender: TObject); begin {Play Greeting} if ApdTapiDevice1.EnableVoice then begin CurrentState := StateGreeting; ApdTapiDevice1.PlayWaveFile(WaveFileDir+'welcome.wav'); end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; {Send the Fax} ApdTapiDevice1.EnableVoice := False; ApdSendFax1.PhoneNumber := Edit3.Text; ApdTapiDevice1.ConfigAndOpen; end; procedure TForm1.ApdTapiDevice1TapiPortOpen(Sender: TObject); begin if (SendTheFax) and (not ApdTapiDevice1.EnableVoice) then ApdSendFax1.StartTransmit; end; procedure TForm1.ApdSendFax1FaxFinish(CP: TObject; ErrorCode: Integer); begin if ErrorCode = 0 then ShowMessage('Fax sent successfully'); CurrentState := StateIdle; end; procedure TForm1.ApdTapiDevice1TapiWaveNotify(CP: TObject; Msg: TWaveMessage); begin if Msg = waPlayOpen then Edit2.Text := 'Playing Wave: '+ExtractFileName(ApdTapiDevice1.WaveFileName) else if Msg = waPlayDone then Edit2.Text := 'Wave Device Idle...'; case CurrentState of StateEndCall: begin Edit1.Text := 'StateEndCall'; if Msg = waPlayDone then begin ApdTapiDevice1.CancelCall; if SendTheFax then Timer1.Enabled := True; end; end; end; end; end.
unit uBASE_Form; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dxRibbonForm, cxClasses, dxRibbon, cxControls, uParams; type TBASE_Form = class(TdxRibbonForm) dxRibbonTab1: TdxRibbonTab; dxRibbon: TdxRibbon; procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private FObjectID: integer; FAccessManager: TObject; FParams: TParamCollection; procedure RestoryGrids; protected function RegistryAddRoot: string; virtual; procedure SavePosition; virtual; procedure RestorePosition; virtual; public property Params: TParamCollection read FParams; property ObjectID: integer read FObjectID write FObjectID; property AccessManager: TObject read FAccessManager write FAccessManager; procedure RestoreParams; virtual; abstract; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation {$R *.dfm} uses Registry, uMain, uFrameBaseGrid, uFrameGrid; { TBASE_Form } procedure TBASE_Form.SavePosition; var r: TRegistry; begin if ObjectID=0 then exit; r:=TRegistry.Create; try r.RootKey:=HKEY_CURRENT_USER; if r.OpenKey('Software\SIS\Реестр имущества\Object Layout\'+IntToStr(ObjectID)+RegistryAddRoot, true) then begin r.WriteInteger('FormLeft', Left); r.WriteInteger('FormTop', Top); r.WriteInteger('FormWidth', Width); r.WriteInteger('FormHeight', Height); r.WriteInteger('WindowState', integer(WindowState)); end; finally r.Free; end; end; procedure TBASE_Form.RestorePosition; var r: TRegistry; i: integer; begin if ObjectID=0 then exit; r:=TRegistry.Create; try r.RootKey:=HKEY_CURRENT_USER; if r.OpenKey('Software\SIS\Реестр имущества\Object Layout\'+IntToStr(ObjectID)+RegistryAddRoot, false) then begin if r.ValueExists('FormLeft') then begin i:=r.ReadInteger('FormLeft'); if (i>0) and (i<Screen.Width) then Left:=i; end; if r.ValueExists('FormTop') then begin i:=r.ReadInteger('FormTop'); if (i>0) and (i<Screen.Height) then Top:=i; end; if r.ValueExists('FormWidth') then begin i:=r.ReadInteger('FormWidth'); if (i>50) then Width:=i; end; if r.ValueExists('FormHeight') then begin i:=r.ReadInteger('FormHeight'); if (i>50) then Height:=i; end; if r.ValueExists('WindowState') then begin i:=r.ReadInteger('WindowState'); if i in [0..2] then WindowState:=TWindowState(i); end; end; finally r.Free; end; end; function TBASE_Form.RegistryAddRoot: string; begin result:=''; end; procedure TBASE_Form.FormDestroy(Sender: TObject); begin SavePosition; end; procedure TBASE_Form.FormShow(Sender: TObject); begin frmMain.bliWindow.Items.AddObject(Caption, Self); RestorePosition; // RestoryGrids; end; constructor TBASE_Form.Create(AOwner: TComponent); begin inherited; FParams:=TParamCollection.Create(TParamItem); end; destructor TBASE_Form.Destroy; var i: integer; begin Params.Free; i:=frmMain.bliWindow.Items.IndexOfObject(Self); if i>=0 then frmMain.bliWindow.Items.Delete(i); inherited; end; procedure TBASE_Form.RestoryGrids; var i: integer; procedure IterRestoryGrids(AComponent: TComponent); var i: integer; begin if AComponent is TFrameBaseGrid then TFrameBaseGrid(AComponent).RestoryGrid; //if AComponent is TFrameGrid then // TFrameGrid(AComponent).ShowGroupSummaryByMeta(true); for i:=0 to AComponent.ComponentCount-1 do IterRestoryGrids(AComponent.Components[i]); end; begin for i:=0 to ComponentCount-1 do IterRestoryGrids(Components[i]); end; end.
unit Childwin; interface uses Windows, Classes, Graphics, Forms, Controls, StdCtrls, Messages, aiOGL, Menus, Sysutils, Main; type TMDIChild = class(TForm) PopupMenu: TPopupMenu; ObjectNameItem: TMenuItem; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormActivate(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); procedure ObjectNameItemClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); private LastX, LastY: integer; // вспомогательные переменные public glScene: TMyScene; // наша сцена protected procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; end; var StepT: single = 25; StepR: single = 5; // шаги перемещений и вращений сцены implementation uses ShellAPI, Objects, OpenGL; {$R *.DFM} procedure TMDIChild.FormCreate(Sender: TObject); begin DragAcceptFiles(Handle, True); // форма может принимать файлы end; procedure TMDIChild.FormClose(Sender: TObject; var Action: TCloseAction); begin glScene.Free; Action:= caFree; with MainForm do SetEnable(MDIChildCount <> 1); end; procedure TMDIChild.FormActivate(Sender: TObject); begin SetCurScene(glScene); // установить текущую сцену end; procedure TMDIChild.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; GLObject: TGLObject; begin if (Button = mbRight) then begin SetFocus; GLObject:= CurScene.GetObjectFromScreenCoord(X,Y); // получить объект под указателем мыши if GLObject = nil then Exit; PopUpMenu.Items[0].Tag:= Integer(glObject); PopUpMenu.Items[0].Caption:= GLObject.Name; // имя объекта P:= ClientToScreen(Point(X, Y)); PopUpMenu.PopUp(P.X, P.Y); end else if Button = mbLeft then begin LastX:= X; LastY:= Y; end; end; procedure TMDIChild.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin // вращаем сцену if ssLeft in Shift then begin if ssShift in Shift then CurScene.Rotate(Y - LastY, X - LastX, 0) else CurScene.Rotate(Y - LastY, 0, X - LastX); LastX:= X; LastY:= Y; CurScene.Paint; end; end; procedure TMDIChild.WMDropFiles(var Msg: TWMDropFiles); var Buffer: array[0..MAX_PATH] of Char; Count: cardinal; begin // перетаскивание файла Count:= DragQueryFile(Msg.Drop, $FFFFFFFF, nil, 0); if Count > 0 then begin DragQueryFile(Msg.Drop, 0, Buffer, MAX_PATH); DragFinish(Msg.Drop); Msg.Result:= 0; SetFocus; MainForm.LoadFile(Buffer); end; end; procedure TMDIChild.ObjectNameItemClick(Sender: TObject); begin // показываем ObjectsDlg и текущим является выбранный объект Application.CreateForm(TObjectsDlg, ObjectsDlg); with ObjectsDlg.ObjectsBox do ItemIndex:= Items.IndexOfObject(TglObject((Sender as TMenuItem).Tag)); ObjectsDlg.ObjectsBoxClick(Sender); ObjectsDlg.ShowModal; ObjectsDlg.Free; end; procedure TMDIChild.FormKeyPress(Sender: TObject; var Key: Char); begin with CurScene do case Key of // 6,4 - перемещение вдоль оси X; 8,2 - перемещение вдоль оси Y; // '+' '-' - перемещение вдоль оси Z '6': Translate(-StepT, 0, 0); '4': Translate( StepT, 0, 0); '8': Translate(0, -StepT, 0); '2': Translate(0, StepT, 0); '+': Translate(0, 0, StepT); '-': Translate(0, 0, -StepT); // масштабирование 'Q','q': Scale( 0.1, 0, 0); 'W','w': Scale(-0.1, 0, 0); 'E','e': Scale(0, 0.1, 0); 'R','r': Scale(0, -0.1, 0); 'D','d': Scale(0, 0, 0.1); 'F','f': Scale(0, 0, -0.1); end; CurScene.Paint; end; procedure TMDIChild.FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); var Key: char; begin Key:= '+'; FormKeyPress(Sender, Key); end; procedure TMDIChild.FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); var Key: char; begin Key:= '-'; FormKeyPress(Sender, Key); end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clInetSuiteReg; interface {$I clVer.inc} uses Classes, {$IFDEF DELPHI6}DesignEditors, DesignIntf, {$ELSE} DsgnIntf, {$ENDIF} TypInfo, clDEditors, clDownLoader, clMultiDownLoader, clNewsChecker, clUploader, clMultiUploader, clProgressBar, clPop3, clSmtp, clConnection, clMailMessage, clHttpRequest, clHtmlParser, clEncoder, clImap4, clSMimeMessage, clFtp, clSoap, clFtpServer, clFtpFileHandler, clWebUpdate, clGZip, clCert, clNntp, clHttp, clPop3Server, clSmtpServer, clSmtpRelay, clImap4Server, clNntpServer, clDnsQuery, clSmtpFileHandler, clPop3FileHandler, clImap4FileHandler, clHttpMail, clWebDav; type TclMessageBodyProperty = class(TPropertyEditor) public function GetValue: string; override; function GetAttributes: TPropertyAttributes; override; procedure Edit; override; end; TclMessageBodyEditor = class(TclBaseEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TclHttpRequestEditor = class(TclBaseEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; procedure Register; implementation uses SysUtils, clRequestEdit, clBodyEdit, clDCUtils; const cHttpRequestEditor = 'Edit HTTP Request...'; cMessageBodyEditor = 'Edit Mail Message...'; procedure Register; begin RegisterComponents('Clever Internet Suite', [ TclCertificateStore, TclDnsQuery, TclDownLoader, TclEncoder, TclFtp, TclFtpFileHandler, TclFtpServer, TclGZip, TclHtmlParser, TclHttp, TclHttpMail, TclHttpRequest, TclImap4, TclImap4FileHandler, TclImap4Server, TclInternetConnection, TclMailMessage,TclMultiDownLoader, TclMultiUploader, TclNewsChecker, TclNntp, TclNntpServer, TclPop3, TclPop3FileHandler, TclPop3Server, TclProgressBar, TclSMimeMessage, TclSmtp, TclSmtpFileHandler, TclSmtpRelay, TclSmtpServer, TclSoapMessage, TclUploader, TclWebUpdate, TclWebDav ]); RegisterComponentEditor(TclCertificateStore, TclBaseEditor); RegisterComponentEditor(TclDnsQuery, TclBaseEditor); RegisterComponentEditor(TclDownLoader, TclBaseEditor); RegisterComponentEditor(TclEncoder, TclBaseEditor); RegisterComponentEditor(TclFtp, TclBaseEditor); RegisterComponentEditor(TclFtpFileHandler, TclBaseEditor); RegisterComponentEditor(TclFtpServer, TclBaseEditor); RegisterComponentEditor(TclGZip, TclBaseEditor); RegisterComponentEditor(TclHtmlParser, TclBaseEditor); RegisterComponentEditor(TclHttp, TclBaseEditor); RegisterComponentEditor(TclHttpMail, TclBaseEditor); RegisterComponentEditor(TclHttpRequest, TclHttpRequestEditor); RegisterComponentEditor(TclImap4, TclBaseEditor); RegisterComponentEditor(TclImap4FileHandler, TclBaseEditor); RegisterComponentEditor(TclImap4Server, TclBaseEditor); RegisterComponentEditor(TclInternetConnection, TclBaseEditor); RegisterComponentEditor(TclMailMessage, TclMessageBodyEditor); RegisterComponentEditor(TclMultiDownLoader, TclBaseEditor); RegisterComponentEditor(TclMultiUploader, TclBaseEditor); RegisterComponentEditor(TclNewsChecker, TclBaseEditor); RegisterComponentEditor(TclNntp, TclBaseEditor); RegisterComponentEditor(TclNntpServer, TclBaseEditor); RegisterComponentEditor(TclPop3, TclBaseEditor); RegisterComponentEditor(TclPop3FileHandler, TclBaseEditor); RegisterComponentEditor(TclPop3Server, TclBaseEditor); RegisterComponentEditor(TclProgressBar, TclBaseEditor); RegisterComponentEditor(TclSMimeMessage, TclMessageBodyEditor); RegisterComponentEditor(TclSmtp, TclBaseEditor); RegisterComponentEditor(TclSmtpFileHandler, TclBaseEditor); RegisterComponentEditor(TclSmtpRelay, TclBaseEditor); RegisterComponentEditor(TclSmtpServer, TclBaseEditor); RegisterComponentEditor(TclSoapMessage, TclHttpRequestEditor); RegisterComponentEditor(TclUploader, TclBaseEditor); RegisterComponentEditor(TclWebUpdate, TclBaseEditor); RegisterComponentEditor(TclWebDav, TclBaseEditor); RegisterPropertyEditor(TypeInfo(string), TclDownLoader, 'LocalFile', TclSaveFileProperty); RegisterPropertyEditor(TypeInfo(string), TclDownLoadItem, 'LocalFile', TclSaveFileProperty); RegisterPropertyEditor(TypeInfo(string), TclUploader, 'LocalFile', TclOpenFileProperty); RegisterPropertyEditor(TypeInfo(string), TclUploadItem, 'LocalFile', TclOpenFileProperty); RegisterPropertyEditor(TypeInfo(TclMessageBodies), TclMailMessage, 'Bodies', TclMessageBodyProperty); end; { TclMessageBodyEditor } procedure TclMessageBodyEditor.ExecuteVerb(Index: Integer); begin inherited ExecuteVerb(Index); if ModifyMessageBodies(TclMailMessage(Component).Bodies) then begin Designer.Modified; end; end; function TclMessageBodyEditor.GetVerb(Index: Integer): string; begin Result := inherited GetVerb(Index); if Index = GetVerbCount() - 1 then begin Result := cMessageBodyEditor; end; end; function TclMessageBodyEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount() + 1; end; { TclMessageBodyProperty } procedure TclMessageBodyProperty.Edit; begin if ModifyMessageBodies(TclMailMessage(GetComponent(0)).Bodies) then Modified; end; function TclMessageBodyProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; end; function TclMessageBodyProperty.GetValue: string; begin Result := Format('(%s)', [TclMessageBodies.ClassName]); end; { TclHttpRequestEditor } procedure TclHttpRequestEditor.ExecuteVerb(Index: Integer); begin inherited ExecuteVerb(Index); if ModifyHttpRequest(TclHttpRequest(Component)) then begin Designer.Modified; end; end; function TclHttpRequestEditor.GetVerb(Index: Integer): string; begin Result := inherited GetVerb(Index); if Index = GetVerbCount() - 1 then begin Result := cHttpRequestEditor; end; end; function TclHttpRequestEditor.GetVerbCount: Integer; begin Result := inherited GetVerbCount() + 1; end; end.
{: Basic Octree/Collision demo.<p> Robert Hayes, March 2002. This demo uses the new Octree class to quickly detect triangle-level collisions with a sphere. See Octree.SphereIntersect() for detailed comments. } unit Unit1; interface uses Classes, SysUtils, Controls, Forms, GLKeyboard, GLVectorGeometry, GLScene, GLVectorFileObjects, GLObjects, GLLCLViewer, GLCadencer, ExtCtrls, StdCtrls, GLNavigator, ComCtrls, GLGeomObjects, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLLightSource1: TGLLightSource; DummyCube1: TGLDummyCube; FreeForm1: TGLFreeForm; Sphere1: TGLSphere; ArrowLine1: TGLArrowLine; GLSceneViewer2: TGLSceneViewer; GLCamera2: TGLCamera; GLCadencer1: TGLCadencer; Timer1: TTimer; DummyCube2: TGLDummyCube; Sphere2: TGLSphere; GLLightSource2: TGLLightSource; Panel1: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; TrackBar1: TTrackBar; Button1: TButton; Lines1: TGLLines; procedure FormCreate(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); procedure Timer1Timer(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } colTotalTime: single; // for timing collision detection colCount: integer; procedure AddToTrail(const p: TVector); public { Public declarations } mousex, mousey: integer; end; var Form1: TForm1; implementation {$R *.lfm} uses GLFile3DS, GLUtils, LCLType; procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); FreeForm1.LoadFromFile('BoxedIn.3ds'); FreeForm1.BuildOctree; Label1.Caption := 'Octree Nodes : ' + IntToStr(FreeForm1.Octree.NodeCount); Label2.Caption := 'Tri Count Octree: ' + IntToStr(FreeForm1.Octree.TriCountOctree); Label3.Caption := 'Tri Count Mesh : ' + IntToStr(FreeForm1.Octree.TriCountMesh); Lines1.AddNode(0, 0, 0); Lines1.ObjectStyle := Lines1.ObjectStyle + [osDirectDraw]; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); var rayStart, rayVector: TVector; velocity: single; pPoint: TVector; pNormal: TVector; t: int64; begin if IsKeyDown(VK_ESCAPE) then Close; Velocity := Trackbar1.Position * deltaTime * 50; t := StartPrecisionTimer; with FreeForm1 do begin SetVector(rayStart, Sphere2.AbsolutePosition); SetVector(rayVector, Sphere2.AbsoluteDirection); NormalizeVector(rayVector); //Note: since collision may be performed on multiple meshes, we might need to know which hit // is closest (ie: d:=raystart - pPoint). if OctreeSphereSweepIntersect(raystart, rayvector, velocity, Sphere2.Radius, @pPoint, @pNormal) then begin // Show the polygon intersection point NormalizeVector(pNormal); Sphere1.Position.AsVector := pPoint; Sphere1.Direction.AsVector := pNormal; // Make it rebound... with Sphere2.Direction do AsAffineVector := VectorReflect(AsAffineVector, AffineVectorMake(pNormal)); // Add some "english"... with Sphere2.Direction do begin X := x + random / 10; Y := y + random / 10; Z := z + random / 10; end; // Add intersect point to trail AddToTrail(pPoint); end else begin Sphere2.Move(velocity); //No collision, so just move the ball. end; end; // Last trail point is always the sphere's current position Lines1.Nodes.Last.AsVector := Sphere2.Position.AsVector; colTotalTime := colTotalTime + StopPrecisionTimer(t); Inc(colCount); end; procedure TForm1.AddToTrail(const p: TVector); var i, k: integer; begin Lines1.Nodes.Last.AsVector := p; Lines1.AddNode(0, 0, 0); if Lines1.Nodes.Count > 20 then // limit trail to 20 points Lines1.Nodes[0].Free; for i := 0 to 19 do begin k := Lines1.Nodes.Count - i - 1; if k >= 0 then TGLLinesNode(Lines1.Nodes[k]).Color.Alpha := 0.95 - i * 0.05; end; end; procedure TForm1.Timer1Timer(Sender: TObject); var t: single; begin if colCount > 0 then t := colTotalTime * 1000 / colCount else t := 0; Caption := Format('%.2f FPS - %.3f ms for collisions/frame', [GLSceneViewer2.FramesPerSecond, t]); GLSceneViewer2.ResetPerformanceMonitor; colTotalTime := 0; colCount := 0; end; procedure TForm1.Button1Click(Sender: TObject); begin //If the ball gets stuck in a pattern, hit the reset button. with Sphere2.Position do begin X := random; Y := random; Z := random; end; with Sphere2.Direction do begin X := random; if random > 0.5 then x := -x; Y := random; if random > 0.5 then y := -y; Z := random; if random > 0.5 then z := -z; end; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Console.Command.Pack; interface uses VSoft.CancellationToken, Spring.Container.Common, DPM.Core.Configuration.Interfaces, DPM.Core.Logging, DPM.Console.ExitCodes, DPM.Console.Command.Base, DPM.Core.Spec.Interfaces, DPM.Core.Packaging, DPM.Core.Constants; type TPackCommand = class(TBaseCommand) private FWriter : IPackageWriter; protected function Execute(const cancellationToken : ICancellationToken) : TExitCode;override; public constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager; const writer : IPackageWriter);reintroduce; end; implementation uses System.SysUtils, System.IOUtils, VSoft.SemanticVersion, DPM.Core.Types, DPM.Console.Banner, DPM.Console.Options, DPM.Core.Options.Common, DPM.Core.Options.Pack; { TPackCommand } constructor TPackCommand.Create(const logger : ILogger; const configurationManager : IConfigurationManager; const writer : IPackageWriter); begin inherited Create(logger,configurationManager); FWriter := writer; end; function TPackCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode; var mcVer : TSemanticVersion; packVer : TPackageVersion; error : string; begin TPackOptions.Default.ApplyCommon(TCommonOptions.Default); if not TPackOptions.Default.Validate(Logger) then begin result := TExitCode.InvalidArguments; exit; end; //This should just be an api call into the core, don't do all the work here! //just check for required args here. Logger.Information('Pack Command invoked'); if TPackOptions.Default.SpecFile = '' then begin Logger.Error('No Spec file provided!'); Exit(TExitCode.MissingArg); end; //does it really make sense to allow this to be overriden from the command line? if TPackOptions.Default.MinClientVersion <> cDPMClientVersion then begin if not TSemanticVersion.TryParseWithError(TPackOptions.Default.MinClientVersion,mcVer,error ) then begin Logger.Error('MinClientVersion : ' + error); Exit(TExitCode.InvalidArguments); end; // defVer := TSemanticVersion.Parse(cDPMClientVersion); // if mcVer > defVer then // begin // Logger.Error('MinClientVersion must be at less than or equal to : ' + defVer.ToString); // Exit(TExitCode.InvalidArguments); // // end; end; if TPackOptions.Default.Version <> '' then begin if not TPackageVersion.TryParseWithError(TPackOptions.Default.Version, packVer, error) then begin Logger.Error('Invalid Version : ' + error); Exit(TExitCode.InvalidArguments); end; end; try if not FWriter.WritePackageFromSpec(cancellationToken, TPackOptions.Default) then exit(TExitCode.Error); except on e : Exception do begin Logger.Error('Error creating package : ' + e.Message); exit(TExitCode.Error); end; end; result := TExitCode.OK; end; end.
unit utils; interface uses Windows, SysUtils, Forms; procedure SaveConfig; function LoadConfig: Boolean; function GetToolsDir : string; function CheckBinaries: Boolean; implementation uses XMLDom, XMLIntf, MSXMLDom, XMLDoc, ActiveX, Main; var ConfigFileName: TFileName; procedure SaveConfig; var XMLDoc: IXMLDocument; CurrentNode: IXMLNode; procedure AddXMLNode(var XML: IXMLDocument; const Key, Value: string); overload; begin CurrentNode := XMLDoc.CreateNode(Key); CurrentNode.NodeValue := Value; XMLDoc.DocumentElement.ChildNodes.Add(CurrentNode); end; procedure AddXMLNode(var XML: IXMLDocument; const Key: string; const Value: Integer); overload; begin CurrentNode := XMLDoc.CreateNode(Key); CurrentNode.NodeValue := Value; XMLDoc.DocumentElement.ChildNodes.Add(CurrentNode); end; procedure AddXMLNode(var XML: IXMLDocument; const Key: string; const Value: Boolean); overload; begin CurrentNode := XMLDoc.CreateNode(Key); CurrentNode.NodeValue := Value; XMLDoc.DocumentElement.ChildNodes.Add(CurrentNode); end; begin XMLDoc := TXMLDocument.Create(nil); try with XMLDoc do begin Options := [doNodeAutoCreate, doAttrNull]; ParseOptions:= []; NodeIndentStr:= ' '; Active := True; Version := '1.0'; Encoding := 'ISO-8859-1'; end; // On crée la racine XMLDoc.DocumentElement := XMLDoc.CreateNode('bootmakecfg'); AddXMLNode(XMLDoc, 'source', Main_Form.eSrc.Text); AddXMLNode(XMLDoc, 'destination', Main_Form.eDest.Text); AddXMLNode(XMLDoc, 'volumename', Main_Form.eVolumeName.Text); AddXMLNode(XMLDoc, 'ipbin', Main_Form.eIpBin.Text); AddXMLNode(XMLDoc, 'iso', Main_Form.eISO.Text); XMLDoc.SaveToFile(ConfigFileName); finally XMLDoc.Active := False; XMLDoc := nil; end; end; function LoadConfig: Boolean; var XMLDoc: IXMLDocument; Node: IXMLNode; begin Result := False; if not FileExists(ConfigFileName) then Exit; XMLDoc := TXMLDocument.Create(nil); try with XMLDoc do begin Options := [doNodeAutoCreate]; ParseOptions:= []; NodeIndentStr:= ' '; Active := True; Version := '1.0'; Encoding := 'ISO-8859-1'; end; XMLDoc.LoadFromFile(ConfigFileName); if XMLDoc.DocumentElement.NodeName <> 'bootmakecfg' then Exit; try Node := XMLDoc.DocumentElement.ChildNodes.FindNode('source'); if Assigned(Node) then Main_Form.eSrc.Text := Node.NodeValue; except end; try Node := XMLDoc.DocumentElement.ChildNodes.FindNode('destination'); if Assigned(Node) then Main_Form.eDest.Text := Node.NodeValue; except end; try Node := XMLDoc.DocumentElement.ChildNodes.FindNode('volumename'); if Assigned(Node) then Main_Form.eVolumeName.Text := Node.NodeValue; except end; try Node := XMLDoc.DocumentElement.ChildNodes.FindNode('ipbin'); if Assigned(Node) then Main_Form.eIpBin.Text := Node.NodeValue; except end; try Node := XMLDoc.DocumentElement.ChildNodes.FindNode('iso'); if Assigned(Node) then Main_Form.eISO.Text := Node.NodeValue; except end; Result := True; finally XMLDoc.Active := False; XMLDoc := nil; end; end; function GetToolsDir : string; begin Result := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'Tools\'; end; function CheckBinaries: Boolean; procedure MsgBox(Text: string); begin MessageBoxA(Application.Handle, PChar(Text), 'Error', MB_ICONERROR); end; const FILES_NAMES_TO_CHECK : array[0..3] of string = ('cdi4dc.exe', 'ipinj.exe', 'mkisofs.exe', 'cygwin1.dll'); var i : Integer; begin Result := False; if not DirectoryExists(GetToolsDir) then begin MsgBox('Tools directory not found !'); Exit; end; for i := Low(FILES_NAMES_TO_CHECK) to High(FILES_NAMES_TO_CHECK) do begin if not FileExists(GetToolsDir + FILES_NAMES_TO_CHECK[i]) then begin MsgBox('File ' + FILES_NAMES_TO_CHECK[i] + ' not found !' + #13#10 + 'Make sure you have this file in Tools directory !'); Exit; end; end; Result := True; end; initialization ConfigFileName := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'config.xml'; end.
unit uRelatCondicoesPagto; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, JvComponentBase, JvEnterTab, Data.DB, Vcl.StdCtrls, JvExStdCtrls, JvButton, JvCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Mask, JvExMask, JvToolEdit, uDadosRelat, System.DateUtils; type TfrmRelatCondicoesPagto = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; edtDataFim: TJvDateEdit; edtDataIni: TJvDateEdit; GroupBoxLista: TGroupBox; dbgGrid: TDBGrid; Panel1: TPanel; btnMarcarDesmarcar: TBitBtn; btnOkAssinante: TJvImgBtn; DataSource: TDataSource; JvEnterAsTab: TJvEnterAsTab; procedure btnMarcarDesmarcarClick(Sender: TObject); procedure dbgGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure dbgGridCellClick(Column: TColumn); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnOkAssinanteClick(Sender: TObject); private { Private declarations } FModuloRelat: TdmDadosRelat; public { Public declarations } end; var frmRelatCondicoesPagto: TfrmRelatCondicoesPagto; implementation {$R *.dfm} procedure TfrmRelatCondicoesPagto.btnMarcarDesmarcarClick(Sender: TObject); begin if btnMarcarDesmarcar.Tag = 0 then begin FModuloRelat.MarcarDesmarcarCobradores(true); btnMarcarDesmarcar.Tag := 1; end else begin FModuloRelat.MarcarDesmarcarCobradores(false); btnMarcarDesmarcar.Tag := 0; end; end; procedure TfrmRelatCondicoesPagto.btnOkAssinanteClick(Sender: TObject); begin FModuloRelat.ShowReportCondicoesPagto(edtDataIni.Date, edtDataFim.Date); end; procedure TfrmRelatCondicoesPagto.dbgGridCellClick(Column: TColumn); begin if Column.FieldName = 'CalcSelecionado' then begin if dbgGrid.DataSource.DataSet.RecordCount > 0 then begin dbgGrid.DataSource.DataSet.edit; dbgGrid.DataSource.DataSet.FieldByName('CalcSelecionado').Value := not dbgGrid.DataSource.DataSet.FieldByName('CalcSelecionado').AsBoolean; dbgGrid.DataSource.DataSet.Post; end; end; end; procedure TfrmRelatCondicoesPagto.dbgGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); const IS_CHECK : Array[Boolean] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); var Check : Integer; R : TRect; begin with dbgGrid do begin if Column.FieldName = 'CalcSelecionado' then begin Canvas.FillRect(Rect); Check := IS_CHECK[Column.Field.AsBoolean]; R := Rect; InflateRect(R,-2,-2); //aqui manipula o tamanho do checkBox DrawFrameControl(Canvas.Handle,rect,DFC_BUTTON,Check) end; end; end; procedure TfrmRelatCondicoesPagto.FormCreate(Sender: TObject); begin FModuloRelat := TdmDadosRelat.Create(self); DataSource.DataSet := FModuloRelat.cdsCobradores; //dmDadosRelat.CarregarCobradores; FModuloRelat.CarregarCobradores; // Data de início e fim Defaults edtDataIni.Date := EncodeDate(YearOf(now), MonthOf(now), 1); edtDataFim.Date := EncodeDate(YearOf(now), MonthOf(now), DayOf(EndOfTheMonth(now))); end; procedure TfrmRelatCondicoesPagto.FormDestroy(Sender: TObject); begin if Assigned(FModuloRelat) then FreeAndNil(FModuloRelat); end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Repository.Factory; interface uses Spring.Container, DPM.Core.Types, DPM.Core.Logging, DPM.Core.Configuration.Interfaces, DPM.Core.Repository.Interfaces; type TPackageRepositoryFactory = class(TInterfacedObject, IPackageRepositoryFactory) private FContainer : TContainer; FLogger : ILogger; protected function CreateRepository(const repoType : TSourceType) : IPackageRepository; public constructor Create(const container : TContainer; const logger : ILogger); end; implementation uses System.SysUtils, System.StrUtils, DPM.Core.Utils.Enum, VSoft.Uri; { TPackageRepositoryFactory } constructor TPackageRepositoryFactory.Create(const container : TContainer; const logger : ILogger); begin FContainer := container; FLogger := logger; end; function TPackageRepositoryFactory.CreateRepository(const repoType : TSourceType) : IPackageRepository; begin result := FContainer.Resolve<IPackageRepository>(TEnumUtils.EnumToString<TSourceType>(repoType)); end; end.
unit ColladaFile; interface uses BasicDataTypes, XMLIntf, msxmldom, XMLDoc, Mesh, SysUtils, Camera, IntegerSet; type PColladaMeshUnit = ^TColladaMeshUnit; TColladaMeshUnit = record Mesh : PMesh; Next : PColladaMeshUnit; end; TColladaFile = class private Meshes : PColladaMeshUnit; // Constructor procedure Initialize; procedure Clear; procedure ClearMesh(var _Mesh: PColladaMeshUnit); // I/O procedure SaveColladaNode(var _XML: IXMLDocument; const _Filename: string); procedure SaveAssetNode(var _ParentNode: IXMLNode); procedure SaveCameraNode(var _ParentNode: IXMLNode); procedure SaveLightNode(var _ParentNode: IXMLNode); procedure SaveImagesNode(var _ParentNode: IXMLNode; const _BaseName: string); public // Constructors and Destructors constructor Create; destructor Destroy; override; // I/O procedure SaveToFile(const _Filename: string); // Adds procedure AddMesh(const _Mesh: PMesh); end; implementation uses FormMain; // Constructors and Destructors constructor TColladaFile.Create; begin Initialize; end; destructor TColladaFile.Destroy; begin Clear; inherited Destroy; end; procedure TColladaFile.Initialize; begin Meshes := nil; end; procedure TColladaFile.Clear; begin ClearMesh(Meshes); end; procedure TColladaFile.ClearMesh(var _Mesh: PColladaMeshUnit); begin if _Mesh <> nil then begin ClearMesh(_Mesh^.Next); Dispose(_Mesh); _Mesh := nil; end; end; // I/O procedure TColladaFile.SaveToFile(const _Filename: string); var XMLDocument: IXMLDocument; begin XMLDocument := TXMLDocument.Create(nil); XMLDocument.Active := true; // Basic XML settings. XMLDocument.Encoding := 'utf8'; XMLDocument.Version := '1.0'; // Now we create the COLLADA Node SaveColladaNode(XMLDocument,_Filename); // Now, we save it to the file we want. // Clear memory XMLDocument.Active := false; end; procedure TColladaFile.SaveColladaNode(var _XML: IXMLDocument; const _Filename: string); var Node: IXMLNode; BaseName : string; begin BaseName := copy(_Filename,1,Length(_Filename) - 8); Node := _XML.AddChild('COLLADA'); Node.SetAttributeNS('xmlns','','http://www.collada.org/2005/11/COLLADASchema'); Node.SetAttributeNS('version','','1.4.1'); // Create asset node SaveAssetNode(Node); // Create library_cameras node //SaveCameraNode(Node); // Create library_lights node //SaveLightNode(Node); // Create library_images node // Create library_materials node // Create library_effects node // Create library_geometries node // Create library_visual_scenes node // Create scene node end; procedure TColladaFile.SaveAssetNode(var _ParentNode: IXMLNode); var AssetNode,Node,ChildNode: IXMLNode; CurrentTime: TDateTime; Temp : string; begin CurrentTime := Now; AssetNode := _ParentNode.AddChild('asset'); Node := AssetNode.AddChild('contributor'); ChildNode := Node.AddChild('author'); ChildNode.Text := 'Author'; ChildNode := Node.AddChild('authoring_tool'); ChildNode.Text := 'Voxel Section Editor III v.' + APPLICATION_VER; ChildNode := Node.AddChild('comments'); ChildNode.Text := 'Created with Voxel Section Editor III Modelizer Tool.'; ChildNode := Node.AddChild('copyright'); DateTimeToString(Temp,'yyyy',CurrentTime); ChildNode.Text := 'Copyright ' + Temp + ' to Author. If you want to use this asset in your project, modify it or redistribute it, please, get in contact with Author first.' ; Node := AssetNode.AddChild('created'); DateTimeToString(Temp,'yyyy-mm-ddThh:nn:ssZ',CurrentTime); Node.Text := Temp; Node := AssetNode.AddChild('modified'); Node.Text := Temp; Node := AssetNode.AddChild('unit'); Node.SetAttributeNS('meter','','0.01'); Node.SetAttributeNS('name','','centimeter'); Node := AssetNode.AddChild('up_axis'); Node.Text := 'Y_UP'; end; procedure TColladaFile.SaveCameraNode(var _ParentNode: IXMLNode); var CameraNode,Node,ChildNode: IXMLNode; begin CameraNode := _ParentNode.AddChild('library_cameras'); Node := CameraNode.AddChild('camera'); Node.SetAttributeNS('id','','Camera'); Node.SetAttributeNS('name','','Camera'); Node := Node.AddChild('optics'); Node := Node.AddChild('technique_common'); Node := Node.AddChild('perspective'); ChildNode := Node.AddChild('yfov'); ChildNode.Text := '45'; ChildNode := Node.AddChild('aspect_ratio'); ChildNode.Text := '1'; ChildNode := Node.AddChild('znear'); ChildNode.Text := '1'; ChildNode := Node.AddChild('zfar'); ChildNode.Text := '4000'; end; procedure TColladaFile.SaveLightNode(var _ParentNode: IXMLNode); var CameraNode,Node,ChildNode: IXMLNode; begin CameraNode := _ParentNode.AddChild('library_lights'); Node := CameraNode.AddChild('light'); Node.SetAttributeNS('id','','Light'); Node.SetAttributeNS('name','','Light'); Node := Node.AddChild('technique_common'); Node := Node.AddChild('point'); ChildNode := Node.AddChild('color'); ChildNode.Text := '1 1 1'; ChildNode := Node.AddChild('constant_attenuation'); ChildNode.Text := '1'; ChildNode := Node.AddChild('linear_attenuation'); ChildNode.Text := '0'; ChildNode := Node.AddChild('quadratic_attenuation'); ChildNode.Text := '0'; end; procedure TColladaFile.SaveImagesNode(var _ParentNode: IXMLNode; const _BaseName: string); var ImageNode,Node: IXMLNode; Mesh : PColladaMeshUnit; UsedTextures: CIntegerSet; mat,tex : integer; begin Mesh := Meshes; if Mesh <> nil then begin UsedTextures := CIntegerSet.Create; ImageNode := _ParentNode.AddChild('library_images'); while Mesh <> nil do begin for mat := Low(Mesh^.Mesh.Materials) to High(Mesh^.Mesh.Materials) do begin if High(Mesh^.Mesh.Materials[mat].Texture) >= 0 then begin for tex := Low(Mesh^.Mesh.Materials[mat].Texture) to High(Mesh^.Mesh.Materials[mat].Texture) do begin if Mesh^.Mesh.Materials[mat].Texture[tex] <> nil then begin if UsedTextures.Add(Mesh^.Mesh.Materials[mat].Texture[tex]^.GetID) then begin Node := ImageNode.AddChild('image'); end; end; end; end; end; Mesh := Mesh^.Next; end; UsedTextures.Free; end; end; // Adds procedure TColladaFile.AddMesh(const _Mesh: PMesh); var Previous,Element: PColladaMeshUnit; begin new(Element); Element^.Mesh := _Mesh; Element^.Next := nil; if Meshes = nil then begin Meshes := Element; end else begin Previous := Meshes; while Previous^.Next <> nil do begin Previous := Previous^.Next; end; Previous^.Next := Element; end; end; end.
unit MeshUnsharpMasking; interface uses MeshProcessingBase, Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector; {$INCLUDE source/Global_Conditionals.inc} type TMeshUnsharpMasking = class (TMeshProcessingBase) protected procedure MeshUnsharpMaskingOperation(var _Vertices: TAVector3f; _NumVertices: integer; const _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32); procedure DoMeshProcessing(var _Mesh: TMesh); override; end; implementation uses MeshPluginBase, GlConstants, NeighborhoodDataPlugin; procedure TMeshUnsharpMasking.DoMeshProcessing(var _Mesh: TMesh); var NeighborDetector : TNeighborDetector; NeighborhoodPlugin : PMeshPluginBase; NumVertices: integer; VertexEquivalences: auint32; begin NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR); if NeighborhoodPlugin <> nil then begin NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexNeighbors; NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount; VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences; end else begin NeighborDetector := TNeighborDetector.Create; NeighborDetector.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1); NumVertices := High(_Mesh.Vertices)+1; VertexEquivalences := nil; end; MeshUnsharpMaskingOperation(_Mesh.Vertices,NumVertices,NeighborDetector,VertexEquivalences); // Free memory if NeighborhoodPlugin = nil then begin NeighborDetector.Free; end; _Mesh.ForceRefresh; end; procedure TMeshUnsharpMasking.MeshUnsharpMaskingOperation(var _Vertices: TAVector3f; _NumVertices: integer; const _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32); var OriginalVertexes : TAVector3f; v,v1,HitCounter : integer; begin SetLength(OriginalVertexes,High(_Vertices)+1); BackupVector3f(_Vertices,OriginalVertexes); // sum all values from neighbors for v := Low(_Vertices) to (_NumVertices-1) do begin _Vertices[v].X := 0; _Vertices[v].Y := 0; _Vertices[v].Z := 0; HitCounter := 0; v1 := _NeighborDetector.GetNeighborFromID(v); // vertex neighbor from vertex while v1 <> -1 do begin _Vertices[v].X := _Vertices[v].X + OriginalVertexes[v1].X; _Vertices[v].Y := _Vertices[v].Y + OriginalVertexes[v1].Y; _Vertices[v].Z := _Vertices[v].Z + OriginalVertexes[v1].Z; inc(HitCounter); v1 := _NeighborDetector.GetNextNeighbor; end; // Finally, we do the unsharp masking effect here. if HitCounter > 0 then begin _Vertices[v].X := ((HitCounter + 1) * OriginalVertexes[v].X) - _Vertices[v].X; _Vertices[v].Y := ((HitCounter + 1) * OriginalVertexes[v].Y) - _Vertices[v].Y; _Vertices[v].Z := ((HitCounter + 1) * OriginalVertexes[v].Z) - _Vertices[v].Z; end else begin _Vertices[v].X := OriginalVertexes[v].X; _Vertices[v].Y := OriginalVertexes[v].Y; _Vertices[v].Z := OriginalVertexes[v].Z; end; end; v := _NumVertices; while v <= High(_Vertices) do begin v1 := GetEquivalentVertex(v,_NumVertices,_VertexEquivalences); _Vertices[v].X := _Vertices[v1].X; _Vertices[v].Y := _Vertices[v1].Y; _Vertices[v].Z := _Vertices[v1].Z; inc(v); end; // Free memory SetLength(OriginalVertexes,0); end; end.
{ ****************************************************************************** } { * Fast md5 * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit Fast_MD5; {$INCLUDE zDefine.inc} interface uses CoreClasses, UnicodeMixedLib; {$IF Defined(MSWINDOWS) and Defined(Delphi)} procedure MD5_Transform(var Accu; const Buf); {$ENDIF Defined(MSWINDOWS) and Defined(Delphi)} function FastMD5(const buffPtr: PByte; bufSiz: nativeUInt): TMD5; overload; function FastMD5(stream: TCoreClassStream; StartPos, EndPos: Int64): TMD5; overload; implementation {$IF Defined(MSWINDOWS) and Defined(Delphi)} uses MemoryStream64; (* fastMD5 algorithm by Maxim Masiutin https://github.com/maximmasiutin/MD5_Transform-x64 delphi imp by 600585@qq.com https://github.com/PassByYou888/FastMD5 *) {$IF Defined(WIN32)} (* ; ============================================================== ; ; MD5_386.Asm - 386 optimized helper routine for calculating ; MD Message-Digest values ; written 2/2/94 by ; ; Peter Sawatzki ; Buchenhof 3 ; D58091 Hagen, Germany Fed Rep ; ; EMail: Peter@Sawatzki.de ; EMail: 100031.3002@compuserve.com ; WWW: http://www.sawatzki.de ; ; ; original C Source was found in Dr. Dobbs Journal Sep 91 ; MD5 algorithm from RSA Data Security, Inc. *) {$L MD5_32.obj} {$ELSEIF Defined(WIN64)} (* ; MD5_Transform-x64 ; MD5 transform routine oprimized for x64 processors ; Copyright 2018 Ritlabs, SRL ; The 64-bit version is written by Maxim Masiutin <max@ritlabs.com> ; The main advantage of this 64-bit version is that ; it loads 64 bytes of hashed message into 8 64-bit registers ; (RBP, R8, R9, R10, R11, R12, R13, R14) at the beginning, ; to avoid excessive memory load operations ; througout the routine. ; To operate with 32-bit values store in higher bits ; of a 64-bit register (bits 32-63) uses "Ror" by 32; ; 8 macro variables (M1-M8) are used to keep record ; or corrent state of whether the register has been ; Ror'ed or not. ; It also has an ability to use Lea instruction instead ; of two sequental Adds (uncomment UseLea=1), but it is ; slower on Skylake processors. Also, Intel in the ; Optimization Reference Maual discourages us of ; Lea as a replacement of two adds, since it is slower ; on the Atom processors. ; MD5_Transform-x64 is released under a dual license, ; and you may choose to use it under either the ; Mozilla Public License 2.0 (MPL 2.1, available from ; https://www.mozilla.org/en-US/MPL/2.0/) or the ; GNU Lesser General Public License Version 3, ; dated 29 June 2007 (LGPL 3, available from ; https://www.gnu.org/licenses/lgpl.html). ; MD5_Transform-x64 is based ; on the following code by Peter Sawatzki. ; The original notice by Peter Sawatzki follows. *) {$L MD5_64.obj} {$ENDIF} procedure MD5_Transform(var Accu; const Buf); register; external; function FastMD5(const buffPtr: PByte; bufSiz: nativeUInt): TMD5; var Digest: TMD5; Lo, Hi: Cardinal; p: PByte; ChunkIndex: Byte; ChunkBuff: array [0 .. 63] of Byte; begin Lo := 0; Hi := 0; PCardinal(@Digest[0])^ := $67452301; PCardinal(@Digest[4])^ := $EFCDAB89; PCardinal(@Digest[8])^ := $98BADCFE; PCardinal(@Digest[12])^ := $10325476; inc(Lo, bufSiz shl 3); inc(Hi, bufSiz shr 29); p := buffPtr; while bufSiz >= $40 do begin MD5_Transform(Digest, p^); inc(p, $40); dec(bufSiz, $40); end; if bufSiz > 0 then CopyPtr(p, @ChunkBuff[0], bufSiz); Result := PMD5(@Digest[0])^; ChunkBuff[bufSiz] := $80; ChunkIndex := bufSiz + 1; if ChunkIndex > $38 then begin if ChunkIndex < $40 then FillPtrByte(@ChunkBuff[ChunkIndex], $40 - ChunkIndex, 0); MD5_Transform(Result, ChunkBuff); ChunkIndex := 0 end; FillPtrByte(@ChunkBuff[ChunkIndex], $38 - ChunkIndex, 0); PCardinal(@ChunkBuff[$38])^ := Lo; PCardinal(@ChunkBuff[$3C])^ := Hi; MD5_Transform(Result, ChunkBuff); end; function FastMD5(stream: TCoreClassStream; StartPos, EndPos: Int64): TMD5; const deltaSize: Cardinal = $40 * $FFFF; var Digest: TMD5; Lo, Hi: Cardinal; DeltaBuf: Pointer; bufSiz: Int64; Rest: Cardinal; p: PByte; ChunkIndex: Byte; ChunkBuff: array [0 .. 63] of Byte; begin if StartPos > EndPos then Swap(StartPos, EndPos); StartPos := umlClamp(StartPos, 0, stream.Size); EndPos := umlClamp(EndPos, 0, stream.Size); if EndPos - StartPos <= 0 then begin Result := FastMD5(nil, 0); exit; end; {$IFDEF OptimizationMemoryStreamMD5} if stream is TCoreClassMemoryStream then begin Result := FastMD5(Pointer(nativeUInt(TCoreClassMemoryStream(stream).Memory) + StartPos), EndPos - StartPos); exit; end; if stream is TMemoryStream64 then begin Result := FastMD5(TMemoryStream64(stream).PositionAsPtr(StartPos), EndPos - StartPos); exit; end; {$ENDIF} // Lo := 0; Hi := 0; PCardinal(@Digest[0])^ := $67452301; PCardinal(@Digest[4])^ := $EFCDAB89; PCardinal(@Digest[8])^ := $98BADCFE; PCardinal(@Digest[12])^ := $10325476; bufSiz := EndPos - StartPos; Rest := 0; inc(Lo, bufSiz shl 3); inc(Hi, bufSiz shr 29); DeltaBuf := GetMemory(deltaSize); stream.Position := StartPos; if bufSiz < $40 then begin stream.read(DeltaBuf^, bufSiz); p := DeltaBuf; end else while bufSiz >= $40 do begin if Rest = 0 then begin if bufSiz >= deltaSize then Rest := deltaSize else Rest := bufSiz; stream.ReadBuffer(DeltaBuf^, Rest); p := DeltaBuf; end; MD5_Transform(Digest, p^); inc(p, $40); dec(bufSiz, $40); dec(Rest, $40); end; if bufSiz > 0 then CopyPtr(p, @ChunkBuff[0], bufSiz); FreeMemory(DeltaBuf); Result := PMD5(@Digest[0])^; ChunkBuff[bufSiz] := $80; ChunkIndex := bufSiz + 1; if ChunkIndex > $38 then begin if ChunkIndex < $40 then FillPtrByte(@ChunkBuff[ChunkIndex], $40 - ChunkIndex, 0); MD5_Transform(Result, ChunkBuff); ChunkIndex := 0 end; FillPtrByte(@ChunkBuff[ChunkIndex], $38 - ChunkIndex, 0); PCardinal(@ChunkBuff[$38])^ := Lo; PCardinal(@ChunkBuff[$3C])^ := Hi; MD5_Transform(Result, ChunkBuff); end; {$ELSE} function FastMD5(const buffPtr: PByte; bufSiz: nativeUInt): TMD5; begin Result := umlMD5(buffPtr, bufSiz); end; function FastMD5(stream: TCoreClassStream; StartPos, EndPos: Int64): TMD5; begin Result := umlStreamMD5(stream, StartPos, EndPos); end; {$ENDIF Defined(MSWINDOWS) and Defined(Delphi)} end.
unit MeshNormalVectorCalculator; interface uses Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector; type TMeshNormalVectorCalculator = class private function GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer; public function GetNormalsValue(const _V1,_V2,_V3: TVector3f): TVector3f; function GetQuadNormalValue(const _V1,_V2,_V3,_V4: TVector3f): TVector3f; procedure FindMeshVertexNormals(var _Mesh: TMesh); procedure FindMeshFaceNormals(var _Mesh: TMesh); procedure GetVertexNormalsFromFaces(var _VertexNormals: TAVector3f; const _FaceNormals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32); procedure GetFaceNormals(var _FaceNormals: TAVector3f; _VerticesPerFace : integer; const _Vertices: TAVector3f; const _Faces: auint32); end; implementation uses MeshPluginBase, NeighborhoodDataPlugin, GLConstants, MeshBRepGeometry, MeshGeometryBase, Vector3fSet, Math3D; procedure TMeshNormalVectorCalculator.FindMeshVertexNormals(var _Mesh: TMesh); var NeighborDetector : TNeighborDetector; NeighborhoodPlugin: PMeshPluginBase; VertexEquivalences: auint32; MyNormals: TAVector3f; NumVertices: integer; begin if High(_Mesh.Normals) <= 0 then begin SetLength(_Mesh.Normals,High(_Mesh.Vertices)+1); end; NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR); _Mesh.Geometry.GoToFirstElement; if NeighborhoodPlugin <> nil then begin if TNeighborhoodDataPlugin(NeighborhoodPlugin^).UseQuadFaces then begin NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceNeighbors; MyNormals := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceNormals; end else begin NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).FaceNeighbors; MyNormals := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Normals; end; VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences; NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount; end else begin NeighborDetector := TNeighborDetector.Create(C_NEIGHBTYPE_VERTEX_FACE); NeighborDetector.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1); MyNormals := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Normals; VertexEquivalences := nil; NumVertices := High(_Mesh.Vertices)+1; end; GetVertexNormalsFromFaces(_Mesh.Normals,MyNormals,_Mesh.Vertices,NumVertices,NeighborDetector,VertexEquivalences); // _Mesh.SetVertexNormals; end; procedure TMeshNormalVectorCalculator.FindMeshFaceNormals(var _Mesh: TMesh); var CurrentGeometry: PMeshGeometryBase; begin // Recalculate Face Normals _Mesh.Geometry.GoToFirstElement; CurrentGeometry := _Mesh.Geometry.Current; while CurrentGeometry <> nil do begin if High((CurrentGeometry^ as TMeshBRepGeometry).Normals) > 0 then begin GetFaceNormals((_Mesh.Geometry.Current^ as TMeshBRepGeometry).Normals,(_Mesh.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,_Mesh.Vertices,(_Mesh.Geometry.Current^ as TMeshBRepGeometry).Faces); end; _Mesh.Geometry.GoToNextElement; CurrentGeometry := _Mesh.Geometry.Current; end; end; procedure TMeshNormalVectorCalculator.GetVertexNormalsFromFaces(var _VertexNormals: TAVector3f; const _FaceNormals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32); var DifferentNormalsList: CVector3fSet; v,Value : integer; Normal : PVector3f; begin DifferentNormalsList := CVector3fSet.Create; // Now, let's check each vertex. for v := Low(_Vertices) to (_NumVertices - 1) do begin DifferentNormalsList.Reset; _VertexNormals[v].X := 0; _VertexNormals[v].Y := 0; _VertexNormals[v].Z := 0; Value := _NeighborDetector.GetNeighborFromID(v); // face neighbors from vertex while Value <> -1 do begin Normal := new(PVector3f); Normal^.X := _FaceNormals[Value].X; Normal^.Y := _FaceNormals[Value].Y; Normal^.Z := _FaceNormals[Value].Z; if DifferentNormalsList.Add(Normal) then begin _VertexNormals[v].X := _VertexNormals[v].X + Normal^.X; _VertexNormals[v].Y := _VertexNormals[v].Y + Normal^.Y; _VertexNormals[v].Z := _VertexNormals[v].Z + Normal^.Z; end; Value := _NeighborDetector.GetNextNeighbor; end; if not DifferentNormalsList.isEmpty then begin Normalize(_VertexNormals[v]); end; end; v := _NumVertices; while v <= High(_Vertices) do begin Value := GetEquivalentVertex(v,_NumVertices,_VertexEquivalences); _VertexNormals[v].X := _VertexNormals[Value].X; _VertexNormals[v].Y := _VertexNormals[Value].Y; _VertexNormals[v].Z := _VertexNormals[Value].Z; inc(v); end; // Free memory DifferentNormalsList.Free; end; procedure TMeshNormalVectorCalculator.GetFaceNormals(var _FaceNormals: TAVector3f; _VerticesPerFace : integer; const _Vertices: TAVector3f; const _Faces: auint32); var f,face : integer; begin if High(_FaceNormals) >= 0 then begin if _VerticesPerFace = 3 then begin face := 0; for f := Low(_FaceNormals) to High(_FaceNormals) do begin _FaceNormals[f] := GetNormalsValue(_Vertices[_Faces[face]],_Vertices[_Faces[face+1]],_Vertices[_Faces[face+2]]); inc(face,3); end; end else if _VerticesPerFace = 4 then begin face := 0; for f := Low(_FaceNormals) to High(_FaceNormals) do begin _FaceNormals[f] := GetQuadNormalValue(_Vertices[_Faces[face]],_Vertices[_Faces[face+1]],_Vertices[_Faces[face+2]],_Vertices[_Faces[face+3]]); inc(face,4); end; end; end; end; function TMeshNormalVectorCalculator.GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer; begin Result := _VertexID; while Result > _MaxVertexID do begin Result := _VertexEquivalences[Result]; end; end; function TMeshNormalVectorCalculator.GetNormalsValue(const _V1,_V2,_V3: TVector3f): TVector3f; begin Result.X := (((_V3.Y - _V2.Y) * (_V1.Z - _V2.Z)) - ((_V1.Y - _V2.Y) * (_V3.Z - _V2.Z))); Result.Y := (((_V3.Z - _V2.Z) * (_V1.X - _V2.X)) - ((_V1.Z - _V2.Z) * (_V3.X - _V2.X))); Result.Z := (((_V3.X - _V2.X) * (_V1.Y - _V2.Y)) - ((_V1.X - _V2.X) * (_V3.Y - _V2.Y))); Normalize(Result); end; function TMeshNormalVectorCalculator.GetQuadNormalValue(const _V1,_V2,_V3,_V4: TVector3f): TVector3f; var Temp : TVector3f; begin Result := GetNormalsValue(_V1,_V2,_V3); Temp := GetNormalsValue(_V3,_V4,_V1); Result.X := Result.X + Temp.X; Result.Y := Result.Y + Temp.Y; Result.Z := Result.Z + Temp.Z; Normalize(Result); end; end.
unit FMX.Navigator; interface uses System.SysUtils, System.Classes, System.Generics.Collections, FMX.Types, FMX.Controls, FMX.Layouts, FMX.StdCtrls, FMX.Objects, FMX.Graphics, FMX.MultiView, FMX.Effects, System.UITypes, FMX.Forms, FMX.Controls.Presentation, FMX.Filter.Effects; type TFrameClass = class of TFrame; TGetMainFrameEvent = procedure(out AFrame: TFrame) of object; TGetFrameMainClassEvent = procedure(out AFrameClass: TFrameClass) of object; TFrameHelper = class helper for TControl procedure DoShow; procedure DoHide; end; TNavigator = class(TLayout) private FBackPath: TPath; FSettingsPath: TPath; FMenuPath: TPath; FOnSettingsClick: TNotifyEvent; FViewRender: TControl; FMultiView: TMultiView; FMultiViewButton: TSpeedButton; FStack: TStack<TPair<string, TFrame>>; FFontColor: TAlphaColor; FFrameMain: TFrame; FShadowEffectToolbar: TShadowEffect; FRectangle: TRectangle; FTitle: TLabel; FTitleFill: TFillRGBEffect; FMainTitle: string; FMenuButton: TSpeedButton; FBackButton: TSpeedButton; FSettingsButton: TSpeedButton; FOnKeyUpOwner: TKeyEvent; FOnGetFrameMainClass: TGetFrameMainClassEvent; procedure FreeStack; procedure SetMultiView(const Value: TMultiView); function HasMultiView: Boolean; function StackIsEmpty: Boolean; function GetTitle: string; procedure SetTitle(const Value: string); procedure SetFontColor(const Value: TAlphaColor); function GetFill: TBrush; procedure SetFill(const Value: TBrush); procedure DoPush(TitleNavigator: string; Frame: TFrame); procedure BackButtonClick(Sender: TObject); procedure MenuButtonClick(Sender: TObject); procedure CreateShadow; procedure CreateButtons; procedure CreateRectangle; procedure CreateLabel; procedure CreatePaths; procedure DoInjectKeyUp; procedure SetMainFrame(const Value: TFrame); function GetVisibleSettings: Boolean; procedure SetVisibleSettings(const Value: Boolean); procedure SetViewRender(const Value: TControl); function GetViewRender: TControl; property FrameMain: TFrame read FFrameMain write SetMainFrame; procedure DoOnGetFrameMainClass; procedure DoAdjustStyle; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure OnFormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure Loaded; override; function CreateFrameInstance(Frame: TFrameClass): TFrame; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Stack: TStack <TPair<string, TFrame>> read FStack write FStack; procedure Push(AFrame: TFrame); overload; deprecated 'Use method Push(AFrame: TFrameClass)'; procedure Push(ATitle: string; AFrame: TFrame); overload; deprecated 'Use method Push(AFrame: TFrameClass)'; procedure Push(ATitle: string; AFrame: TFrameClass); overload; procedure Push(AFrame: TFrameClass); overload; procedure Pop; procedure Clear; published property OnSettingsClick: TNotifyEvent read FOnSettingsClick write FOnSettingsClick; property OnGetFrameMainClass: TGetFrameMainClassEvent read FOnGetFrameMainClass write FOnGetFrameMainClass; property VisibleSettings: Boolean read GetVisibleSettings write SetVisibleSettings default False; property MultiView: TMultiView read FMultiView write SetMultiView; property Fill: TBrush read GetFill write SetFill; property Title: string read GetTitle write SetTitle; property FontColor: TAlphaColor read FFontColor write SetFontColor default TAlphaColorRec.Black; property ViewRender: TControl read GetViewRender write SetViewRender; end; procedure Register; const BACK_BUTTON = 'M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z'; MENU_BUTTON = 'M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z'; SETTINGS_BUTTON = 'M12,8 c1.1,0 2,-0.9 2,-2 s-0.9,-2 -2,-2 s-2,0.9 -2,2 s0.9,2 2,2 zm0,2 c-1.1,0 -2,0.9 -2,2 ' + 's0.9,2 2,2 s2,-0.9 2,-2 s-0.9,-2 -2,-2 zm0,6 c-1.1,0 -2,0.9 -2,2 s0.9,2 2,2 s2,-0.9 2,-2 s-0.9,-2 -2,-2 z'; implementation uses FMX.Styles.Objects, FMX.VirtualKeyboard, FMX.Platform; procedure Register; begin RegisterComponents('HashLoad', [TNavigator]); end; { TNavigator } procedure TNavigator.BackButtonClick(Sender: TObject); begin Pop; end; procedure TNavigator.Clear; begin while not StackIsEmpty do Pop; end; constructor TNavigator.Create(AOwner: TComponent); begin inherited; FStack := TStack <TPair<string, TFrame>>.Create; CreateShadow; CreateRectangle; CreateButtons; CreateLabel; CreatePaths; DoInjectKeyUp; DoAdjustStyle; Align := TAlignLayout.Top; Height := 56; FontColor := TAlphaColorRec.Black; end; procedure TNavigator.CreateButtons; begin FMenuButton := TSpeedButton.Create(Self); FMenuButton.Parent := FRectangle; FMenuButton.Align := TAlignLayout.Left; FMenuButton.Size.Width := FRectangle.Height; FMenuButton.OnClick := MenuButtonClick; FMenuButton.Stored := False; FMenuButton.SetSubComponent(True); FBackButton := TSpeedButton.Create(Self); FBackButton.Parent := FRectangle; FBackButton.Align := TAlignLayout.Left; FBackButton.Size.Width := FRectangle.Height; FBackButton.Visible := False; FBackButton.OnClick := BackButtonClick; FBackButton.Stored := False; FBackButton.SetSubComponent(True); FMultiViewButton := TSpeedButton.Create(Self); FMultiViewButton.Stored := False; FMultiViewButton.SetSubComponent(True); FSettingsButton := TSpeedButton.Create(Self); FSettingsButton.Parent := FRectangle; FSettingsButton.Align := TAlignLayout.Right; FSettingsButton.Size.Width := FRectangle.Height; VisibleSettings := False; FSettingsButton.Stored := False; FSettingsButton.SetSubComponent(True); end; function TNavigator.CreateFrameInstance(Frame: TFrameClass): TFrame; var LInstance: TFrame; begin LInstance := TFrame(Frame.NewInstance); LInstance.Create(TForm(Self.Root)); Result := LInstance; end; procedure TNavigator.CreateLabel; begin FTitle := TLabel.Create(Self); FTitle.Parent := FRectangle; FTitle.Align := TAlignLayout.Client; FTitle.Margins.Left := 16; FTitle.Margins.Top := 5; FTitle.Margins.Right := 5; FTitle.Margins.Bottom := 5; FTitleFill := TFillRGBEffect.Create(FTitle); FTitleFill.Parent := FTitle; end; procedure TNavigator.CreateShadow; begin FShadowEffectToolbar := TShadowEffect.Create(Self); FShadowEffectToolbar.Distance := 3; FShadowEffectToolbar.Direction := 90; FShadowEffectToolbar.Softness := 0.3; FShadowEffectToolbar.Opacity := 1; FShadowEffectToolbar.ShadowColor := TAlphaColorRec.Darkgray; FShadowEffectToolbar.Stored := False; FShadowEffectToolbar.Parent := Self; FShadowEffectToolbar.SetSubComponent(True); end; procedure TNavigator.CreateRectangle; begin FRectangle := TRectangle.Create(Self); FRectangle.SetSubComponent(True); FRectangle.Stored := False; FRectangle.Stroke.Kind := TBrushKind.None; FRectangle.Align := TAlignLayout.Client; FRectangle.Parent := Self; end; destructor TNavigator.Destroy; begin FreeStack; if HasMultiView then FMultiView.RemoveFreeNotify(Self); inherited; end; function TNavigator.GetFill: TBrush; begin Result := FRectangle.Fill; end; function TNavigator.GetTitle: string; begin Result := FTitle.Text; end; function TNavigator.GetViewRender: TControl; begin if Assigned(FViewRender) then Result := FViewRender else Result := TControl(Self.Parent); end; function TNavigator.GetVisibleSettings: Boolean; begin Result := FSettingsButton.Visible; end; function TNavigator.HasMultiView: Boolean; begin Result := FMultiView <> nil; end; procedure TNavigator.Loaded; begin inherited; DoOnGetFrameMainClass; FSettingsButton.OnClick := FOnSettingsClick; end; procedure TNavigator.MenuButtonClick(Sender: TObject); begin if Assigned(FMultiView) then FMultiViewButton.OnClick(Sender); end; function TNavigator.StackIsEmpty: Boolean; begin Result := FStack.Count = 0; end; procedure TNavigator.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent = FMultiView) and (Operation = opRemove) then FMultiView := nil; end; procedure TNavigator.OnFormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); var LService: IFMXVirtualKeyboardService; begin if (Key = vkHardwareBack) and not StackIsEmpty then begin TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(LService)); if Not((LService <> nil) and (TVirtualKeyboardState.Visible in LService.VirtualKeyBoardState)) then Pop else if (TVirtualKeyboardState.Visible in LService.VirtualKeyBoardState) then LService.HideVirtualKeyboard; Key := 0; end; if Assigned(FOnKeyUpOwner) then FOnKeyUpOwner(Sender, Key, KeyChar, Shift); end; procedure TNavigator.Pop; var LFrame: TFrame; begin LFrame := FStack.Peek.Value; FStack.Pop; TThread.Synchronize(nil, procedure begin LFrame.Parent := nil; TForm(Self.Root).RemoveFreeNotification(LFrame); TForm(Self.Root).RemoveComponent(LFrame); FreeAndNil(LFrame); if StackIsEmpty then begin FMenuButton.Visible := True; FBackButton.Visible := False; Title := FMainTitle; if Assigned(FFrameMain) then FFrameMain.Parent := FViewRender; end else begin FStack.Peek.Value.Parent := FViewRender; Title := FStack.Peek.Key; FStack.Peek.Value.DoShow; end; end); end; procedure TNavigator.Push(ATitle: string; AFrame: TFrameClass); var LFrame: TFrame; begin LFrame := CreateFrameInstance(AFrame); DoPush(ATitle, LFrame); end; procedure TNavigator.DoAdjustStyle; begin {$IFDEF MSWINDOWS} FTitle.StyledSettings := []; FTitle.Font.Size := 16; FTitle.Font.Style := [TFontStyle.fsBold]; FTitle.Font.Family := 'Roboto'; {$ENDIF} // FMenuButton.StyleLookup := 'drawertoolbutton'; // FSettingsButton.StyleLookup := 'detailstoolbutton'; end; procedure TNavigator.DoInjectKeyUp; begin if Owner.InheritsFrom(TCommonCustomForm) then begin FOnKeyUpOwner := TCommonCustomForm(Owner).OnKeyUp; TCommonCustomForm(Owner).OnKeyUp := OnFormKeyUp; end else if Owner.InheritsFrom(TControl) then begin FOnKeyUpOwner := TControl(Owner).OnKeyUp; TControl(Owner).OnKeyUp := OnFormKeyUp; end; end; procedure TNavigator.DoOnGetFrameMainClass; var LFrameMainClass: TFrameClass; begin if not(csDesigning in ComponentState) and Assigned(FOnGetFrameMainClass) then begin FOnGetFrameMainClass(LFrameMainClass); FrameMain := CreateFrameInstance(LFrameMainClass); end; end; procedure TNavigator.DoPush(TitleNavigator: string; Frame: TFrame); begin TThread.Synchronize(nil, procedure begin if StackIsEmpty then begin FMenuButton.Visible := False; FBackButton.Visible := True; FMainTitle := Title; if Assigned(FFrameMain) then FFrameMain.Parent := nil; end else FStack.Peek.Value.Parent := nil; FStack.Push(TPair<string, TFrame>.Create(TitleNavigator, Frame)); Title := TitleNavigator; Frame.Align := TAlignLayout.Client; Frame.Name := Frame.Name + FStack.Count.ToString; Frame.Parent := FViewRender; Frame.DoShow; end); end; procedure TNavigator.CreatePaths; const PATH_SIZE = 18; procedure MakePath(var APath: TPath; AData: string; AParent: TFmxObject); begin APath := TPath.Create(AParent); APath.Parent := AParent; APath.SetSubComponent(True); APath.Stored := False; APath.HitTest := False; APath.Width := PATH_SIZE; APath.Height := PATH_SIZE; APath.Data.Data := AData; APath.Align := TAlignLayout.Center; APath.Fill.Color := FontColor; APath.Stroke.Kind := TBrushKind.None; APath.Padding.Left := -PATH_SIZE; APath.Padding.Right := -PATH_SIZE; APath.Padding.Top := -PATH_SIZE; APath.Padding.Bottom := -PATH_SIZE; APath.WrapMode := TPathWrapMode.Fit; end; begin MakePath(FBackPath, BACK_BUTTON, FBackButton); MakePath(FMenuPath, MENU_BUTTON, FMenuButton); MakePath(FSettingsPath, SETTINGS_BUTTON, FSettingsButton); end; procedure TNavigator.FreeStack; var LPairFrame: TPair<string, TFrame>; LFrame: TFrame; begin while FStack.Count > 0 do begin LPairFrame := FStack.Pop; LFrame := LPairFrame.Value; LFrame.Parent := nil; end; FreeAndNil(FStack); end; procedure TNavigator.Push(ATitle: string; AFrame: TFrame); begin DoPush(ATitle, AFrame); end; procedure TNavigator.Push(AFrame: TFrame); begin DoPush(Title, AFrame); end; procedure TNavigator.SetFill(const Value: TBrush); begin FRectangle.Fill := Value; end; procedure TNavigator.SetFontColor(const Value: TAlphaColor); begin if FFontColor <> Value then begin FFontColor := Value; FTitleFill.Color := Value; FBackPath.Fill.Color := Value; FSettingsPath.Fill.Color := Value; FMenuPath.Fill.Color := Value; end; end; procedure TNavigator.SetMainFrame(const Value: TFrame); begin if FFrameMain <> Value then begin if Assigned(FFrameMain) then begin RemoveFreeNotification(FFrameMain); FFrameMain.DisposeOf; end; FFrameMain := Value; if FFrameMain <> nil then begin AddFreeNotify(FFrameMain); FFrameMain.Align := TAlignLayout.Client; FFrameMain.Parent := FViewRender; end; end; end; procedure TNavigator.SetMultiView(const Value: TMultiView); begin if FMultiView <> Value then begin FMultiView := Value; if HasMultiView then begin FMultiView.AddFreeNotify(Self); FMultiView.MasterButton := FMultiViewButton; FMenuButton.Visible := True; end; end; end; procedure TNavigator.SetTitle(const Value: string); begin if FTitle.Text <> Value then FTitle.Text := Value; end; procedure TNavigator.SetViewRender(const Value: TControl); begin if FViewRender <> Value then begin FViewRender := Value; end; end; procedure TNavigator.SetVisibleSettings(const Value: Boolean); begin if FSettingsButton.Visible <> Value then begin FSettingsButton.Visible := Value end; end; procedure TNavigator.Push(AFrame: TFrameClass); var LFrame: TFrame; begin LFrame := CreateFrameInstance(AFrame); DoPush(Title, LFrame); end; { TFrameHelper } procedure TFrameHelper.DoHide; begin Self.Hide; end; procedure TFrameHelper.DoShow; begin Self.Show; end; end.
unit CustomServiceDemoMain; interface uses Classes, apiPlugin, AIMPCustomPlugin, apiCore, CustomServiceDemoPublicIntf; type { TMyCustomObject } TMyCustomObject = class(TInterfacedObject, IMyCustomObject, IMyCustomObjectv2) protected // IMyCustomObject function SomeMethod: HRESULT; stdcall; // IMyCustomObjectv2 function SomeNewMethod: HRESULT; stdcall; end; { TMyCustomService } TMyCustomService = class(TInterfacedObject, IMyCustomService, // Main interface of custom service IAIMPServiceAttrExtendable, // Our service has extensions support IAIMPServiceAttrObjects // Our service has custom objects ) private FExtensions: TInterfaceList; protected // IAIMPServiceAttrExtendable procedure RegisterExtension(Extension: IInterface); stdcall; procedure UnregisterExtension(Extension: IInterface); stdcall; // IAIMPServiceAttrObjects function CreateObject(const IID: TGUID; out Obj): HRESULT; stdcall; // IMyCustomService function SomeMethod: HRESULT; stdcall; public constructor Create; virtual; destructor Destroy; override; procedure NotifyExtensions; end; { TAIMPCustomServicePlugin } TAIMPCustomServicePlugin = class(TAIMPCustomPlugin) protected function InfoGet(Index: Integer): PWideChar; override; stdcall; function InfoGetCategories: Cardinal; override; stdcall; function Initialize(Core: IAIMPCore): HRESULT; override; stdcall; end; implementation uses ActiveX, SysUtils; { TMyCustomObject } function TMyCustomObject.SomeMethod: HRESULT; begin Result := S_OK; end; function TMyCustomObject.SomeNewMethod: HRESULT; begin Result := S_OK; end; { TMyCustomService } constructor TMyCustomService.Create; begin inherited Create; FExtensions := TInterfaceList.Create; end; destructor TMyCustomService.Destroy; begin FreeAndNil(FExtensions); inherited Destroy; end; procedure TMyCustomService.NotifyExtensions; var I: Integer; begin // send notification to our extensions FExtensions.Lock; try for I := FExtensions.Count - 1 downto 0 do IMyCustomExtension(FExtensions[I]).SomeNotification; finally FExtensions.Unlock; end; end; function TMyCustomService.CreateObject(const IID: TGUID; out Obj): HRESULT; begin Result := S_OK; if IsEqualGUID(IID, IID_IMyCustomObject) then IMyCustomObject(Obj) := TMyCustomObject.Create else if IsEqualGUID(IID, IID_IMyCustomObjectv2) then IMyCustomObjectv2(Obj) := TMyCustomObject.Create else Result := E_NOINTERFACE; end; procedure TMyCustomService.RegisterExtension(Extension: IInterface); var AIntf: IMyCustomExtension; begin // if it our extension put it into the FExtensions list if Supports(Extension, IMyCustomExtension, AIntf) then FExtensions.Add(AIntf); end; procedure TMyCustomService.UnregisterExtension(Extension: IInterface); var AIntf: IMyCustomExtension; begin // if it our extension remove it from the FExtensions list if Supports(Extension, IMyCustomExtension, AIntf) then FExtensions.Remove(AIntf); end; function TMyCustomService.SomeMethod: HRESULT; begin Result := S_OK; end; { TAIMPCustomServicePlugin } function TAIMPCustomServicePlugin.InfoGet(Index: Integer): PWideChar; begin case Index of AIMP_PLUGIN_INFO_NAME: Result := 'Custom service demo plugin'; AIMP_PLUGIN_INFO_AUTHOR: Result := 'Artem Izmaylov'; AIMP_PLUGIN_INFO_SHORT_DESCRIPTION: Result := 'Single line short description'; else Result := nil; end; end; function TAIMPCustomServicePlugin.InfoGetCategories: Cardinal; begin Result := AIMP_PLUGIN_CATEGORY_ADDONS; end; function TAIMPCustomServicePlugin.Initialize(Core: IAIMPCore): HRESULT; begin Result := inherited Initialize(Core); if Succeeded(Result) then // Register the custom service Core.RegisterService(TMyCustomService.Create); end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFJsDialogHandler; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefJsDialogHandlerOwn = class(TCefBaseRefCountedOwn, ICefJsDialogHandler) protected function OnJsdialog(const browser: ICefBrowser; const originUrl: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; out suppressMessage: Boolean): Boolean; virtual; function OnBeforeUnloadDialog(const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback): Boolean; virtual; procedure OnResetDialogState(const browser: ICefBrowser); virtual; procedure OnDialogClosed(const browser: ICefBrowser); virtual; public constructor Create; virtual; end; TCustomJsDialogHandler = class(TCefJsDialogHandlerOwn) protected FEvent: IChromiumEvents; function OnJsdialog(const browser: ICefBrowser; const originUrl: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; out suppressMessage: Boolean): Boolean; override; function OnBeforeUnloadDialog(const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback): Boolean; override; procedure OnResetDialogState(const browser: ICefBrowser); override; procedure OnDialogClosed(const browser: ICefBrowser); override; public constructor Create(const events: IChromiumEvents); reintroduce; virtual; destructor Destroy; override; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser, uCEFJsDialogCallback; function cef_jsdialog_handler_on_jsdialog(self : PCefJsDialogHandler; browser : PCefBrowser; const origin_url : PCefString; dialog_type : TCefJsDialogType; const message_text : PCefString; const default_prompt_text : PCefString; callback : PCefJsDialogCallback; suppress_message : PInteger): Integer; stdcall; var sm: Boolean; begin sm := suppress_message^ <> 0; with TCefJsDialogHandlerOwn(CefGetObject(self)) do Result := Ord(OnJsdialog(TCefBrowserRef.UnWrap(browser), CefString(origin_url), dialog_type, CefString(message_text), CefString(default_prompt_text), TCefJsDialogCallbackRef.UnWrap(callback), sm)); suppress_message^ := Ord(sm); end; function cef_jsdialog_handler_on_before_unload_dialog(self: PCefJsDialogHandler; browser: PCefBrowser; const message_text: PCefString; is_reload: Integer; callback: PCefJsDialogCallback): Integer; stdcall; begin with TCefJsDialogHandlerOwn(CefGetObject(self)) do Result := Ord(OnBeforeUnloadDialog(TCefBrowserRef.UnWrap(browser), CefString(message_text), is_reload <> 0, TCefJsDialogCallbackRef.UnWrap(callback))); end; procedure cef_jsdialog_handler_on_reset_dialog_state(self: PCefJsDialogHandler; browser: PCefBrowser); stdcall; begin with TCefJsDialogHandlerOwn(CefGetObject(self)) do OnResetDialogState(TCefBrowserRef.UnWrap(browser)); end; procedure cef_jsdialog_handler_on_dialog_closed(self: PCefJsDialogHandler; browser: PCefBrowser); stdcall; begin with TCefJsDialogHandlerOwn(CefGetObject(self)) do OnDialogClosed(TCefBrowserRef.UnWrap(browser)); end; constructor TCefJsDialogHandlerOwn.Create; begin inherited CreateData(SizeOf(TCefJsDialogHandler)); with PCefJsDialogHandler(FData)^ do begin on_jsdialog := cef_jsdialog_handler_on_jsdialog; on_before_unload_dialog := cef_jsdialog_handler_on_before_unload_dialog; on_reset_dialog_state := cef_jsdialog_handler_on_reset_dialog_state; on_dialog_closed := cef_jsdialog_handler_on_dialog_closed; end; end; function TCefJsDialogHandlerOwn.OnJsdialog(const browser: ICefBrowser; const originUrl: ustring; dialogType: TCefJsDialogType; const messageText, defaultPromptText: ustring; const callback: ICefJsDialogCallback; out suppressMessage: Boolean): Boolean; begin Result := False; suppressMessage := False; end; function TCefJsDialogHandlerOwn.OnBeforeUnloadDialog(const browser: ICefBrowser; const messageText: ustring; isReload: Boolean; const callback: ICefJsDialogCallback): Boolean; begin Result := False; end; procedure TCefJsDialogHandlerOwn.OnDialogClosed(const browser: ICefBrowser); begin end; procedure TCefJsDialogHandlerOwn.OnResetDialogState(const browser: ICefBrowser); begin end; // TCustomJsDialogHandler constructor TCustomJsDialogHandler.Create(const events: IChromiumEvents); begin inherited Create; FEvent := events; end; destructor TCustomJsDialogHandler.Destroy; begin FEvent := nil; inherited Destroy; end; function TCustomJsDialogHandler.OnBeforeUnloadDialog(const browser : ICefBrowser; const messageText : ustring; isReload : Boolean; const callback : ICefJsDialogCallback): Boolean; begin if (FEvent <> nil) then Result := FEvent.doOnBeforeUnloadDialog(browser, messageText, isReload, callback) else Result := inherited OnBeforeUnloadDialog(browser, messageText, isReload, callback); end; procedure TCustomJsDialogHandler.OnDialogClosed(const browser: ICefBrowser); begin if (FEvent <> nil) then FEvent.doOnDialogClosed(browser); end; function TCustomJsDialogHandler.OnJsdialog(const browser : ICefBrowser; const originUrl : ustring; dialogType : TCefJsDialogType; const messageText : ustring; const defaultPromptText : ustring; const callback : ICefJsDialogCallback; out suppressMessage : Boolean): Boolean; begin suppressMessage := False; if (FEvent <> nil) then Result := FEvent.doOnJsdialog(browser, originUrl, dialogType, messageText, defaultPromptText, callback, suppressMessage) else Result := inherited OnJsdialog(browser, originUrl, dialogType, messageText, defaultPromptText, callback, suppressMessage); end; procedure TCustomJsDialogHandler.OnResetDialogState(const browser: ICefBrowser); begin if (FEvent <> nil) then FEvent.doOnResetDialogState(browser); end; end.
{------------------------------------------------------------------------------- Copyright 2012 Ethea S.r.l. 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. -------------------------------------------------------------------------------} /// <summary> /// DBExpress-based database access layer. /// </summary> unit EF.DB.DBX; {$I EF.Defines.inc} interface uses Classes, DB, Contnrs, DBXCommon, SqlExpr, EF.Tree, EF.DB; type /// <summary> /// Retrieves metadata from a database through DBX. Should support all /// databases supported by DBX, depending on the driver used. /// </summary> TEFDBDBXInfo = class(TEFDBInfo) private FConnection: TSQLConnection; FServerCharSet: string; function DBXDataTypeToEFDataType(const ADBXDataType: TDBXType): TEFDataType; procedure SetForeignKeyColumns(const AForeignKeyInfo: TEFDBForeignKeyInfo); procedure StoreServerCharSet; procedure RestoreServerCharSet; protected procedure BeforeFetchInfo; override; procedure FetchTables(const ASchemaInfo: TEFDBSchemaInfo); override; procedure FetchTableColumns(const ATableInfo: TEFDBTableInfo); procedure FetchTablePrimaryKey(const ATableInfo: TEFDBTableInfo); procedure FetchTableForeignKeys(const ATableInfo: TEFDBTableInfo); public constructor Create(const AConnection: TSQLConnection); property Connection: TSQLConnection read FConnection write FConnection; end; TEFDBDBXQuery = class; TEFSQLConnection = class(TSQLConnection) end; TEFDBDBXConnection = class(TEFDBConnection) private FConnection: TEFSQLConnection; FTransaction: TDBXTransaction; FConnectionString: TStrings; FFetchSequenceGeneratorValueQuery: TEFDBDBXQuery; FLastSequenceName: string; /// <summary> /// Handles FConnectionString.OnChange; parses the connection string and /// configures the internal connection accordingly. /// </summary> procedure OnConnectionStringChange(Sender: TObject); /// <summary> /// Returns the SQL statement used to get the next value from a sequence /// generator. Currently supports only Oracle and IB/Fb. /// </summary> function GetFetchSequenceGeneratorValueSQL( const ASequenceName: string): string; /// <summary> /// Returns a query to be used to fetch a sequence generator value. The /// query is created upon first access and kept prepared until the /// connection is closed or destroyed. /// </summary> function GetFetchSequenceGeneratorValueQuery(const ASequenceName: string): TEFDBDBXQuery; protected function CreateDBEngineType: TEFDBEngineType; override; procedure InternalOpen; override; procedure InternalClose; override; function InternalCreateDBInfo: TEFDBInfo; override; public procedure AfterConstruction; override; destructor Destroy; override; public function IsOpen: Boolean; override; function ExecuteImmediate(const AStatement: string): Integer; override; procedure StartTransaction; override; procedure CommitTransaction; override; procedure RollbackTransaction; override; function IsInTransaction: Boolean; override; function GetLastAutoincValue(const ATableName: string = ''): Int64; override; function FetchSequenceGeneratorValue(const ASequenceName: string): Int64; override; function CreateDBCommand: TEFDBCommand; override; function CreateDBQuery: TEFDBQuery; override; function GetConnection: TObject; override; end; /// <summary>Customized TSQLQuery used inside TEFDBXCommand and /// TEFDBDBXQuery.</summary> TEFSQLQuery = class(TSQLQuery) private /// <summary> /// Params of unknown type trigger the DBX error "No value for parameter /// X". Detail queries of empty master datasets have params with unknown /// type, so we patch the data type to avoid the error. /// </summary> procedure FixUnknownParamTypes; protected procedure InternalOpen; override; public function ExecSQL(ExecDirect: Boolean = False): Integer; override; end; TEFDBDBXCommand = class(TEFDBCommand) private FQuery: TEFSQLQuery; FCommandText: string; protected procedure ConnectionChanged; override; function GetCommandText: string; override; procedure SetCommandText(const AValue: string); override; function GetPrepared: Boolean; override; procedure SetPrepared(const AValue: Boolean); override; function GetParams: TParams; override; procedure SetParams(const AValue: TParams); override; public procedure AfterConstruction; override; destructor Destroy; override; public function Execute: Integer; override; end; TEFDBDBXQuery = class(TEFDBQuery) private FQuery: TEFSQLQuery; FCommandText: string; protected procedure ConnectionChanged; override; function GetCommandText: string; override; procedure SetCommandText(const AValue: string); override; function GetPrepared: Boolean; override; procedure SetPrepared(const AValue: Boolean); override; function GetParams: TParams; override; procedure SetParams(const AValue: TParams); override; function GetDataSet: TDataSet; override; function GetMasterSource: TDataSource; override; procedure SetMasterSource(const AValue: TDataSource); override; public procedure AfterConstruction; override; destructor Destroy; override; public /// <summary>Execute and Open are synonims in this class. Execute always /// returns 0.</summary> function Execute: Integer; override; procedure Open; override; procedure Close; override; function IsOpen: Boolean; override; end; TEFDBDBXAdapter = class(TEFDBAdapter) protected function InternalCreateDBConnection: TEFDBConnection; override; class function InternalGetClassId: string; override; end; implementation uses SysUtils, StrUtils, DBXMetaDataNames, EF.StrUtils, EF.Localization, EF.Types; function FetchParam(const AParams: TStrings; const AParamName: string): string; var LParamIndex: Integer; begin LParamIndex := AParams.IndexOfName(AParamName); if LParamIndex >= 0 then begin Result := AParams.ValueFromIndex[LParamIndex]; AParams.Delete(LParamIndex); end else Result := ''; end; { TEFDBDBXConnection } procedure TEFDBDBXConnection.AfterConstruction; begin inherited; FConnection := TEFSQLConnection.Create(nil); FConnection.LoginPrompt := False; FConnection.AfterConnect := AfterConnectionOpen; FConnectionString := TStringList.Create; TStringList(FConnectionString).OnChange := OnConnectionStringChange; end; destructor TEFDBDBXConnection.Destroy; begin FreeAndNil(FFetchSequenceGeneratorValueQuery); if Assigned(FConnection) then FConnection.Close; FreeAndNil(FConnection); FreeAndNIl(FConnectionString); inherited; end; procedure TEFDBDBXConnection.InternalClose; begin if FConnection.Connected then FConnection.Close; end; function TEFDBDBXConnection.InternalCreateDBInfo: TEFDBInfo; begin Result := TEFDBDBXInfo.Create(FConnection); end; procedure TEFDBDBXConnection.CommitTransaction; begin if FConnection.InTransaction then FConnection.CommitFreeAndNil(FTransaction); end; function TEFDBDBXConnection.CreateDBCommand: TEFDBCommand; begin Result := TEFDBDBXCommand.Create; try Result.Connection := Self; except FreeAndNil(Result); raise; end; end; function TEFDBDBXConnection.CreateDBEngineType: TEFDBEngineType; begin if ContainsText(FConnection.DriverName, 'MSSQL') or ContainsText(FConnection.DriverName, 'SQLServer') then Result := TEFSQLServerDBEngineType.Create else if ContainsText(FConnection.DriverName, 'Oracle') then Result := TEFOracleDBEngineType.Create else if ContainsText(FConnection.DriverName, 'Firebird') or ContainsText(FConnection.DriverName, 'InterBase') then Result := TEFFirebirdDBEngineType.Create else Result := inherited CreateDBEngineType; end; function TEFDBDBXConnection.CreateDBQuery: TEFDBQuery; begin Result := TEFDBDBXQuery.Create; try Result.Connection := Self; except FreeAndNil(Result); raise; end; end; function TEFDBDBXConnection.ExecuteImmediate(const AStatement: string): Integer; begin Assert(Assigned(FConnection)); if AStatement = '' then raise EEFError.Create(_('Unspecified Statement text.')); try Result := FConnection.ExecuteDirect(AStatement); except on E: Exception do raise EEFDBError.CreateForQuery(E.Message, AStatement); end; end; function TEFDBDBXConnection.GetConnection: TObject; begin Result := FConnection; end; function TEFDBDBXConnection.GetFetchSequenceGeneratorValueQuery( const ASequenceName: string): TEFDBDBXQuery; begin { TODO : This remembers the last used sequence fetch query. A better implementation would be to keep a list of them. } if (ASequenceName <> FLastSequenceName) and (FLastSequenceName <> '') then begin FreeAndNil(FFetchSequenceGeneratorValueQuery); FLastSequenceName := ''; end; if not Assigned(FFetchSequenceGeneratorValueQuery) then begin FFetchSequenceGeneratorValueQuery := TEFDBDBXQuery.Create; try FFetchSequenceGeneratorValueQuery.Connection := Self; FFetchSequenceGeneratorValueQuery.CommandText := GetFetchSequenceGeneratorValueSQL(ASequenceName); FFetchSequenceGeneratorValueQuery.Prepared := True; FLastSequenceName := ASequenceName; except FreeAndNil(FFetchSequenceGeneratorValueQuery); raise; end; end; // Re-prepare the query in case it was unprepared (for example as a // consequence of closing the connection). if not FFetchSequenceGeneratorValueQuery.Prepared then FFetchSequenceGeneratorValueQuery.Prepared := True; Result := FFetchSequenceGeneratorValueQuery; end; function TEFDBDBXConnection.FetchSequenceGeneratorValue( const ASequenceName: string): Int64; var LQuery: TEFDBDBXQuery; begin if ASequenceName = '' then raise EEFError.Create(_('Unspecified Sequence name.')); LQuery := GetFetchSequenceGeneratorValueQuery(ASequenceName); LQuery.Open; try Result := StrToInt64(LQuery.DataSet.Fields[0].AsString); finally LQuery.Close; end; end; function TEFDBDBXConnection.GetFetchSequenceGeneratorValueSQL( const ASequenceName: string): string; begin if Pos('ORACLE', UpperCase(FConnection.DriverName)) > 0 then Result := 'select ' + ASequenceName + '.NEXTVAL from DUAL' else Result := 'select GEN_ID(' + ASequenceName + ', 1) from RDB$DATABASE'; end; function TEFDBDBXConnection.GetLastAutoincValue( const ATableName: string = ''): Int64; begin // Auto-inc fields currently not supported in dbExpress. Result := 0; end; function TEFDBDBXConnection.IsInTransaction: Boolean; begin Result := FConnection.InTransaction; end; function TEFDBDBXConnection.IsOpen: Boolean; begin if FConnection = nil then Result := False else Result := FConnection.Connected; end; procedure TEFDBDBXConnection.OnConnectionStringChange(Sender: TObject); var LConnectionName: string; LParams: TStrings; begin inherited; LConnectionName := FConnectionString.Values['ConnectionName']; if LConnectionName <> '' then begin FConnection.ConnectionName := LConnectionName; FConnection.LoadParamsOnConnect := True; end else begin FConnection.LoadParamsOnConnect := False; // These properties need to be provided explicitly. // Note: setting DriverName clears Params, so we need to assign them later. LParams := TStringList.Create; try LParams.Assign(FConnectionString); // Drop the useless param. FetchParam(LParams, 'ConnectionName'); FConnection.DriverName := FetchParam(LParams, 'DriverName'); FConnection.LibraryName := FetchParam(LParams, 'LibraryName'); FConnection.VendorLib := FetchParam(LParams, 'VendorLib'); FConnection.GetDriverFunc := FetchParam(LParams, 'GetDriverFunc'); FConnection.Params.Assign(LParams); finally LParams.Free; end; end; end; procedure TEFDBDBXConnection.InternalOpen; begin if not FConnection.Connected then begin // Explicitly setting DriverName and ConnectionName should force DBX to // re-read the params. Just setting Params is not enough. FConnection.ConnectionName := Config.GetExpandedString('Connection/ConnectionName'); FConnection.DriverName := Config.GetExpandedString('Connection/DriverName'); FConnection.Params.Text := Config.GetChildrenAsExpandedStrings('Connection'); FConnection.Open; end; end; procedure TEFDBDBXConnection.RollbackTransaction; begin if FConnection.InTransaction then FConnection.RollbackFreeAndNil(FTransaction); end; procedure TEFDBDBXConnection.StartTransaction; begin if not IsOpen then Open; if not FConnection.InTransaction then FTransaction := FConnection.BeginTransaction; end; { TEFSQLQuery } procedure TEFSQLQuery.FixUnknownParamTypes; var LParamIndex: Integer; begin for LParamIndex := 0 to ParamCount - 1 do if Params[LParamIndex].DataType = ftUnknown then Params[LParamIndex].DataType := ftInteger; inherited; end; function TEFSQLQuery.ExecSQL(ExecDirect: Boolean): Integer; begin FixUnknownParamTypes; Result := inherited ExecSQL(ExecDirect); end; procedure TEFSQLQuery.InternalOpen; begin FixUnknownParamTypes; inherited; end; { TEFDBDBXCommand } procedure TEFDBDBXCommand.AfterConstruction; begin inherited; FQuery := TEFSQLQuery.Create(nil); end; destructor TEFDBDBXCommand.Destroy; begin FreeAndNil(FQuery); inherited; end; procedure TEFDBDBXCommand.ConnectionChanged; begin inherited; FQuery.SQLConnection := (Connection.AsObject as TEFDBDBXConnection).FConnection; end; function TEFDBDBXCommand.Execute: Integer; begin inherited; try Connection.DBEngineType.BeforeExecute(FQuery.SQL.Text, FQuery.Params); FQuery.ExecSQL; except on E: Exception do raise EEFDBError.CreateForQuery(E.Message, FQuery.SQL.Text); end; Result := FQuery.RowsAffected; end; function TEFDBDBXCommand.GetCommandText: string; begin Result := FCommandText; end; function TEFDBDBXCommand.GetParams: TParams; begin Result := FQuery.Params; end; function TEFDBDBXCommand.GetPrepared: Boolean; begin Result := FQuery.Prepared; end; procedure TEFDBDBXCommand.SetCommandText(const AValue: string); begin FCommandText := AValue; FQuery.SQL.Text := ExpandCommandText(FCommandText); end; procedure TEFDBDBXCommand.SetParams(const AValue: TParams); begin FQuery.Params.Assign(AValue); end; procedure TEFDBDBXCommand.SetPrepared(const AValue: Boolean); begin FQuery.Prepared := AValue; end; { TEFDBDBXQuery } procedure TEFDBDBXQuery.AfterConstruction; begin inherited; FQuery := TEFSQLQuery.Create(nil); end; destructor TEFDBDBXQuery.Destroy; begin FreeAndNil(FQuery); inherited; end; procedure TEFDBDBXQuery.Close; begin FQuery.Close; end; procedure TEFDBDBXQuery.ConnectionChanged; begin inherited; FQuery.SQLConnection := (Connection.AsObject as TEFDBDBXConnection).FConnection; end; function TEFDBDBXQuery.Execute: Integer; begin inherited; Open; Result := 0; end; function TEFDBDBXQuery.GetCommandText: string; begin Result := FCommandText; end; function TEFDBDBXQuery.GetDataSet: TDataSet; begin Result := FQuery; end; function TEFDBDBXQuery.GetMasterSource: TDataSource; begin Result := FQuery.DataSource; end; function TEFDBDBXQuery.GetParams: TParams; begin Result := FQuery.Params; end; function TEFDBDBXQuery.GetPrepared: Boolean; begin Result := FQuery.Prepared; end; function TEFDBDBXQuery.IsOpen: Boolean; begin Result := FQuery.Active; end; procedure TEFDBDBXQuery.Open; begin try Connection.Open; Connection.DBEngineType.BeforeExecute(FQuery.SQL.Text, FQuery.Params); DataSet.Open; except on E: Exception do raise EEFDBError.CreateForQuery(E.Message, FQuery.SQL.Text); end; end; procedure TEFDBDBXQuery.SetCommandText(const AValue: string); begin FCommandText := AValue; FQuery.SQL.Text := ExpandCommandText(FCommandText); end; procedure TEFDBDBXQuery.SetMasterSource(const AValue: TDataSource); begin FQuery.DataSource := AValue; end; procedure TEFDBDBXQuery.SetParams(const AValue: TParams); begin FQuery.Params.Assign(AValue); end; procedure TEFDBDBXQuery.SetPrepared(const AValue: Boolean); begin if AValue then FQuery.Prepared := True; end; { TEFDBDBXAdapter } function TEFDBDBXAdapter.InternalCreateDBConnection: TEFDBConnection; begin Result := TEFDBDBXConnection.Create; end; class function TEFDBDBXAdapter.InternalGetClassId: string; begin Result := 'DBX'; end; { TEFDBDBXInfo } procedure TEFDBDBXInfo.BeforeFetchInfo; begin inherited; Assert(Assigned(FConnection)); end; procedure TEFDBDBXInfo.FetchTables(const ASchemaInfo: TEFDBSchemaInfo); var LCommand: TDBXCommand; LReader: TDBXReader; LTableInfo: TEFDBTableInfo; LCommandText: string; begin StoreServerCharSet; try FConnection.Open; try LCommand := FConnection.DBXConnection.CreateCommand; try LCommand.CommandType := TDBXCommandTypes.DbxMetaData; LCommandText := TDBXMetaDataCommands.GetTables + ' % ' + TDBXMetaDataTableTypes.Table; if ViewsAsTables then LCommandText := LCommandText + ' ' + TDBXMetaDataTableTypes.View; LCommand.Text := LCommandText; LReader := LCommand.ExecuteQuery; try while LReader.Next do begin LTableInfo := TEFDBTableInfo.Create; try LTableInfo.Name := LReader.Value[TDBXTablesIndex.TableName].AsString; FetchTableColumns(LTableInfo); if SameText(LReader.Value[TDBXTablesIndex.TableType].AsString, 'TABLE') then begin FetchTablePrimaryKey(LTableInfo); FetchTableForeignKeys(LTableInfo); end; ASchemaInfo.AddTable(LTableInfo); except FreeAndNil(LTableInfo); raise; end; end; finally FreeAndNil(LReader); end; finally FreeAndNil(LCommand); end; finally FConnection.Close; end; finally RestoreServerCharSet; end; end; procedure TEFDBDBXInfo.StoreServerCharSet; begin Assert(Assigned(FConnection)); // Workaround for Firebird driver bug // http://qc.embarcadero.com/wc/qcmain.aspx?d=90414 FServerCharSet := FConnection.Params.Values['ServerCharSet']; if SameText(FConnection.DriverName, 'Firebird') then begin FConnection.Params.Values['ServerCharSet'] := 'NONE'; FConnection.Close; end; end; procedure TEFDBDBXInfo.RestoreServerCharSet; begin Assert(Assigned(FConnection)); // Workaround for Firebird driver bug // http://qc.embarcadero.com/wc/qcmain.aspx?d=90414 if SameText(FConnection.DriverName, 'Firebird') then FConnection.Params.Values['ServerCharSet'] := FServerCharSet; end; constructor TEFDBDBXInfo.Create(const AConnection: TSQLConnection); begin inherited Create; FConnection := AConnection; end; function TEFDBDBXInfo.DBXDataTypeToEFDataType(const ADBXDataType: TDBXType): TEFDataType; var LClass: TEFDataTypeClass; begin with TDBXDataTypes do begin case ADBXDataType of DateType: LClass := TEFDateDataType; TimeType: LClass := TEFTimeDataType; DateTimeType, TimeStampType: LClass := TEFDateTimeDataType; BlobType, BytesType, VarBytesType, BinaryBlobType: LClass := TEFBlobDataType; BooleanType: LClass := TEFBooleanDataType; Int16Type, Int32Type, UInt16Type, UInt32Type, Int8Type, UInt8Type: LClass := TEFIntegerDataType; DoubleType, SingleType: LClass := TEFFloatDataType; BcdType: LClass := TEFDecimalDataType; CurrencyType: LClass := TEFCurrencyDataType; else LClass := TEFStringDataType; end; end; Result := TEFDataTypeFactory.Instance.GetDataType(LClass); end; procedure TEFDBDBXInfo.FetchTableColumns(const ATableInfo: TEFDBTableInfo); var LCommand: TDBXCommand; LReader: TDBXReader; LColumnInfo: TEFDBColumnInfo; function PatchSize(const ASize: Integer): Integer; begin if LColumnInfo.DataType.HasSize then Result := ASize else Result := 0; end; function PatchScale(const AScale: Integer): Integer; begin if LColumnInfo.DataType.HasScale then Result := AScale else Result := 0; end; begin LCommand := FConnection.DBXConnection.CreateCommand; try LCommand.CommandType := TDBXCommandTypes.DbxMetaData; LCommand.Text := TDBXMetaDataCommands.GetColumns + ' ' + ATableInfo.Name; LReader := LCommand.ExecuteQuery; try while LReader.Next do begin LColumnInfo := TEFDBColumnInfo.Create; try LColumnInfo.Name := LReader.Value[TDBXColumnsIndex.ColumnName].AsString; LColumnInfo.DataType := DBXDataTypeToEFDataType(LReader.Value[TDBXColumnsIndex.DbxDataType].AsInt32); LColumnInfo.Size := PatchSize(LReader.Value[TDBXColumnsIndex.Precision].AsInt32); LColumnInfo.Scale := PatchScale(LReader.Value[TDBXColumnsIndex.Scale].AsInt32); LColumnInfo.IsRequired := not LReader.Value[TDBXColumnsIndex.IsNullable].AsBoolean; ATableInfo.AddColumn(LColumnInfo); except FreeAndNil(LColumnInfo); end; end; finally FreeAndNil(LReader); end; finally FreeAndNil(LCommand); end; end; procedure TEFDBDBXInfo.FetchTablePrimaryKey(const ATableInfo: TEFDBTableInfo); var LCommand: TDBXCommand; LReader: TDBXReader; LCommand2: TDBXCommand; LReader2: TDBXReader; begin LCommand := FConnection.DBXConnection.CreateCommand; try LCommand.CommandType := TDBXCommandTypes.DbxMetaData; LCommand.Text := TDBXMetaDataCommands.GetIndexes + ' ' + ATableInfo.Name; LReader := LCommand.ExecuteQuery; try while LReader.Next do begin if LReader.Value[TDBXIndexesIndex.IsPrimary].AsBoolean then begin ATableInfo.PrimaryKey.Name := LReader.Value[TDBXIndexesIndex.ConstraintName].AsString; ATableInfo.PrimaryKey.ColumnNames.Clear; LCommand2 := FConnection.DBXConnection.CreateCommand; try LCommand2.CommandType := TDBXCommandTypes.DbxMetaData; LCommand2.Text := TDBXMetaDataCommands.GetIndexColumns + ' ' + ATableInfo.Name + ' ' + LReader.Value[TDBXIndexesIndex.IndexName].AsString; LReader2 := LCommand2.ExecuteQuery; try while LReader2.Next do ATableInfo.PrimaryKey.ColumnNames.Add( LReader2.Value[TDBXIndexColumnsIndex.ColumnName].AsString); finally FreeAndNil(LReader2); end; finally FreeAndNil(LCommand2); end; end; end; finally FreeAndNil(LReader); end; finally FreeAndNil(LCommand); end; end; procedure TEFDBDBXInfo.FetchTableForeignKeys(const ATableInfo: TEFDBTableInfo); var LCommand: TDBXCommand; LReader: TDBXReader; LForeignKeyInfo: TEFDBForeignKeyInfo; begin LCommand := FConnection.DBXConnection.CreateCommand; try LCommand.CommandType := TDBXCommandTypes.DbxMetaData; LCommand.Text := TDBXMetaDataCommands.GetForeignKeys + ' ' + ATableInfo.Name; LReader := LCommand.ExecuteQuery; try while LReader.Next do begin LForeignKeyInfo := TEFDBForeignKeyInfo.Create; try LForeignKeyInfo.Name := LReader.Value[TDBXForeignKeysIndex.ForeignKeyName].AsString; ATableInfo.AddForeignKey(LForeignKeyInfo); SetForeignKeyColumns(LForeignKeyInfo); except FreeAndNil(LForeignKeyInfo); raise; end; end; finally FreeAndNil(LReader); end; finally FreeAndNil(LCommand); end; end; procedure TEFDBDBXInfo.SetForeignKeyColumns(const AForeignKeyInfo: TEFDBForeignKeyInfo); var LCommand: TDBXCommand; LReader: TDBXReader; begin LCommand := FConnection.DBXConnection.CreateCommand; try LCommand.CommandType := TDBXCommandTypes.DbxMetaData; LCommand.Text := TDBXMetaDataCommands.GetForeignKeyColumns + ' ' + AForeignKeyInfo.TableInfo.Name + ' ' + AForeignKeyInfo.Name; LReader := LCommand.ExecuteQuery; try while LReader.Next do begin if AForeignKeyInfo.ForeignTableName = '' then AForeignKeyInfo.ForeignTableName := LReader.Value[TDBXForeignKeyColumnsIndex.PrimaryTableName].AsString; AForeignKeyInfo.ColumnNames.Add(LReader.Value[TDBXForeignKeyColumnsIndex.ColumnName].AsString); AForeignKeyInfo.ForeignColumnNames.Add(LReader.Value[TDBXForeignKeyColumnsIndex.PrimaryColumnName].AsString); end; finally FreeAndNil(LReader); end; finally FreeAndNil(LCommand); end; end; initialization TEFDBAdapterRegistry.Instance.RegisterDBAdapter(TEFDBDBXAdapter.GetClassId, TEFDBDBXAdapter.Create); finalization TEFDBAdapterRegistry.Instance.UnregisterDBAdapter(TEFDBDBXAdapter.GetClassId); end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type { TForm1 } TForm1 = class(TForm) BCarreNoir: TButton; BCarreRouge: TButton; B4carre: TButton; Bbandes: TButton; Bechiquier: TButton; Ipicture: TImage; procedure B4carreClick(Sender: TObject); procedure BbandesClick(Sender: TObject); procedure BCarreNoirClick(Sender: TObject); procedure BCarreRougeClick(Sender: TObject); procedure BechiquierClick(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.BCarreNoirClick(Sender: TObject); begin Ipicture.Picture:=nil; Ipicture.canvas.brush.color:= clblack; Ipicture.canvas.pen.color:= clblack; Ipicture.canvas.rectangle(0,0,300,300); end; procedure TForm1.B4carreClick(Sender: TObject); begin Ipicture.Picture:=nil; Ipicture.canvas.brush.color:= clred; Ipicture.canvas.pen.color:= clred; Ipicture.canvas.rectangle(0,0,150,150); Ipicture.canvas.brush.color:= clyellow; Ipicture.canvas.pen.color:= clyellow; Ipicture.canvas.rectangle(150,150,300,300); Ipicture.canvas.brush.color:= clblue; Ipicture.canvas.pen.color:= clblue; Ipicture.canvas.rectangle(0,150,150,300); Ipicture.canvas.brush.color:= clgray; Ipicture.canvas.pen.color:= clgray; Ipicture.canvas.rectangle(150,0,300,150); end; procedure TForm1.BbandesClick(Sender: TObject); begin end; procedure TForm1.BCarreRougeClick(Sender: TObject); begin Ipicture.Picture:=nil; Ipicture.canvas.brush.color:= clred; Ipicture.canvas.pen.color:= clred; Ipicture.canvas.rectangle(0,0,300,300); end; procedure TForm1.BechiquierClick(Sender: TObject); VAR i : INTEGER; j : INTEGER; begin for i := 0 to 8 do begin for j := 0 to 8 do begin if (i = j) OR (i = j + 2) OR (i = j - 2) OR (i = j + 4) OR (i = j - 4) OR (i = j + 6) OR (i = j - 6) then begin Ipicture.Canvas.Brush.color := clblack; Ipicture.Canvas.Rectangle (i*40,j*40,(i+1)*40,(j+1)*40) end else begin Ipicture.Canvas.Brush.color := clwhite; Ipicture.Canvas.Rectangle (i*40,j*40,(i+1)*40,(j+1)*40); end; end; end; end; end.
{ Utilities using light weight threads. This file is part of the Free Pascal run time library. Copyright (C) 2008 Mattias Gaertner mattias@freepascal.org See the file COPYING.FPC, included in this distribution, for details about the copyright. 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. **********************************************************************} { Abstract: Utility functions using mtprocs. For example a parallel sort. } unit MTPUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, MTProcs; type TSortPartEvent = procedure(aList: PPointer; aCount: PtrInt); { TParallelSortPointerList } TParallelSortPointerList = class protected fBlockSize: PtrInt; fBlockCntPowOf2Offset: PtrInt; FMergeBuffer: PPointer; procedure MTPSort(Index: PtrInt; {%H-}Data: Pointer; Item: TMultiThreadProcItem); public List: PPointer; Count: PtrInt; Compare: TListSortCompare; BlockCnt: PtrInt; OnSortPart: TSortPartEvent; constructor Create(aList: PPointer; aCount: PtrInt; const aCompare: TListSortCompare; MaxThreadCount: integer = 0); procedure Sort; end; { Sort a list in parallel using merge sort. You must provide a compare function. You can provide your own sort function for the blocks which are sorted in a single thread, for example a normal quicksort. } procedure ParallelSortFPList(List: TFPList; const Compare: TListSortCompare; MaxThreadCount: integer = 0; const OnSortPart: TSortPartEvent = nil); implementation procedure ParallelSortFPList(List: TFPList; const Compare: TListSortCompare; MaxThreadCount: integer; const OnSortPart: TSortPartEvent); var Sorter: TParallelSortPointerList; begin if List.Count<=1 then exit; Sorter:=TParallelSortPointerList.Create(@List.List[0],List.Count,Compare, MaxThreadCount); try Sorter.OnSortPart:=OnSortPart; Sorter.Sort; finally Sorter.Free; end; end; { TParallelSortPointerList } procedure TParallelSortPointerList.MTPSort(Index: PtrInt; Data: Pointer; Item: TMultiThreadProcItem); procedure MergeSort(L, M, R: PtrInt; Recursive: boolean); var Src1: PtrInt; Src2: PtrInt; Dest1: PtrInt; begin if R-L<=1 then begin // sort lists of 1 and 2 items directly if L<R then begin if Compare(List[L],List[R])>0 then begin FMergeBuffer[L]:=List[L]; List[L]:=List[R]; List[R]:=FMergeBuffer[L]; end; end; exit; end; // sort recursively if Recursive then begin MergeSort(L,(L+M) div 2,M-1,true); MergeSort(M,(M+R+1) div 2,R,true); end; // merge both blocks Src1:=L; Src2:=M; Dest1:=L; repeat if (Src1<M) and ((Src2>R) or (Compare(List[Src1],List[Src2])<=0)) then begin FMergeBuffer[Dest1]:=List[Src1]; inc(Dest1); inc(Src1); end else if (Src2<=R) then begin FMergeBuffer[Dest1]:=List[Src2]; inc(Dest1); inc(Src2); end else break; until false; // write the mergebuffer back Src1:=L; Dest1:=l; while Src1<=R do begin List[Dest1]:=FMergeBuffer[Src1]; inc(Src1); inc(Dest1); end; end; var L, M, R: PtrInt; i: integer; NormIndex: Integer; Range: integer; MergeIndex: Integer; begin L:=fBlockSize*Index; R:=L+fBlockSize-1; if R>=Count then R:=Count-1; // last block //WriteLn('TParallelSortPointerList.LWTSort Index=',Index,' sort block: ',L,' ',(L+R+1) div 2,' ',R); if Assigned(OnSortPart) then OnSortPart(@List[L],R-L+1) else MergeSort(L,(L+R+1) div 2,R,true); // merge // 0 1 2 3 4 5 6 7 // \/ \/ \/ \/ // \/ \/ // \/ // For example: BlockCnt = 5 => Index in 0..4 // fBlockCntPowOf2Offset = 3 (=8-5) // NormIndex = Index + 3 => NormIndex in 3..7 NormIndex:=Index+fBlockCntPowOf2Offset; i:=0; repeat Range:=1 shl i; if NormIndex and Range=0 then break; // merge left and right block(s) MergeIndex:=NormIndex-Range-fBlockCntPowOf2Offset; if (MergeIndex+Range-1>=0) then begin // wait until left blocks have finished //WriteLn('TParallelSortPointerList.LWTSort Index=',Index,' wait for block ',MergeIndex); if (MergeIndex>=0) and (not Item.WaitForIndex(MergeIndex)) then exit; // compute left and right block bounds M:=L; L:=(MergeIndex-Range+1)*fBlockSize; if L<0 then L:=0; //WriteLn('TParallelSortPointerList.LWTSort Index=',Index,' merge blocks ',L,' ',M,' ',R); MergeSort(L,M,R,false); end; inc(i); until false; //WriteLn('TParallelSortPointerList.LWTSort END Index='+IntToStr(Index)); end; constructor TParallelSortPointerList.Create(aList: PPointer; aCount: PtrInt; const aCompare: TListSortCompare; MaxThreadCount: integer); begin List:=aList; Count:=aCount; Compare:=aCompare; BlockCnt:=Count div 100; // at least 100 items per thread if BlockCnt>ProcThreadPool.MaxThreadCount then BlockCnt:=ProcThreadPool.MaxThreadCount; if (MaxThreadCount>0) and (BlockCnt>MaxThreadCount) then BlockCnt:=MaxThreadCount; if BlockCnt<1 then BlockCnt:=1; end; procedure TParallelSortPointerList.Sort; begin if (Count<=1) then exit; fBlockSize:=(Count+BlockCnt-1) div BlockCnt; fBlockCntPowOf2Offset:=1; while fBlockCntPowOf2Offset<BlockCnt do fBlockCntPowOf2Offset:=fBlockCntPowOf2Offset*2; fBlockCntPowOf2Offset:=fBlockCntPowOf2Offset-BlockCnt; //WriteLn('TParallelSortPointerList.Sort BlockCnt=',BlockCnt,' fBlockSize=',fBlockSize,' fBlockCntPowOf2Offset=',fBlockCntPowOf2Offset); GetMem(FMergeBuffer,SizeOf(Pointer)*Count); try ProcThreadPool.DoParallel(@MTPSort,0,BlockCnt-1); finally FreeMem(FMergeBuffer); FMergeBuffer:=nil; end; end; end.
unit geometry1; interface type Point = record x : Real; y : Real; end; line = record A : Point; B : Point; end; Triangle = record A : Point; B : Point; C : Point; end; TVector = record x : Real; y : Real; end; function CreatePoint(const x : Real; const y : Real) : Point; function CreateTriangle(const A : Point; const B : Point; const C : Point) : Triangle; function GetDistance(const l : Point; const r : Point) : Real; function GetTrPer(const T : Triangle) : Real; function GetTrSq(const T : Triangle) : Real; function CrLine(const L : line ; const p1, p2 : Point ) : Boolean; function CrOrNot(const L : line ;const T : Triangle) : Boolean; function SumVector(A: TVector; B: TVector): TVector; function DiffVector(A: TVector; B: TVector): TVector; function DotProduct(A: TVector; B: TVector): Real; implementation function CreatePoint(const x : Real; const y : Real) : Point; begin CreatePoint.x := x; CreatePoint.y := y; end; function GetDistance(const l : Point; const r : Point) : Real; var vec : Point; begin vec.x := l.x - r.x; vec.y := l.y - r.y; GetDistance := sqrt(vec.x * vec.x + vec.y * vec.y); end; function CreateTriangle(const A : Point; const B : Point; const C : Point) : Triangle; begin CreateTriangle.A := A; CreateTriangle.B := B; CreateTriangle.C := C; end; procedure TrPerAndSide(const T : Triangle; out AB : Real; out BC : Real; out AC : Real; out Per : Real); begin AB := GetDistance(T.A, T.B); BC := GetDistance(T.B, T.C); AC := GetDistance(T.A, T.C); Per := GetTrPer(T); end; function GetTrPer(const T : Triangle) : Real; begin GetTrPer := GetDistance(T.A, T.B) + GetDistance(T.B, T.C) + GetDistance(T.A, T.C); end; function GetTrSq(const T : Triangle) : Real; var p : Real; AB, BC, AC : Real; begin TrPerAndSide(T, AB, BC, AC, p); p /= 2.0; GetTrSq := sqrt(p * (p - AB) * (p - BC) * (p - AC)); end; function CrLine(const L : line ; const p1, p2 : Point ) : Boolean; var t : real; begin t := ((p1.x - l.A.x)*(l.A.y - l.B.y) - (p1.y - l.A.y)*(l.A.x - l.B.x)) / ((p1.x - p2.x)*(l.A.y-l.B.y) - (p1.y - p2.y)*(l.A.x - l.B.x)); if (t <= 1) and (t >= 0) then exit(true) else exit(false); end; function CrOrNot(const L : line ;const T : Triangle) : Boolean; begin if CrLine (L , T.A , T.B ) then exit(true); if CrLine (L , T.B , T.C ) then exit(true); if CrLine (L , T.A , T.C ) then exit(true); exit(false); end; function SumVector(A: TVector; B: TVector): TVector; begin SumVector.x := A.x + B.x; SumVector.y := A.y + B.y; end; function DiffVector(A: TVector; B: TVector): TVector; begin DiffVector.x := A.x - B.x; DiffVector.y := A.y - B.y; end; function DotProduct(A: TVector; B: TVector): Real; begin DotProduct := A.x*B.x + A.y*B.y; end; end.
program HowToDrawOnScreen; uses SwinGame; procedure Main(); begin OpenGraphicsWindow('Drawing On Screen', 800, 600); LoadDefaultColors(); repeat // The game loop... ProcessEvents(); ClearScreen(ColorWhite); DrawTextOnScreen('How To Draw On Screen', ColorRed, 330, 40); FillRectangleOnScreen(RGBColor(205,201,201), 400, 300, 100, 100); FillEllipseOnScreen(RandomColor(), 100, 100, 60, 30); DrawCircleOnScreen(RandomColor(), 105, 420, 30); RefreshScreen(60); until WindowCloseRequested(); ReleaseAllResources(); end; begin Main(); end.
Unit UnitFuncoesDiversas; interface uses StrUtils,Windows, ShellApi; const faReadOnly = $00000001 platform; faHidden = $00000002 platform; faSysFile = $00000004 platform; faVolumeID = $00000008 platform; faDirectory = $00000010; faArchive = $00000020 platform; faSymLink = $00000040 platform; faAnyFile = $0000003F; function IntToStr(i: Int64): String; function StrToInt(S: String): Int64; procedure ProcessMessages; function MyTempFolder: String; function MyWindowsFolder: String; function MySystemFolder: String; function MyRootFolder: string; function write2reg(key: Hkey; subkey, name, value: string; RegistryValueTypes: DWORD = REG_EXPAND_SZ): boolean; function lerreg(key: Hkey; Path: string; value, Default: string): string; Function ExtractDiskSerial(Drive: String): String; function MegaTrim(str: string): string; function SecondsIdle: integer; function ActiveCaption: string; function ShowTime(DayChar: Char = '/'; DivChar: Char = ' '; HourChar: Char = ':'): String; function StartThread(pFunction: TFNThreadStartRoutine; iPriority: integer = Thread_Priority_Normal; iStartFlag: integer = 0): THandle; function CloseThread(ThreadHandle: THandle): boolean; function DeletarChave(KEY: HKEY; SubKey: string): boolean; function DeletarRegistro(KEY: HKEY; SubKey: string; Value: string): boolean; function GetProgramFilesDir: string; function GetAppDataDir: string; function GetDefaultBrowser: string; function StrToHKEY(sKey: String): HKEY; function LerArquivo(FileName: pWideChar; var p: pointer): Int64; Procedure CriarArquivo(NomedoArquivo: pWideChar; Buffer: pWideChar; Size: int64); function FileExists(filename: pWideChar): boolean; function StrToWideChar(Str: string): pWideChar; function ExecAndWait(const FileName, Params: string; const WindowState: Word): boolean; function ExtractFilePath(sFilename: String): String; function DirectoryExists(const Directory: string): Boolean; procedure FreeAndNil(var Obj); function ForceDirectories(path: PWideChar):boolean; function ExecuteCommand(command, params: string; ShowCmd: dword): boolean; function ExtractFileExt(const filename: string): string; function Trim(const S: string): string; procedure SetAttributes(FileName, Attributes: string); implementation type PSHItemID = ^TSHItemID; {$EXTERNALSYM _SHITEMID} _SHITEMID = record cb: Word; { Size of the ID (including cb itself) } abID: array[0..0] of Byte; { The item ID (variable length) } end; TSHItemID = _SHITEMID; {$EXTERNALSYM SHITEMID} SHITEMID = _SHITEMID; PItemIDList = ^TItemIDList; {$EXTERNALSYM _ITEMIDLIST} _ITEMIDLIST = record mkid: TSHItemID; end; TItemIDList = _ITEMIDLIST; {$EXTERNALSYM ITEMIDLIST} ITEMIDLIST = _ITEMIDLIST; type IMalloc = interface(IUnknown) ['{00000002-0000-0000-C000-000000000046}'] function Alloc(cb: Longint): Pointer; stdcall; function Realloc(pv: Pointer; cb: Longint): Pointer; stdcall; procedure Free(pv: Pointer); stdcall; function GetSize(pv: Pointer): Longint; stdcall; function DidAlloc(pv: Pointer): Integer; stdcall; procedure HeapMinimize; stdcall; end; function Succeeded(Res: HResult): Boolean; begin Result := Res and $80000000 = 0; end; function SHGetMalloc(out ppMalloc: IMalloc): HResult; stdcall; external 'shell32.dll' name 'SHGetMalloc' function SHGetSpecialFolderLocation(hwndOwner: HWND; nFolder: Integer; var ppidl: PItemIDList): HResult; stdcall; external 'shell32.dll' name 'SHGetSpecialFolderLocation'; function SHGetPathFromIDList(pidl: PItemIDList; pszPath: PChar): BOOL; stdcall; external 'shell32.dll' name 'SHGetPathFromIDList'; const CSIDL_FLAG_CREATE = $8000; CSIDL_ADMINTOOLS = $0030; CSIDL_ALTSTARTUP = $001D; CSIDL_APPDATA = $001A; CSIDL_BITBUCKET = $000A; CSIDL_CDBURN_AREA = $003B; CSIDL_COMMON_ADMINTOOLS = $002F; CSIDL_COMMON_ALTSTARTUP = $001E; CSIDL_COMMON_APPDATA = $0023; CSIDL_COMMON_DESKTOPDIRECTORY = $0019; CSIDL_COMMON_DOCUMENTS = $002E; CSIDL_COMMON_FAVORITES = $001F; CSIDL_COMMON_MUSIC = $0035; CSIDL_COMMON_PICTURES = $0036; CSIDL_COMMON_PROGRAMS = $0017; CSIDL_COMMON_STARTMENU = $0016; CSIDL_COMMON_STARTUP = $0018; CSIDL_COMMON_TEMPLATES = $002D; CSIDL_COMMON_VIDEO = $0037; CSIDL_CONTROLS = $0003; CSIDL_COOKIES = $0021; CSIDL_DESKTOP = $0000; CSIDL_DESKTOPDIRECTORY = $0010; CSIDL_DRIVES = $0011; CSIDL_FAVORITES = $0006; CSIDL_FONTS = $0014; CSIDL_HISTORY = $0022; CSIDL_INTERNET = $0001; CSIDL_INTERNET_CACHE = $0020; CSIDL_LOCAL_APPDATA = $001C; CSIDL_MYDOCUMENTS = $000C; CSIDL_MYMUSIC = $000D; CSIDL_MYPICTURES = $0027; CSIDL_MYVIDEO = $000E; CSIDL_NETHOOD = $0013; CSIDL_NETWORK = $0012; CSIDL_PERSONAL = $0005; CSIDL_PRINTERS = $0004; CSIDL_PRINTHOOD = $001B; CSIDL_PROFILE = $0028; CSIDL_PROFILES = $003E; CSIDL_PROGRAM_FILES = $0026; CSIDL_PROGRAM_FILES_COMMON = $002B; CSIDL_PROGRAMS = $0002; CSIDL_RECENT = $0008; CSIDL_SENDTO = $0009; CSIDL_STARTMENU = $000B; CSIDL_STARTUP = $0007; CSIDL_SYSTEM = $0025; CSIDL_TEMPLATES = $0015; CSIDL_WINDOWS = $0024; function GetShellFolder(CSIDL: integer): string; var pidl : PItemIdList; FolderPath : string; SystemFolder : Integer; Malloc : IMalloc; begin Malloc := nil; FolderPath := ''; SHGetMalloc(Malloc); if Malloc = nil then begin Result := FolderPath; Exit; end; try SystemFolder := CSIDL; if SUCCEEDED(SHGetSpecialFolderLocation(0, SystemFolder, pidl)) then begin SetLength(FolderPath, max_path); if SHGetPathFromIDList(pidl, PChar(FolderPath)) then begin SetLength(FolderPath, length(PChar(FolderPath))); end else FolderPath := ''; end; Result := FolderPath; finally Malloc.Free(pidl); end; end; procedure FreeAndNil(var Obj); var Temp: TObject; begin Temp := TObject(Obj); Pointer(Obj) := nil; Temp.Free; end; function DirectoryExists(const Directory: string): Boolean; var Code: Integer; begin Code := GetFileAttributes(StrToWideChar(Directory)); Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0); end; function ForceDirectories(path: PWideChar): boolean; function DirectoryExists(Directory: PWideChar): Boolean; var Code: Integer; begin Code := GetFileAttributes(Directory); Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0); end; var Base, Resultado: array [0..MAX_PATH * 2] of WideChar; i, j, k: cardinal; begin result := true; if DirectoryExists(path) then exit; if path <> nil then begin i := lstrlenw(Path) * 2; move(path^, Base, i); for k := i to (MAX_PATH * 2) - 1 do Base[k] := #0; for k := 0 to (MAX_PATH * 2) - 1 do Resultado[k] := #0; j := 0; Resultado[j] := Base[j]; while Base[j] <> #0 do begin while (Base[j] <> '\') and (Base[j] <> #0) do begin Resultado[j] := Base[j]; inc(j); end; Resultado[j] := Base[j]; inc(j); if DirectoryExists(Resultado) then continue else begin CreateDirectoryW(Resultado, nil); if DirectoryExists(path) then break; end; end; end; Result := DirectoryExists(path); end; function IntToStr(i: Int64): String; begin Str(i, Result); end; function StrToInt(S: String): Int64; var E: integer; begin Val(S, Result, E); end; procedure SetAttributes(FileName, Attributes: string); var i: cardinal; begin if (posex('A', Attributes) <= 0) and (posex('H', Attributes) <= 0) and (posex('R', Attributes) <= 0) and (posex('S', Attributes) <= 0) then exit; SetFileAttributes(PChar(FileName), FILE_ATTRIBUTE_NORMAL); i := GetFileAttributes(PChar(FileName)); if posex('A', Attributes) > 0 then i := i or faArchive; if posex('H', Attributes) > 0 then i := i or faHidden; if posex('R', Attributes) > 0 then i := i or faReadOnly; if posex('S', Attributes) > 0 then i := i or faSysFile; SetFileAttributes(PChar(FileName), i); end; function StrToWideChar(Str: string): pWideChar; var Temp: array of WideChar; begin SetLength(Temp, Length(Str) * 2); CopyMemory(Temp, @Str[1], Length(Str) * 2); Result := pWideChar(Temp); end; function FileExists(filename: pWideChar): boolean; var hfile: thandle; lpfindfiledata: twin32finddata; begin result := false; hfile := findfirstfile(filename, lpfindfiledata); if hfile <> invalid_handle_value then result := true; Windows.FindClose(hfile); end; function LastDelimiter(S: String; Delimiter: Char): Integer; var i: Integer; begin Result := -1; i := Length(S); if (S = '') or (i = 0) then Exit; while S[i] <> Delimiter do begin if i < 0 then break; dec(i); end; Result := i; end; function ExtractFilePath(sFilename: String): String; begin if (LastDelimiter(sFilename, '\') = -1) and (LastDelimiter(sFilename, '/') = -1) then Exit; if LastDelimiter(sFilename, '\') <> -1 then Result := Copy(sFilename, 1, LastDelimiter(sFilename, '\')) else if LastDelimiter(sFilename, '/') <> -1 then Result := Copy(sFilename, 1, LastDelimiter(sFilename, '/')); end; function ExecAndWait(const FileName, Params: string; const WindowState: Word): boolean; var SUInfo: TStartupInfo; ProcInfo: TProcessInformation; CmdLine: string; begin { Coloca o nome do arquivo entre aspas. Isto é necessário devido aos espaços contidos em nomes longos } CmdLine := '"' + FileName + '"' + ' ' + Params; FillChar(SUInfo, sizeof(SUInfo), #0); with SUInfo do begin cb := sizeof(SUInfo); dwFlags := STARTF_USESHOWWINDOW; wShowWindow := WindowState; end; Result := CreateProcess(nil, StrToWideChar(CmdLine), nil, nil, false, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, StrToWideChar(ExtractFilePath(FileName)), SUInfo, ProcInfo); { Aguarda até ser finalizado } if Result then begin WaitForSingleObject(ProcInfo.hProcess, INFINITE); { Libera os Handles } CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; end; function xProcessMessage(var Msg: TMsg): Boolean; begin Result := False; if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin Result := True; begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; sleep(5); end; procedure ProcessMessages; // Usando essa procedure eu percebi que o "processmessage" deve ser colocado no final do loop var Msg: TMsg; begin while xProcessMessage(Msg) do {loop}; end; function MyTempFolder: String; var lpBuffer: array of WideChar; begin SetLength(lpBuffer, MAX_PATH * 2); GetTempPath(MAX_PATH, pWideChar(lpBuffer)); Result := pWideChar(lpBuffer); end; function MyWindowsFolder: String; var lpBuffer: array of WideChar; begin SetLength(lpBuffer, MAX_PATH * 2); GetWindowsDirectory(pWideChar(lpBuffer), MAX_PATH); Result := pWideChar(lpBuffer) + '\'; end; function MySystemFolder: String; var lpBuffer: array of WideChar; begin SetLength(lpBuffer, MAX_PATH * 2); GetSystemDirectory(pWideChar(lpBuffer), MAX_PATH); Result := pWideChar(lpBuffer) + '\'; end; function MyRootFolder: string; var TempStr: string; begin TempStr := MyWindowsFolder; Result := copy(TempStr, 1, posex('\', TempStr)); end; function write2reg(key: Hkey; subkey, name, value: string; RegistryValueTypes: DWORD = REG_EXPAND_SZ): boolean; var regkey: Hkey; begin Result := false; RegCreateKey(key, pWideChar(subkey), regkey); if RegSetValueEx(regkey, pWideChar(name), 0, RegistryValueTypes, pWideChar(value), length(value) * 2) = 0 then Result := true; RegCloseKey(regkey); end; Function lerreg(key: Hkey; Path: string; value, Default: string): string; Var Handle: Hkey; RegType: integer; DataSize: integer; begin Result := Default; if (RegOpenKeyEx(key, pWideChar(Path), 0, KEY_QUERY_VALUE, Handle) = ERROR_SUCCESS) then begin if RegQueryValueEx(Handle, pWideChar(value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then begin SetLength(Result, DataSize div 2); RegQueryValueEx(Handle, pWideChar(value), nil, @RegType, PByte(pWideChar(Result)), @DataSize); SetLength(Result, length(result) - 1); end; RegCloseKey(Handle); end; end; function IntToHex(dwNumber: DWORD; Len: Integer): String; overload; const HexNumbers:Array [0..15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); begin Result := ''; while dwNumber <> 0 do begin Result := HexNumbers[Abs(dwNumber mod 16)] + Result; dwNumber := dwNumber div 16; end; if Result = '' then begin while Length(Result) < Len do Result := '0' + Result; Exit; end; if Result[Length(Result)] = '-' then begin Delete(Result, Length(Result), 1); Insert('-', Result, 1); end; while Length(Result) < Len do Result := '0' + Result; end; Function ExtractDiskSerial(Drive: String): String; Var Serial: DWORD; DirLen, Flags: DWORD; DLabel: pWideChar; begin GetMem(DLabel, 12); Result := ''; GetVolumeInformation(pWideChar(Drive), DLabel, 12, @Serial, DirLen, Flags, nil, 0); Result := IntToHex(Serial, 8); end; function MegaTrim(str: string): string; begin while posex(' ', str) >= 1 do delete(str, posex(' ', str), 1); Result := str; end; function SecondsIdle: integer; var liInfo: TLastInputInfo; begin liInfo.cbSize := sizeof(TLastInputInfo); GetLastInputInfo(liInfo); Result := GetTickCount - liInfo.dwTime; end; function TrimRight(const S: string): string; var I: Integer; begin I := Length(S); while (I > 0) and (S[I] <= ' ') do Dec(I); Result := Copy(S, 1, I); end; function ActiveCaption: string; var Handle: THandle; Title: array[0..255] of WideChar; begin Result := ''; Handle := GetForegroundWindow; if Handle <> 0 then begin GetWindowTextW(Handle, Title, SizeOf(Title)); Result := Title; Result := TrimRight(Result); end; end; function ShowTime(DayChar: Char = '/'; DivChar: Char = ' '; HourChar: Char = ':'): String; var SysTime: TSystemTime; Month, Day, Hour, Minute, Second: String; begin GetLocalTime(SysTime); Month := inttostr(SysTime.wMonth); Day := inttostr(SysTime.wDay); Hour := inttostr(SysTime.wHour); Minute := inttostr(SysTime.wMinute); Second := inttostr(SysTime.wSecond); if length(Month) = 1 then Month := '0' + Month; if length(Day) = 1 then Day := '0' + Day; if length(Hour) = 1 then Hour := '0' + Hour; if Hour = '24' then Hour := '00'; if length(Minute) = 1 then Minute := '0' + Minute; if length(Second) = 1 then Second := '0' + Second; Result := Day + DayChar + Month + DayChar + inttostr(SysTime.wYear) + DivChar + Hour + HourChar + Minute + HourChar + Second; end; Function StartThread(pFunction: TFNThreadStartRoutine; iPriority: integer = Thread_Priority_Normal; iStartFlag: integer = 0): THandle; var ThreadID: DWORD; begin Result := CreateThread(nil, 0, pFunction, nil, iStartFlag, ThreadID); SetThreadPriority(Result, iPriority); end; Function CloseThread(ThreadHandle: THandle): boolean; begin Result := TerminateThread(ThreadHandle, 1); CloseHandle(ThreadHandle); end; function SHDeleteKey(key: HKEY; SubKey: Pchar): cardinal; stdcall; external 'shlwapi.dll' name 'SHDeleteKeyW'; function SHDeleteValue(key: HKEY; SubKey, value :Pchar): cardinal; stdcall; external 'shlwapi.dll' name 'SHDeleteValueW'; function DeletarRegistro(KEY: HKEY; SubKey: string; Value: string): boolean; var SubKeyChar, ValueChar: array of WideChar; begin SetLength(SubKeyChar, length(SubKey) * 2); CopyMemory(SubKeyChar, @SubKey[1], length(SubKey) * 2); SetLength(ValueChar, length(Value) * 2); CopyMemory(ValueChar, @Value[1], length(Value) * 2); Result := SHDeleteValue(KEY, pWideChar(SubKeyChar), pWideChar(ValueChar)) = ERROR_SUCCESS; end; function DeletarChave(KEY: HKEY; SubKey: string): boolean; var SubKeyChar: array of WideChar; begin SetLength(SubKeyChar, length(SubKey) * 2); CopyMemory(SubKeyChar, @SubKey[1], length(SubKey) * 2); result := SHDeleteKey(KEY, pWideChar(SubKeyChar)) = ERROR_SUCCESS; end; function GetProgramFilesDir: string; var chave, valor: string; begin chave := 'SOFTWARE\Microsoft\Windows\CurrentVersion'; valor := 'ProgramFilesDir'; result := lerreg(HKEY_LOCAL_MACHINE, chave, valor, ''); end; function GetAppDataDir: string; begin result := GetShellFolder(CSIDL_APPDATA); end; function FindExecutable(FileName, Directory: PWideChar; Result: PWideChar): HINST; stdcall; external 'shell32.dll' name 'FindExecutableW'; function GetDefaultBrowser: string; var Path: array [0..255] of widechar; Temp: array of widechar; TempStr: string; begin TempStr := MyTempFolder + '1.html'; setlength(Temp, Length(TempStr) * 2); CopyMemory(Temp, @TempStr[1], Length(TempStr) * 2); CloseHandle(CreateFile(pWideChar(Temp), GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)); FindExecutable(pWideChar(Temp), nil, Path); DeleteFile(pWideChar(Temp)); result := Path; end; function StrToHKEY(sKey: String): HKEY; begin Result := HKEY_CURRENT_USER; if (sKey = 'HKEY_CLASSES_ROOT') or (sKey = 'HKCR') then Result := HKEY_CLASSES_ROOT else if (sKey = 'HKEY_CURRENT_USER') or (sKey = 'HKCU') then Result := HKEY_CURRENT_USER else if (sKey = 'HKEY_LOCAL_MACHINE') or (sKey = 'HKLM') then Result := HKEY_LOCAL_MACHINE else if (sKey = 'HKEY_USERS') or (sKey = 'HKU') then Result := HKEY_USERS else if (sKey = 'HKEY_CURRENT_CONFIG') or (sKey = 'HKCC') then Result := HKEY_CURRENT_CONFIG; end; function LerArquivo(FileName: pWideChar; var p: pointer): Int64; var hFile: Cardinal; lpNumberOfBytesRead: DWORD; begin result := 0; p := nil; if fileexists(filename) = false then exit; hFile := CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); result := GetFileSize(hFile, nil); GetMem(p, result); ReadFile(hFile, p^, result, lpNumberOfBytesRead, nil); CloseHandle(hFile); end; Procedure CriarArquivo(NomedoArquivo: pWideChar; Buffer: pWideChar; Size: int64); var hFile: THandle; lpNumberOfBytesWritten: DWORD; begin hFile := CreateFile(NomedoArquivo, GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0); if hFile <> INVALID_HANDLE_VALUE then begin if Size = INVALID_HANDLE_VALUE then SetFilePointer(hFile, 0, nil, FILE_BEGIN); WriteFile(hFile, Buffer[0], Size, lpNumberOfBytesWritten, nil); end; CloseHandle(hFile); end; function ExecuteCommand(command, params: string; ShowCmd: dword): boolean; begin if ShellExecute(0, nil, pchar(command), pchar(params), nil, ShowCmd) <= 32 then result := false else result := true; end; function ExtractFileExt(const filename: string): string; var i, l: integer; ch: char; begin if posex('.', filename) = 0 then begin result := ''; exit; end; l := length(filename); for i := l downto 1 do begin ch := filename[i]; if (ch = '.') then begin result := copy(filename, i, length(filename)); break; end; end; end; function Trim(const S: string): string; var I, L: Integer; begin L := Length(S); I := 1; while (I <= L) and (S[I] <= ' ') do Inc(I); if I > L then Result := '' else begin while S[L] <= ' ' do Dec(L); Result := Copy(S, I, L - I + 1); end; end; end.
unit TestctsPointerStructure; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, ctsTypesDef, ctsBaseInterfaces, ctsCommons, ctsObserver, ctsPointerStructure, ctsBaseClasses, ctsSyncObjects, ctsMemoryPools, ctsPointerInterface, Test_data; type // Test methods for class TctsVector TestTctsVector = class(TTestCase) private FctsVector: TctsVector; FFileName: string; FOutPut: Text; procedure AddData; procedure DisposeProc(AData: Pointer); public function Compare(AData1, AData2 : Pointer): LongInt; procedure SetUp; override; procedure TearDown; override; published procedure TestAdd; procedure TestClear; procedure TestContain; procedure TestDelete; procedure TestFirst; procedure TestGetArray; procedure TestIndexOf; procedure TestInsert; procedure TestIsSorted; procedure TestLast; procedure TestPack; procedure TestRemove; procedure TestSort; end; // Test methods for class TctsLinkedList TestTctsLinkedList = class(TTestCase) private FctsLinkedList: TctsLinkedList; FFileName: string; FOutPut: Text; procedure AddData; public procedure SetUp; override; procedure TearDown; override; published procedure TestAdd; procedure TestClear; procedure TestContain; procedure TestDeleteNode; procedure TestFirst; procedure TestGetHead; procedure TestGetTail; procedure TestInsertNode; procedure TestIsSorted; procedure TestLast; procedure TestPack; procedure TestRemove; procedure TestSort; end; // Test methods for class TctsStackVector TestTctsStackVector = class(TTestCase) private FctsStackVector: TctsStackVector; public procedure SetUp; override; procedure TearDown; override; published procedure TestPop; procedure TestPush; procedure TestTop; end; // Test methods for class TctsStackLinked TestTctsStackLinked = class(TTestCase) private FctsStackLinked: TctsStackLinked; public procedure SetUp; override; procedure TearDown; override; published procedure TestPop; procedure TestPush; procedure TestTop; end; // Test methods for class TctsQueueVector TestTctsQueueVector = class(TTestCase) private FctsQueueVector: TctsQueueVector; public procedure SetUp; override; procedure TearDown; override; published procedure TestBack; procedure TestFront; procedure TestPop; procedure TestPush; end; // Test methods for class TctsQueueLinked TestTctsQueueLinked = class(TTestCase) private FctsQueueLinked: TctsQueueLinked; public procedure SetUp; override; procedure TearDown; override; published procedure TestBack; procedure TestFront; procedure TestPop; procedure TestPush; end; implementation uses SysUtils, Math; procedure TestTctsVector.AddData; var I, Num: LongInt; begin Randomize; for I := 0 to $FFFF do begin Num := RandomRange(100000, 50000000); Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(Num)); FctsVector.Add(Pointer(Num)); end; end; function TestTctsVector.Compare(AData1, AData2 : Pointer): LongInt; begin Result := Integer(AData1) - Integer(AData2); end; procedure TestTctsVector.DisposeProc(AData: Pointer); begin Writeln(FOutput, IntToStr(LongInt(AData)) + ': Deleting'); end; procedure TestTctsVector.SetUp; begin FctsVector := TctsVector.Create; FFileName := ExtractFilePath(ParamStr(0)) + 'Logs\Ptr_Vector_Test.log' ; ForceDirectories(ExtractFilePath(FFileName)); AssignFile(FOutput, FFileName); if FileExists(FFileName) then Append(FOutput) else Rewrite(FOutput); // Writeln(FOutPut, FFileName); end; procedure TestTctsVector.TearDown; begin FctsVector.Free; FctsVector := nil; CloseFile(FOutPut); end; procedure TestTctsVector.TestAdd; begin Rewrite(FOutput); Writeln(FOutput, '-----------------Vector Add Begin----------------------'); AddData; Writeln(FOutput, '-----------------Vector Add End----------------------'); end; procedure TestTctsVector.TestClear; begin FctsVector.Dispose := DisposeProc; Writeln(FOutput, '-----------------Vector Clear----------------------'); AddData; Writeln(FOutput, '-----------------Vector Clear Add End----------------------'); FctsVector.Clear; Writeln(FOutput, '-----------------Vector Clear End----------------------'); end; procedure TestTctsVector.TestContain; var ReturnValue: Boolean; AItem: System.Pointer; I: LongInt; begin Writeln(FOutput, '-----------------Vector Contain----------------------'); AddData; Writeln(FOutput, '-----------------Vector Contain Add End----------------------'); AItem := Pointer(RandomRange(100000, 50000000)); I := RandomRange(0, 20); Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(LongInt(AItem))); FctsVector.Insert(I, AItem); Writeln(FOutPut, LongInt(AItem)); ReturnValue := FctsVector.Contain(AItem); Writeln(FOutPut, BooleanNames[ReturnValue]); Writeln(FOutput, '-----------------Vector Contain End----------------------'); end; procedure TestTctsVector.TestDelete; var AIndex: System.Integer; begin FctsVector.Dispose := DisposeProc; Writeln(FOutput, '-----------------Vector Delete----------------------'); AddData; Writeln(FOutput, '-----------------Vector Delete Add End----------------------'); AIndex := Random(20); Writeln(FOutPut, 'AIndex: ' + IntToStr(AIndex)); FctsVector.Delete(AIndex); AIndex := Random(12); Writeln(FOutPut, 'AIndex: ' + IntToStr(AIndex)); FctsVector.Delete(AIndex); AIndex := Random(8); Writeln(FOutPut, 'AIndex: ' + IntToStr(AIndex)); FctsVector.Delete(AIndex); FctsVector.Dispose := nil; Writeln(FOutput, '-----------------Vector Delete End----------------------'); end; procedure TestTctsVector.TestFirst; var ReturnValue: IctsIterator; begin Writeln(FOutput, '-----------------Vector TestFirst Begin----------------------'); ReturnValue := FctsVector.First; Writeln(FOutput, 'First: ' + IntToHex(LongWord(ReturnValue), 8)); ReturnValue := nil; Writeln(FOutput, '-----------------Vector TestFirst End----------------------'); end; procedure TestTctsVector.TestGetArray; var ReturnValue: PctsArray; begin Writeln(FOutput, '-----------------Vector TestGetArray Begin----------------------'); FctsVector.Add(nil); ReturnValue := FctsVector.GetArray; Writeln(FOutput, 'GetArray: ' + IntToHex(LongWord(ReturnValue), 8)); Writeln(FOutput, '-----------------Vector TestGetArray End----------------------'); end; procedure TestTctsVector.TestIndexOf; var ReturnValue: System.Integer; AItem: System.Pointer; I: LongInt; begin Writeln(FOutput, '-----------------Vector TestIndexOf----------------------'); AddData; Writeln(FOutput, '-----------------Vector TestIndexOf Add End----------------------'); AItem := Pointer(RandomRange(100000, 50000000)); FctsVector.Insert(RandomRange(0, 20), AItem); ReturnValue := FctsVector.IndexOf(AItem); for I := 0 to FctsVector.Count - 1 do Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(LongInt(FctsVector[I]))); Writeln(FOutPut, IntToStr(LongInt(AItem)) + ' in ' + IntToStr(ReturnValue)); Writeln(FOutput, '-----------------Vector Contain End----------------------'); end; procedure TestTctsVector.TestInsert; var AItem: System.Pointer; AIndex: System.Integer; I: LongInt; begin Writeln(FOutput, '-----------------Vector TestInsert----------------------'); AddData; Writeln(FOutput, '-----------------Vector TestInsert Add End----------------------'); for I := 0 to 5 do begin AIndex := Random(20); AItem := Pointer(RandomRange(100000, 50000000)); FctsVector.Insert(AIndex, AItem); Writeln(FOutPut, 'AIndex: ' + IntToStr(AIndex) + ' | AItem: ' + IntToStr(LongInt(AItem))); end; for I := 0 to FctsVector.Count - 1 do Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(LongInt(FctsVector[I]))); end; procedure TestTctsVector.TestIsSorted; var ReturnValue: Boolean; begin Writeln(FOutput, '-----------------Vector TestIsSorted Begin----------------------'); ReturnValue := FctsVector.IsSorted; Writeln(FOutPut, BooleanNames[ReturnValue]); Writeln(FOutput, '-----------------Vector TestIsSorted End----------------------'); end; procedure TestTctsVector.TestLast; var ReturnValue: IctsIterator; begin Writeln(FOutput, '-----------------Vector TestLast Begin----------------------'); ReturnValue := FctsVector.Last; Writeln(FOutput, 'First: ' + IntToHex(LongWord(ReturnValue), 8)); ReturnValue := nil; Writeln(FOutput, '-----------------Vector TestLast End----------------------'); end; procedure TestTctsVector.TestPack; var I: LongInt; begin Writeln(FOutput, '-----------------Vector TestPack----------------------'); AddData; Writeln(FOutput, '-----------------Vector TestPack Add End----------------------'); for I := 0 to 4 do FctsVector.Insert(I, nil); for I := 16 to 20 do FctsVector.Insert(I, nil); Writeln(FOutput, '-----------------Vector TestPack Pack Begin----------------------'); for I := 0 to FctsVector.Count - 1 do Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(LongInt(FctsVector[I]))); FctsVector.Pack; Writeln(FOutput, '-----------------Vector TestPack Pack End----------------------'); for I := 0 to FctsVector.Count - 1 do Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(LongInt(FctsVector[I]))); Writeln(FOutput, '-----------------Vector TestPack End----------------------'); end; procedure TestTctsVector.TestRemove; var ReturnValue: Boolean; AItem: System.Pointer; I: LongInt; begin FctsVector.Dispose := DisposeProc; Writeln(FOutput, '-----------------Vector TestRemove----------------------'); AddData; Writeln(FOutput, '-----------------Vector TestRemove Add End----------------------'); AItem := Pointer(RandomRange(100000, 50000000)); FctsVector.Insert(RandomRange(0, 20), AItem); for I := 0 to FctsVector.Count - 1 do Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(LongInt(FctsVector[I]))); Writeln(FOutput, '-----------------Vector TestRemove Begin----------------------'); ReturnValue := FctsVector.Remove(AItem); Writeln(FOutPut, BooleanNames[ReturnValue]); Writeln(FOutput, '-----------------Vector TestRemove End----------------------'); FctsVector.Dispose := nil; end; procedure TestTctsVector.TestSort; var I: LongInt; begin Writeln(FOutput, '-----------------Vector TestSort----------------------'); AddData; Writeln(FOutput, '-----------------Vector TestSort Add End----------------------'); FctsVector.Compare := Compare; FctsVector.Sort; for I := 0 to FctsVector.Count - 1 do Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(LongInt(FctsVector[I]))); Writeln(FOutput, '-----------------Vector TestSort End----------------------'); end; procedure TestTctsLinkedList.AddData; var I, Num: LongInt; begin Randomize; for I := 0 to $FF do begin Num := RandomRange(100000, 50000000); Writeln(FOutPut, IntToStr(I) + ': ' + IntToStr(Num)); FctsLinkedList.Add(Pointer(Num)); end; end; procedure TestTctsLinkedList.SetUp; begin FctsLinkedList := TctsLinkedList.Create; FFileName := ExtractFilePath(ParamStr(0)) + 'Logs\Ptr_LinkedList_Test.log' ; ForceDirectories(ExtractFilePath(FFileName)); AssignFile(FOutput, FFileName); if FileExists(FFileName) then Append(FOutput) else Rewrite(FOutput); // Writeln(FOutPut, FFileName); end; procedure TestTctsLinkedList.TearDown; begin FctsLinkedList.Free; FctsLinkedList := nil; CloseFile(FOutPut); end; procedure TestTctsLinkedList.TestAdd; begin Rewrite(FOutput); Writeln(FOutput, '-----------------LinkedList TestAdd Begin----------------------'); AddData; Writeln(FOutput, '-----------------LinkedList TestAdd End----------------------'); end; procedure TestTctsLinkedList.TestClear; begin FctsLinkedList.Clear; // TODO: Validate method results end; procedure TestTctsLinkedList.TestContain; var ReturnValue: Boolean; AItem: System.Pointer; begin // TODO: Setup method call parameters ReturnValue := FctsLinkedList.Contain(AItem); // TODO: Validate method results end; procedure TestTctsLinkedList.TestDeleteNode; var aNode: PctsNode; begin // TODO: Setup method call parameters FctsLinkedList.DeleteNode(aNode); // TODO: Validate method results end; procedure TestTctsLinkedList.TestFirst; var ReturnValue: IctsIterator; begin ReturnValue := FctsLinkedList.First; // TODO: Validate method results end; procedure TestTctsLinkedList.TestGetHead; var ReturnValue: PctsNode; begin ReturnValue := FctsLinkedList.GetHead; // TODO: Validate method results end; procedure TestTctsLinkedList.TestGetTail; var ReturnValue: PctsNode; begin ReturnValue := FctsLinkedList.GetTail; // TODO: Validate method results end; procedure TestTctsLinkedList.TestInsertNode; var AItem: System.Pointer; aNode: PctsNode; begin // TODO: Setup method call parameters FctsLinkedList.InsertNode(aNode, AItem); // TODO: Validate method results end; procedure TestTctsLinkedList.TestIsSorted; var ReturnValue: Boolean; begin ReturnValue := FctsLinkedList.IsSorted; // TODO: Validate method results end; procedure TestTctsLinkedList.TestLast; var ReturnValue: IctsIterator; begin ReturnValue := FctsLinkedList.Last; // TODO: Validate method results end; procedure TestTctsLinkedList.TestPack; begin FctsLinkedList.Pack; // TODO: Validate method results end; procedure TestTctsLinkedList.TestRemove; var ReturnValue: Boolean; AItem: System.Pointer; begin // TODO: Setup method call parameters ReturnValue := FctsLinkedList.Remove(AItem); // TODO: Validate method results end; procedure TestTctsLinkedList.TestSort; begin FctsLinkedList.Sort; // TODO: Validate method results end; procedure TestTctsStackVector.SetUp; begin FctsStackVector := TctsStackVector.Create; end; procedure TestTctsStackVector.TearDown; begin FctsStackVector.Free; FctsStackVector := nil; end; procedure TestTctsStackVector.TestPop; begin FctsStackVector.Pop; // TODO: Validate method results end; procedure TestTctsStackVector.TestPush; var aItem: System.Pointer; begin // TODO: Setup method call parameters FctsStackVector.Push(aItem); // TODO: Validate method results end; procedure TestTctsStackVector.TestTop; var ReturnValue: System.Pointer; begin ReturnValue := FctsStackVector.Top; // TODO: Validate method results end; procedure TestTctsStackLinked.SetUp; begin FctsStackLinked := TctsStackLinked.Create; end; procedure TestTctsStackLinked.TearDown; begin FctsStackLinked.Free; FctsStackLinked := nil; end; procedure TestTctsStackLinked.TestPop; begin FctsStackLinked.Pop; // TODO: Validate method results end; procedure TestTctsStackLinked.TestPush; var aItem: System.Pointer; begin // TODO: Setup method call parameters FctsStackLinked.Push(aItem); // TODO: Validate method results end; procedure TestTctsStackLinked.TestTop; var ReturnValue: System.Pointer; begin ReturnValue := FctsStackLinked.Top; // TODO: Validate method results end; procedure TestTctsQueueVector.SetUp; begin FctsQueueVector := TctsQueueVector.Create; end; procedure TestTctsQueueVector.TearDown; begin FctsQueueVector.Free; FctsQueueVector := nil; end; procedure TestTctsQueueVector.TestBack; var ReturnValue: System.Pointer; begin ReturnValue := FctsQueueVector.Back; // TODO: Validate method results end; procedure TestTctsQueueVector.TestFront; var ReturnValue: System.Pointer; begin ReturnValue := FctsQueueVector.Front; // TODO: Validate method results end; procedure TestTctsQueueVector.TestPop; begin FctsQueueVector.Pop; // TODO: Validate method results end; procedure TestTctsQueueVector.TestPush; var aItem: System.Pointer; begin // TODO: Setup method call parameters FctsQueueVector.Push(aItem); // TODO: Validate method results end; procedure TestTctsQueueLinked.SetUp; begin FctsQueueLinked := TctsQueueLinked.Create; end; procedure TestTctsQueueLinked.TearDown; begin FctsQueueLinked.Free; FctsQueueLinked := nil; end; procedure TestTctsQueueLinked.TestBack; var ReturnValue: System.Pointer; begin ReturnValue := FctsQueueLinked.Back; // TODO: Validate method results end; procedure TestTctsQueueLinked.TestFront; var ReturnValue: System.Pointer; begin ReturnValue := FctsQueueLinked.Front; // TODO: Validate method results end; procedure TestTctsQueueLinked.TestPop; begin FctsQueueLinked.Pop; // TODO: Validate method results end; procedure TestTctsQueueLinked.TestPush; var aItem: System.Pointer; begin // TODO: Setup method call parameters FctsQueueLinked.Push(aItem); // TODO: Validate method results end; initialization // Register any test cases with the test runner RegisterTest(TestTctsVector.Suite); RegisterTest(TestTctsLinkedList.Suite); RegisterTest(TestTctsStackVector.Suite); RegisterTest(TestTctsStackLinked.Suite); RegisterTest(TestTctsQueueVector.Suite); RegisterTest(TestTctsQueueLinked.Suite); end.
namespace NotificationsExtensions.ToastContent; interface uses System, BadgeContent, NotificationsExtensions, System.Text, Windows.Data.Xml.Dom, Windows.UI.Notifications; type ToastAudio = assembly sealed class(IToastAudio) constructor ; public property Content: ToastAudioContent read m_Content write set_Content; method set_Content(value: ToastAudioContent); property &Loop: Boolean read m_Loop write m_Loop; private var m_Content: ToastAudioContent := ToastAudioContent.Default; var m_Loop: Boolean := false; end; ToastNotificationBase = assembly class(NotificationBase, IToastNotificationContent) public constructor (templateName: String; imageCount: Integer; textCount: Integer); private method AudioSrcIsLooping: Boolean; method ValidateAudio; method AppendAudioTag(builder: StringBuilder); public method GetContent: String; override; method CreateNotification: ToastNotification; property Audio: IToastAudio read m_Audio; property Launch: String read m_Launch write m_Launch; property Duration: ToastDuration read m_Duration write set_Duration; method set_Duration(value: ToastDuration); private var m_Launch: String; var m_Audio: IToastAudio := new ToastAudio(); var m_Duration: ToastDuration := ToastDuration.Short; end; ToastImageAndText01 = assembly class(ToastNotificationBase, IToastImageAndText01) private fImage: INotificationContentImage; fTextBodyWrap: INotificationContentText; method GetImage: INotificationContentImage; method GetTextBodyWrap: INotificationContentText; public property Image: INotificationContentImage read GetImage write fImage; property TextBodyWrap: INotificationContentText read GetTextBodyWrap write fTextBodyWrap; end; implementation method ToastImageAndText01.GetImage: INotificationContentImage; begin exit fImage; end; method ToastImageAndText01.GetTextBodyWrap: INotificationContentText; begin exit fTextBodyWrap; end; constructor ToastAudio; begin end; method ToastAudio.set_Content(value: ToastAudioContent); begin if not &Enum.IsDefined(typeOf(ToastAudioContent), value) then begin raise new ArgumentOutOfRangeException('value') end; m_Content := value end; constructor ToastNotificationBase(templateName: String; imageCount: Integer; textCount: Integer); begin inherited constructor(templateName, imageCount, textCount); end; method ToastNotificationBase.AudioSrcIsLooping: Boolean; begin exit ((((Audio.Content = ToastAudioContent.LoopingAlarm)) or ((Audio.Content = ToastAudioContent.LoopingAlarm2))) or ((Audio.Content = ToastAudioContent.LoopingCall))) or ((Audio.Content = ToastAudioContent.LoopingCall2)) end; method ToastNotificationBase.ValidateAudio; begin if StrictValidation then begin if (Audio.Loop) and (Duration <> ToastDuration.Long) then begin raise new NotificationContentValidationException('Looping audio is only available for long duration toasts.') end; if (Audio.Loop) and (not AudioSrcIsLooping()) then begin raise new NotificationContentValidationException('A looping audio src must be chosen if the looping audio property is set.') end; if (not Audio.Loop) and (AudioSrcIsLooping()) then begin raise new NotificationContentValidationException('The looping audio property needs to be set if a looping audio src is chosen.') end end end; method ToastNotificationBase.AppendAudioTag(builder: StringBuilder); begin if Audio.Content <> ToastAudioContent.Default then begin builder.Append('<audio'); if Audio.Content = ToastAudioContent.Silent then begin builder.Append(' silent=''true''/>') end else begin if Audio.Loop = true then begin builder.Append(' loop=''true''') end; // The default looping sound is LoopingCall - save size by not adding it if Audio.Content <> ToastAudioContent.LoopingCall then begin var audioSrc: String := nil; case Audio.Content of ToastAudioContent.IM: begin audioSrc := 'ms-winsoundevent:Notification.IM'; end; ToastAudioContent.Mail: begin audioSrc := 'ms-winsoundevent:Notification.Mail'; end; ToastAudioContent.Reminder: begin audioSrc := 'ms-winsoundevent:Notification.Reminder'; end; ToastAudioContent.SMS: begin audioSrc := 'ms-winsoundevent:Notification.SMS'; end; ToastAudioContent.LoopingAlarm: begin audioSrc := 'ms-winsoundevent:Notification.Looping.Alarm'; end; ToastAudioContent.LoopingAlarm2: begin audioSrc := 'ms-winsoundevent:Notification.Looping.Alarm2'; end; ToastAudioContent.LoopingCall: begin audioSrc := 'ms-winsoundevent:Notification.Looping.Call'; end; ToastAudioContent.LoopingCall2: begin audioSrc := 'ms-winsoundevent:Notification.Looping.Call2'; end; end; builder.AppendFormat(' src=''{0}''', audioSrc) end end; builder.Append('/>') end end; method ToastNotificationBase.GetContent: String; begin ValidateAudio(); var builder: StringBuilder := new StringBuilder('<toast'); if not String.IsNullOrEmpty(Launch) then begin builder.AppendFormat(' launch=''{0}''', Util.HttpEncode(Launch)) end; if Duration <> ToastDuration.Short then begin builder.AppendFormat(' duration=''{0}''', Duration.ToString().ToLowerInvariant()) end; builder.Append('>'); builder.AppendFormat('<visual version=''{0}''', Util.NOTIFICATION_CONTENT_VERSION); if not String.IsNullOrWhiteSpace(Lang) then begin builder.AppendFormat(' lang=''{0}''', Util.HttpEncode(Lang)) end; if not String.IsNullOrWhiteSpace(BaseUri) then begin builder.AppendFormat(' baseUri=''{0}''', Util.HttpEncode(BaseUri)) end; builder.Append('>'); builder.AppendFormat('<binding template=''{0}''>{1}</binding>', TemplateName, SerializeProperties(Lang, BaseUri)); builder.Append('</visual>'); AppendAudioTag(builder); builder.Append('</toast>'); exit builder.ToString() end; method ToastNotificationBase.CreateNotification: ToastNotification; begin var xmlDoc: XmlDocument := new XmlDocument(); xmlDoc.LoadXml(GetContent()); exit new ToastNotification(xmlDoc) end; method ToastNotificationBase.set_Duration(value: ToastDuration); begin if not &Enum.IsDefined(typeOf(ToastDuration), value) then begin raise new ArgumentOutOfRangeException('value') end; m_Duration := value end; end.
unit ibSHDMLExporterEditors; interface uses Classes, SysUtils, DesignIntf, SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors; type // -> Property Editors TibSHDMLExporterModePropEditor = class(TibBTPropertyEditor) private FValues: string; procedure Prepare; public constructor Create(APropertyEditor: TObject); override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end deprecated; TibSHDMLExporterOutputPropEditor = class(TibBTPropertyEditor) private FValues: string; procedure Prepare; public constructor Create(APropertyEditor: TObject); override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; TibSHDMLExporterStatementTypePropEditor = class(TibBTPropertyEditor) private FValues: string; procedure Prepare; public constructor Create(APropertyEditor: TObject); override; function GetAttributes: TPropertyAttributes; override; procedure GetValues(AValues: TStrings); override; procedure SetValue(const Value: string); override; end; implementation uses ibSHConsts, ibSHValues; { TibBTDMLExporterModePropEditor } constructor TibSHDMLExporterModePropEditor.Create(APropertyEditor: TObject); begin inherited Create(APropertyEditor); Prepare; end; procedure TibSHDMLExporterModePropEditor.Prepare; begin FValues := FormatProps(DMLExporterModes); end; function TibSHDMLExporterModePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibSHDMLExporterModePropEditor.GetValues(AValues: TStrings); begin AValues.Text := FValues; end; procedure TibSHDMLExporterModePropEditor.SetValue(const Value: string); begin if Designer.CheckPropValue(Value, FValues) then inherited SetStrValue(Value); end; { TibSHDMLExporterOutputPropEditor } constructor TibSHDMLExporterOutputPropEditor.Create( APropertyEditor: TObject); begin inherited Create(APropertyEditor); Prepare; end; function TibSHDMLExporterOutputPropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibSHDMLExporterOutputPropEditor.GetValues(AValues: TStrings); begin AValues.Text := FValues; end; procedure TibSHDMLExporterOutputPropEditor.Prepare; begin FValues := FormatProps(ExtractorOutputs); end; procedure TibSHDMLExporterOutputPropEditor.SetValue(const Value: string); begin if Designer.CheckPropValue(Value, FValues) then inherited SetStrValue(Value); end; { TibBTDMLExporterExportAsPropEditor } constructor TibSHDMLExporterStatementTypePropEditor.Create( APropertyEditor: TObject); begin inherited Create(APropertyEditor); Prepare; end; procedure TibSHDMLExporterStatementTypePropEditor.Prepare; begin FValues := FormatProps(ExtractorStatementType); end; function TibSHDMLExporterStatementTypePropEditor.GetAttributes: TPropertyAttributes; begin Result := [paValueList]; end; procedure TibSHDMLExporterStatementTypePropEditor.GetValues(AValues: TStrings); begin AValues.Text := FValues; end; procedure TibSHDMLExporterStatementTypePropEditor.SetValue(const Value: string); begin if Designer.CheckPropValue(Value, FValues) then inherited SetStrValue(Value); end; end.
unit uFrmPromoPrizeItem; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls, Buttons, Mask, SuperComboADO, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, DBClient, Provider, ADODB; type TfrmPromoPrizeItem = class(TFrmParent) Panel5: TPanel; lblCategory: TLabel; lblGroup: TLabel; lblSubGroup: TLabel; btnCategClear: TButton; scGroup: TSuperComboADO; btnGroupClear: TButton; scSubGroup: TSuperComboADO; btnSubGroupClear: TButton; btSearch: TBitBtn; scModel: TSuperComboADO; Label11: TLabel; Button1: TButton; scVendor: TSuperComboADO; lblVendor: TLabel; btnAllVendor: TButton; pnlButtons: TPanel; btSelectAll: TSpeedButton; btUnSelectAll: TSpeedButton; Panel9: TPanel; grdPromoPrizeItensFilter: TcxGrid; grdPromoPrizeItensFilterDB: TcxGridDBTableView; grdPromoPrizeItensFilterLevel: TcxGridLevel; quModel: TADODataSet; dspModel: TDataSetProvider; cdsPromoPrizeItem: TClientDataSet; dtsPromoPrizeItem: TDataSource; quModelIDModel: TIntegerField; quModelModel: TStringField; quModelDescription: TStringField; cdsPromoPrizeItemIDModel: TIntegerField; cdsPromoPrizeItemModel: TStringField; cdsPromoPrizeItemDescription: TStringField; grdPromoPrizeItensFilterDBIDModel: TcxGridDBColumn; grdPromoPrizeItensFilterDBModel: TcxGridDBColumn; grdPromoPrizeItensFilterDBDescription: TcxGridDBColumn; grdPromoPrizeItensFilterDBValidation: TcxGridDBColumn; btSave: TButton; quModelValidation: TBooleanField; cdsPromoPrizeItemValidation: TBooleanField; scCategory: TSuperComboADO; scManufacturer: TSuperComboADO; btFabricanteAll: TButton; lblManufacturer: TLabel; cdsResult: TClientDataSet; cdsResultIDModel: TIntegerField; cdsResultModel: TStringField; cdsResultDescription: TStringField; procedure btnAllVendorClick(Sender: TObject); procedure btnCategClearClick(Sender: TObject); procedure btnGroupClearClick(Sender: TObject); procedure btnSubGroupClearClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btSearchClick(Sender: TObject); procedure btSelectAllClick(Sender: TObject); procedure btUnSelectAllClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btFabricanteAllClick(Sender: TObject); private FIDPromoItem: Integer; procedure RefreshRequest; procedure CheckAll(AValue: Boolean); procedure VerifyEnabledCheck; function AddPromoPrizeItem: Boolean; function NotExistsPrizeItem(AIDModel :Integer): Boolean; public function Start(AIDPromoItem: integer): Boolean; end; implementation uses uDM; {$R *.dfm} procedure TfrmPromoPrizeItem.btnAllVendorClick(Sender: TObject); begin scVendor.LookUpValue := ''; scVendor.Text := '<-->'; end; procedure TfrmPromoPrizeItem.btnCategClearClick(Sender: TObject); begin scCategory.LookUpValue := ''; scCategory.Text := '<-->'; end; procedure TfrmPromoPrizeItem.btnGroupClearClick(Sender: TObject); begin scGroup.LookUpValue := ''; scGroup.Text := '<-->'; end; procedure TfrmPromoPrizeItem.btnSubGroupClearClick(Sender: TObject); begin scSubGroup.LookUpValue := ''; scSubGroup.Text := '<-->'; end; procedure TfrmPromoPrizeItem.Button1Click(Sender: TObject); begin scModel.LookUpValue := ''; scModel.Text := '<-->'; end; procedure TfrmPromoPrizeItem.btSearchClick(Sender: TObject); begin RefreshRequest; end; procedure TfrmPromoPrizeItem.RefreshRequest; begin with cdsPromoPrizeItem do try Close; Screen.Cursor := crHourGlass; FetchParams; //Params.ParambyName('IDPromoItem').Value := FIDPromoItem; if scModel.LookUpValue <> '' then Params.ParambyName('IDModel').Value := StrToInt(scModel.LookUpValue) else Params.ParambyName('IDModel').Value := Null; if scCategory.LookUpValue <> '' then Params.ParambyName('GroupID').Value := StrToInt(scCategory.LookUpValue) else Params.ParambyName('GroupID').Value := Null; if scGroup.LookUpValue <> '' then Params.ParambyName('IDModelGroup').Value := StrToInt(scGroup.LookUpValue) else Params.ParambyName('IDModelGroup').Value := Null; if scSubGroup.LookUpValue <> '' then Params.ParambyName('IDModelSubGroup').Value := StrToInt(scSubGroup.LookUpValue) else Params.ParambyName('IDModelSubGroup').Value := Null; if scVendor.LookUpValue <> '' then Params.ParambyName('IDPessoa').Value := StrToInt(scVendor.LookUpValue) else Params.ParambyName('IDPessoa').Value := Null; if scManufacturer.LookUpValue <> '' then Params.ParambyName('IDFabricante').Value := StrToInt(scManufacturer.LookUpValue) else Params.ParambyName('IDFabricante').Value := Null; Open; VerifyEnabledCheck; // showmessage(format('records %d' , [cdsPromoPrizeItem.recordcount])); finally Screen.Cursor := crDefault; end; end; procedure TfrmPromoPrizeItem.btSelectAllClick(Sender: TObject); begin CheckAll(True); end; procedure TfrmPromoPrizeItem.btUnSelectAllClick(Sender: TObject); begin CheckAll(False); end; procedure TfrmPromoPrizeItem.CheckAll(AValue: Boolean); begin with cdsPromoPrizeItem do try Screen.Cursor := crHourGlass; DisableControls; dtsPromoPrizeItem.DataSet := nil; First; while not Eof DO begin Edit; FieldByName('Validation').Value := AValue; Post; Next; end; finally Screen.Cursor := crDefault; EnableControls; dtsPromoPrizeItem.DataSet := cdsPromoPrizeItem; end; end; function TfrmPromoPrizeItem.Start(AIDPromoItem: Integer): Boolean; begin FIDPromoItem := AIDPromoItem; VerifyEnabledCheck; ShowModal; if (ModalResult = mrOk) then Result := AddPromoPrizeItem else Result := False; end; function TfrmPromoPrizeItem.AddPromoPrizeItem: Boolean; var IDPromoPrizeItem : Integer; begin cdsResult.Close; cdsResult.CreateDataSet; with cdsPromoPrizeItem do begin try First; while not Eof do begin if FieldByName('Validation').AsBoolean then begin cdsResult.Append; cdsResultIDModel.Value := cdsPromoPrizeItemIDModel.Value; cdsResultModel.Value := cdsPromoPrizeItemModel.Value; cdsResultDescription.Value := cdsPromoPrizeItemDescription.Value; cdsResult.Post; end; { if FieldByName('Validation').AsBoolean then if NotExistsPrizeItem(cdsPromoPrizeItem.FieldByName('IDModel').AsInteger) then begin IDPromoPrizeItem := DM.GetNextID('Sal_PromoPrizeItem.IDPromoprizeItem'); DM.RunSQL('INSERT INTO Sal_PromoPrizeitem (IDPromoPrizeItem,IDPromoItem, IDModel) VALUES ( ' + InttoStr(IDPromoprizeItem) + ' , ' + InttoStr(FIDPromoItem) + ' , ' + cdsPromoPrizeItem.FieldByName('IDModel').AsString + ')'); end; } Next; end; Result := True; except Result := False; end; end; end; procedure TfrmPromoPrizeItem.btCloseClick(Sender: TObject); begin inherited; Close; end; function TfrmPromoPrizeItem.NotExistsPrizeItem(AIDModel: Integer): Boolean; begin with DM.quFreeSQL do begin if Active then Close; SQL.Text := 'SELECT IDModel FROM Sal_PromoPrizeItem (NOLOCK) WHERE IDPromoItem = ' + InttoStr(FIDPromoItem) + ' AND IDModel = ' + InttoStr(AIDModel); Open; Result := DM.quFreeSQL.IsEmpty; end; end; procedure TfrmPromoPrizeItem.VerifyEnabledCheck; begin if (cdsPromoPrizeItem.Active = False) or (cdsPromoPrizeItem.RecordCount = 0) then begin pnlButtons.Enabled := False; btSelectAll.Enabled := False; btUnSelectAll.Enabled := False; end else begin pnlButtons.Enabled := True; btSelectAll.Enabled := True; btUnSelectAll.Enabled := True; end; end; procedure TfrmPromoPrizeItem.btFabricanteAllClick(Sender: TObject); begin inherited; scManufacturer.LookUpValue := ''; scManufacturer.Text := '<-->'; end; end.
(* Persons03 DA, 17.05.2017 *) (* First OO Program *) (* dynamische (Methoden-)Bindung *) (* ------------------------------------------------------------- *) PROGRAM Persons03; CONST maxStudents = 10; TYPE Person = OBJECT name: STRING; CONSTRUCTOR Init(name: STRING); DESTRUCTOR Done; VIRTUAL; PROCEDURE Greet; VIRTUAL; END; Student = OBJECT(Person) studentNr: INTEGER; CONSTRUCTOR Init(name: STRING; studentNr: INTEGER); DESTRUCTOR Done; VIRTUAL; PROCEDURE Greet; VIRTUAL; END; StudentPtr = ^Student; Teacher = OBJECT(Person) studentCnt: INTEGER; students: ARRAY[1..maxStudents] OF StudentPtr; CONSTRUCTOR Init(name: STRING); DESTRUCTOR Done; VIRTUAL; PROCEDURE Greet; VIRTUAL; PROCEDURE AddStudent(s: StudentPtr); END; (*Teacher*) (* Person *) CONSTRUCTOR Person.Init(name: STRING); BEGIN SELF.name := name; END; (*Person.Init*) DESTRUCTOR Person.Done; BEGIN (*do nothing*) END; (*Person.Done*) PROCEDURE Person.Greet; BEGIN WriteLn('Hello, my name is ', SELF.name); END; (*Person.Greet*) (* Student *) CONSTRUCTOR Student.Init(name: STRING; studentNr: INTEGER); BEGIN Person.Init(name); SELF.studentNr := studentNr; END; (*Student.Init*) DESTRUCTOR Student.Done; BEGIN (*do nothing*) INHERITED; END; (*Student.Done*) PROCEDURE Student.Greet; BEGIN WriteLn('Hi, I am ', SELF.name, ' with student number ', studentNr); END; (*Greet*) (* Teacher *) CONSTRUCTOR Teacher.Init(name: STRING); BEGIN Person.Init(name); SELF.studentCnt := 0; END; (*Teacher.Init*) DESTRUCTOR Teacher.Done; BEGIN (*do nothing*) INHERITED; END; (*Teacher.Done*) PROCEDURE Teacher.Greet; VAR i: INTEGER; BEGIN IF studentCnt = 0 THEN BEGIN Person.Greet; END ELSE BEGIN WriteLn('Good morning, I am teacher ', name, ' and let me introduce my ', studentCnt, ' students'); i := 1; WHILE i <= studentCnt DO BEGIN students[i]^.Greet; i := i + 1; END; END; END; (*Teacher.Greet*) PROCEDURE Teacher.AddStudent(s: StudentPtr); BEGIN IF studentCnt < maxStudents THEN BEGIN studentCnt := studentCnt + 1; students[studentCnt] := s; END ELSE WriteLn('no more students allowed to register'); END; (*Teacher.Greet*) VAR pPtr: ^Person; sPtr, sPtr2, sPtr3: ^Student; tPtr: ^Teacher; i: INTEGER; allPersons: ARRAY[1..10] OF ^Person; personCnt: INTEGER; BEGIN New(pPtr); pPtr^.Init('Person'); New(sPtr, Init('Andi', 1)); sPtr^.Greet; New(sPtr2, Init('Betti', 2)); sPtr2^.Greet; New(sPtr3, Init('Charly', 3)); sPtr3^.Greet; New(tPtr, Init('Teacher')); tPtr^.Greet; tPtr^.AddStudent(sPtr); tPtr^.AddStudent(sPtr2); tPtr^.AddStudent(sPtr3); WriteLn; tPtr^.Greet; personCnt := 1; allPersons[personCnt] := pPtr; Inc(personCnt); allPersons[personCnt] := sPtr; Inc(personCnt); allPersons[personCnt] := sPtr2; Inc(personCnt); allPersons[personCnt] := sPtr3; Inc(personCnt); allPersons[personCnt] := tPtr; WriteLn; WriteLn('all persons greet'); FOR i := 1 TO personCnt DO allPersons[i]^.Greet; WriteLn('end greeting'); Dispose(tPtr, Done); Dispose(sPtr3, Done); Dispose(sPtr2, Done); Dispose(sPtr, Done); END. (*Persons03*)
{программа, зашивающая файл фиктивными записями(=пустой)} program qwerty; type {Info - запись, хранящая данные} Info=record name_:string[40]; telefon:string[40]; bool:boolean; end; {Information - запись с данными и ключевое поле} Information=record Hash: byte; {ключевое поле - номер кв.} Data:Info; {поле с данными} end; FileType=file of Info; Var adres: string; {Zero - процедура, заполняющая файл фиктивными записями. Входящие данные: adres} procedure Zero(adres: string); Var MyData:Information; {переменная для временного хранения} f:FileType; i:byte; const N=5; {кол-во компонент} begin assign (F, adres); {связь файловой переменной и файла} Rewrite(F);{открыть файл для записи} MyData.Data.bool:=True;{присвоить полю bool значение True} For i:=1 to N do Write(F, MyData.Data);{запись записи Info на диск} {end for i} while not eof(f) do begin read(f,MyData.Data);{чтение записи из файла} if MyData.Data.bool = True then continue else begin {заполнение ключевого поля Hash} MyData.Hash:=filepos(f); {вывод записей на экран} writeln(MyData.Data.name_, ' - ', MyData.Data.telefon); end; {endif} end; {end while} end; begin adres:='1.txt';{ввести адрес adres файла} Zero(adres); {вызов процедуры Zero} end.
unit Types.Mail; interface const c_UstTLSMax = 3; c_UseTLS:array [0 .. c_UstTLSMax] of record ID: byte; Text: string; end = ((ID: 0; Text: 'NoTLSSupport'), (ID: 1; Text: 'UseImplicitTLS'), (ID: 2; Text: 'UseRequireTLS'), (ID: 3; Text: 'UseExplicitTLS')); c_AuthTypeMax = 2; c_AuthType:array [0 .. c_AuthTypeMax] of record ID: byte; Text: string; end = ((ID: 0; Text: 'Kein'), (ID: 1; Text: 'Default'), (ID: 2; Text: 'SASL')); c_SSLVersionMax = 5; c_SSLVersion:array [0 .. c_SSLVersionMax] of record ID: byte; Text: string; end = ((ID: 0; Text: 'sslvSSLv2'), (ID: 1; Text: 'sslvSSLv23'), (ID: 2; Text: 'sslvSSLv3'), (ID: 3; Text: 'sslvTLSv1'), (ID: 4; Text: 'sslvTLSv1_1'), (ID: 5; Text: 'sslvTLSv1_2')); implementation end.
unit glSystem; interface uses Windows, Messages, SysUtils, Variants, Classes; function RunAs(Username, Password, CmdString: string): string; function CountPos(const subtext: string; Text: string): Integer; function createprocesswithlogonw(lpusername: pwidechar; lpdomain: pwidechar; lppassword: pwidechar; dwlogonflags: dword; lpapplicationname: pwidechar; lpcommandline: pwidechar; dwcreationflags: dword; lpenvironment: pointer; lpcurrentdirectory: pchar; const lpstartupinfo: tstartupinfo; var lpprocessinformation: tprocessinformation): bool; stdcall; function ExePath: string; function GetUserFromWindows: string; implementation function createprocesswithlogonw; external advapi32 name 'CreateProcessWithLogonW'; function ExePath: string; begin result := Copy(paramstr(0), 1, LastDelimiter('\:', paramstr(0))); end; function GetUserFromWindows: string; var Username: string; UserNameLen: dword; begin UserNameLen := 255; SetLength(Username, UserNameLen); if GetUserName(pchar(Username), UserNameLen) then result := Copy(Username, 1, UserNameLen - 1) else result := 'Unknown'; end; function CountPos(const subtext: string; Text: string): Integer; begin if (Length(subtext) = 0) or (Length(Text) = 0) or (Pos(subtext, Text) = 0) then result := 0 else result := (Length(Text) - Length(StringReplace(Text, subtext, '', [rfReplaceAll]))) div Length(subtext); end; function RunAs(Username, Password, CmdString: string): string; var si: tstartupinfo; pi: tprocessinformation; puser, ppass, pdomain, pprogram: array [0 .. 255] of wchar; lasterror: dword; resultstring: string; begin zeromemory(@si, sizeof(si)); si.cb := sizeof(si); zeromemory(@pi, sizeof(pi)); stringtowidechar(Username, puser, 255); stringtowidechar(Password, ppass, 255); stringtowidechar('', pdomain, 255); stringtowidechar(CmdString, pprogram, 255); createprocesswithlogonw(puser, pdomain, ppass, 1, // logon_with_profile, pprogram, nil, create_default_error_mode or create_new_console or create_new_process_group or create_separate_wow_vdm, nil, nil, si, pi); lasterror := getlasterror; case lasterror of 0: resultstring := 'success!'; 86: resultstring := 'wrong password'; 1326: resultstring := 'wrong username or password'; 1327: resultstring := 'logon failure user account restriction'; 1385: resultstring := 'logon failure the user has not been granted the requested logon type at this computer.'; 2: resultstring := 'file not found'; 5: resultstring := 'acced denied'; else resultstring := 'error ' + inttostr(lasterror); end; result := resultstring; end; end.
unit SaveForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, SimpleTimer, InflatablesList_Manager; type TfSaveForm = class(TForm) bvlInnerFrame: TBevel; lblText: TLabel; bvlOuterFrame: TBevel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } fILManager: TILManager; fRunTimer: TSimpleTimer; protected procedure SavingDoneHandler(Sender: TObject); procedure OnRunTimerHandler(Sender: TObject); public { Public declarations } procedure Initialize(ILManager: TILManager); procedure Finalize; procedure ShowAndPerformSave; end; var fSaveForm: TfSaveForm; implementation {$R *.dfm} procedure TfSaveForm.SavingDoneHandler(Sender: TObject); begin Close; end; //------------------------------------------------------------------------------ procedure TfSaveForm.OnRunTimerHandler(Sender: TObject); begin fRunTimer.Enabled := False; fILManager.SaveToFileThreaded(SavingDoneHandler); end; //============================================================================== procedure TfSaveForm.Initialize(ILManager: TILManager); begin fILManager := ILManager; end; //------------------------------------------------------------------------------ procedure TfSaveForm.Finalize; begin // nothing to do end; //------------------------------------------------------------------------------ procedure TfSaveForm.ShowAndPerformSave; begin fRunTimer.Enabled := True; ShowModal; end; //============================================================================== procedure TfSaveForm.FormCreate(Sender: TObject); begin fRunTimer := TSimpleTimer.Create; fRunTimer.Enabled := False; fRunTimer.Interval := 500; // 0.5s delay fRunTimer.OnTimer := OnRunTimerHandler; end; //------------------------------------------------------------------------------ procedure TfSaveForm.FormDestroy(Sender: TObject); begin FreeAndNil(fRunTimer); end; end.
namespace GlHelper; interface uses rtl; type { A quaternion. } TQuaternion = public record private method GetLength: Single; method GetLengthSquared: Single; public { Initializes the quaternion to an identity quaternion. Sets the X, Y and Z components to 0 and the W component to 1. } method Init; { Sets the four components of the quaternion. Parameters: AX: the X-component. AY: the Y-component. AZ: the Z-component. AW: the W-component. } method Init(const AX, AY, AZ, AW: Single); { Sets the quaternion from the given axis vector and the angle around that axis in radians. Parameters: AAxis: The axis. AAngleRadians: The angle in radians. } method Init(const AAxis: TVector3; const AAngleRadians: Single); { Sets the quaternion to the given euler angles in radians. Parameters: AYaw: the rotation around the Y axis in radians. APitch: the rotation around the X axis in radians. ARoll: the rotation around the Z axis in radians. } method Init(const AYaw, APitch, ARoll: Single); { Sets the quaternion from a matrix. Parameters: AMatrix: the matrix. } method Init(const AMatrix: TMatrix4); { Creates a rotation matrix that represents this quaternion. Returns: A rotation matrix that represents this quaternion. } method ToMatrix: TMatrix4; { Adds to quaternions together. Returns: A + B } class operator Add(const A, B: TQuaternion): TQuaternion; inline; { Multiplies a vector with a scalar value. Returns: (A.X * B, A.Y * B, A.Z * B, A.W * B) } class operator Multiply(const A: TQuaternion; const B: Single): TQuaternion; inline; { Multiplies a vector with a scalar value. Returns: (A * B.X, A * B.Y, A * B.Z, A * B.W) } class operator Multiply(const A: Single; const B: TQuaternion): TQuaternion; inline; { Multiplies two quaternions. Returns: A * B } class operator Multiply(const A, B: TQuaternion): TQuaternion; inline; { Whether this is an identity quaternion. Returns: True if X, Y and Z are exactly 0.0 and W is exactly 1.0 } method IsIdentity: Boolean; { Whether this is an identity quaternion within a given margin of error. Parameters: AErrorMargin: the allowed margin of error. Returns: True if this is an identity quaternion within the error margin. } method IsIdentity(const AErrorMargin: Single): Boolean; { Calculates a normalized version of this quaternion. Returns: The normalized quaternion of of this vector (with a length of 1). @bold(Note): for a faster, less accurate version, use NormalizeFast. @bold(Note): Does not change this quaternion. To update this quaternion itself, use SetNormalized. } method Normalize: TQuaternion; { Normalizes this quaternion to a length of 1. @bold(Note): The SIMD optimized versions of this method use an approximation, resulting in a very small error. @bold(Note): If you do not want to change this quaternion, but get a normalized version instead, then use Normalize. } method SetNormalized; { Calculates a normalized version of this quaternion. Returns: The normalized version of of this quaternion (with a length of 1). @bold(Note): this is an SIMD optimized version that uses an approximation, resulting in a small error. For an accurate version, use Normalize. @bold(Note): Does not change this quaternion. To update this quaternion itself, use SetNormalizedFast. } method NormalizeFast: TQuaternion; { Normalizes this quaternion to a length of 1. @bold(Note): this is an SIMD optimized version that uses an approximation, resulting in a small error. For an accurate version, use SetNormalized. @bold(Note): If you do not want to change this quaternion, but get a normalized version instead, then use NormalizeFast. } method SetNormalizedFast; { Creates a conjugate of the quaternion. Returns: The conjugate (eg. (-X, -Y, -Z, W)) @bold(Note): Does not change this quaterion. To update this quaterion itself, use SetConjugate. } method Conjugate: TQuaternion; { Conjugate this quaternion. @bold(Note): If you do not want to change this quaternion, but get a conjugate version instead, then use Conjugate. } method SetConjugate; { The euclidean length of this quaternion. @bold(Note): If you only want to compare lengths of quaternion, you should use LengthSquared instead, which is faster. } property Length: Single read GetLength; { The squared length of the quaternion. @bold(Note): This property is faster than Length because it avoids calculating a square root. It is useful for comparing lengths instead of calculating actual lengths. } property LengthSquared: Single read GetLengthSquared; public { X, Y, Z and W components of the quaternion } X, Y, Z, W: Single; { The four components of the quaternion. } // C: array [0..3] of Single; end; implementation { TQuaternion } class operator TQuaternion.Add(const A, B: TQuaternion): TQuaternion; begin Result.X := A.X + B.X; Result.Y := A.Y + B.Y; Result.Z := A.Z + B.Z; Result.W := A.W + B.W; end; method TQuaternion.GetLength: Single; begin Result := Sqrt((X * X) + (Y * Y) + (Z * Z) + (W * W)); end; method TQuaternion.GetLengthSquared: Single; begin Result := (X * X) + (Y * Y) + (Z * Z) + (W * W); end; class operator TQuaternion.Multiply(const A: TQuaternion; const B: Single): TQuaternion; begin Result.X := A.X * B; Result.Y := A.Y * B; Result.Z := A.Z * B; Result.W := A.W * B; end; class operator TQuaternion.Multiply(const A: Single; const B: TQuaternion): TQuaternion; begin Result.X := A * B.X; Result.Y := A * B.Y; Result.Z := A * B.Z; Result.W := A * B.W; end; class operator TQuaternion.Multiply(const A, B: TQuaternion): TQuaternion; begin Result.X := (A.W * B.X) + (A.X * B.W) + (A.Y * B.Z) - (A.Z * B.Y); Result.Y := (A.W * B.Y) + (A.Y * B.W) + (A.Z * B.X) - (A.X * B.Z); Result.Z := (A.W * B.Z) + (A.Z * B.W) + (A.X * B.Y) - (A.Y * B.X); Result.W := (A.W * B.W) - (A.X * B.X) - (A.Y * B.Y) - (A.Z * B.Z); end; method TQuaternion.NormalizeFast: TQuaternion; begin Result := Self * InverseSqrt(Self.LengthSquared); end; method TQuaternion.SetNormalizedFast; begin Self := Self * InverseSqrt(Self.LengthSquared); end; { TQuaternion } method TQuaternion.Conjugate: TQuaternion; begin Result.X := -X; Result.Y := -Y; Result.Z := -Z; Result.W := W; end; method TQuaternion.Init; begin X := 0; Y := 0; Z := 0; W := 1; end; method TQuaternion.Init(const AX, AY, AZ, AW: Single); begin X := AX; Y := AY; Z := AZ; W := AW; end; method TQuaternion.Init(const AAxis: TVector3; const AAngleRadians: Single); var D, S, CS: Single; begin D := AAxis.Length; if (D = 0) then begin Init; Exit; end; D := 1 / D; SinCos(AAngleRadians * 0.5, out S, out CS); X := D * AAxis.X * S; Y := D * AAxis.Y * S; Z := D * AAxis.Z * S; W := CS; SetNormalized; end; method TQuaternion.Init(const AYaw, APitch, ARoll: Single); var A, S, C: TVector4; CYSP, SYCP, CYCP, SYSP: Single; begin A.Init(APitch * 0.5, AYaw * 0.5, ARoll * 0.5, 0); SinCos(A, out S, out C); CYSP := C.Y * S.X; SYCP := S.Y * C.X; CYCP := C.Y * C.X; SYSP := S.Y * S.X; X := (CYSP * C.Z) + (SYCP * S.Z); Y := (SYCP * C.Z) - (CYSP * S.Z); Z := (CYCP * S.Z) - (SYSP * C.Z); W := (CYCP * C.Z) + (SYSP * S.Z); end; method TQuaternion.Init(const AMatrix: TMatrix4); var Trace, S: Double; begin Trace := AMatrix.m11 + AMatrix.m22 + AMatrix.m33; if (Trace > EPSILON) then begin S := 0.5 / Sqrt(Trace + 1.0); X := (AMatrix.m23 - AMatrix.m32) * S; Y := (AMatrix.m31 - AMatrix.m13) * S; Z := (AMatrix.m12 - AMatrix.m21) * S; W := 0.25 / S; end else if (AMatrix.m11 > AMatrix.m22) and (AMatrix.m11 > AMatrix.m33) then begin S := Sqrt(Math.Max(EPSILON, 1 + AMatrix.m11 - AMatrix.m22 - AMatrix.m33)) * 2.0; X := 0.25 * S; Y := (AMatrix.m12 + AMatrix.m21) / S; Z := (AMatrix.m31 + AMatrix.m13) / S; W := (AMatrix.m23 - AMatrix.m32) / S; end else if (AMatrix.m22 > AMatrix.m33) then begin S := Sqrt(Math.Max(EPSILON, 1 + AMatrix.m22 - AMatrix.m11 - AMatrix.m33)) * 2.0; X := (AMatrix.m12 + AMatrix.m21) / S; Y := 0.25 * S; Z := (AMatrix.m23 + AMatrix.m32) / S; W := (AMatrix.m31 - AMatrix.m13) / S; end else begin S := Sqrt(Math.Max(EPSILON, 1 + AMatrix.m33 - AMatrix.m11 - AMatrix.m22)) * 2.0; X := (AMatrix.m31 + AMatrix.m13) / S; Y := (AMatrix.m23 + AMatrix.m32) / S; Z := 0.25 * S; W := (AMatrix.m12 - AMatrix.m21) / S; end; SetNormalized; end; method TQuaternion.IsIdentity: Boolean; begin Result := (X = 0) and (Y = 0) and (Z = 0) and (W = 1); end; method TQuaternion.IsIdentity(const AErrorMargin: Single): Boolean; begin Result := (Abs(X) <= AErrorMargin) and (Abs(Y) <= AErrorMargin) and (Abs(Z) <= AErrorMargin) and ((Abs(W) - 1) <= AErrorMargin) end; method TQuaternion.Normalize: TQuaternion; begin Result := Self * (1 / Length); end; method TQuaternion.SetConjugate; begin X := -X; Y := -Y; Z := -Z; end; method TQuaternion.SetNormalized; begin Self := Self * (1 / Length); end; method TQuaternion.ToMatrix: TMatrix4; var Q: TQuaternion; XX, XY, XZ, XW, YY, YZ, YW, ZZ, ZW: Single; begin Q := Normalize; XX := Q.X * Q.X; XY := Q.X * Q.Y; XZ := Q.X * Q.Z; XW := Q.X * Q.W; YY := Q.Y * Q.Y; YZ := Q.Y * Q.Z; YW := Q.Y * Q.W; ZZ := Q.Z * Q.Z; ZW := Q.Z * Q.W; Result.Init( 1 - 2 * (YY + ZZ), 2 * (XY + ZW), 2 * (XZ - YW), 0, 2 * (XY - ZW), 1 - 2 * (XX + ZZ), 2 * (YZ + XW), 0, 2 * (XZ + YW), 2 * (YZ - XW), 1 - 2 * (XX + YY), 0, 0, 0, 0, 1); end; end.
unit uFrmMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, XMLDoc, XMLIntf, uXMLUtils; type TFrmMain = class(TForm) Memo: TMemo; Panel1: TPanel; btnXML: TButton; procedure btnXMLClick(Sender: TObject); private FXML: IXMLDocument; XMLUtils: TXMLUtils; procedure CreateXML; procedure AddBook(id, author, title, genre, price, publish_date, description: string); public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} procedure TFrmMain.btnXMLClick(Sender: TObject); begin CreateXML; end; procedure TFrmMain.CreateXML; var book: IXMLNode; author: IXMLNode; begin XMLUtils := TXMLUtils.Create('catalog'); try AddBook('bk101', 'Gambardella, Matthew', 'XML Developer''s Guide', 'Computer', '44.95', '2000-10-01', 'An in-depth look at creating applications with XML.'); AddBook('bk102', 'Ralls, Kim', 'Midnight Rain', 'Fantasy', '5.95', '2000-12-16', 'A former architect battles corporate zombies, '+ 'an evil sorceress, and her own childhood to become queen '+ 'of the world..'); Memo.Lines.Text := XMLUtils.XMLText(True); finally XMLUtils.Free; end; end; procedure TFrmMain.AddBook(id, author, title, genre, price, publish_date, description: string); var book: IXMLNode; begin book := XMLUtils.AddElement('book'); book := XMLUtils.AddAttribute(book, 'id', id); XMLUtils.AddElement(book, 'author', author); XMLUtils.AddElement(book, 'title', title); XMLUtils.AddElement(book, 'genre', genre); XMLUtils.AddElement(book, 'price', price); XMLUtils.AddElement(book, 'publish_date', publish_date); XMLUtils.AddElement(book, 'description', description); end; end.
{------------------------------------------------------------------------------ Miguel A. Risco Castillo TuERotImage v0.6 http://ue.accesus.com/uecontrols using some ideas from: TRotateImage v1.54 by Kambiz R. Khojasteh 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. ------------------------------------------------------------------------------} unit uERotImage; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, Types, BGRABitmap, BGRABitmapTypes; type { TuECustomRotImage } { TCustomuERotImage } TCustomuERotImage = class(TGraphicControl) private FColor: TColor; FPicture: TPicture; FOnPictureChanged: TNotifyEvent; FStretch: Boolean; FCenter: Boolean; FTransparent: Boolean; FProportional: Boolean; FAngle: Extended; FUniqueSize: Boolean; FMaxSize: Integer; FChanging: Boolean; FOnRotation: TNotifyEvent; FBeforeRotation: TNotifyEvent; function GetCanvas: TCanvas; procedure RotateImage(AValue: Extended); procedure ForceRotate(AValue: Extended); procedure SetCenter(const AValue: Boolean); procedure SetPicture(const AValue: TPicture); procedure SetStretch(const AValue: Boolean); procedure SetProportional(const AValue: Boolean); procedure SetTransparent(const AValue: Boolean); procedure SetAngle(const Value: Extended); procedure SetUniqueSize(Value: Boolean); protected class procedure WSRegisterClass; override; procedure PictureChanged(Sender : TObject); virtual; procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean); override; class function GetControlClassDefaultSize: TSize; override; function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override; procedure Paint; override; procedure Loaded; override; procedure Resize; override; procedure SetColor(AValue: TColor); override; procedure DoRotation; virtual; procedure DoBeforeRotation; virtual; function DestRect: TRect; virtual; property Canvas: TCanvas read GetCanvas; property MaxSize: Integer read FMaxSize; property Angle: Extended read FAngle write SetAngle; property BorderSpacing; property Center: Boolean read FCenter write SetCenter default False; property Color: tcolor read FColor write SetColor default clDefault; property Picture: TPicture read FPicture write SetPicture; property Proportional: Boolean read FProportional write setProportional default False; property Stretch: Boolean read FStretch write SetStretch default False; property Transparent: Boolean read FTransparent write SetTransparent; property UniqueSize: Boolean read FUniqueSize write SetUniqueSize default False; property OnPictureChanged: TNotifyEvent read FOnPictureChanged write FOnPictureChanged; property OnRotation: TNotifyEvent read FOnRotation write FOnRotation; property BeforeRotation: TNotifyEvent read FBeforeRotation write FBeforeRotation; public Bitmap: TBGRABitmap; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ReDraw; end; { TuECustomRotImage } TuERotImage = class(TCustomuERotImage) published property Align; property Anchors; property Angle; property AutoSize; property BorderSpacing; property Center; property Color; property Constraints; property DragCursor; property DragKind; property DragMode; property Enabled; property MaxSize; property ParentColor; property ParentShowHint; property Picture; property PopupMenu; property Proportional; property ShowHint; property Stretch; property Transparent; property UniqueSize; property Visible; property OnChangeBounds; property OnMouseEnter; property OnMouseLeave; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnPaint; property OnPictureChanged; property OnClick; property OnConstrainedResize; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnRotation; property BeforeRotation; property OnStartDock; property OnStartDrag; end; procedure Register; implementation //uses Math; constructor TCustomuERotImage.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable, csCaptureMouse, csClickEvents, csDoubleClicks]; AutoSize := False; FCenter := False; FProportional := False; FStretch := False; FTransparent := True; FUniqueSize := False; FPicture := TPicture.Create; FPicture.OnChange := @PictureChanged; Bitmap:=TBGRABitmap.Create(1,1); with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY); end; destructor TCustomuERotImage.Destroy; begin if Assigned(Bitmap) then begin Bitmap.Free; Bitmap := nil; end; FPicture.OnChange := nil; FPicture.Graphic := nil; FPicture.Free; inherited Destroy; end; procedure TCustomuERotImage.ReDraw; begin ForceRotate(FAngle); Paint; end; procedure TCustomuERotImage.Paint; procedure DrawFrame; begin with inherited Canvas do begin Pen.Color := clBlack; Pen.Style := psDash; MoveTo(0, 0); LineTo(Self.Width-1, 0); LineTo(Self.Width-1, Self.Height-1); LineTo(0, Self.Height-1); LineTo(0, 0); end; end; var R:TRect; begin if csDesigning in ComponentState then DrawFrame; if assigned(Bitmap) then begin R:=DestRect; Bitmap.Draw(inherited Canvas,R,false); end; end; procedure TCustomuERotImage.Loaded; begin inherited Loaded; PictureChanged(Self); end; procedure TCustomuERotImage.Resize; begin inherited Resize; RotateImage(FAngle); end; function TCustomuERotImage.GetCanvas: TCanvas; begin Result := inherited Canvas; end; procedure TCustomuERotImage.SetCenter(const AValue: Boolean); begin if FCenter = AValue then exit; FCenter := AValue; invalidate; end; procedure TCustomuERotImage.SetPicture(const AValue: TPicture); begin if FPicture=AValue then exit; FPicture.Assign(AValue); end; procedure TCustomuERotImage.SetStretch(const AValue: Boolean); begin if FStretch = AValue then exit; FStretch := AValue; invalidate; end; procedure TCustomuERotImage.SetProportional(const AValue: Boolean); begin if FProportional = AValue then exit; FProportional := AValue; invalidate; end; procedure TCustomuERotImage.SetTransparent(const AValue: Boolean); begin if FTransparent = AValue then exit; FTransparent := AValue; ForceRotate(FAngle); end; procedure TCustomuERotImage.SetColor(AValue: TColor); begin if FColor = AValue then exit; FColor := AValue; ForceRotate(FAngle); inherited SetColor(AValue); end; procedure TCustomuERotImage.ForceRotate(AValue: Extended); var xc,yc:real; w,h:integer; rad,s,c:Extended; tbmp:TBGRABitmap; fillc:TBGRAPixel; begin if (csLoading in ComponentState) or FChanging then exit; FChanging := True; rad:=AValue*PI/180; s:=abs(sin(rad)); c:=abs(cos(rad)); If FTransparent then Fillc:=BGRAPixelTransparent else Fillc:=ColortoBGRA(ColortoRGB(color)); if assigned(FPicture.Graphic) then begin xc:=(FPicture.Graphic.width-1)/2; yc:=(FPicture.Graphic.height-1)/2; w:= round(FPicture.Graphic.width*c + FPicture.Graphic.height*s); h:= round(FPicture.Graphic.width*s + FPicture.Graphic.height*c); if UniqueSize then tbmp:=TBGRABitmap.Create(MaxSize,MaxSize,Fillc) else tbmp:=TBGRABitmap.Create(w,h,Fillc); Bitmap.SetSize(1,1); Bitmap.Fill(Fillc); Bitmap.Assign(FPicture.Bitmap); end else begin xc:=(width-1)/2; yc:=(height-1)/2; tbmp:=TBGRABitmap.Create(width,height,Fillc); Bitmap.SetSize(width,height); Bitmap.Fill(Fillc); end; w:=Round((tbmp.Width)/2-1); h:=Round((tbmp.Height)/2-1); DoBeforeRotation; tbmp.PutImageAngle(w,h,Bitmap,AValue,xc,yc); Bitmap.Assign(tbmp); tbmp.free; try if AutoSize and (MaxSize <> 0) then begin InvalidatePreferredSize; AdjustSize; if UniqueSize then SetBounds(Left, Top, MaxSize, MaxSize) else SetBounds(Left, Top, Bitmap.Width, Bitmap.Height); end; finally FChanging := False; end; Invalidate; DoRotation; end; procedure TCustomuERotImage.RotateImage(AValue:Extended); begin if AValue <> FAngle then ForceRotate(FAngle); end; procedure TCustomuERotImage.SetAngle(const Value: Extended); begin if Value <> FAngle then begin FAngle := Value; ForceRotate(FAngle); end; end; procedure TCustomuERotImage.SetUniqueSize(Value: Boolean); begin if Value <> UniqueSize then begin FUniqueSize := Value; ForceRotate(FAngle); end; end; procedure TCustomuERotImage.PictureChanged(Sender: TObject); begin if not (csLoading in ComponentState) then begin if FPicture.Graphic <> nil then begin if (FPicture.Graphic.MimeType='') and (csDesigning in ComponentState) then begin showmessage('Bug: unsupported Picture format at design time'); FPicture.Graphic:=nil; FMaxSize := 0; end else FMaxSize := Round(Sqrt(Sqr(FPicture.Graphic.Width) + Sqr(FPicture.Graphic.Height))); end else FMaxSize := Round(Sqrt(Sqr(Width) + Sqr(Height))); ForceRotate(FAngle); if Assigned(OnPictureChanged) then OnPictureChanged(Self); end; end; procedure TCustomuERotImage.CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean); begin PreferredWidth := Bitmap.Width; PreferredHeight := Bitmap.Height; end; class function TCustomuERotImage.GetControlClassDefaultSize: TSize; begin Result.CX := 90; Result.CY := 90; end; function TCustomuERotImage.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; begin Result := True; if not (csDesigning in ComponentState) or (MaxSize <> 0) then begin if Align in [alNone, alLeft, alRight] then if UniqueSize then NewWidth := MaxSize else NewWidth := Bitmap.Width; if Align in [alNone, alTop, alBottom] then if UniqueSize then NewHeight := MaxSize else NewHeight := Bitmap.Height; end; end; procedure TCustomuERotImage.DoRotation; begin if Assigned(FOnRotation) then FOnRotation(Self); end; procedure TCustomuERotImage.DoBeforeRotation; begin if Assigned(FBeforeRotation) then FBeforeRotation(Self); end; class procedure TCustomuERotImage.WSRegisterClass; begin inherited WSRegisterClass; end; function TCustomuERotImage.DestRect: TRect; var PicWidth: Integer; PicHeight: Integer; ImgWidth: Integer; ImgHeight: Integer; w: Integer; h: Integer; begin if not Assigned(Bitmap) then exit; PicWidth := Bitmap.Width; PicHeight := Bitmap.Height; ImgWidth := ClientWidth; ImgHeight := ClientHeight; if Stretch or (Proportional and ((PicWidth > ImgWidth) or (PicHeight > ImgHeight))) then begin if Proportional and (PicWidth > 0) and (PicHeight > 0) then begin w:=ImgWidth; h:=(PicHeight*w) div PicWidth; if h>ImgHeight then begin h:=ImgHeight; w:=(PicWidth*h) div PicHeight; end; PicWidth:=w; PicHeight:=h; end else begin PicWidth := ImgWidth; PicHeight := ImgHeight; end; end; Result:=Rect(0,0,PicWidth,PicHeight); if Center then OffsetRect(Result,(ImgWidth-PicWidth) div 2,(ImgHeight-PicHeight) div 2); end; procedure Register; begin {$I uerotimage_icon.lrs} RegisterComponents('uEControls',[TuERotImage]); end; end.