text
stringlengths
14
6.51M
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC BDE Aliases Importer } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.BDE.Import; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Option; type TFDAliasImportOverwriteEvent = procedure (const AName: String; var AOverwrite: Integer) of object; TFDBDEAliasImporter = class(TObject) private FSrcParams: TFDStringList; FDestParams: TStrings; FOpts: IFDStanOptions; FFetch: TFDFetchOptions; FFmt: TFDFormatOptions; FUpd: TFDUpdateOptions; FRes: TFDResourceOptions; FConnectionDefFileName: String; FOverwriteDefs: Boolean; FAliasesToImport: TFDStringList; FOnOverwrite: TFDAliasImportOverwriteEvent; function GetSrcBool(const AName: String; var AResult: Boolean): Boolean; function GetSrcInt(const AName: String; var AResult: Integer): Boolean; function GetSrcStr(const AName: String; var AResult: String): Boolean; procedure ImportSQLCommon; procedure ImportOracle(AImportMode: Boolean); procedure ImportIB(AImportMode: Boolean); procedure ImportMSSQL(AImportMode: Boolean); procedure ImportMSAccess(AImportMode: Boolean); procedure ImportODBC(AImportMode: Boolean); procedure ImportDB2(AImportMode: Boolean); procedure ImportMySQL(AImportMode: Boolean); public constructor Create; destructor Destroy; override; procedure Execute; procedure MakeBDECompatible( const AConnectionDef: IFDStanConnectionDef; AEnableBCD, AEnableInteger: Boolean); property ConnectionDefFileName: String read FConnectionDefFileName write FConnectionDefFileName; property AliasesToImport: TFDStringList read FAliasesToImport; property OverwriteDefs: Boolean read FOverwriteDefs write FOverwriteDefs; property OnOverwrite: TFDAliasImportOverwriteEvent read FOnOverwrite write FOnOverwrite; end; implementation uses VCL.Dialogs, System.SysUtils, Bde.DBTables, BDE, FireDAC.Stan.Factory, FireDAC.Stan.ResStrs, FireDAC.Stan.Error, FireDAC.Stan.Util, FireDAC.Phys.Intf, System.TypInfo; const S_OpenODBC = 'OpenODBC'; DRIVERNAME_KEY = 'DriverName'; {-------------------------------------------------------------------------------} constructor TFDBDEAliasImporter.Create; begin inherited Create; FAliasesToImport := TFDStringList.Create(dupAccept, True, False); end; {-------------------------------------------------------------------------------} destructor TFDBDEAliasImporter.Destroy; begin FDFreeAndNil(FAliasesToImport); inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDBDEAliasImporter.GetSrcBool(const AName: String; var AResult: Boolean): Boolean; var i: Integer; begin i := FSrcParams.IndexOfName(AName); Result := i <> -1; AResult := False; if Result then AResult := CompareText(FSrcParams.Values[AName], S_FD_True) = 0; end; {-------------------------------------------------------------------------------} function TFDBDEAliasImporter.GetSrcInt(const AName: String; var AResult: Integer): Boolean; var i: Integer; begin i := FSrcParams.IndexOfName(AName); Result := i <> -1; AResult := 0; if Result then AResult := StrToInt(FSrcParams.Values[AName]); end; {-------------------------------------------------------------------------------} function TFDBDEAliasImporter.GetSrcStr(const AName: String; var AResult: String): Boolean; var i: Integer; begin i := FSrcParams.IndexOfName(AName); Result := i <> -1; AResult := ''; if Result then AResult := FSrcParams.Values[AName]; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportSQLCommon; var sVal: String; iVal: Integer; lVal: Boolean; begin if GetSrcInt(szROWSETSIZE, iVal) and (iVal <> 20) then FFetch.RowsetSize := iVal; if GetSrcInt(szBLOBCOUNT, iVal) and (iVal = 0) then if iVal > 0 then FFetch.Cache := FFetch.Cache + [fiBlobs] else FFetch.Cache := FFetch.Cache - [fiBlobs]; if GetSrcBool(szENABLESCHEMACACHE, lVal) then if lVal then FFetch.Cache := FFetch.Cache + [fiMeta] else FFetch.Cache := FFetch.Cache - [fiMeta]; if GetSrcInt(szMAXROWS, iVal) and (iVal <> -1) then FFetch.RecsMax := iVal; if GetSrcStr(szPASSWORD, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Password] := sVal; if (GetSrcStr(szUSERNAME, sVal) or GetSrcStr(UpperCase(S_FD_ConnParam_Common_BDEStyleUserName), sVal)) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_UserName] := sVal; if GetSrcInt(szCFGDRVTRACEMODE, iVal) and (iVal > 0) then begin if iVal <> 0 then sVal := S_FD_MoniRemote else sVal := ''; FDestParams.Values[S_FD_ConnParam_Common_MonitorBy] := sVal; end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportOracle(AImportMode: Boolean); var sVal: String; lVal: Boolean; oRule: TFDMapRule; begin if AImportMode then FDestParams.Values[S_FD_ConnParam_Common_DriverID] := S_FD_OraId; FFmt.OwnMapRules := True; FFmt.MaxBcdPrecision := $7FFFFFFF; FFmt.MaxBcdScale := $7FFFFFFF; if GetSrcBool(szORAINTEGER, lVal) and lVal then begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.ScaleMin := 0; oRule.ScaleMax := 0; oRule.PrecMin := 0; oRule.PrecMax := 5; oRule.TargetDataType := dtInt16; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.ScaleMin := 0; oRule.ScaleMax := 0; oRule.PrecMin := 6; oRule.PrecMax := 10; oRule.TargetDataType := dtInt32; end; if GetSrcBool(szCFGDBENABLEBCD, lVal) and lVal then begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDouble; oRule.TargetDataType := dtBCD; end else begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.TargetDataType := dtDouble; end; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtAnsiString; oRule.SizeMin := 256; oRule.TargetDataType := dtMemo; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtWideString; oRule.SizeMax := 255; oRule.TargetDataType := dtAnsiString; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtWideString; oRule.SizeMin := 256; oRule.TargetDataType := dtMemo; if AImportMode then begin if GetSrcStr(szCFGDRVVENDINIT, sVal) and (CompareText(sVal, 'OCI.DLL') <> 0) then FDestParams.Values[S_FD_DrvVendorLib] := sVal; if GetSrcStr(szSERVERNAME, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Database] := sVal; ImportSQLCommon; end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportIB(AImportMode: Boolean); var sVal: String; lVal: Boolean; oRule: TFDMapRule; begin // all TX related settings are not imported if AImportMode then FDestParams.Values[S_FD_ConnParam_Common_DriverID] := S_FD_IBId; FFmt.OwnMapRules := True; FFmt.MaxBcdPrecision := $7FFFFFFF; FFmt.MaxBcdScale := $7FFFFFFF; if GetSrcBool(szCFGDBENABLEBCD, lVal) and lVal then begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtCurrency; oRule.TargetDataType := dtBCD; end else begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.TargetDataType := dtDouble; end; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtAnsiString; oRule.SizeMin := 256; oRule.TargetDataType := dtMemo; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtByteString; oRule.SizeMin := 256; oRule.TargetDataType := dtMemo; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtWideString; oRule.SizeMax := 255; oRule.TargetDataType := dtAnsiString; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtWideString; oRule.SizeMin := 256; oRule.TargetDataType := dtMemo; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDateTimeStamp; oRule.TargetDataType := dtDateTime; if AImportMode then begin if GetSrcStr(szCFGDRVVENDINIT, sVal) and (CompareText(sVal, 'GDS32.DLL') <> 0) then FDestParams.Values[S_FD_DrvVendorLib] := sVal; if GetSrcStr(szSERVERNAME, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Database] := sVal; ImportSQLCommon; end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportMSSQL(AImportMode: Boolean); var sVal: String; lVal: Boolean; iVal: Integer; oRule: TFDMapRule; begin if AImportMode then FDestParams.Values[S_FD_ConnParam_Common_DriverID] := S_FD_MSSQLId; FFmt.OwnMapRules := True; FFmt.MaxBcdPrecision := $7FFFFFFF; FFmt.MaxBcdScale := $7FFFFFFF; if GetSrcBool(szCFGDBENABLEBCD, lVal) and lVal then begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDouble; oRule.ScaleMin := 1; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDouble; oRule.ScaleMin := 1; oRule.PrecMax := 17; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDouble; oRule.ScaleMin := 1; oRule.PrecMin := 19; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtInt64; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtCurrency; oRule.TargetDataType := dtBCD; end else begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.TargetDataType := dtDouble; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtInt64; oRule.TargetDataType := dtDouble; end; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDateTimeStamp; oRule.TargetDataType := dtDateTime; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtByte; oRule.TargetDataType := dtInt16; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtGUID; oRule.TargetDataType := dtByteString; if AImportMode then begin if GetSrcInt(szMAXQUERYTIME, iVal) and (iVal <> $7FFFFFFF) then FRes.CmdExecTimeout := iVal * 1000; if GetSrcStr(szSYBLAPP, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_ApplicationName] := sVal; if GetSrcStr(szDATABASENAME, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Database] := sVal; if GetSrcStr(szSYBLHOST, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_MSSQL_Address] := sVal; if GetSrcStr(szSYBLNATLANG, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_MSSQL_Language] := sVal; if GetSrcStr(szSERVERNAME, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Server] := sVal; ImportSQLCommon; end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportMSAccess(AImportMode: Boolean); var sVal: String; oRule: TFDMapRule; begin if AImportMode then FDestParams.Values[S_FD_ConnParam_Common_DriverID] := S_FD_MSAccId; FFmt.OwnMapRules := True; FFmt.MaxBcdPrecision := $7FFFFFFF; FFmt.MaxBcdScale := $7FFFFFFF; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.TargetDataType := dtDouble; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDateTimeStamp; oRule.TargetDataType := dtDateTime; if AImportMode then begin if GetSrcStr(szDATABASENAME, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Database] := sVal; if GetSrcStr(szCFGSYSTEMDB, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_MSAcc_SystemDB] := sVal; if GetSrcStr(szUSERNAME, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_UserName] := sVal; if GetSrcStr(szPASSWORD, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Password] := sVal; if GetSrcStr(szOPENMODE, sVal) and (CompareText(sVal, szREADONLY) = 0) then FDestParams.Values[S_FD_ConnParam_MSAcc_ReadOnly] := S_FD_True; end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportDB2(AImportMode: Boolean); var sVal: String; lVal: Boolean; iVal: Integer; oRule: TFDMapRule; begin if AImportMode then FDestParams.Values[S_FD_ConnParam_Common_DriverID] := S_FD_DB2Id; FFmt.OwnMapRules := True; FFmt.MaxBcdPrecision := $7FFFFFFF; FFmt.MaxBcdScale := $7FFFFFFF; if not (GetSrcBool(szCFGDBENABLEBCD, lVal) and lVal) then begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.TargetDataType := dtDouble; end; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDateTimeStamp; oRule.TargetDataType := dtDateTime; if AImportMode then begin if GetSrcInt(szMAXQUERYTIME, iVal) and (iVal <> $7FFFFFFF) then FRes.CmdExecTimeout := iVal * 1000; if GetSrcStr('DB2 DSN', sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_DB2_Alias] := sVal; ImportSQLCommon; end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportMySQL(AImportMode: Boolean); begin ImportODBC(AImportMode); end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.ImportODBC(AImportMode: Boolean); var sDrv, sVal: String; lVal: Boolean; oRule: TFDMapRule; begin if GetSrcStr(szCFGODBCDSN, sVal) then begin end; if AImportMode then FDestParams.Values[S_FD_ConnParam_Common_DriverID] := S_FD_ODBCId; FFmt.OwnMapRules := True; FFmt.MaxBcdPrecision := $7FFFFFFF; FFmt.MaxBcdScale := $7FFFFFFF; if GetSrcBool(szCFGDBENABLEBCD, lVal) and lVal then begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDouble; oRule.ScaleMin := 1; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDouble; oRule.ScaleMin := 1; oRule.PrecMax := 17; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDouble; oRule.ScaleMin := 1; oRule.PrecMin := 19; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.ScaleMin := 0; oRule.ScaleMax := 0; oRule.PrecMin := 18; oRule.PrecMax := 18; oRule.TargetDataType := dtDouble; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtInt64; oRule.TargetDataType := dtBCD; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtCurrency; oRule.TargetDataType := dtBCD; end else begin oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtBCD; oRule.TargetDataType := dtDouble; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtInt64; oRule.TargetDataType := dtDouble; end; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtDateTimeStamp; oRule.TargetDataType := dtDateTime; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtByte; oRule.TargetDataType := dtInt16; oRule := FFmt.MapRules.Add; oRule.SourceDataType := dtGUID; oRule.TargetDataType := dtByteString; if AImportMode then begin if GetSrcStr(szTYPe, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_ODBC_ODBCDriver] := sVal; if GetSrcStr(szCFGODBCDSN, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_ODBC_DataSource] := sVal; if GetSrcStr(szDATABASENAME, sVal) and (sVal <> '') then FDestParams.Values[S_FD_ConnParam_Common_Database] := sDrv; ImportSQLCommon; end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.MakeBDECompatible( const AConnectionDef: IFDStanConnectionDef; AEnableBCD, AEnableInteger: Boolean); var sDrv: String; oManMeta: IFDPhysManagerMetadata; iKind: TFDRDBMSKind; begin FSrcParams := TFDStringList.Create(dupAccept, True, False); if AEnableBCD then FSrcParams.Add(szCFGDBENABLEBCD + '=' + UpperCase(S_FD_True)); if AEnableInteger then FSrcParams.Add(szORAINTEGER + '=' + UpperCase(S_FD_True)); FDestParams := AConnectionDef.Params; FFetch := TFDFetchOptions.Create(nil); FFmt := TFDFormatOptions.Create(nil); FUpd := TFDUpdateOptions.Create(nil); FRes := TFDResourceOptions.Create(nil); AConnectionDef.ReadOptions(FFmt, FUpd, FFetch, FRes); try FDPhysManager.CreateMetadata(oManMeta); iKind := oManMeta.GetRDBMSKind(AConnectionDef.Params.DriverID); if iKind = TFDRDBMSKinds.Other then begin sDrv := UpperCase(AConnectionDef.AsString[DRIVERNAME_KEY]); if sDrv = '' then Exit; if CompareText(sDrv, S_OpenODBC) <> 0 then raise Exception.Create(S_FD_CantMakeConnDefBDEComp); iKind := oManMeta.GetRDBMSKind(AConnectionDef.AsString[S_FD_ConnParam_Common_RDBMS]); end; case iKind of TFDRDBMSKinds.Oracle: ImportOracle(False); TFDRDBMSKinds.Interbase: ImportIB(False); TFDRDBMSKinds.MySQL: ImportMySQL(False); TFDRDBMSKinds.MSSQL: ImportMSSQL(False); TFDRDBMSKinds.MSAccess: ImportMSAccess(False); TFDRDBMSKinds.DB2: ImportDB2(False); else ImportODBC(False); end; AConnectionDef.WriteOptions(FFmt, FUpd, FFetch, FRes); finally FDFreeAndNil(FSrcParams); FDestParams := nil; FDFreeAndNil(FFetch); FDFreeAndNil(FFmt); FDFreeAndNil(FUpd); FDFreeAndNil(FRes); end; end; {-------------------------------------------------------------------------------} procedure TFDBDEAliasImporter.Execute; var i, j: Integer; oAliases, oDrvParams: TFDStringList; sType, sName: String; oDefs: IFDStanConnectionDefs; oDef: IFDStanConnectionDef; iOverwrite: Integer; oManMeta: IFDPhysManagerMetadata; begin oAliases := TFDStringList.Create; oDrvParams := TFDStringList.Create; FSrcParams := TFDStringList.Create(dupAccept, True, False); FDestParams := TFDStringList.Create; FOpts := TFDOptionsContainer.Create(nil, TFDFetchOptions, TFDUpdateOptions, TFDResourceOptions, nil); FFetch := FOpts.FetchOptions; FFmt := FOpts.FormatOptions; FUpd := FOpts.UpdateOptions; FRes := FOpts.ResourceOptions; FDCreateInterface(IFDStanConnectionDefs, oDefs); if FConnectionDefFileName <> '' then oDefs.Storage.FileName := FConnectionDefFileName; oDefs.Load; try Session.GetAliasNames(oAliases); for i := 0 to oAliases.Count - 1 do if (FAliasesToImport.Count = 0) or (FAliasesToImport.IndexOf(oAliases[i]) <> -1) then begin FDestParams.Clear; sType := Session.GetAliasDriverName(oAliases[i]); Session.GetDriverParams(sType, oDrvParams); Session.GetAliasParams(oAliases[i], FSrcParams); for j := 0 to oDrvParams.Count - 1 do if FSrcParams.IndexOfName(oDrvParams.KeyNames[j]) = -1 then FSrcParams.Add(oDrvParams[j]); FDPhysManager.CreateMetadata(oManMeta); case oManMeta.GetRDBMSKind(sType) of TFDRDBMSKinds.Oracle: ImportOracle(True); TFDRDBMSKinds.Interbase: ImportIB(True); TFDRDBMSKinds.MSSQL: ImportMSSQL(True); TFDRDBMSKinds.MSAccess: ImportMSAccess(True); TFDRDBMSKinds.DB2: ImportDB2(True); else if FSrcParams.IndexOfName(szCFGODBCDSN) <> -1 then ImportODBC(True) else begin ShowMessage(Format('BDE driver [%s] is not supported.'#13#10 + 'Alias [%s] cannot be converted.', [sType, oAliases[i]])); Continue; end; end; if OverwriteDefs then begin oDef := oDefs.FindConnectionDef(oAliases[i]); if (oDef <> nil) and Assigned(FOnOverwrite) then begin iOverwrite := 1; FOnOverwrite(oAliases[i], iOverwrite); if iOverwrite = 0 then oDef := nil else if iOverwrite = -1 then Exit; end end else oDef := nil; if oDef = nil then oDef := oDefs.Add as IFDStanConnectionDef; oDef.Params.SetStrings(FDestParams); sName := oAliases[i]; if not OverwriteDefs then begin j := 0; while oDefs.FindConnectionDef(sName) <> nil do begin Inc(j); sName := Format('%s_%d', [oAliases[i], j]); end; end; oDef.Name := sName; oDef.WriteOptions(FFmt, FUpd, FFetch, FRes); oDef.MarkPersistent; end; oDefs.Save; finally FDFreeAndNil(oAliases); FDFreeAndNil(oDrvParams); FDFreeAndNil(FSrcParams); FDFreeAndNil(FDestParams); FFetch := nil; FFmt := nil; FUpd := nil; FRes := nil; FOpts := nil; end; end; (* -------------------------- ALL 'TYPE' f('DriverID') # not dbExpress 'DriverId = S_FD_TDBXId' & 'DriverName = Oracle' # dbExpress 'DLL32' x -------------------------- SQL Common 'BLOB SIZE' 'BlobSize' # dbExpress 'BLOBS TO CACHE' f('FetchOptions.Cache' & fiBlobs) 'ENABLE SCHEMA CACHE' f('FetchOptions.Cache' & fiMeta) 'LANGDRIVER' x 'MAX ROWS' 'FetchOptions.RecsMax' 'PASSWORD' 'Password' 'SCHEMA CACHE DIR' x 'SCHEMA CACHE SIZE' x 'SCHEMA CACHE TIME' x 'SQLPASSTHRU MODE' x 'SQLQRYMODE' x 'USER NAME' 'User_Name' 'TRACE MODE' 'Tracing' -------------------------- Oracle 'ENABLE BCD' f('FormatOptions.MapRules') 'ENABLE INTEGERS' f('FormatOptions.MapRules') 'LIST SYNONYMS' x 'NET PROTOCOL' x 'OBJECT MODE' x 'ROWSET SIZE' 'FetchOptions.RowsetSize' # not dbExpress 'RowsetSize' # dbExpress 'SERVER NAME' 'Database' 'VENDOR INIT' 'VendorLib' -------------------------- MSSQL 'APPLICATION NAME' 'App'=v 'BLOB EDIT LOGGING' x 'CONNECT TIMEOUT' x 'DATABASE NAME' 'Database'=v 'DATE MODE' x 'ENABLE BCD' f('FormatOptions.MapRules') 'HOST NAME' 'Address'=v 'NATIONAL LANG NAME' 'Language'=v 'MAX QUERY TIME' 'ResourceOptions.CmdExecTimeout'=v*1000 'SERVER NAME' 'Server'=v 'TDS PACKET SIZE' x 'TIMEOUT' x -------------------------- IB 'BATCH COUNT' x 'COMMIT RETAIN' ? 'ENABLE BCD' f('FormatOptions.MapRules') 'OPEN MODE' ? 'ROLE NAME' 'RoleName'=v 'SERVER NAME' 'Database'=v 'WAIT ON LOCKS' ? -------------------------- MSAccess 'DATABASE NAME' 'DBQ'=v 'LANGDRIVER' x 'OPEN MODE' 'ReadOnly'=READ/WRITE -> 0, READ ONLY -> 1 'SYSTEM DATABASE' 'SystemDB'=v 'USER NAME' 'UID'=v 'PASSWORD' 'PWD'=v -------------------------- ODBC 'BATCH COUNT' x 'DATABASE NAME' 'Database'=v 'ENABLE BCD' f('FormatOptions.MapRules') 'ODBC DSN' 'DSN'=v 'OPEN MODE' 'ReadOnly'=READ/WRITE -> 0, READ ONLY -> 1 'ROWSET SIZE' 'FetchOptions.RowsetSize' # not dbExpress 'RowsetSize' # dbExpress *) end.
program constants; const message = 'Hello, world'; count = 5; var i: integer; begin for i := 1 to count do writeln(message); end.
unit Systray; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ShellApi, Menus; const SH_CALLBACK = WM_USER +1; type TSystray = class(TCustomControl) private FIconData : PNOTIFYICONDATA; FIcon : TIcon; FMenu : TPopupMenu; FToolTip : array [0..63] of AnsiChar; FtoolTipS : string; procedure CallBack (var Message : TMessage); message SH_CALLBACK; protected FCreated : boolean; procedure SetParent (AParent: TWinControl); override; procedure SetIcon (AIcon : TIcon); virtual; procedure SetMenu (AMenu : TPopupMenu); virtual; function GetTool : string; virtual; procedure SetTool (S : string); virtual; procedure IconChange (Sender : TObject); procedure MenuChange (Sender : TObject;Source : TMenuItem;Rebuild : boolean); public constructor Create (AOwner : TComponent); override; procedure Reset; destructor Destroy; override; published property Menu : TPopupMenu read FMenu write SetMenu; property Icon : TIcon read FIcon write SetIcon; property ToolTip : String read GetTool write SetTool; // property OnMouseMove read end; procedure Register; implementation const ID : integer = 1; constructor TSystray.Create; begin inherited Create (AOwner); ControlStyle := ControlStyle + [csAcceptsControls]; Width := 50; Height := 50; FIcon := TIcon.Create; FIcon.OnChange := IconChange; FMenu := TPopupMenu.Create (Self); FtoolTipS := 'ToolTip'; getmem (FIconData,sizeof (NOTIFYICONDATA)); if not (csDesigning in ComponentState) then with FIconData^ do begin cbSize := sizeof (NOTIFYICONDATA); uFlags := NIF_ICON or NIF_TIP or NIF_MESSAGE; uID := ID; uCallBackMessage := SH_CALLBACK; end; FCreated := false; end; procedure TSystray.SetTool; var i : integer; begin FToolTipS := S; i := 1; FTooltip [0] := #0; if length (s) > 0 then repeat FToolTip[i-1] := S[i]; inc (i); until i > length (S); FToolTip [i] := #0; Reset; end; function TSystray.GetTool; begin { SetLength (S,64); i := 1; repeat s[i] := FToolTip [i-1]; inc (i); until FToolTip [i] = #0;} result := FToolTipS; end; procedure TSystray.SetMenu; var i : integer;M : TMenuItem; begin FMenu.Free; FMenu := AMenu; Reset; end; procedure TSystray.CallBack; var P : TPoint; begin GetCursorPos (P); if (message.LParam = WM_LBUTTONUP) or (message.LParam = WM_RBUTTONUP)then SetForegroundWindow (Self.handle); if message.LParam = WM_RBUTTONUP then if Assigned (FMenu) then FMenu.Popup (P.x,P.y); end; procedure TSystray.IconChange; begin Reset; end; procedure Tsystray.MenuChange; begin end; procedure TSystray.SetIcon; begin FIcon.Assign( AIcon ); end; procedure Tsystray.Reset; begin if not (csDesigning in ComponentState) then begin FIconData.Wnd := Handle; FIconData.hIcon := FIcon.Handle; Move (FToolTip,FIconData.szTip,64); if FCreated then Shell_NotifyIcon (NIM_MODIFY,FIconData) else Shell_NotifyIcon (NIM_ADD,FIconData); FCreated := true; end; end; destructor TSystray.Destroy; begin if ComponentState = [csDestroying] then begin Shell_NotifyIcon (NIM_DELETE,FIconData); end; Freemem (FIconData,sizeof (NOTIFYICONDATA)); FIcon.Free; // FMenu.Free; inherited Destroy; end; procedure Register; begin RegisterComponents('Additional', [TSystray]); end; procedure TSystray.SetParent(AParent: TWinControl); begin inherited SetParent (AParent); if ComponentState = [] then Reset; end; end.
unit ubooksearch; {Berisi fungsi (F03, F04) untuk mencari buku di perpustakaan} {REFERENSI : - } interface uses ucsvwrapper, ubook, ubookutils; {PUBLIC, FUNCTION, PROCEDURE} function categoryValid(q : string): boolean; procedure findBookByCategoryUtil(category: string; ptrbook:pbook); {F03} procedure findBookByYearUtil(year:integer; category:string; ptrbook:pbook); {F04} implementation {FUNGSI dan PROSEDUR} function fitCategory(year:integer; category:string; currentyear:integer) : boolean; {DESKRIPSI : mencocokkan kategori dengan tahun terbit buku.} {PARAMETER : year menyatakan tahun terbit buku, category menyatakan kategori dari buku, dan current year adalah input tahun yang dimasukkan.} {RETURN : apakah dia fitcategory atau tidak.} {ALGORITMA} begin if (category = '<') then begin fitcategory := currentyear < year; end else if (category = '=') then begin fitcategory := currentyear = year; end else if (category = '>') then begin fitcategory := currentyear > year; end else if (category = '<=') then begin fitcategory := currentyear <= year; end else if (category = '>=') then begin fitcategory := currentyear >= year; end; end; function categoryValid(q : string): boolean; {DESKRIPSI : mengecek apakah query yang dimasukkan user valid/tidak.} {PARAMETER : kategori input user.} {RETURN : boolean apakah kategori valid.} {KAMUS LOKAL} var str : string; i : integer; {ALGORITMA} begin categoryValid := false; for i := 1 to NUMCATEGORIES do begin str := CATEGORIES[i]; if (q = str) then begin categoryValid := true; end; end; end; procedure findBookByCategoryUtil(category: string; ptrbook:pbook); {DESKRIPSI : (F03) mencari buku dengan kategori tertentu sesuai input dari user} {I.S. : array of Book terdefinisi} {F.S. : ID buku, judul buku, penulis buku dengan kategori yang diinput ditampilkan di layar dengan judul tersusun sesuai abjad} {Proses : Menanyakan pada user kategori apa yang dicari, lalu mencari ID, judul dan penulis buku tersebut lalu menampilkannya di layar} {KAMUS LOKAL} var i, counter : integer; found : boolean; filteredBooks : tbook; ptr : pbook; {ALGORITMA} begin if (categoryValid(category)) then begin i := 1; counter := 0; {skema pencarian dengan boolean} found := false; while (i <= bookNeff) do begin if (category = ptrbook^[i].category) then begin found := true; counter += 1; filteredBooks[counter] := ptrbook^[i]; end; i += 1 end; { i > userNeff or found } if (found) then begin new(ptr); ptr^ := filteredBooks; sortBookByTitle(ptr, counter); for i := 1 to counter do begin writeln(ptr^[i].id, ' | ' , unwraptext(ptr^[i].title) , ' | ' , unwraptext(ptr^[i].author)); end; end else begin writeln ('Tidak ada buku dalam kategori ini.'); end; end else begin writeln ('Kategori ', category ,' tidak valid.'); writeln(); end; end; procedure findBookByYearUtil(year:integer; category:string; ptrbook:pbook); {DESKRIPSI : (F04) mencari buku berdasarkan tahun yang diinput oleh user.} {I.S. : array of book terdefinisi.} {F.S. : ID buku, judul buku, penulis buku berdasarkan tahun yang diinput ditampilkan di layar dengan judul tersusun sesuai abjad.} {Proses : Menanyakan pada user tahun terbit berapa yang dicari, lalu mencari ID, judul dan penulis buku tersebut dan menampilkannya di layar.} {KAMUS LOKAL} var i, counter : integer; found : boolean; filteredBooks : tbook; ptr : pbook; {ALGORITMA} begin writeln(); writeln('Buku yang terbit pada tahun ', category, ' ', year, ':'); {skema pencarian dengan boolean} i := 1; counter := 0; found := false; while (i <= bookNeff) do begin if (fitcategory(year, category, ptrbook^[i].year)) then begin found := true; counter += 1; filteredBooks[counter] := ptrbook^[i]; end; i += 1 end; if (found) then begin new(ptr); ptr^ := filteredBooks; sortBookByTitle(ptr, counter); for i := 1 to counter do begin writeln(ptr^[i].id, '|', unwraptext(ptr^[i].title), '|', unwraptext(ptr^[i].author)); found := true; end; end else begin writeln('Tidak ada buku yang sesuai'); end; end; end.
{----------------------------------------------------------------------------- Author: Roman Fadeyev Purpose: Диалог для выбора индикатора для вставки его в чарт History: -----------------------------------------------------------------------------} unit FC.StockChart.CreateIndicatorDialog; {$I Compiler.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufmDialogOKCancel_B, ActnList, StdCtrls, ExtendControls, ExtCtrls, StockChart.Definitions,FC.Definitions, ComCtrls; type TIndicatorNode = class(TTreeNode) private FIndicator : ISCIndicatorInfo; public property Indicator: ISCIndicatorInfo read FIndicator write FIndicator; end; TfmCreateIndicatorDialog = class(TfmDialogOkCancel_B) Panel1: TPanel; tvIndicators: TExtendTreeView; laHeader: TLabel; procedure tvIndicatorsAdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); procedure tvIndicatorsDblClick(Sender: TObject); procedure acOKUpdate(Sender: TObject); private FIndicators: ISCIndicatorInfoCollection; FKind : TSCIndicatorKind; function GetSelected: ISCIndicatorInfo; procedure SetSelected(const Value: ISCIndicatorInfo); protected procedure CreateWnd; override; public constructor Create(aOwner:TComponent); override; procedure Init(const Value: ISCIndicatorInfoCollection; aKind:TSCIndicatorKind); property Indicators: ISCIndicatorInfoCollection read FIndicators; property SelectedIndicator: ISCIndicatorInfo read GetSelected write SetSelected; class function RunSingleSelection(aIndicators: ISCIndicatorInfoCollection; aKind:TSCIndicatorKind; var aSelected: ISCIndicatorINfo): boolean; end; implementation uses ufmDialog_B,FC.Factory, ufmForm_B, ufmDialogOK_B,Properties.Dialog, Types; type TTreeViewFriend = class (TExtendTreeView); {$R *.dfm} { TfmCreateIndicatorDialog } class function TfmCreateIndicatorDialog.RunSingleSelection(aIndicators: ISCIndicatorInfoCollection; aKind:TSCIndicatorKind; var aSelected: ISCIndicatorInfo): boolean; begin with TfmCreateIndicatorDialog.Create(nil) do try Init(aIndicators,aKind); result:=ShowModal = mrOk; if result then aSelected:= SelectedIndicator; finally Free; end; end; constructor TfmCreateIndicatorDialog.Create(aOwner: TComponent); begin inherited; TTreeViewFriend(tvIndicators).CreateWndRestores:=false; end; procedure TfmCreateIndicatorDialog.CreateWnd; begin inherited; if FIndicators<>nil then Init(FIndicators,FKind); end; function TfmCreateIndicatorDialog.GetSelected: ISCIndicatorInfo; var aNode: TIndicatorNode; begin result:=nil; if (tvIndicators.Selected<>nil) and (tvIndicators.Selected is TIndicatorNode) then begin aNode:=TIndicatorNode(tvIndicators.Selected); result:=aNode.Indicator; end; end; procedure TfmCreateIndicatorDialog.SetSelected(const Value: ISCIndicatorInfo); begin end; procedure TfmCreateIndicatorDialog.tvIndicatorsAdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); var x,y: integer; begin inherited; if (Node is TIndicatorNode) and (TIndicatorNode(Node).Indicator=nil) then //and (Stage in [cdPrePaint, cdPreErase, cdPostErase]) then begin DefaultDraw:=false; Sender.Canvas.Brush.Color:=clGroupHeader; Sender.Canvas.FillRect(Node.DisplayRect(false)); if cdsSelected in State then Sender.Canvas.Font.Color:=clHighlightText else Sender.Canvas.Font.Color:=clWindowText; with Node.DisplayRect(true) do begin x:=Left; y:=(Bottom+Top-Sender.Canvas.TextHeight(Node.Text)) div 2; end; Sender.Canvas.TextOut(x,y,Node.Text); end; end; procedure TfmCreateIndicatorDialog.tvIndicatorsDblClick(Sender: TObject); begin inherited; acOK.Execute; end; procedure TfmCreateIndicatorDialog.Init(const Value: ISCIndicatorInfoCollection; aKind:TSCIndicatorKind); var aCategories : TStringList; i,j : integer; aIndicator: ISCIndicatorInfo; aNode0 : TTreeNode; aNode1 : TTreeNode; aNode2 : TIndicatorNode; begin FIndicators:=Value; FKind:=aKind; Caption:='Select '+IndicatorKindNamesSingle[FKind]; laHeader.Caption:=Caption; tvIndicators.Items.Clear; tvIndicators.HandleNeeded; tvIndicators.Items.Clear; if (FIndicators=nil) or (FIndicators.Count=0) then exit; //Заполняем список индикаторов aCategories:=TStringList.Create; tvIndicators.Items.BeginUpdate; try aCategories.Sorted:=true; aCategories.Duplicates:=dupIgnore; for i:=0 to FIndicators.Count-1 do aCategories.Add(FIndicators.Items[i].Category); aNode0:=nil; for i:=0 to aCategories.Count-1 do begin aNode1:=nil; for j:=0 to FIndicators.Count-1 do begin aIndicator:=FIndicators.Items[j]; if (aIndicator.Category=aCategories[i]) and (aIndicator.Kind=FKind) then begin if aNode1=nil then aNode1:=tvIndicators.Items.AddChild(aNode0,aCategories[i]); aNode2:=TIndicatorNode.Create(tvIndicators.Items); //aNode2.Text:=aIndicator.Name; aNode2.Indicator:=aIndicator; tvIndicators.Items.AddNode(aNode2, aNode1, aIndicator.Name, nil, naAddChild); end; end; end; for i:=0 to tvIndicators.Items.Count-1 do tvIndicators.Items[i].Expanded:=true; finally tvIndicators.Items.EndUpdate; aCategories.Free; end; tvIndicators.AlphaSort(true); if tvIndicators.Items.Count>0 then begin tvIndicators.Items[0].MakeVisible; tvIndicators.Items[0].Focused:=true; tvIndicators.Items[0].Selected:=true; end; end; procedure TfmCreateIndicatorDialog.acOKUpdate(Sender: TObject); begin TAction(Sender).Enabled:=SelectedIndicator<>nil; end; end.
program fft; Uses Math, sysutils; Type SArray = Array of String; Type RArray = Array of Real; //-------------------------------------------------- //-- COMPLEX NUMBERS HANDLING ---------------------- type Complex = Array [0..1] of Real; type CArray = Array of Complex; function multiply(c1, c2 : Complex) : Complex; var prod : Complex; begin prod[0] := c1[0] * c2[0] - c1[1] * c2[1]; prod[1] := c1[0] * c2[1] + c1[1] * c2[0]; multiply:= prod; end; function add(c1,c2 : Complex):Complex; var sum : Complex; begin sum[0] := c1[0] + c2[0]; sum[1] := c1[1] + c2[1]; add := sum; end; function substract(c1,c2 : Complex):Complex; var sum : Complex; begin sum[0] := c1[0] - c2[0]; sum[1] := c1[1] - c2[1]; substract := sum; end; function conjugate(c1 : Complex):Complex; var conj : Complex; begin conj[0] := c1[0]; conj[1] := - c1[1]; conjugate := conj; end; function conjugateArray(c1 : CArray):CArray; var conjArray : CArray; i, n : Integer; begin n := length(c1); SetLength(conjArray, n); for i:=0 to n - 1 do begin conjArray[i][0] := c1[i][0]; conjArray[i][1] := - c1[i][1]; end; conjugateArray := conjArray; end; //-------------------------------------------------- //-------------------------------------------------- //-- INPUT DATA HANDLING --------------------------- // Split a string to an array using the given separator function occurs(const str, separator: string):integer; var i, nSep:integer; begin nSep:= 0; for i:= 1 to Length(str) do if str[i] = separator then Inc(nSep); occurs:= nSep; end; procedure split(const str: String; const separator: String; var Result:SArray; var numberOfItems:Integer); var i, n: Integer; strline, strfield: String; begin n := occurs(str, separator); SetLength(Result, n + 1); i := 0; strline := str; repeat if Pos(separator, strline) > 0 then begin strfield := Copy(strline, 1, Pos(separator, strline) - 1); strline := Copy(strline, Pos(separator, strline) + 1, Length(strline) - pos(separator,strline)); end else begin strfield:= strline; strline:= ''; end; Result[i]:= strfield; Inc(i); until strline= ''; if Result[High(Result)] = '' then SetLength(Result, Length(Result) - 1); numberOfItems := i; end; // Read the given string and convert it to a vector of complex numbers procedure processInput(var result:CArray; var dimension:Integer); var inputFile:TextFile; input:String; stringArray:SArray; complexNumber:Complex; numberInLine:Integer; begin numberInLine := 0; dimension := 0; //readln(input); // Read line by line assign(inputFile, 'source.d'); reset(inputFile); // Put pointer at the beginning of the file repeat // For each line readln(inputFile, input); dimension := dimension + 1; SetLength(result, dimension); // Split real and imaginary part (using ',' separator) split(input, ',', stringArray, numberInLine); complexNumber[0] := StrToFloat(stringArray[0]); complexNumber[1] := StrToFloat(stringArray[1]); // Add this number to output result[dimension-1] := complexNumber; until(EOF(inputFile)); close(inputFile); end; //-------------------------------------------------- //-------------------------------------------------- //-- DATA DIMENSION DETECTION ---------------------- // Read the value of a bit from any variable function getBit(const Val: DWord; const BitVal: Byte): Boolean; begin getBit := (Val and (1 shl BitVal)) <> 0; end; // Set the value of a bit in any variable function enableBit(const Val: DWord; const BitVal: Byte; const SetOn: Boolean): DWord; begin enableBit := (Val or (1 shl BitVal)) xor (Integer(not SetOn) shl BitVal); end; // Determine wether a number is a power of two procedure isPowerOfTwo(n:Integer; var result:Boolean; var power:Integer); var bitCounter:Integer; keepIncrementingPower:Boolean; begin bitCounter := 0; keepIncrementingPower := true; power := 0; // n is a power of two <=> it has only one bit set to 1 while (n > 0) do begin if ((n and 1) = 1) then begin Inc(bitCounter); keepIncrementingPower := false; end; n := n >> 1; // Bitwise shift if (keepIncrementingPower) then Inc(power); end; result := (bitCounter = 1); end; //-------------------------------------------------- //-------------------------------------------------- //-- MIRROR PERMUTATION ---------------------------- function mirrorTransform(n,m:Integer):Integer; var i,p : Integer; begin p := 0; for i:=0 to m-1 do begin p := enableBit(p, m-1-i, getBit(n, i)); end; mirrorTransform:=p; end; function doPermutation(source:CArray; m:Integer):CArray; var i, n : Integer; result : CArray; begin n := length(source); SetLength(result, n); for i:=0 to n-1 do begin result[i] := source[mirrorTransform(i, m)]; end; doPermutation := result; end; //-------------------------------------------------- //-------------------------------------------------- //-- FFT COMPUTATION STEP -------------------------- function doStep(k, M : Longint; prev:CArray):CArray; var expTerm, substractTerm : Complex; dimension, q, j, offset : Longint; u : CArray; begin // INITIALIzATION //offset = 2^(M-k) offset := system.round(intpower(2, M-k)); SetLength(u, length(prev)); // COMPUTE EACH COORDINATE OF u_k for q:=0 to system.round(intpower(2, k-1) - 1) do begin // For each block of the matrix for j:=0 to (offset - 1) do begin // Fo each line of this block // First half u[q*2*offset + j] := add( prev[q*2*offset + j], prev[q*2*offset + j + offset] ); // Second half expTerm[0] := cos( (j * PI) / offset ); expTerm[1] := sin( (j * PI) / offset ); substractTerm := substract( prev[q*2*offset + j], prev[q*2*offset + j + offset] ); u[q*2*offset + j + offset] := multiply(expTerm, substractTerm); end; end; // Output result doStep := u; end; // DISCRETE FOURIER TRANSFORM USING COOLEY-TUKEY'S FFT ALGORITHM function fft(g:CArray; order:Integer):CArray; var previousRank, nextRank : CArray; i : Integer; begin previousRank := g; for i:=1 to order do begin nextRank := doStep(i, order, previousRank); previousRank := nextRank; end; // Mirror transform nextRank := doPermutation(nextRank, order); fft := nextRank; end; // INVERSE FOURIER TRANSFORM function ifft(G:CArray; order:Integer):CArray; var result : CArray; i, n : Longint; begin n := length(G); SetLength(result, n); //La transformée inverse est le conjugué de la transformée du conjugué result := fft(conjugateArray(G), order); result := conjugateArray(result); //...ajustée par un facteur 1/n for i := 0 to n - 1 do begin result[i][0] := result[i][0] / n; result[i][1] := result[i][1] / n; end; ifft := result; end; //-------------------------------------------------- //-------------------------------------------------- //-- RESULT OUTPUT --------------------------------- procedure writeResult(result : CArray); var i, dimension : Integer; begin dimension := length(result); for i := 0 to dimension - 1 do begin write(result[i][0]:2:5); write(' + '); write(result[i][1]:2:5); writeln(' I'); end; end; // Output one complex number per line using the format: // real part, imaginary part procedure saveResult(result : CArray); var i, dimension : Integer; outputFile : TextFile; begin dimension := length(result); // Open output file assign(outputFile, 'result.d'); rewrite(outputFile); // Write each complex number to a new line for i := 0 to dimension - 1 do begin write(outputFile, result[i][0]); write(outputFile, ', '); writeln(outputFile, result[i][1]); end; close(outputFile); end; //-------------------------------------------------- //-------------------------------------------------- //-- MAIN ------------------------------------------ var received, result, guessedData : CArray; n, m : Integer; isAcceptable : Boolean; begin n := 0; m := 0; isAcceptable := false; // READ INPUT DATA processInput(received, n); // Dimension detection: only accept powers of 2 isPowerOfTwo(n, isAcceptable, m); if isAcceptable then begin // Acceptable dimension write('The given vector is of dimension : 2^'); writeln(m); //La dimension de g nous donne M write('We thus have M='); writeln(m); // APPLY TRANSFORM result := fft(received, m); // PRINT RESULT writeln('Transformed result:'); writeResult(result); // DEMO: find back the original vector using inverse tranform writeln('We find back the original vector using the inverse transform:'); guessedData := ifft(result, m); writeResult(guessedData); // WRITE RESULT TO result.d saveResult(result); end else // Dimension is not acceptable begin writeln('The given vector doesn''t have a dimension of 2^M.'); end; end. //--------------------------------------------------
(* This example represents a sampling of the way that you might approach trapping a number of database errors. A complete listing of the database errorcodes is found in the DBIErrs.Int file in the Delphi/Doc directory or in the IDAPI.h file in the Borland Database Engine. Database errors are defined by category and code. Here's a sample: { ERRCAT_INTEGRITY } ERRCODE_KEYVIOL = 1; { Key violation } ERRCODE_MINVALERR = 2; { Min val check failed } ERRCODE_MAXVALERR = 3; { Max val check failed } ERRCODE_REQDERR = 4; { Field value required } ERRCODE_FORIEGNKEYERR = 5; { Master record missing } ERRCODE_DETAILRECORDSEXIST = 6; { Cannot MODIFY or DELETE this Master record } ERRCODE_MASTERTBLLEVEL = 7; { Master Table Level is incorrect } ERRCODE_LOOKUPTABLEERR = 8; { Field value out of lookup tbl range } ERRCODE_LOOKUPTBLOPENERR = 9; { Lookup Table Open failed } ERRCODE_DETAILTBLOPENERR = 10; { 0x0a Detail Table Open failed } ERRCODE_MASTERTBLOPENERR = 11; { 0x0b Master Table Open failed } ERRCODE_FIELDISBLANK = 12; { 0x0c Field is blank } The constant for the base category is added to these constants to represent a unique DBI errorcode; DBIERR_KEYVIOL = (ERRBASE_INTEGRITY + ERRCODE_KEYVIOL); DBIERR_REQDERR = (ERRBASE_INTEGRITY + ERRCODE_REQDERR); DBIERR_DETAILRECORDSEXIST = (ERRBASE_INTEGRITY + ERRCODE_DETAILRECORDSEXIST); DBIERR_FORIEGNKEYERR = (ERRBASE_INTEGRITY + ERRCODE_FORIEGNKEYERR); The ERRBASE_INTEGRITY value is $2600 (Hex 2600) or 9728 decimal. Thus, for example, the errorcode for keyviol is 9729 for master with details is 9734. *) unit DM1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DBTables, DB; type TDM = class(TDataModule) Customer: TTable; CustomerCustNo: TFloatField; CustomerCompany: TStringField; CustomerSource: TDataSource; Orders: TTable; OrdersSource: TDataSource; Items: TTable; ItemsOrderNo: TFloatField; ItemsItemNo: TFloatField; ItemsPartNo: TFloatField; ItemsQty: TIntegerField; ItemsDiscount: TFloatField; ItemsSource: TDataSource; OrdersOrderNo: TFloatField; OrdersCustNo: TFloatField; OrdersSaleDate: TDateTimeField; OrdersShipDate: TDateTimeField; OrdersEmpNo: TIntegerField; procedure CustomerPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure CustomerDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure ItemsPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure OrdersPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure OrdersDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); private { Private declarations } public { Public declarations } end; var DM: TDM; const {Declare constants we're interested in} eKeyViol = 9729; eRequiredFieldMissing = 9732; eForeignKey = 9733; eDetailsExist = 9734; implementation {$R *.DFM} procedure TDM.CustomerPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin if (E is EDBEngineError) then if (E as EDBEngineError).Errors[0].Errorcode = eKeyViol then begin MessageDlg('Unable to post: Duplicate Customer ID.', mtWarning, [mbOK], 0); Abort; end; end; procedure TDM.CustomerDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin if (E is EDBEngineError) then if (E as EDBEngineError).Errors[0].Errorcode = eDetailsExist then {the customer record has dependent details in the Orders table.} begin MessageDlg('To delete this record, first delete related orders and items.', mtWarning, [mbOK], 0); Abort; end; end; procedure TDM.ItemsPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin {This error will occur when a part number is specified that is not in the parts table.} if (E as EDBEngineError).Errors[0].Errorcode = eForeignKey then begin MessageDlg('Part number is invalid', mtWarning,[mbOK],0); Abort; end; end; procedure TDM.OrdersPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); var iDBIError: Integer; begin if (E is EDBEngineError) then begin iDBIError := (E as EDBEngineError).Errors[0].Errorcode; case iDBIError of eRequiredFieldMissing: {The EmpNo field is defined as being required.} begin MessageDlg('Please provide an Employee ID', mtWarning, [mbOK], 0); Abort; end; eKeyViol: {The primary key is OrderNo} begin MessageDlg('Unable to post. Duplicate Order Number', mtWarning, [mbOK], 0); Abort; end; end; end; end; procedure TDM.OrdersDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin if E is EDBEngineError then if (E as EDBEngineError).Errors[0].Errorcode = eDetailsExist then begin if MessageDlg('Delete this order and related items?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin {Delete related records in linked 'items' table} while Items.RecordCount > 0 do Items.delete; {Finally,delete this record} Action := daRetry; end else Abort; end; end; end.
unit FrmPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Frm.Pais, Frm.Estado, Frm.Cidade,Frm.Produto, Frm.Cliente,Frm.Venda; type TForm1 = class(TForm) mm1: TMainMenu; Cadastros: TMenuItem; Localizao1: TMenuItem; Pas1: TMenuItem; Estado1: TMenuItem; Cidade1: TMenuItem; Geral1: TMenuItem; Produto1: TMenuItem; Cliente1: TMenuItem; Movimentao1: TMenuItem; RealizaodeVenda1: TMenuItem; procedure Pas1Click(Sender: TObject); procedure Estado1Click(Sender: TObject); procedure Cidade1Click(Sender: TObject); procedure Produto1Click(Sender: TObject); procedure Cliente1Click(Sender: TObject); procedure RealizaodeVenda1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Cidade1Click(Sender: TObject); var vFrmCidade: TFrmCidade; //Variavel do tipo formulário do País begin vFrmCidade := TFrmCidade.Create(nil); //Cria o formulário sem proprietarios try vFrmCidade.ShowModal; //Mostra o formulário na tela finally FreeAndNil(vFrmCidade); end; end; procedure TForm1.Cliente1Click(Sender: TObject); var vFrmCliente: TFrmCliente; //Variavel do tipo formulário do País begin vFrmCliente := TFrmCliente.Create(nil); //Cria o formulário sem proprietarios try vFrmCliente.ShowModal; //Mostra o formulário na tela finally FreeAndNil(vFrmCliente); end; end; procedure TForm1.Estado1Click(Sender: TObject); var vFrmEstado: TFrmEstado; //Variavel do tipo formulário do País begin vFrmEstado := TFrmEstado.Create(nil); //Cria o formulário sem proprietarios try vFrmEstado.ShowModal; //Mostra o formulário na tela finally FreeAndNil(vFrmEstado); end; end; procedure TForm1.Pas1Click(Sender: TObject); var vFrmPais: TFrmPais; //Variavel do tipo formulário do País begin vFrmPais := TFrmPais.Create(nil); //Cria o formulário sem proprietarios try vFrmPais.ShowModal; //Mostra o formulário na tela finally FreeAndNil(vFrmPais); end; end; procedure TForm1.Produto1Click(Sender: TObject); var vFrmProduto: TFrmProduto; //Variavel do tipo formulário do País begin vFrmProduto := TFrmProduto.Create(nil); //Cria o formulário sem proprietarios try vFrmProduto.ShowModal; //Mostra o formulário na tela finally FreeAndNil(vFrmProduto); end; end; procedure TForm1.RealizaodeVenda1Click(Sender: TObject); var vFrmVenda: TFrmVenda; //Variavel do tipo formulário do País begin vFrmVenda := TFrmVenda.Create(nil); //Cria o formulário sem proprietarios try vFrmVenda.ShowModal; //Mostra o formulário na tela finally FreeAndNil(vFrmVenda ); end; end; end.
unit Bank_impl; {This file was generated on 15 Jun 2000 15:40:10 GMT by version 03.03.03.C1.04} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file account.idl. } {Delphi Pascal unit : Bank_impl } {derived from IDL module : Bank } interface uses SysUtils, CORBA, Bank_i, Bank_c; type TAccount = class; TAccount = class(TInterfacedObject, Bank_i.Account) protected _balance : Single; public constructor Create; function balance : Single; procedure deposit ( const value : Single); procedure withdrawl ( const value : Single); procedure DoException ; end; implementation uses ServerMain; constructor TAccount.Create; begin inherited; _balance := Random * 1000; end; function TAccount.balance : Single; begin Result := _balance; Form1.Memo1.Lines.Add('Got a balance call from the client...'); end; procedure TAccount.deposit ( const value : Single); begin _balance := _balance + value; end; procedure TAccount.withdrawl ( const value : Single); begin if (value > _balance) then raise EAccountOverRun.Create(_balance) else _balance := _balance - value; end; procedure TAccount.DoException; var myFooStruct : errStruct; begin myFooStruct := TerrStruct.Create(12345, 'This is the struct guy'); raise EFoo.Create(myFooStruct); (* You can choose to raise the ThrowOne exception instead. You can't throw both at the same time *) //raise EThrowOne.Create('This is the Throw One Exception'); end; initialization Randomize; end.
unit ProducerTypesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, OrderQuery, DSWrap; type TProducerTypeW = class(TOrderW) private FProducerType: TFieldWrap; FID: TFieldWrap; public constructor Create(AOwner: TComponent); override; property ProducerType: TFieldWrap read FProducerType; property ID: TFieldWrap read FID; end; TQueryProducerTypes = class(TQueryOrder) FDUpdateSQL: TFDUpdateSQL; private FW: TProducerTypeW; { Private declarations } protected function CreateDSWrap: TDSWrap; override; public constructor Create(AOwner: TComponent); override; function LocateOrAppend(const AValue: string): Boolean; property W: TProducerTypeW read FW; { Public declarations } end; implementation {$R *.dfm} uses NotifyEvents; constructor TQueryProducerTypes.Create(AOwner: TComponent); begin inherited; FW := FDSWrap as TProducerTypeW; AutoTransaction := False; end; function TQueryProducerTypes.CreateDSWrap: TDSWrap; begin Result := TProducerTypeW.Create(FDQuery); end; function TQueryProducerTypes.LocateOrAppend(const AValue: string): Boolean; begin Assert(not AValue.IsEmpty); Result := FDQuery.LocateEx(W.ProducerType.FieldName, AValue, [lxoCaseInsensitive]); if not Result then begin W.TryAppend; W.ProducerType.F.AsString := AValue; W.TryPost; end; end; constructor TProducerTypeW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FProducerType := TFieldWrap.Create(Self, 'ProducerType', 'زوُ'); FOrd := TFieldWrap.Create(Self, 'Ord'); end; end.
unit iaDemo.IFileDialogCustomize.CustomComboBox; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) butOpenFile: TButton; ExampleDialog: TFileOpenDialog; Label1: TLabel; lstCustomItems: TListBox; Label2: TLabel; procedure ExampleDialogFileOkClick(Sender: TObject; var CanClose: Boolean); procedure ExampleDialogExecute(Sender: TObject); procedure butOpenFileClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; const CUSTOM_CONTROL_ID = 1; //multiple custom controls are allowed per dialog, uniquely numbered implementation uses WinAPI.ShlObj; {$R *.dfm} //Standard Onclick event except manage custom control's selection result via the .Tag property //Using .Tag is an easy approach for a single numeric custom response. procedure TForm1.butOpenFileClick(Sender: TObject); begin ExampleDialog.Tag := 0; //reset on use if ExampleDialog.Execute(self.Handle) then begin ShowMessage(Format('You selected custom item index %d' + sLineBreak + 'When opening file: %s', [ExampleDialog.Tag, ExampleDialog.FileName])); end; end; //let's customize the FileOpen Dialog by adding a custom combobox procedure TForm1.ExampleDialogExecute(Sender: TObject); var iCustomize:IFileDialogCustomize; vItem:string; i:Integer; begin if ExampleDialog.Dialog.QueryInterface(IFileDialogCustomize, iCustomize) = S_OK then begin //https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialogcustomize-startvisualgroup iCustomize.StartVisualGroup(0, 'Custom description here'); try //https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialogcustomize-addcombobox //note other controls available: AddCheckButton, AddEditBox, AddPushButton, AddRadioButtonList... iCustomize.AddComboBox(CUSTOM_CONTROL_ID); for i := 0 to lstCustomItems.Items.Count - 1 do begin vItem := lstCustomItems.Items[i]; //https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialogcustomize-addcontrolitem //+1 note: If user doesn't select an item, the result is 0 so lets start indexed items with 1 iCustomize.AddControlItem(CUSTOM_CONTROL_ID, i+1, PChar(vItem)); end; if lstCustomItems.ItemIndex >= 0 then //let's optionally pre-select a custom item begin //https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialogcustomize-setselectedcontrolitem iCustomize.SetSelectedControlItem(CUSTOM_CONTROL_ID, lstCustomItems.ItemIndex+1); end; finally //https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialogcustomize-endvisualgroup iCustomize.EndVisualGroup; end; end; end; //Grab the custom control's selection procedure TForm1.ExampleDialogFileOkClick(Sender: TObject; var CanClose: Boolean); var iCustomize: IFileDialogCustomize; vSelectedIndex:DWORD; begin vSelectedIndex := 0; if ExampleDialog.Dialog.QueryInterface(IFileDialogCustomize, iCustomize) = S_OK then begin //https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialogcustomize-getselectedcontrolitem iCustomize.GetSelectedControlItem(CUSTOM_CONTROL_ID, vSelectedIndex); ExampleDialog.Tag := vSelectedIndex; end; end; end.
unit uRelayBox; interface uses Windows, Messages, SysUtils, Variants, Classes, CPortX; type TChangeRelaysEvent = procedure(Sender: TObject) of object; TChangeRelayEvent = procedure(Sender: TObject; Index: Integer; State: boolean) of object; type TRelayBox = class(TComponent) private ComPort: TCPortX; FActive: boolean; FEnable: boolean; FCount: Integer; FRelay: array of boolean; FChangeRelay: TChangeRelayEvent; FChangeRelays: TChangeRelaysEvent; procedure DoCmd(Cmd: string); procedure DoDoCmd(Cmd: string; recursive: boolean); function GetBaudRate: string; function GetDataBits: string; function GetFlowControl: string; function GetParity: string; function GetPort: string; function GetRelay(Index: integer): boolean; function GetStopBits: string; procedure SetAvtive(const Value: boolean); procedure SetBaudRate(const Value: string); procedure SetDataBits(const Value: string); procedure SetFlowControl(const Value: string); procedure SetParity(const Value: string); procedure SetPort(const Value: string); procedure SetRelay(Index: integer; const Value: boolean); procedure SetStopBits(const Value: string); procedure SetEnable(const Value: boolean); function MakeSendMess: string; public property Active: boolean read FActive write SetAvtive; property Count: Integer read FCount; property Enable: boolean read FEnable write SetEnable; property Relay[Index: integer]: boolean read GetRelay write SetRelay; property ChangeRelays: TChangeRelaysEvent read FChangeRelays write FChangeRelays; property ChangeRelay: TChangeRelayEvent read FChangeRelay write FChangeRelay; // RS232関連 property BaudRate: string read GetBaudRate write SetBaudRate; property DataBits: string read GetDataBits write SetDataBits; property FlowControl: string read GetFlowControl write SetFlowControl; property Parity: string read GetParity write SetParity; property Port: string read GetPort write SetPort; property StopBits: string read GetStopBits write SetStopBits; constructor Create(Owner: TComponent; Count: integer); destructor Destroy; override; procedure Open(); procedure Close(); end; implementation { TRelayBox } constructor TRelayBox.Create(Owner: TComponent; Count: integer); var i: integer; begin inherited Create(Owner); FActive := false; FCount := Count; SetLength(FRelay, Count); for i := Low(FRelay) to High(FRelay) do FRelay[i] := false; end; destructor TRelayBox.Destroy; begin inherited; end; procedure TRelayBox.Close; begin if FActive then begin ComPort.Clear; ComPort.Close; FActive := false; end; end; procedure TRelayBox.DoCmd(Cmd: string); // Cmdの内容を解析しながら送る begin if FActive then DoDoCmd(Cmd, true); end; procedure TRelayBox.DoDoCmd(Cmd: string; recursive: boolean); // Cmdの内容を解析しながら送る var b: boolean; i,j: integer; s,s1, s2,sz: string; begin try s1 := Copy(s, 1, 1); s2 := Copy(s, 1, 4); if (s1 = 'Y') then begin TryStrToInt(Copy(s, 2, 1), j); if Copy(s, 3, 1) = '1' then b := true else b := false; // Relay.SetRelay(j - 1, b); ComPort.SendStr(s + #13); end; finally end; end; function TRelayBox.GetBaudRate: string; begin result := Comport.BaudRate; end; function TRelayBox.GetDataBits: string; begin result := ComPort.DataBits; end; function TRelayBox.GetFlowControl: string; begin result := ComPort.FlowControl; end; function TRelayBox.GetParity: string; begin result := ComPort.Parity; end; function TRelayBox.GetPort: string; begin result := ComPort.Port; end; function TRelayBox.GetRelay(Index: integer): boolean; begin if FEnable and (Index <= FCount) then result := FRelay[Index] else result := false; end; function TRelayBox.GetStopBits: string; begin result := ComPort.StopBits; end; procedure TRelayBox.Open; begin if FEnable and not FActive then begin Comport.Delimiter := #10; // GS232用固定 Comport.TriggersOnRxChar := false; // Comport.OnRecvMsg := GetDirectionOnRx; // RTX-59,GS-232共通化するため使わない // Comport.OnException := ComException; // ComPort.OnError := ComError; ComPort.Open; ComPort.Clear; FActive := true; end; end; procedure TRelayBox.SetAvtive(const Value: boolean); begin if Value <> FActive then if Value then Open else Close; end; procedure TRelayBox.SetBaudRate(const Value: string); begin ComPort.BaudRate := Value; end; procedure TRelayBox.SetDataBits(const Value: string); begin ComPort.DataBits := Value; end; procedure TRelayBox.SetEnable(const Value: boolean); begin if not FActive then FEnable := Value; end; procedure TRelayBox.SetFlowControl(const Value: string); begin ComPort.FlowControl := Value; end; procedure TRelayBox.SetParity(const Value: string); begin ComPort.Parity := Value; end; procedure TRelayBox.SetPort(const Value: string); begin ComPort.Port := Value; end; procedure TRelayBox.SetRelay(Index: integer; const Value: boolean); begin if not FActive then exit; if (Index < Low(FRelay)) or (Index > High(FRelay)) then exit; if Value <> Relay[Index] then begin FRelay[Index] := value; if Assigned(FChangeRelay) then FChangeRelay(self, Index, Value); if Assigned(FChangeRelays) then FChangeRelays(self); end; end; procedure TRelayBox.SetStopBits(const Value: string); begin ComPort.StopBits := Value; end; function TRelayBox.MakeSendMess: string; var i: integer; b: byte; begin b := 0; for i := 0 to 7 do begin b := b shl 1; if FRelay[i] then b := b or 1; end; result := chr(b); end; end.
unit uActionFactory_b; interface uses uQueryServer_a, uQueryCommon_a; type TActionFactory_b = class(TActionFactory_a) private FCurrRequestPart: string; public property CurrRequestPart: string read FCurrRequestPart; procedure AddRequestActions(AActions: TFiFoActionQueue_a); override; end; implementation uses uStubManager_a, uConst_h, uTestActions, uDbActions, uTriggerAction, uCommonActions, Variants; //---------------------------------------------------------------------------- // N,PS: procedure TActionFactory_b.AddRequestActions(AActions: TFiFoActionQueue_a); function nGetPartToProcess(...): string; var lRequest: TMessage_a; begin lRequest := StubManager.GetServerStub.GetRequestReference(...); if lRequest.GetParamValue(CRequests) = Unassigned then raise EIntern.fire(self, 'Invalid reaquest: CRequests not defined'); if not lRequest.ParamById[CRequests].DeQValElem(Result) then raise EIntern.Fire(Self, 'Request empty'); end; begin // no inherited (abstract); if AActions = nil then raise EIntern.fire(self, 'Param = nil'); FCurrRequestPart := nGetPartToProcess(...); if CurrRequestPart = CTest then AActions.EnQueue(TTestAction) else if CurrRequestPart = CDatabaseLoad then AActions.EnQueue(TDbLoadAction) ... else if CurrRequestPart = CFinishFetchExternalData then AActions.EnQueue(TFinishExternalDataFetchAction); end; end.
unit ncHttp; interface uses SysUtils, Classes, IdTCPConnection, IdTCPClient, IdHTTP, IdMultipartFormData; type ThttpThreadGet = class ( TThread ) protected procedure Execute; override; public FAddChaveSeg: Boolean; FUrl, FParams, FRes : String; FRetryOnErro : Boolean; constructor Create(aURL, aParams: String; aAddChaveSeg, aRetryOnErro: Boolean); destructor Destroy; override; property Res: String read FRes; end; ThttpThreadPost= class ( TThread ) private FUrl : String; FMS : TIdMultiPartFormDataStream; FRes : String; FMaxTries: Byte; protected procedure Execute; override; function _Post: Boolean; public constructor Create(aUrl: String; aMS: TidMultiPartFormDataStream; const aMaxTries: Byte = 1); destructor Destroy; override; property Res: String read FRes; end; function httpPost(aURL, aParams: String): String; function httpGet(aURL: String; aParams: String = ''; const aAddChaveSeg: Boolean = False): String; function threadGetJaExiste(aUrl, aParams: String): Boolean; function httpThreadGet(aURL: String; aParams: String = ''; aOnTerminate: TNotifyEvent = nil; const aAddChaveSeg: Boolean = False; const aUnique: Boolean = False; const aRetryOnErro: Boolean = False): Boolean; function MesmaURL(A, B: String): Boolean; function httpGetChaveSeg: String; var gThreadGets : TThreadList; implementation uses uNR_chaveseg, ncDebug, ncClassesBase, nexUrls; function threadGetJaExiste(aUrl, aParams: String): Boolean; var I : Integer; begin with gThreadGets.LockList do try for I := 0 to Count-1 do with ThttpThreadGet(Items[I]) do if SameText(aUrl, FUrl) and SameText(aParams, FParams) then begin Result := True; Exit; end; Result := False; finally gThreadGets.UnlockList; end; end; function httpThreadGet(aURL: String; aParams: String = ''; aOnTerminate: TNotifyEvent = nil; const aAddChaveSeg: Boolean = False; const aUnique: Boolean = False; const aRetryOnErro: Boolean = False): Boolean; begin Result := False; if aUnique and threadGetJaExiste(aUrl, aParams) then Exit; with ThttpThreadGet.Create(aUrl, aParams, aAddChaveSeg, aRetryOnErro) do begin OnTerminate := aOnTerminate; Resume; end; Result := True; end; function MesmaURL(A, B: String): Boolean; function NormURL(S: String): String; begin if pos('http://', S)=1 then Delete(S, 1, 7); if pos('www.', S)=1 then Delete(S, 1, 4); if Copy(S, Length(S), 1)='/' then Delete(S, Length(S), 1); end; begin A := LowerCase(A); B := LowerCase(B); Result := SameText(NormURL(A), NormURL(B)); end; function httpGetChaveSeg: String; begin Result := httpGet(gUrls.Url('contas_obtemchaveseg')); end; function httpPost(aURL, aParams: String): String; var H : TidHttp; sl : TStrings; i : integer; begin try H := TidHttp.Create(nil); sl := TStringList.Create; try H.HandleRedirects := True; sl.Text := aParams; for I := 0 to sl.Count - 1 do sl.ValueFromIndex[i] := AnsiToUTF8(sl.ValueFromIndex[i]); Result := H.Post(aUrl, sl); finally H.Free; sl.Free; end; except end; end; function httpGet(aURL: String; aParams: String = ''; const aAddChaveSeg: Boolean = False): String; var H : TidHttp; S : String; begin if aAddChaveSeg then begin S := 'chaveseg='+httpGetChaveSeg+'&senhaseg='+geraSenhaSeg(S); if aParams>'' then aParams := aParams+'&'+S else aParams := S; end; try H := TidHttp.Create(nil); try H.HandleRedirects := True; if Trim(aParams)>'' then aUrl := AddParamUrl(aUrl, aParams); Result := H.Get(aUrl); finally H.Free; end; except end; end; { ThttpThreadGet } constructor ThttpThreadGet.Create(aURL, aParams: String; aAddChaveSeg, aRetryOnErro: Boolean); begin inherited Create(True); FreeOnTerminate := True; FUrl := aURL; FParams := aParams; FAddChaveSeg := aAddChaveSeg; FRes := ''; FRetryOnErro := aRetryOnErro; gThreadGets.Add(Self); end; destructor ThttpThreadGet.Destroy; begin gThreadGets.Remove(Self); inherited; end; procedure ThttpThreadGet.Execute; var OK: Boolean; aNext: Cardinal; aInc : Cardinal; procedure _Get; begin FRes := httpGet(FURL, FParams, FAddChaveSeg); end; procedure _RaiseOnErro; var sl : TStrings; begin if not FRetryOnErro then Exit; sl := TStringList.Create; try if (sl.Values['erro']>'') and (sl.Values['erro']<>'0') then raise exception.Create('Erro: '+sl.Values['erro']); finally sl.Free; end; end; begin Ok := False; aNext := 0; aInc := 5000; repeat if GetTickCount>=aNext then begin try _Get; _RaiseOnErro; Ok := True; except on E: Exception do begin aInc := aInc * 2; aNext := GetTickCount + aInc; DebugMsg('ThttpThreadGet.Execute - Exception - '+E.ClassName+': '+E.Message); end; end; end else Sleep(100); until Ok or Terminated or ncClassesBase.EncerrarThreads; end; { ThttpThreadPost } constructor ThttpThreadPost.Create(aUrl: String; aMS: TidMultiPartFormDataStream; const aMaxTries: Byte = 1); begin inherited Create(True); FreeOnTerminate := True; FUrl := aURL; FRes := ''; FMS := aMS; FMaxTries := aMaxTries; end; destructor ThttpThreadPost.Destroy; begin FMS.Free; inherited; end; procedure ThttpThreadPost.Execute; var T: Byte; aNext, aInc : Cardinal; begin Sleep(0); T := 0; aNext := 0; aInc := 5000; repeat if GetTickCount>=aNext then begin Inc(T); if _Post then T := FMaxTries else if T<FMaxTries then begin aInc := aInc * 2; aNext := GetTickCount + aInc; end; end; if T<FMaxTries then Sleep(5000); until (T>=FMaxTries) or Terminated or EncerrarThreads; end; function ThttpThreadPost._Post: Boolean; var H : TidHttp; begin result := False; H := nil; try H := TidHttp.Create; try H.HandleRedirects := True; FRes := H.Post(FUrl, FMS); Result := True; DebugMsg('ThttpThreadPost.Execute OK - Url: '+FUrl+' - Resultado: '+FRes); finally H.Free; end; except on E: Exception do begin DebugMsg('ThtttpThreadPost.Execute Exception: - Url: '+FUrl+' - ClassName: '+E.ClassName+' - Erro: '+E.Message); FRes := E.Message; end; end; end; initialization gThreadGets := TThreadList.Create; finalization gThreadGets.Free; end.
unit uNamedPipes; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type PTrustee = ^TTrustee; TTrustee = record pMultipleTrustee: PTrustee; MultipleTrusteeOperation: DWORD; TrusteeForm: DWORD; TrusteeType: DWORD; ptstrName: PAnsiChar; end; TExplicitAccess = record grfAccessPermissions: DWORD; grfAccessMode: DWORD; grfInheritance: DWORD; Trustee: TTrustee; end; function VerifyChild(hPipe: THandle): Boolean; function VerifyParent(hPipe: THandle): Boolean; function GetCurrentUserSID(var SID: TBytes): Boolean; implementation uses JwaWinNT, Windows, uProcessInfo, uDebug; var GetNamedPipeClientProcessId: function(Pipe: HANDLE; ClientProcessId: PULONG): BOOL; stdcall; function VerifyChild(hPipe: HANDLE): Boolean; var ClientProcessId: ULONG; begin if GetNamedPipeClientProcessId(hPipe, @ClientProcessId) then begin // Allow to connect from child process and same executable only if GetCurrentProcessId = GetParentProcessId(ClientProcessId) then begin DCDebug('My: ', GetProcessFileName(GetCurrentProcess)); DCDebug('Client: ', GetProcessFileNameEx(ClientProcessId)); if UnicodeSameText(GetProcessFileName(GetCurrentProcess), GetProcessFileNameEx(ClientProcessId)) then Exit(True); end; end; Result:= False; end; function VerifyParent(hPipe: HANDLE): Boolean; var ClientProcessId: ULONG; begin if GetNamedPipeClientProcessId(hPipe, @ClientProcessId) then begin // Allow to connect from parent process and same executable only if ClientProcessId = GetParentProcessId(GetCurrentProcessId) then begin DCDebug('My: ', GetProcessFileName(GetCurrentProcess)); DCDebug('Client: ', GetProcessFileNameEx(ClientProcessId)); if UnicodeSameText(GetProcessFileName(GetCurrentProcess), GetProcessFileNameEx(ClientProcessId)) then Exit(True); end; end; Result:= False; end; function GetCurrentUserSID(var SID: TBytes): Boolean; var ReturnLength: DWORD = 0; TokenHandle: HANDLE = INVALID_HANDLE_VALUE; TokenInformation: array [0..SECURITY_MAX_SID_SIZE] of Byte; UserToken: TTokenUser absolute TokenInformation; begin Result:= OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, TokenHandle); if not Result then begin if GetLastError = ERROR_NO_TOKEN then Result:= OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, TokenHandle); end; if Result then begin Result:= GetTokenInformation(TokenHandle, TokenUser, @TokenInformation, SizeOf(TokenInformation), ReturnLength); CloseHandle(TokenHandle); if Result then begin SetLength(SID, GetLengthSid(UserToken.User.Sid)); CopySid(Length(SID), PSID(@SID[0]), UserToken.User.Sid); end; end; end; initialization Pointer(GetNamedPipeClientProcessId):= GetProcAddress(GetModuleHandleW(kernel32), 'GetNamedPipeClientProcessId'); end.
unit Player.AudioOutput.AllTypes; interface uses Windows,SysUtils,Classes,Graphics,SyncObjs, Player.AudioOutput.Base,MediaProcessing.Definitions; type TPlayerAudioOutput_AllTypes = class (TPlayerAudioOutputWaveOut) protected function GetStreamTypeHandlerClass(aType: TStreamType): TAudioOutputDecoderClass; override; public constructor Create; override; end; implementation uses Player.AudioOutput.PCM, Player.AudioOutput.PCMU, {$IFNDEF DISABLE_HH} Player.AudioOutput.HH, {$ENDIF} Player.AudioOutput.ACM; { TPlayerAudioOutput_AllTypes } constructor TPlayerAudioOutput_AllTypes.Create; begin inherited Create; RegisterDecoderClass(stPCM,TAudioOutputDecoder_PCM); RegisterDecoderClass(stPCMU,TAudioOutputDecoder_PCMU); {$IFNDEF DISABLE_HH} RegisterDecoderClass(stHHAU,TAudioOutputDecoder_HH); {$ENDIF} // SetStreamType(stHH); end; function TPlayerAudioOutput_AllTypes.GetStreamTypeHandlerClass( aType: TStreamType): TAudioOutputDecoderClass; begin result:=inherited GetStreamTypeHandlerClass(aType); if result=nil then result:=TAudioOutputDecoder_ACM; end; end.
unit Thread.Trim.Helper.Device; interface uses SysUtils, Windows, OSFile, OSFile.ForInternal, Getter.PartitionExtent, CommandSet, CommandSet.Factory; type TPendingTrimOperation = record IsUnusedSpaceFound: Boolean; StartLBA: UInt64; LengthInLBA: UInt64; end; TDeviceTrimmer = class(TOSFileForInternal) private PendingTrimOperation: TPendingTrimOperation; CommandSet: TCommandSet; function GetMotherDrivePath: String; procedure SetCommandSet; public constructor Create(const FileToGetAccess: String); override; destructor Destroy; override; procedure Flush; procedure SetStartPoint(StartLBA, LengthInLBA: UInt64); procedure IncreaseLength(LengthInLBA: UInt64); function IsUnusedSpaceFound: Boolean; function IsLBACountOverLimit: Boolean; end; implementation { TDeviceTrimmer } constructor TDeviceTrimmer.Create(const FileToGetAccess: String); begin inherited; SetCommandSet; ZeroMemory(@PendingTrimOperation, SizeOf(PendingTrimOperation)); end; destructor TDeviceTrimmer.Destroy; begin FreeAndNil(CommandSet); inherited; end; procedure TDeviceTrimmer.SetCommandSet; begin if CommandSet <> nil then exit; CommandSet := CommandSetFactory.GetSuitableCommandSet(GetMotherDrivePath); CommandSet.IdentifyDevice; end; function TDeviceTrimmer.GetMotherDrivePath: String; var PartitionExtentGetter: TPartitionExtentGetter; PartitionExtentList: TPartitionExtentList; begin PartitionExtentGetter := TPartitionExtentGetter.Create(GetPathOfFileAccessing); PartitionExtentList := PartitionExtentGetter.GetPartitionExtentList; result := ThisComputerPrefix + PhysicalDrivePrefix + IntToStr(PartitionExtentList[0].DriveNumber); FreeAndNil(PartitionExtentList); FreeAndNil(PartitionExtentGetter); end; procedure TDeviceTrimmer.SetStartPoint(StartLBA, LengthInLBA: UInt64); begin PendingTrimOperation.IsUnusedSpaceFound := true; PendingTrimOperation.StartLBA := StartLBA; PendingTrimOperation.LengthInLBA := LengthInLBA; end; procedure TDeviceTrimmer.IncreaseLength(LengthInLBA: UInt64); begin PendingTrimOperation.LengthInLBA := PendingTrimOperation.LengthInLBA + LengthInLBA; end; procedure TDeviceTrimmer.Flush; begin CommandSet.DataSetManagement( PendingTrimOperation.StartLBA, PendingTrimOperation.LengthInLBA); ZeroMemory(@PendingTrimOperation, SizeOf(PendingTrimOperation)); end; function TDeviceTrimmer.IsLBACountOverLimit: Boolean; const LimitLengthInLBA = 65500; begin result := PendingTrimOperation.LengthInLBA > LimitLengthInLBA; end; function TDeviceTrimmer.IsUnusedSpaceFound: Boolean; begin result := PendingTrimOperation.IsUnusedSpaceFound; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: Q3BSP<p> Simple Quake III BSP file loader.<p> <b>History : </b><font size=-1><ul> <li>16/10/08 - UweR - Compatibility fix for Delphi 2009 <li>30/01/03 - Egg - Creation, based on Philip Stefou's document and bits from Jan Horn's loader </ul></font> } unit Q3BSP; interface uses Classes, GLVectorTypes; const FACE_POLYGON = 1; const MAX_TEXTURES = 1000; type TBSPHeader = record StrID : array [0..3] of AnsiChar; // This should always be 'IBSP' Version : Integer; // This should be 0x2e for Quake 3 files end; TBSPLump = record Offset : Integer; // The offset into the file for the start of this lump Length : Integer; // The length in bytes for this lump end; TBSPBBox = array [0..5] of Integer; TBSPNode = record Plane : Integer; // Space partitioning plane Children : array [0..1] of Integer; // Back and front child nodes BBox : TBSPBBox; // Bounding box of node end; TBSPLeaf = record Cluster : Integer; // Visibility cluster number Area : Integer; // Volume of the leaf BBox : TBSPBBox; // Bounding box of leaf FirstFace, NumFaces : Integer; // Lookup for the face list (indexes are for faces) FirstBrush, NumBrushes : Integer; // Lookup for the brush list (indexes are for brushes) end; TBSPModel = record BBox : TBSPBBox; // Bounding box of model FirstFace, NumFaces : Integer; // Lookup for the face list (indexes are for faces) FirstBrush, NumBrushes : Integer; // Lookup for the brush list (indexes are for brushes) end; TBSPVertex = record Position : TVector3f; // (x, y, z) position. TextureCoord : TVector2f; // (u, v) texture coordinate LightmapCoord : TVector2f; // (u, v) lightmap coordinate Normal : TVector3f; // (x, y, z) normal vector Color : array [0..3] of Byte // RGBA color for the vertex end; PBSPVertex = ^TBSPVertex; TBSPFace = record textureID : Integer; // The index into the texture array effect : Integer; // The index for the effects (or -1 = n/a) FaceType : Integer; // 1=polygon, 2=patch, 3=mesh, 4=billboard startVertIndex : Integer; // The starting index into this face's first vertex numOfVerts : Integer; // The number of vertices for this face meshVertIndex : Integer; // The index into the first meshvertex numMeshVerts : Integer; // The number of mesh vertices lightmapID : Integer; // The texture index for the lightmap lMapCorner : array [0..1] of Integer; // The face's lightmap corner in the image lMapSize : array [0..1] of Integer; // The size of the lightmap section lMapPos : TVector3f; // The 3D origin of lightmap. lMapVecs : array [0..1] of TVector3f; // The 3D space for s and t unit vectors. vNormal : TVector3f; // The face normal. Size : array [0..1] of Integer; // The bezier patch dimensions. end; PBSPFace = ^TBSPFace; TBSPTexture = record TextureName : array [0..63] of AnsiChar; // The name of the texture w/o the extension flags : Integer; // The surface flags (unknown) contents : Integer; // The content flags (unknown) end; PBSPTexture = ^TBSPTexture; TBSPLightmap = record imageBits : array [0..49151] of Byte; // The RGB data in a 128x128 image end; PBSPLightmap = ^TBSPLightmap; TBSPVisData = record numOfClusters : Integer; bytesPerCluster : Integer; bitSets : array of Byte; end; // TQ3BSP // TQ3BSP = class (TObject) public { Public Declarations } Header : TBSPHeader; Lumps : array of TBSPLump; NumOfVerts : Integer; NumOfNodes : Integer; NumOfPlanes : Integer; NumOfLeaves : Integer; NumOfFaces : Integer; NumOfTextures : Integer; NumOfLightmaps : Integer; Vertices : array of TBSPVertex; Nodes : array of TBSPNode; Planes : array of TVector4f; Leaves : array of TBSPLeaf; Faces : array of TBSPFace; Textures : array of TBSPTexture; // texture names (without extension) Lightmaps : array of TBSPLightmap; VisData : TBSPVisData; constructor Create(bspStream : TStream); end; const kEntities = 0; // Stores player/object positions, etc... kTextures = 1; // Stores texture information kPlanes = 2; // Stores the splitting planes kNodes = 3; // Stores the BSP nodes kLeafs = 4; // Stores the leafs of the nodes kLeafFaces = 5; // Stores the leaf's indices into the faces kLeafBrushes = 6; // Stores the leaf's indices into the brushes kModels = 7; // Stores the info of world models kBrushes = 8; // Stores the brushes info (for collision) kBrushSides = 9; // Stores the brush surfaces info kVertices = 10; // Stores the level vertices kMeshVerts = 11; // Stores the model vertices offsets kShaders = 12; // Stores the shader files (blending, anims..) kFaces = 13; // Stores the faces for the level kLightmaps = 14; // Stores the lightmaps for the level kLightVolumes= 15; // Stores extra world lighting information kVisData = 16; // Stores PVS and cluster info (visibility) kMaxLumps = 17; // A constant to store the number of lumps // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses SysUtils; // ------------------ // ------------------ TQ3BSP ------------------ // ------------------ // Create // constructor TQ3BSP.Create(bspStream : TStream); begin SetLength(Lumps, kMaxLumps); // Read in the header and lump data bspStream.Read(Header, SizeOf(Header)); bspStream.Read(Lumps[0], kMaxLumps*SizeOf(TBSPLump)); NumOfNodes:=Round(lumps[kNodes].length/SizeOf(TBSPNode)); SetLength(Nodes, NumOfNodes); bspStream.Position:=lumps[kNodes].offset; bspStream.Read(Nodes[0], NumOfNodes*SizeOf(TBSPNode)); NumOfPlanes:=Round(lumps[kPlanes].length/SizeOf(TVector4f)); SetLength(Planes, NumOfPlanes); bspStream.Position:=lumps[kPlanes].offset; bspStream.Read(Planes[0], NumOfPlanes*SizeOf(TVector4f)); NumOfLeaves:=Round(lumps[kLeafs].length/SizeOf(TBSPLeaf)); SetLength(Leaves, NumOfLeaves); bspStream.Position:=lumps[kLeafs].offset; bspStream.Read(Leaves[0], NumOfLeaves*SizeOf(TBSPLeaf)); NumOfVerts:=Round(lumps[kVertices].length/SizeOf(TBSPVertex)); SetLength(Vertices, numOfVerts); bspStream.Position:=lumps[kVertices].offset; bspStream.Read(Vertices[0], numOfVerts*SizeOf(TBSPVertex)); numOfFaces:=Round(lumps[kFaces].length/SizeOf(TBSPFace)); SetLength(Faces, numOfFaces); bspStream.Position:=lumps[kFaces].offset; bspStream.Read(Faces[0], numOfFaces*SizeOf(TBSPFace)); NumOfTextures:=Round(lumps[kTextures].length/SizeOf(TBSPTexture)); SetLength(Textures, NumOfTextures); bspStream.Position:=lumps[kTextures].offset; bspStream.Read(Textures[0], NumOfTextures*SizeOf(TBSPTexture)); NumOfLightmaps:=Round(lumps[kLightmaps].length/SizeOf(TBSPLightmap)); SetLength(Lightmaps, NumOfLightmaps); bspStream.Position:=lumps[kLightmaps].offset; bspStream.Read(Lightmaps[0], NumOfLightmaps*SizeOf(TBSPLightmap)); bspStream.Position:=lumps[kVisData].offset; bspStream.Read(VisData.numOfClusters, SizeOf(Integer)); bspStream.Read(VisData.bytesPerCluster, SizeOf(Integer)); if VisData.numOfClusters*VisData.bytesPerCluster>0 then begin SetLength(VisData.bitSets, VisData.numOfClusters*VisData.bytesPerCluster); bspStream.Read(VisData.bitSets[0], VisData.numOfClusters*VisData.bytesPerCluster); end; end; end.
unit MediaStream.PtzProtocol.HH; interface uses SysUtils, MediaStream.PtzProtocol.Base,MediaServer.Net.Ms3s.Stream, HHCommon,HHNet,HHNetAPI; type TPtzProtocol_HH = class (TPtzProtocol) private FServer : THHNetServer; FChannelNo: integer; procedure CheckValid; public procedure Init(aServer: THHNetServer; aChannelNo: integer); procedure PtzApertureDecrease(aDuration: cardinal); override; procedure PtzApertureDecreaseStop; override; procedure PtzApertureIncrease(aDuration: cardinal); override; procedure PtzApertureIncreaseStop; override; procedure PtzFocusIn(aDuration: cardinal); override; procedure PtzFocusInStop; override; procedure PtzFocusOut(aDuration: cardinal); override; procedure PtzFocusOutStop; override; procedure PtzZoomIn(aDuration: cardinal); override; procedure PtzZoomInStop; override; procedure PtzZoomOut(aDuration: cardinal); override; procedure PtzZoomOutStop; override; procedure PtzMoveDown(aDuration: cardinal; aSpeed: byte); override; procedure PtzMoveDownStop; override; procedure PtzMoveLeft(aDuration: cardinal; aSpeed: byte); override; procedure PtzMoveLeftStop; override; procedure PtzMoveRight(aDuration: cardinal; aSpeed: byte); override; procedure PtzMoveRightStop; override; procedure PtzMoveUp(aDuration: cardinal; aSpeed: byte); override; procedure PtzMoveUpStop; override; //===== Перемещение на заданную позицию //Движение на указанную точку-пресет procedure PtzMoveToPoint(aId: cardinal);override; //Движение в указанную позицию. Позиция указывается по оси X и Y в градусах procedure PtzMoveToPosition(const aPositionPan,aPositionTilt: double); override; end; implementation procedure TPtzProtocol_HH.CheckValid; begin if FServer=nil then raise Exception.Create('Не инициализирован канал'); end; procedure TPtzProtocol_HH.Init(aServer: THHNetServer; aChannelNo: integer); begin FServer:=aServer; FChannelNo:=aChannelNo; end; procedure TPtzProtocol_HH.PtzApertureDecrease; begin CheckValid; FServer.PtzApertureDecrease(FChannelNo); end; procedure TPtzProtocol_HH.PtzApertureDecreaseStop; begin CheckValid; FServer.PtzApertureDecreaseStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzApertureIncrease; begin CheckValid; FServer.PtzApertureIncrease(FChannelNo); end; procedure TPtzProtocol_HH.PtzApertureIncreaseStop; begin CheckValid; FServer.PtzApertureIncreaseStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzFocusIn; begin CheckValid; FServer.PtzFocusIn(FChannelNo); end; procedure TPtzProtocol_HH.PtzFocusInStop; begin CheckValid; FServer.PtzFocusInStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzFocusOut; begin CheckValid; FServer.PtzFocusOut(FChannelNo); end; procedure TPtzProtocol_HH.PtzFocusOutStop; begin CheckValid; FServer.PtzFocusOutStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzMoveDown(aDuration: cardinal; aSpeed: byte); begin CheckValid; FServer.PtzMoveDown(FChannelNo,aSpeed); end; procedure TPtzProtocol_HH.PtzMoveDownStop; begin CheckValid; FServer.PtzMoveDownStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzMoveLeft(aDuration: cardinal; aSpeed: byte); begin CheckValid; FServer.PtzMoveLeft(FChannelNo,aSpeed); end; procedure TPtzProtocol_HH.PtzMoveLeftStop; begin CheckValid; FServer.PtzMoveLeftStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzMoveRight(aDuration: cardinal; aSpeed: byte); begin CheckValid; FServer.PtzMoveRight(FChannelNo,aSpeed); end; procedure TPtzProtocol_HH.PtzMoveRightStop; begin CheckValid; FServer.PtzMoveRightStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzMoveToPoint(aId: cardinal); begin if aId>255 then raise Exception.Create('Недопустимый идентификатор точки'); FServer.PtzMoveToPreset(FChannelNo,aId); end; procedure TPtzProtocol_HH.PtzMoveToPosition(const aPositionPan, aPositionTilt: double); begin CheckValid; FServer.PtzMoveToPosition(FChannelNo,aPositionPan,aPositionTilt); end; procedure TPtzProtocol_HH.PtzMoveUp(aDuration: cardinal; aSpeed: byte); begin CheckValid; FServer.PtzMoveUp(FChannelNo,aSpeed); end; procedure TPtzProtocol_HH.PtzMoveUpStop; begin CheckValid; FServer.PtzMoveUpStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzZoomIn(aDuration: cardinal); begin CheckValid; FServer.PtzZoomIn(FChannelNo); end; procedure TPtzProtocol_HH.PtzZoomInStop; begin CheckValid; FServer.PtzZoomInStop(FChannelNo); end; procedure TPtzProtocol_HH.PtzZoomOut(aDuration: cardinal); begin CheckValid; FServer.PtzZoomOut(FChannelNo); end; procedure TPtzProtocol_HH.PtzZoomOutStop; begin CheckValid; FServer.PtzZoomOutStop(FChannelNo); end; end.
unit frame_message; {$mode objfpc} {$r *.lfm} interface uses Classes, SysUtils, FileUtil, LSControls, LResources, Forms, Controls, StdCtrls, ExtCtrls, ComCtrls, u_xpl_custom_message; type // TTMessageFrame ======================================================== TTMessageFrame = class(TFrame) cbMsgType: TLSComboBox; cbSchema: TLSComboBox; cbTarget: TLSComboBox; edtBody: TLSMemo; edtSource: TLSEdit; Image1: TImage; Image2: TImage; sbMessage: TStatusBar; procedure cbMsgTypeEditingDone(Sender: TObject); procedure cbSchemaEditingDone(Sender: TObject); procedure cbTargetEditingDone(Sender: TObject); procedure edtBodyEditingDone(Sender: TObject); procedure edtSourceEditingDone(Sender: TObject); private fMessage : TxPLCustomMessage; procedure Set_Message(const AValue: TxPLCustomMessage); procedure Set_ReadOnly(const AValue: boolean); procedure UpdateDisplay; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure SetTargets(const aValue : TStringList); published property TheMessage : TxPLCustomMessage read fMessage write Set_Message; property ReadOnly : boolean write Set_ReadOnly; end; implementation //============================================================== uses Graphics , u_xpl_header , u_xpl_schema , u_xpl_application , u_xpl_gui_resource , uxPLConst ; // TTMessageFrame ============================================================= constructor TTMessageFrame.Create(TheOwner: TComponent); var i : integer; begin inherited; fMessage := TxPLCustomMessage.Create(nil); for i := 0 to xPLApplication.VendorFile.Schemas.Count-1 do // Fill known schema list cbSchema.Items.Add(xPLApplication.VendorFile.Schemas[i].name); edtSource.Pattern := K_REGEXPR_ADDRESS; edtSource.ValidationType := vtExit; edtSource.FocusColor := clMoneyGreen; edtSource.ValidationColor := clGradientActiveCaption; cbTarget.Pattern := K_REGEXPR_TARGET; cbTarget.ValidationType := vtExit; cbTarget.FocusColor := clMoneyGreen; cbTarget.ValidationColor := clGradientActiveCaption; cbSchema.Pattern := K_REGEXPR_SCHEMA; cbSchema.ValidationType := vtExit; cbSchema.FocusColor := clMoneyGreen; cbSchema.ValidationColor := clGradientActiveCaption; edtBody.Pattern := K_RE_BODY_LINE; edtBody.ValidationType := vtExit; // edtBody.FocusColor := clMoneyGreen; // edtBody.ValidationColor := clGradientActiveCaption; cbMsgType.FocusColor := clMoneyGreen; cbMsgType.ValidationColor := clGradientActiveCaption; end; destructor TTMessageFrame.Destroy; begin fMessage.Free; inherited Destroy; end; procedure TTMessageFrame.edtSourceEditingDone(Sender: TObject); begin fMessage.source.RawxPL := edtSource.Caption; UpdateDisplay; end; procedure TTMessageFrame.cbTargetEditingDone(Sender: TObject); begin fMessage.target.RawxPL := cbTarget.Text; UpdateDisplay; end; procedure TTMessageFrame.edtBodyEditingDone(Sender: TObject); begin fMessage.Body.Strings := edtBody.Lines; UpdateDisplay; end; procedure TTMessageFrame.cbMsgTypeEditingDone(Sender: TObject); begin fMessage.MsgTypeAsStr := cbMsgType.Text; UpdateDisplay; end; procedure TTMessageFrame.cbSchemaEditingDone(Sender: TObject); begin fMessage.schema.RawxPL := cbSchema.Text; UpdateDisplay; end; procedure TTMessageFrame.UpdateDisplay; begin try Image2.Picture.LoadFromLazarusResource(fMessage.MsgTypeAsStr); Image1.Visible := (lazarusResources.Find(fMessage.schema.Classe)<>nil); // The ressource may not be present for the searched class of messages If Image1.Visible then Image1.Picture.LoadFromLazarusResource(fMessage.schema.Classe); SbMessage.Panels[3].Text := IntToStr(fMessage.Size); except end; end; procedure TTMessageFrame.Set_Message(const AValue: TxPLCustomMessage); begin fMessage.Assign(aValue); cbMsgType.Text := fMessage.MsgTypeAsStr; SbMessage.Panels[1].Text := IntToStr(fMessage.hop); SbMessage.Panels[5].Text := DateTimeToStr(fMessage.TimeStamp); edtSource.Caption := fMessage.Source.RawxPL; cbTarget.Caption := fMessage.Target.RawxPL; cbSchema.Text := fMessage.schema.RawxPL; edtBody.Lines.Assign(fMessage.Body.Strings); UpdateDisplay; end; procedure TTMessageFrame.Set_ReadOnly(const AValue: boolean); begin edtBody.ReadOnly := AValue; edtSource.ReadOnly := AValue; cbMsgType.ReadOnly := AValue; cbMsgType.Enabled := not AValue; end; procedure TTMessageFrame.SetTargets(const aValue: TStringList); begin cbTarget.Items.Assign(aValue); end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright (c) 1995,1996 Borland International } { } {*******************************************************} unit VcsIntf; { VCS Interface declarations } { This file defines the cooperative interface between the IDE and a VCS Manager DLL. The VCS Manager DLL must be named in the registry at startup time under the isVersionContol key, as the value for the ivVCSManager variable. As the IDE loads, it will load the specified DLL and attempt to obtain a proc address for the DLL's initialization function, which must be exported using the VCSManagerEntryPoint constant. } interface uses Windows, VirtIntf, ToolIntf; const isVersionControl = 'Version Control'; ivVCSManager = 'VCSManager'; VCSManagerEntryPoint = 'INITVCS0014'; type { The VCS client object should be returned by the VCS Manager DLL as the result of the init call. The IDE is responsible for freeing the client object before unloading the VCS Manager DLL. GetIDString - Called at initialization. Client should return a unique identification string. The following string is reserved for Borland use: Borland.StdVcs ExecuteVerb - Called when the user selects a verb from a menu. GetMenuName - Called to retrieve the name of the main menu item to be added to the application's menu bar. Return a blank string to indicate no menu. GetVerb - Called to retrieve the menu text for each verb. A verb may be returned as a blank string to create a seperator bar. GetVerbCount - Called to determine the number of available verbs. This function will not be called if the GetMenuName function returns a blank string (indicating no menu). GetVerbState - Called to determine the state of a particular verb. The return value is a bit field of various states. (See below for definition of bit values). ProjectChange - Called when there is any state change of the current project, i.e. when a project is destroyed or created. } TIVCSClient = class(TInterface) function GetIDString: string; virtual; stdcall; abstract; procedure ExecuteVerb(Index: Integer); virtual; stdcall; abstract; function GetMenuName: string; virtual; stdcall; abstract; function GetVerb(Index: Integer): string; virtual; stdcall; abstract; function GetVerbCount: Integer; virtual; stdcall; abstract; function GetVerbState(Index: Integer): Word; virtual; stdcall; abstract; procedure ProjectChange; virtual; stdcall; abstract; end; { A function matching this signature must be exported from the VCS Manager DLL. } TVCSManagerInitProc = function (VCSInterface: TIToolServices): TIVCSClient stdcall; { Bit flags for GetVerbState function } const vsEnabled = $01; { Verb enabled if set, otherwise disabled } vsChecked = $02; { Verb checked if set, otherwise cleared } implementation end.
unit Tests.Injection; interface uses DUnitX.TestFramework, System.Classes, System.SysUtils, Pattern.Command; {$M+} type [TestFixture] TestInjection_SingleParam = class(TObject) private FInteger101: integer; FStrings: TStringList; FOwnerComponent: TComponent; public [Setup] procedure Setup; [TearDown] procedure TearDown; published procedure ParameterStringList; procedure ParameterStringList_ToStringsProperty; procedure ParameterStringList_ToObjectProperty; procedure ParameterInteger; procedure ParameterBoolean; procedure ParameterDouble; procedure ParameterDateTime; procedure ParameterWord; procedure ParameterValueBoolean; procedure ParameterValueFloat; procedure ParameterValueInt; procedure ParameterInterface; procedure UnsupportedProperty_Exception; end; [TestFixture] TestInjection_MultipleParams = class(TObject) private FStrings1: TStringList; FStrings2: TStringList; FOwnerComponent: TComponent; public [Setup] procedure Setup; [TearDown] procedure TearDown; published procedure TwoStringLists; procedure InjectAll; end; implementation // ------------------------------------------------------------------------ // sample interfaces injected into components // ------------------------------------------------------------------------ type ISample1 = interface (IInvokable) ['{AB5F0562-A0E6-4E93-910C-DD592FF02ADE}'] function GetValue: integer; end; ISample2 = interface (IInvokable) ['{D0562FD6-5393-4CA8-8285-46308C21B532}'] function GetValue(aValue: integer): integer; end; TSampleClass = class (TInterfacedObject,ISample1) function GetValue: integer; end; TAnotherClass = class (TInterfacedObject,ISample2) function GetValue(aValue: integer): integer; end; function TSampleClass.GetValue: integer; begin Exit(0); end; function TAnotherClass.GetValue(aValue: integer): integer; begin Result := aValue; end; // ------------------------------------------------------------------------ // sample components used in the tests // ------------------------------------------------------------------------ type TStringsComponent = class(TComponent) strict private FStringList: TStringList; FStrings: TStrings; FSameObject: TObject; published property StringList: TStringList read FStringList write FStringList; property Strings: TStrings read FStrings write FStrings; property SameObject: TObject read FSameObject write FSameObject; end; TIntegerComponent = class(TComponent) strict private FNumber: integer; published property Number: integer read FNumber write FNumber; end; TSimpleComponent = class(TComponent) strict private FNumber: integer; FIsTrue: boolean; FFloatNumber: Double; FStartDate: TDateTime; FSample1: ISample1; published property Number: integer read FNumber write FNumber; property IsTrue: boolean read FIsTrue write FIsTrue; property FloatNumber: Double read FFloatNumber write FFloatNumber; property StartDate: TDateTime read FStartDate write FStartDate; property Sample1: ISample1 read FSample1 write FSample1; end; // ------------------------------------------------------------------------ // tests: inject single parameter // ------------------------------------------------------------------------ procedure TestInjection_SingleParam.Setup; begin FOwnerComponent := TComponent.Create(nil); // used as Owner for TCommand-s FStrings := TStringList.Create(); FInteger101 := 101; end; procedure TestInjection_SingleParam.TearDown; begin FOwnerComponent.Free; FreeAndNil(FStrings); end; procedure TestInjection_SingleParam.ParameterStringList; var StringsComponent: TStringsComponent; begin StringsComponent := TStringsComponent.Create(FOwnerComponent); TComponentInjector.InjectProperties(StringsComponent, [FStrings]); Assert.IsNotNull(StringsComponent.StringList); Assert.AreSame(FStrings, StringsComponent.StringList); end; procedure TestInjection_SingleParam.ParameterStringList_ToStringsProperty; var StringsComponent: TStringsComponent; FStrings2: TStringList; begin StringsComponent := TStringsComponent.Create(FOwnerComponent); FStrings2 := TStringList.Create; try TComponentInjector.InjectProperties(StringsComponent, [FStrings,FStrings2]); Assert.IsNotNull(StringsComponent.Strings); Assert.AreSame(FStrings2, StringsComponent.Strings); finally FStrings2.Free; end; end; procedure TestInjection_SingleParam.ParameterStringList_ToObjectProperty; var StringsComponent: TStringsComponent; FStrings2: TStringList; FStrings3: TStringList; begin StringsComponent := TStringsComponent.Create(FOwnerComponent); FStrings2 := TStringList.Create; FStrings3 := TStringList.Create; try TComponentInjector.InjectProperties(StringsComponent, [FStrings,FStrings2,FStrings3]); Assert.IsNotNull(StringsComponent.SameObject); Assert.AreSame(FStrings3, StringsComponent.SameObject); finally FStrings2.Free; FStrings3.Free; end; end; procedure TestInjection_SingleParam.ParameterInteger; var IntegerComponent: TIntegerComponent; begin IntegerComponent := TIntegerComponent.Create(FOwnerComponent); TComponentInjector.InjectProperties(IntegerComponent, [FInteger101]); Assert.AreEqual(FInteger101, IntegerComponent.Number); end; procedure TestInjection_SingleParam.ParameterBoolean; var SimpleComponent: TSimpleComponent; b: boolean; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); b := True; TComponentInjector.InjectProperties(SimpleComponent, [b]); Assert.AreEqual(b, SimpleComponent.IsTrue); end; procedure TestInjection_SingleParam.ParameterDouble; var SimpleComponent: TSimpleComponent; val: Double; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); val := Pi; TComponentInjector.InjectProperties(SimpleComponent, [val]); Assert.AreEqual(val, SimpleComponent.FloatNumber); end; procedure TestInjection_SingleParam.ParameterDateTime; var SimpleComponent: TSimpleComponent; FloatVal: Single; Date: TDateTime; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); FloatVal := 2.1; Date := EncodeDate(2019, 02, 01) + EncodeTime(18, 50, 0, 0); TComponentInjector.InjectProperties(SimpleComponent, [FloatVal, Date]); Assert.AreEqual(Double(FloatVal), SimpleComponent.FloatNumber); Assert.AreEqual(Date, SimpleComponent.StartDate); end; procedure TestInjection_SingleParam.ParameterWord; var SimpleComponent: TSimpleComponent; Value: word; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); Value := 999; TComponentInjector.InjectProperties(SimpleComponent, [Value]); Assert.AreEqual(999, SimpleComponent.Number); end; procedure TestInjection_SingleParam.ParameterValueBoolean; var SimpleComponent: TSimpleComponent; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); TComponentInjector.InjectProperties(SimpleComponent, [True]); Assert.AreEqual(True, SimpleComponent.IsTrue); end; procedure TestInjection_SingleParam.ParameterValueInt; var SimpleComponent: TSimpleComponent; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); TComponentInjector.InjectProperties(SimpleComponent, [55]); Assert.AreEqual(55, SimpleComponent.Number); end; procedure TestInjection_SingleParam.ParameterValueFloat; var SimpleComponent: TSimpleComponent; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); TComponentInjector.InjectProperties(SimpleComponent, [99.99]); Assert.AreEqual(99.99, Extended(SimpleComponent.FloatNumber)); end; procedure TestInjection_SingleParam.ParameterInterface; var SimpleComponent: TSimpleComponent; sample1: ISample1; begin SimpleComponent := TSimpleComponent.Create(FOwnerComponent); sample1 := TSampleClass.Create; TComponentInjector.InjectProperties(SimpleComponent, [sample1]); Assert.IsTrue(SimpleComponent.Sample1 = sample1); end; procedure TestInjection_SingleParam.UnsupportedProperty_Exception; type TMyRec = record a: integer; b: boolean; end; var aRec1: TMyRec; StringsComponent: TStringsComponent; begin StringsComponent := TStringsComponent.Create(FOwnerComponent); Assert.WillRaise( procedure begin TComponentInjector.InjectProperties(StringsComponent, [@aRec1]); end); end; // ------------------------------------------------------------------------ // Test_MoreInjections - tests component with many injected properties // * 2x TStringList, 1x TComponent // ------------------------------------------------------------------------ type TManyPropComponent = class(TComponent) strict private FCount: integer; FEvenLines: TStringList; FOddLines: TStringList; FComponent: TComponent; FStream: TStream; FSample1: ISample1; FSample2: ISample2; public property Count: integer read FCount write FCount; property Stream: TStream read FStream write FStream; published property OddLines: TStringList read FOddLines write FOddLines; property Component: TComponent read FComponent write FComponent; property Sample1: ISample1 read FSample1 write FSample1; property EvenLines: TStringList read FEvenLines write FEvenLines; property Sample2: ISample2 read FSample2 write FSample2; end; procedure TestInjection_MultipleParams.Setup; begin FStrings1 := TStringList.Create; FStrings2 := TStringList.Create; FOwnerComponent := TComponent.Create(nil); end; procedure TestInjection_MultipleParams.TearDown; begin FreeAndNil(FStrings1); FreeAndNil(FStrings2); FreeAndNil(FOwnerComponent); end; procedure TestInjection_MultipleParams.TwoStringLists; var ManyPropComponent: TManyPropComponent; begin // -- ManyPropComponent := TManyPropComponent.Create(FOwnerComponent); // -- TComponentInjector.InjectProperties(ManyPropComponent, [FStrings1, FStrings2]); // -- Assert.AreSame(FStrings1, ManyPropComponent.OddLines); Assert.AreSame(FStrings2, ManyPropComponent.EvenLines); end; procedure TestInjection_MultipleParams.InjectAll; var ManyPropComponent: TManyPropComponent; sample1: ISample1; sample2: ISample2; begin // Arrange: ManyPropComponent := TManyPropComponent.Create(FOwnerComponent); sample1 := TSampleClass.Create; sample2 := TAnotherClass.Create; // Act: TComponentInjector.InjectProperties(ManyPropComponent, [FStrings1, FStrings2, FOwnerComponent, sample2, sample1]); // Assert Assert.AreSame(FStrings1, ManyPropComponent.OddLines); Assert.AreSame(FStrings2, ManyPropComponent.EvenLines); Assert.AreSame(FOwnerComponent, ManyPropComponent.Component); Assert.AreSame(sample1, ManyPropComponent.Sample1); Assert.AreSame(sample2, ManyPropComponent.Sample2); Assert.AreEqual(99, ManyPropComponent.Sample2.GetValue(99)); end; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ initialization TDUnitX.RegisterTestFixture(TestInjection_SingleParam); TDUnitX.RegisterTestFixture(TestInjection_MultipleParams); end.
{***************************************************************************} { } { LayoutDateTime } { } { Copyright (C) MaiconSoft } { } { https://github.com/MaiconSoft } { } { } {***************************************************************************} { } { 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. } { } {***************************************************************************} { Parse and format functions uses a string layout to interpret the date and time in another string. Theses function are the partial translation of Go lang's format.go [https://golang.org/src/time/format.go] (time package) code. All features related to time zone have been removed. Layout codes supported: Date: | Code: month | '1'(no leading) or '01' (zero leading) month | 'Jan' (short month name) or 'January' (long month name) month | '_1' (space leading)) day | '2'(no leading) or '02' (zero leading) day | '_2' (space leading) week day | 'Mon' (short week day name) or 'Monday' (long week day name) year | '06' (two digit year) or '2006' (four digit year) Time: hour | '3'(no leading) or '03' (zero leading) hour | '15'(24 hours mode) hour | 'PM'("AM/PM" mode upercase) or 'pm' ("am/pm" mode lowercase) minute | '4'(no leading) or '04' (zero leading) secound | '5'(no leading) or '05' (zero leading) milisecound | '.999'(no leading) or '.000' (zero leading) Symbol Finish search | '...' (ignore all chars of "value" after this) Spaces: Will be ignored Others: Any other word or symbol in layout, must match with "value" string "alocal" string define a local code for ICU, this will reflect in months and week days names. If not defined (or empty string) the default local will be used. For force USA pattern use "alocal = 'en-US'" and for UK, "en-GB" ps.: Do not localize code words in layout and not change cases, like 'January','Monday' etc. } unit LayoutDateTime; interface uses System.SysUtils, System.DateUtils; type TLayoutDateTimeToken = (stdNone, // none stdAny, // ... stdLongMonth, // "January" stdMonth, // "Jan" stdNumMonth, // "1" stdZeroMonth, // "01" stdLongWeekDay, // "Monday" stdWeekDay, // "Mon" stdDay, // "2" stdUnderDay, // "_2" stdZeroDay, // "02" stdHour, // "15" stdHour12, // "3" stdZeroHour12, // "03" stdMinute, // "4" stdZeroMinute, // "04" stdSecond, // "5" stdZeroSecond, // "05" stdLongYear, // "2006" stdYear, // "06" stdPM, // "PM" stdpm_, // "pm" stdFracSecond0, // ".000", trailing zeros included stdFracSecond9 // ".999", trailing zeros omitted ); TLayoutDateTime = record private class function GetNum(var value: string; Len: Integer; fixed: boolean = False): Integer; static; class function Lookup(var value: string; tab: array of string): Integer; static; class function NextStdChunk(layout: string; var prefix, suffix: string): TLayoutDateTimeToken; static; class function Skip(var value: string; prefix: string): boolean; static; class procedure Split(input: string; index, len: integer; var prefix, suffix: string); static; public class function Parse(layout, value: string; const alocal: string = ''): TDateTime; static; class function Format(layout: string; const DateTime: TDateTime; const alocal: string = ''): string; static; end; const std0x: array[0..5] of TLayoutDateTimeToken = (stdZeroMonth, stdZeroDay, stdZeroHour12, stdZeroMinute, stdZeroSecond, stdYear); implementation class procedure TLayoutDateTime.Split(input: string; index, len: integer; var prefix, suffix: string); begin prefix := input.Substring(0, index); suffix := input.Substring(index + len); end; class function TLayoutDateTime.NextStdChunk(layout: string; var prefix, suffix: string): TLayoutDateTimeToken; var i: integer; c: char; j: Integer; function Check(code: string; std: TLayoutDateTimeToken; var return: TLayoutDateTimeToken): boolean; begin if layout.IndexOf(code) = i then begin Split(layout, i, code.Length, prefix, suffix); return := std; exit(true); end; Result := false; end; begin prefix := ''; suffix := ''; for i := 0 to layout.Length - 1 do begin c := layout[i + 1]; case c of 'J': begin if Check('January', stdLongMonth, result) then exit; if Check('Jan', stdMonth, result) then exit; end; 'M': begin if Check('Monday', stdLongWeekDay, result) then exit; if Check('Mon', stdWeekDay, result) then exit; end; '0': begin for j := 1 to 6 do if Check('0' + j.ToString, std0x[j - 1], result) then exit; end; '1': begin if Check('15', stdHour, result) then exit; if Check('1', stdNumMonth, result) then exit; end; '2': begin if Check('2006', stdLongYear, result) then exit; if Check('2', stdDay, result) then exit; end; '_': begin if Check('_2006', stdLongYear, result) then exit; if Check('_2', stdUnderDay, result) then exit; end; '3': exit(stdHour12); '4': exit(stdMinute); '5': exit(stdSecond); 'P': begin if Check('PM', stdPM, result) then exit; end; 'p': begin if Check('pm', stdpm_, result) then exit; end; '.': begin if Check('...', stdAny, result) then exit; if Check('.999', stdFracSecond9, result) then exit; if Check('.000', stdFracSecond0, result) then exit; end; else begin prefix := layout; suffix := ''; Result := stdNone; end; end; end; end; class function TLayoutDateTime.Skip(var value: string; prefix: string): boolean; begin Result := false; prefix := prefix.Trim; value := value.Trim; if not prefix.IsEmpty then begin Result := value.IndexOf(prefix) <> 0; if not Result then Delete(value, 1, prefix.Length); end; end; class function TLayoutDateTime.Lookup(var value: string; tab: array of string): Integer; var j: Integer; val: string; begin value := value.Trim; Result := -1; for j := low(tab) to high(tab) do begin val := tab[j].ToLower; if value.ToLower.IndexOf(val) = 0 then begin Result := j; delete(value, 1, val.Length); break; end; end; end; class function TLayoutDateTime.GetNum(var value: string; Len: Integer; fixed: boolean = false): Integer; var val: string; begin value := value.Trim; if value.Length < Len then exit(-1); // not length enough while Len > 0 do begin val := value.Substring(0, Len); if TryStrToInt(val, Result) then begin delete(value, 1, Len); exit; end; if fixed then // then number must have length = len exit(-1); dec(Len); // try number with less digits end; end; class function TLayoutDateTime.Parse(layout, value: string; const alocal: string = ''): TDateTime; var prefix, sufflix, p: string; fs: TFormatSettings; pmSet: boolean; year, month, day, hour, min, sec, ms: Integer; begin if alocal.Trim.IsEmpty then fs := TFormatSettings.Create(SysLocale.DefaultLCID) else fs := TFormatSettings.Create(alocal); pmSet := false; year := 1970; month := 1; day := 1; hour := 0; min := 0; sec := 0; ms := 0; repeat var std := NextStdChunk(layout, prefix, sufflix); var stdstr := layout.Substring(prefix.Length, layout.Length - sufflix.Length); if Skip(value, prefix) then raise Exception.Create('Error: Expected prefix: "' + prefix + '", but not found in: ' + value.QuotedString); if std = stdAny then Break; if std = stdNone then begin if value.Length <> 0 then raise Exception.Create('Error: Unknowing pattern in layout'); Break; end; layout := sufflix; case std of stdYear: begin year := GetNum(value, 2, True); if year = -1 then raise Exception.Create('Error: Year ' + value.QuotedString + 'is not a number valid'); if year >= 69 then inc(year, 1900) else inc(year, 2000); end; stdLongYear: begin year := GetNum(value, 4, True); if year = -1 then raise Exception.Create('Error: Year ' + value.QuotedString + 'is not a number valid'); end; stdMonth: begin month := Lookup(value, fs.ShortMonthNames); if (month < 0) or (month > 11) then raise Exception.Create('Error: Month ' + value.QuotedString + ' is not valid'); inc(month); end; stdLongMonth: begin month := Lookup(value, fs.LongMonthNames); if (month < 0) or (month > 11) then raise Exception.Create('Error: Month ' + value.QuotedString + ' is not valid'); inc(month); end; stdNumMonth, stdZeroMonth: begin month := GetNum(value, 2, std = stdZeroMonth); if (month < 1) or (month > 12) then raise Exception.Create('Error: Month ' + month.ToString + ' must be in 1..12'); end; stdWeekDay: begin Lookup(value, fs.ShortDayNames); end; stdLongWeekDay: begin Lookup(value, fs.LongDayNames); end; stdDay, stdUnderDay, stdZeroDay: begin day := GetNum(value, 2, (std = stdZeroDay)); if (day = -1) or (day > 31) then raise Exception.Create('Error: Day ' + value.QuotedString + ' is not valid'); end; stdHour: begin hour := GetNum(value, 2, false); if (hour < 0) or (hour > 24) then raise Exception.Create('Error: Hour ' + value.QuotedString + ' is not valid'); end; stdHour12, stdZeroHour12: begin hour := getnum(value, 2, std = stdZeroHour12); if (hour < 0) or (hour > 12) then raise Exception.Create('Error: Hour ' + value.QuotedString + ' is not valid'); end; stdMinute, stdZeroMinute: begin min := getnum(value, 2, std = stdZeroMinute); if (min < 0) or (min > 60) then raise Exception.Create('Error: Minute ' + value.QuotedString + ' is not valid'); end; stdSecond, stdZeroSecond: begin sec := getnum(value, 2, std = stdZeroMinute); if (sec < 0) or (sec > 60) then raise Exception.Create('Error: Second ' + value.QuotedString + ' is not valid'); end; stdPM: begin p := value.Substring(0, 2); if p = 'PM' then pmSet := true else if p = 'AM' then pmSet := false else raise Exception.Create('Error: PM/AM not valid'); Delete(value, 1, 2); end; stdpm_: begin p := value.Substring(0, 2); if p = 'pm' then pmSet := true else if p = 'am' then pmSet := false else raise Exception.Create('Error: pm/am not valid'); Delete(value, 1, 2); end; stdFracSecond9, stdFracSecond0: begin delete(value, 1, 1); ms := GetNum(value, 3, std = stdFracSecond0); if (ms < 0) or (ms > 999) then raise Exception.Create('Error: Milisecond ' + value.QuotedString + ' is not valid'); end; end; until (False); if (hour < 12) and (pmSet) then inc(hour, 12); Result := EncodeDateTime(year, month, day, hour, min, sec, ms); end; class function TLayoutDateTime.Format(layout: string; const DateTime: TDateTime; const alocal: string = ''): string; const PAD_CHAR: array[boolean] of char = (' ', '0'); var prefix, sufflix, day_str: string; fs: TFormatSettings; year, month, day, hour, min, sec, ms, weekday, hour_12: word; begin Result := ''; if alocal.Trim.IsEmpty then fs := TFormatSettings.Create(SysLocale.DefaultLCID) else fs := TFormatSettings.Create(alocal); DecodeDateTime(DateTime, year, month, day, hour, min, sec, ms); weekday := DayOfWeek(DateTime); repeat var std := NextStdChunk(layout, prefix, sufflix); var stdstr := layout.Substring(prefix.Length, layout.Length - sufflix.Length); if not prefix.IsEmpty then Result := Result + prefix; if std = stdNone then Break; layout := sufflix; case std of stdYear: Result := Result + (year mod 100).ToString; stdLongYear: Result := Result + year.ToString; stdMonth: Result := Result + fs.ShortMonthNames[month]; stdLongMonth: Result := Result + fs.LongMonthNames[month]; stdNumMonth, stdZeroMonth: Result := Result + month.ToString.PadLeft(2, '0'); stdWeekDay: Result := Result + fs.ShortDayNames[weekday]; stdLongWeekDay: Result := Result + fs.LongDayNames[weekday]; stdDay, stdUnderDay, stdZeroDay: begin day_str := day.ToString; if std <> stdDay then day_str := day_str.PadLeft(2, PAD_CHAR[std = stdZeroDay]); Result := Result + day_str; end; stdHour: Result := Result + hour.ToString.PadLeft(2, '0'); stdHour12, stdZeroHour12: begin hour_12 := hour mod 12; if hour_12 = 0 then hour_12 := 12; Result := Result + hour_12.ToString.PadLeft(2, '0'); end; stdMinute: Result := Result + min.ToString; stdZeroMinute: Result := Result + min.ToString.PadLeft(2, '0'); stdSecond: Result := Result + sec.ToString; stdZeroSecond: Result := Result + sec.ToString.PadLeft(2, '0'); stdPM, stdpm_: begin var pm: string; if hour < 12 then pm := fs.TimeAMString else pm := fs.TimePMString; if std = stdPM then Result := Result + pm.ToUpper else Result := Result + pm.ToLower; end; stdFracSecond9: begin if ms > 0 then Result := Result + '.' + ms.ToString; end; stdFracSecond0: Result := Result + '.' + ms.ToString.PadLeft(3, '0'); end; until (False); end; end.
unit uFeaCombo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, ExtCtrls, IniFiles, Math; type TfFeaCombo = class(TForm) Panel1: TPanel; pgControl: TPageControl; btnSad: TSpeedButton; btnCancel: TBitBtn; btnSave: TBitBtn; tabFileCombo: TTabSheet; Label1: TLabel; Label2: TLabel; lbComboName: TLabel; lbComboSize: TLabel; dlgOpen: TOpenDialog; Panel2: TPanel; imgFileCombo: TImage; Label13: TLabel; rbFile: TRadioButton; rbLocalLibrary: TRadioButton; rbInternetLibrary: TRadioButton; Bevel1: TBevel; Label3: TLabel; edComboComponent: TEdit; UpDownComponent: TUpDown; Label5: TLabel; edComboX: TLabeledEdit; edComboY: TLabeledEdit; btnBrowse: TBitBtn; procedure LoadComboFromFile(filename: string); procedure LoadComboFromFile_old(filename: string); procedure AddComboToPanel; procedure GetRAMComboInfo; procedure PreviewCombo; function PX(mm: double; axis: string = ''): integer; procedure EditCombo(combo_id: integer); procedure FormCreate(Sender: TObject); procedure btnBrowseClick(Sender: TObject); procedure ShowComponentName(arr_index: integer); procedure btnSadClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure edComboComponentKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DecimalPoint(Sender: TObject; var Key: Char); procedure UpDownComponentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure UpDownComponentChanging(Sender: TObject; var AllowChange: Boolean); procedure MathExp(Sender: TObject); private { Private declarations } public is_editing: boolean; // udava, ci je okno otvorene pre vytvorenie alebo editovanie prvku edited_combo_ID: integer; // cislo upravovaneho comba end; var fFeaCombo: TfFeaCombo; implementation uses uMain, uObjectFeature, uMyTypes, uConfig, uDebug, uObjectPanel, uPanelSett, uTranslate, uObjectCombo, uLib, uFeaEngrave, uObjectFeaturePolyLine; var featuresArr: array[0..maxComboFeaNum] of TFeatureObject; comboName: string; comboSizeX, comboSizeY, comboScale: double; comboCenter_original: TMyPoint; comboPolohaObject_original: integer; comboPoloha_original: TMyPoint; {$R *.dfm} procedure TfFeaCombo.FormCreate(Sender: TObject); var tmpdir: string; begin fMain.imgList_common.GetBitmap(0, btnSad.Glyph); btnCancel.Glyph := fPanelSett.btnCancel.Glyph; btnSave.Glyph := fPanelSett.btnSave.Glyph; pgControl.ActivePageIndex := 0; // nastavime vychodzi adresar pre umiestnenie panelov tmpdir := fMain.ReadRegistry_string('Config', 'App_CombosDir'); if tmpdir='' then tmpdir := ExtractFilePath( Application.ExeName ) + 'combos\'; dlgOpen.InitialDir := tmpdir; // na mieste obrazkov combo otvorov vykreslime prekrizene ciary PreviewCombo; end; procedure TfFeaCombo.btnSadClick(Sender: TObject); begin fMain.ShowWish('Combo features'); end; procedure TfFeaCombo.btnBrowseClick(Sender: TObject); begin dlgOpen.InitialDir := fMain.ReadRegistry_string( 'Config', 'App_CombosDir' ); if dlgOpen.Execute then begin fMain.WriteRegistry_string('Config', 'App_CombosDir', ExtractFileDir(dlgOpen.FileName) ); LoadComboFromFile( dlgOpen.FileName ); lbComboName.Caption := comboName; lbComboSize.Caption := FloatToStr(comboSizeX) + ' x ' + FloatToStr(comboSizeY) + ' mm'; ShowComponentName(UpDownComponent.Position); PreviewCombo; edComboX.SetFocus; end; end; procedure TfFeaCombo.LoadComboFromFile(filename: string); var rider: TStreamReader; lajn: string; hlavicka, paramsList: TStringList; currSoftVersion, I, feaNum: integer; poleParams, poleVertexy: TPoleTextov; vertex: TMyPoint; begin // detekcia stareho formatu suboru (do 0.3.10) rider := TStreamReader.Create(filename, TEncoding.UTF8); lajn := rider.ReadLine; rider.Free; if (lajn = '[Combo]') then begin LoadComboFromFile_old(filename); Exit; end; // nahravanie noveho formatu suboru hlavicka := TStringList.Create; rider := TStreamReader.Create(filename, TEncoding.UTF8); try lajn := rider.ReadLine; if (lajn = '{>header}') then begin // 1.riadok musi byt zaciatok hlavicky // najprv nacitanie hlavicky while (lajn <> '{/header}') do begin lajn := rider.ReadLine; if (Pos('=', lajn) > 0) then begin hlavicka.Add(lajn); end; // if (Pos('=', lajn) > 0) end; // while (lajn <> '{/header}') // kontrola, ci sa skutocne jedna o subor comba if hlavicka.Values['filetype'] <> 'quickpanel:combo' then begin MessageBox(Application.ActiveFormHandle, PChar(TransTxt('File not found: ')+filename + ' ('+hlavicka.Values['filetype']+')'), PChar(TransTxt('Error')), MB_ICONERROR); RaiseException(1, 0, 0, nil); end; // spracovanie hlavicky - kontrola verzie suboru currSoftVersion := (cfg_swVersion1*10000)+(cfg_swVersion2*100)+cfg_swVersion3; if (StrToInt(hlavicka.Values['filever']) > currSoftVersion) then begin MessageBox(Application.ActiveFormHandle, PChar(TransTxt('File was saved by newer version of the QuickPanel. It might not open correctly.')), PChar(TransTxt('Warning')), MB_ICONWARNING); end; // spracovanie hlavicky - udaje o samotnom paneli comboName := hlavicka.Values['name']; comboSizeX := RoundTo( StrToFloat(hlavicka.Values['sizex']) , -2); comboSizeY := RoundTo( StrToFloat(hlavicka.Values['sizey']) , -2); end; // if lajn = '{>header}' paramsList := TStringList.Create; // *********************** nacitanie ficrov ******************************** while lajn <> '{>features}' do lajn := rider.ReadLine; paramsList.Clear; SetLength(poleParams, 0); feaNum := 1; ExplodeString( hlavicka.Values['structfeatures'], ',', poleParams); // vysvetlivky kodu - vid sekciu ObjectPanel:LoadFromFile:sekcia combos lajn := rider.ReadLine; while lajn <> '{/features}' do begin paramsList.Values[ poleParams[0] ] := lajn; for I := 1 to Length(poleParams)-1 do begin lajn := rider.ReadLine; paramsList.Values[ poleParams[I] ] := lajn; end; if (StrToInt(paramsList.Values['type']) = ftPolyLineGrav) then featuresArr[feaNum] := TFeaturePolyLineObject.Create(nil) else featuresArr[feaNum] := TFeatureObject.Create(nil); featuresArr[feaNum].ID := feaNum; featuresArr[feaNum].Typ := StrToInt(paramsList.Values['type']); featuresArr[feaNum].Rozmer1 := StrToFloat(paramsList.Values['size1']); featuresArr[feaNum].Rozmer2 := StrToFloat(paramsList.Values['size2']); featuresArr[feaNum].Rozmer3 := StrToFloat(paramsList.Values['size3']); featuresArr[feaNum].Rozmer4 := StrToFloat(paramsList.Values['size4']); featuresArr[feaNum].Rozmer5 := StrToFloat(paramsList.Values['size5']); featuresArr[feaNum].Param1 := paramsList.Values['param1']; featuresArr[feaNum].Param2 := paramsList.Values['param2']; featuresArr[feaNum].Param3 := paramsList.Values['param3']; featuresArr[feaNum].Param4 := paramsList.Values['param4']; featuresArr[feaNum].Param5 := paramsList.Values['param5']; featuresArr[feaNum].Poloha := MyPoint( StrToFloat(paramsList.Values['posx']) , StrToFloat(paramsList.Values['posy']) ); featuresArr[feaNum].Hlbka1 := StrToFloat(paramsList.Values['depth']); if (featuresArr[feaNum].Typ = ftTxtGrav) then begin if (featuresArr[feaNum].Rozmer2 = -1) then featuresArr[feaNum].Rozmer2 := 0; // rozmer2 = natocenie textu. V starych verziach sa tam vzdy ukladalo -1 lebo parameter nebol vyuzity. Od verzie 1.0.16 bude ale default = 0 if (featuresArr[feaNum].Param5 = '') then featuresArr[feaNum].Param5 := fFeaEngraving.comTextFontValue.Items[0]; featuresArr[feaNum].AdjustBoundingBox; // ak je to text, musime prepocitat boundingbox lebo tento zavisi od Param1 .. Param4 a ked sa tie nahravaju do ficra, tak tam sa uz AdjustBoundingBox nevola (automaticky sa to vola len pri nastavovani Size1 .. Size5) end; // ak je to polyline, nacitame vertexy if (featuresArr[feaNum].Typ = ftPolyLineGrav) AND (paramsList.Values['vertexarray'] <> '' ) then begin ExplodeString(paramsList.Values['vertexarray'], separChar, poleVertexy); if ((Length(poleVertexy) > 0) AND (poleVertexy[0] <> '')) then // ochrana ak riadok co ma obsahovat vertexy je prazdny (pole bude mat vtedy len jeden prvok - prazdny text) for I := 0 to Length(poleVertexy)-1 do begin vertex.X := StrToFloat( Copy(poleVertexy[I], 0, Pos(',', poleVertexy[I])-1 ) ); vertex.Y := StrToFloat( Copy(poleVertexy[I], Pos(',', poleVertexy[I])+1 ) ); (featuresArr[feaNum] as TFeaturePolyLineObject).AddVertex(vertex); end; end; // pre vsetky, kde sa uplatnuje farba vyplne zrusime vypln ak nie je v konfigu povolena if (featuresArr[feaNum].Typ >= ftTxtGrav) AND (featuresArr[feaNum].Typ < ftThread) then begin if not StrToBool( uConfig.Config_ReadValue('engraving_colorinfill_available') ) then featuresArr[feaNum].Param4 := 'NOFILL'; end; featuresArr[feaNum].Inicializuj; Inc(feaNum); lajn := rider.ReadLine; end; finally hlavicka.Free; paramsList.Free; rider.Free; end; UpDownComponent.Position := 0; UpDownComponent.Max := feaNum-1; comboCenter_original := MyPoint(0,0); // koli Preview comba end; procedure TfFeaCombo.LoadComboFromFile_old(filename: string); var myini: TIniFile; i: integer; iass: string; // i as string begin // nahra combo otvor do docasneho pola featurov "FeaturesArr" // najprv povodne combo vycistime for i:=1 to High(featuresArr) do FreeAndNil( featuresArr[i] ); try myini := TIniFile.Create(filename); for i:=1 to myini.ReadInteger('Combo','FeaNumber',0) do begin iass := IntToStr(i); featuresArr[i] := TFeatureObject.Create(nil); featuresArr[i].ID := i; featuresArr[i].Typ := myini.ReadInteger('Features','FeaType_'+iass, 0); featuresArr[i].Rozmer1 := myini.ReadFloat('Features','Size1_'+iass, 0); featuresArr[i].Rozmer2 := myini.ReadFloat('Features','Size2_'+iass, 0); featuresArr[i].Rozmer3 := myini.ReadFloat('Features','Size3_'+iass, 0); featuresArr[i].Rozmer4 := myini.ReadFloat('Features','Size4_'+iass, 0); featuresArr[i].Param1 := myini.ReadString('Features','Param1_'+iass, ''); featuresArr[i].Param2 := myini.ReadString('Features','Param2_'+iass, ''); featuresArr[i].Param3 := myini.ReadString('Features','Param3_'+iass, ''); featuresArr[i].Param4 := myini.ReadString('Features','Param4_'+iass, ''); featuresArr[i].Poloha := MyPoint( myini.ReadFloat('Features','PosX_'+iass, 0) , myini.ReadFloat('Features','PosY_'+iass, 0)); featuresArr[i].Hlbka1 := myini.ReadFloat('Features','Depth_'+iass, 0); if (featuresArr[i].Typ = ftTxtGrav) then begin if (featuresArr[i].Rozmer2 = -1) then featuresArr[i].Rozmer2 := 0; // rozmer2 = natocenie textu. V starych verziach sa tam vzdy ukladalo -1 lebo parameter nebol vyuzity. Od verzie 1.0.16 bude ale default = 0 if (featuresArr[i].Param5 = '') then featuresArr[i].Param5 := fFeaEngraving.comTextFontValue.Items[0]; featuresArr[i].AdjustBoundingBox; // ak je to text, musime prepocitat boundingbox lebo tento zavisi od Param1 .. Param4 a ked sa tie nahravaju do ficra, tak tam sa uz AdjustBoundingBox nevola (automaticky sa to vola len pri nastavovani Size1 .. Size5) end; // pre vsetky, kde sa uplatnuje farba vyplne zrusime vypln ak nie je v konfigu povolena if (featuresArr[i].Typ >= ftTxtGrav) AND (featuresArr[i].Typ < ftThread) then begin if not StrToBool( uConfig.Config_ReadValue('engraving_colorinfill_available') ) then featuresArr[i].Param4 := 'NOFILL'; end; end; comboName := myini.ReadString('Combo','Name',''); comboSizeX := RoundTo(myini.ReadFloat('Combo','SizeX',0) , -2); comboSizeY := RoundTo(myini.ReadFloat('Combo','SizeY',0) , -2); finally FreeAndNil(myini); end; UpDownComponent.Position := 0; UpDownComponent.Max := i-1; comboCenter_original := MyPoint(0,0); // koli Preview comba end; procedure TfFeaCombo.MathExp(Sender: TObject); begin uLib.SolveMathExpression(Sender); end; procedure TfFeaCombo.AddComboToPanel; var i, newFeaID, newComboID: integer; offX, offY: extended; begin // ak hned 1.prvok v poli comba je prazdny, tak asi nie je nahrate ziadne a koncime if not Assigned(featuresArr[1]) then Exit; _PNL.PrepareUndoStep; // da nahrate combo do panela newComboID := _PNL.AddCombo; _PNL.GetComboByID(newComboID).Name := comboName; // vyrata posunutie comba if (UpDownComponent.Position = 0) then begin // ak je polohovane vzhladom na svoj stred // (standardne su prvky comba kotovane na jeho stred) offX := 0; offY := 0; // ak je combo polohovane na stred (a nie vztahom na nejaky svoj prvok, jeho poloha bude ulozena vo vlastnosti samotneho comba) _PNL.GetComboByID(newComboID).Poloha := MyPoint(StrToFloat(edComboX.Text) , StrToFloat(edComboY.Text)); end else begin // ak je polohovane vzhladom na nejaku zo svojich dier offX := -featuresArr[UpDownComponent.Position].X; offY := -featuresArr[UpDownComponent.Position].Y; end; // vsetky feature postupne vytvorime v paneli for i:=1 to High(featuresArr) do if Assigned( featuresArr[i] ) then begin // gravirovane prvky sa mozu pridavat len a jedine na stranu "A" if (_PNL.StranaVisible <> 1) AND (featuresArr[i].Typ >= ftTxtGrav) AND (featuresArr[i].Typ < ftThread) then Continue; // vytvorime v paneli nove featury a skopirujeme do nich features z combo-lokalneho pola "featuresArr" newFeaID := _PNL.AddFeature( featuresArr[i].Typ ); if (featuresArr[i].Typ = ftPolyLineGrav) then (_PNL.GetFeatureByID(newFeaID) as TFeaturePolyLineObject).CopyFrom( (featuresArr[i] as TFeaturePolyLineObject) ) else _PNL.GetFeatureByID(newFeaID).CopyFrom(featuresArr[i]); _PNL.GetFeatureByID(newFeaID).Strana := _PNL.StranaVisible; _PNL.GetFeatureByID(newFeaID).ComboID := newComboID; // este upravime polohu jednotlivych featurov _PNL.GetFeatureByID(newFeaID).X := StrToFloat( edComboX.Text ) + featuresArr[i].X + offX; _PNL.GetFeatureByID(newFeaID).Y := StrToFloat( edComboY.Text ) + featuresArr[i].Y + offY; // vytvorenie featuru dame do undolistu _PNL.CreateUndoStep('CRT','FEA',newFeaID); // ak tento objekt sluzi ako referencia pri polohovani comba, ulozime to if ( i = UpDownComponent.Position ) then _PNL.GetComboByID(newComboID).PolohaObject := newFeaID; end; // nakoniec dame este aj vytvorenie comba do undolistu _PNL.CreateUndoStep('CRT','COM',newComboID); end; procedure TfFeaCombo.btnSaveClick(Sender: TObject); var newPoloha: TMyPoint; tmp_bod: TMyPoint; edited_combo: TComboObject; co_robit: byte; const bolo_nastred_bude_naobjekt = 1; bolo_naobjekt_bude_nastred = 2; bolo_naobjekt_bude_nainyobjekt = 3; zmena_len_suradnic = 4; begin if (is_editing) then begin _PNL.PrepareUndoStep; edited_combo := _PNL.GetComboByID(edited_combo_ID); co_robit := 0; if (UpDownComponent.Position > 0) AND (comboPolohaObject_original = -1) then co_robit := bolo_nastred_bude_naobjekt else if (UpDownComponent.Position = 0) AND (comboPolohaObject_original > -1) then co_robit := bolo_naobjekt_bude_nastred else if (UpDownComponent.Position > 0) AND (comboPolohaObject_original <> featuresArr[UpDownComponent.Position].ID) then co_robit := bolo_naobjekt_bude_nainyobjekt else if ((UpDownComponent.Position = 0) AND (comboPolohaObject_original = -1)) OR (Assigned(featuresArr[UpDownComponent.Position]) AND (comboPolohaObject_original = featuresArr[UpDownComponent.Position].ID)) then co_robit := zmena_len_suradnic; case co_robit of bolo_nastred_bude_naobjekt: begin // zistime o kolko je posunuty novy ref.bod (objekt) od povodneho (stred) // plus o kolko ho treba posunut, ak user zmenil aj suradnice tmp_bod.x := (comboCenter_original.X - _PNL.getFeatureByID( featuresArr[UpDownComponent.Position].ID ).X ) + (StrToFloat(edComboX.Text) - comboPoloha_original.X); tmp_bod.y := (comboCenter_original.Y - _PNL.getFeatureByID( featuresArr[UpDownComponent.Position].ID ).Y ) + (StrToFloat(edComboY.Text) - comboPoloha_original.Y); // a o tolko posunieme vsetky komponenty comba edited_combo.MoveFeaturesBy(tmp_bod); // teraz nastavime nove suradnice combu _PNL.CreateUndoStep('MOD','COM',edited_combo_ID); edited_combo.PolohaObject := featuresArr[UpDownComponent.Position].ID; edited_combo.Poloha := MyPoint( -1 , -1 ); end; // bolo_nastred_bude_naobjekt bolo_naobjekt_bude_nastred: begin // zistime o kolko je posunuty novy ref.bod (stred) od povodneho (nejakeho combo-komponentu) // plus o kolko ho treba posunut, ak user zmenil aj suradnice tmp_bod.x := (comboPoloha_original.X - comboCenter_original.X) + (StrToFloat(edComboX.Text) - comboPoloha_original.X); tmp_bod.y := (comboPoloha_original.Y - comboCenter_original.Y) + (StrToFloat(edComboY.Text) - comboPoloha_original.Y); // a o tolko posunieme vsetky komponenty comba edited_combo.MoveFeaturesBy(tmp_bod); // teraz nastavime nove suradnice combu _PNL.CreateUndoStep('MOD','COM',edited_combo_ID); newPoloha.X := StrToFloat(edComboX.Text); newPoloha.Y := StrToFloat(edComboY.Text); edited_combo.PolohaObject := -1; edited_combo.Poloha := MyPoint( StrToFloat(edComboX.Text) , StrToFloat(edComboY.Text) ); end; // bolo_naobjekt_bude_nastred bolo_naobjekt_bude_nainyobjekt: begin // zistime o kolko je posunuty novy ref.bod (objekt) od povodneho (objekt) // plus o kolko ho treba posunut, ak user zmenil aj suradnice tmp_bod.x := (_PNL.getFeatureByID( comboPolohaObject_original ).X - _PNL.getFeatureByID( featuresArr[UpDownComponent.Position].ID ).X ) + (StrToFloat(edComboX.Text) - comboPoloha_original.X); tmp_bod.y := (_PNL.getFeatureByID( comboPolohaObject_original ).Y - _PNL.getFeatureByID( featuresArr[UpDownComponent.Position].ID ).Y ) + (StrToFloat(edComboY.Text) - comboPoloha_original.Y); // a o tolko posunieme vsetky komponenty comba edited_combo.MoveFeaturesBy(tmp_bod); // teraz nastavime nove suradnice combu _PNL.CreateUndoStep('MOD','COM',edited_combo_ID); edited_combo.PolohaObject := featuresArr[UpDownComponent.Position].ID; edited_combo.Poloha := MyPoint( -1 , -1 ); end; // bolo_naobjekt_bude_nainyobjekt zmena_len_suradnic: begin if (comboPolohaObject_original = -1) then begin // ak je polohovany od stredu tmp_bod.x := StrToFloat(edComboX.Text) - comboPoloha_original.X; tmp_bod.y := StrToFloat(edComboY.Text) - comboPoloha_original.Y; edited_combo.Poloha := MyPoint( edited_combo.Poloha.X + tmp_bod.X , edited_combo.Poloha.Y + tmp_bod.Y ); edited_combo.MoveFeaturesBy(tmp_bod); end else begin // ak je polohovany od nejakeho objektu tmp_bod.x := StrToFloat(edComboX.Text) - _PNL.getFeatureByID( comboPolohaObject_original ).X; tmp_bod.y := StrToFloat(edComboY.Text) - _PNL.getFeatureByID( comboPolohaObject_original ).Y; edited_combo.MoveFeaturesBy(tmp_bod); end; _PNL.CreateUndoStep('MOD','COM',edited_combo_ID); end; // zmena_len_suradnic end; // CASE end {if (is_editing)} else begin AddComboToPanel; end; _PNL.Draw; end; procedure TfFeaCombo.GetRAMComboInfo; var i : integer; s: string; begin fMain.Log('=ID=|=TYP=|==X===|==Y===|======================'); for i:=1 to High(featuresArr) do if Assigned(featuresArr[i]) then begin s := FormatFloat('000 ',featuresArr[i].ID); s := s + FormatFloat('000 ', featuresArr[i].Typ ); s := s + FormatFloat('##0.00 ', featuresArr[i].Poloha.X ); s := s + FormatFloat('##0.00 ', featuresArr[i].Poloha.Y ); fMain.Log(s); end; fMain.Log(''); fMain.Log('min:'+inttostr(UpDownComponent.Min)); fMain.Log('max:'+inttostr(UpDownComponent.Max)); fMain.Log('pos:'+inttostr(UpDownComponent.Position)); end; function TfFeaCombo.PX(mm: double; axis: string = ''): integer; begin { premeni milimetre na pixle a ak je zadana aj os, tak na to prihliada } if (axis = 'x') then result := Round(mm * comboScale) + Round(imgFileCombo.Width / 2) else if (axis = 'y') then result := imgFileCombo.Height - Round(mm * comboScale) - Round(imgFileCombo.Width / 2) else result := Round(mm * comboScale); end; procedure TfFeaCombo.PreviewCombo; var i, imgsize: integer; obj: ^TFeatureObject; tmp_p1, tmp_p2: TMyPoint; canv : TCanvas; begin imgsize := imgFileCombo.Width; // vymazeme plochu obrazka canv := imgFileCombo.Canvas; canv.Brush.Color := clBtnFace; canv.Pen.Color := canv.Brush.Color; canv.Rectangle(0,0,imgsize,imgsize); // kreslime if not Assigned( featuresArr[1] ) then begin // ak nie je ziadne combo, nakreslime kriz canv.Pen.Color := clBlack; canv.MoveTo( 0,0 ); canv.LineTo( imgsize,imgsize ); canv.MoveTo( 0,imgsize ); canv.LineTo( imgsize,0 ); end else begin // vypocitame mierku pre vykreslovanie comboScale := (imgSize-2) / Max(comboSizeX, comboSizeY); // vykreslime kazdy for i:=1 to High(featuresArr) do begin // standardne nastavenia kreslenia canv.Pen.Color := clGray; canv.Pen.Width := 1; // nastavenia kreslenia, ked sa jedna o vybratu komponentu comba if (UpDownComponent.Position = i) then begin canv.Pen.Color := clRed; canv.Pen.Width := 2; end; // nastavenia kreslenia, ked sa jedna o stred celeho comba if (UpDownComponent.Position = 0) then canv.Pen.Color := clBlack; obj := @featuresArr[i]; if Assigned(featuresArr[i]) then case obj.Typ of ftHoleCirc, ftPocketCirc: begin canv.Brush.Style := bsClear; canv.Ellipse( PX( obj.X - comboCenter_original.X - (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y - (obj.Rozmer1/2) , 'y'), PX( obj.X - comboCenter_original.X + (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y + (obj.Rozmer1/2) , 'y') ); end; ftHoleRect, ftPocketRect: begin canv.Brush.Style := bsClear; canv.RoundRect( PX( obj.X - comboCenter_original.X - (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y - (obj.Rozmer2/2) , 'y'), PX( obj.X - comboCenter_original.X + (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y + (obj.Rozmer2/2) , 'y'), PX(obj.Rozmer3*2), PX(obj.Rozmer3*2) ); end; ftThread: begin canv.Brush.Style := bsClear; canv.Ellipse( PX( obj.X - comboCenter_original.X - (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y - (obj.Rozmer1/2) , 'y'), PX( obj.X - comboCenter_original.X + (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y + (obj.Rozmer1/2) , 'y') ); end; ftSink, ftSinkSpecial, ftSinkCyl: begin canv.Brush.Style := bsClear; canv.Ellipse( PX( obj.X - comboCenter_original.X - (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y - (obj.Rozmer1/2) , 'y'), PX( obj.X - comboCenter_original.X + (obj.Rozmer1/2) , 'x'), PX( obj.Y - comboCenter_original.Y + (obj.Rozmer1/2) , 'y') ); canv.Ellipse( PX( obj.X - comboCenter_original.X - (obj.Rozmer2/2) , 'x'), PX( obj.Y - comboCenter_original.Y - (obj.Rozmer2/2) , 'y'), PX( obj.X - comboCenter_original.X + (obj.Rozmer2/2) , 'x'), PX( obj.Y - comboCenter_original.Y + (obj.Rozmer2/2) , 'y') ); end; ftGrooveLin: begin canv.Brush.Style := bsClear; canv.MoveTo( PX(obj.X - comboCenter_original.X, 'x'), PX(obj.Y - comboCenter_original.Y, 'y') ); canv.LineTo( PX(obj.X - comboCenter_original.X + obj.Rozmer1, 'x'), PX(obj.Y - comboCenter_original.Y + obj.Rozmer2, 'y') ); end; ftGrooveArc: begin canv.Brush.Style := bsClear; // vypocitam body, ktore urcuju start/stop obluka // (podla rovnice kruznice X = A + r*cos ALFA ; Y = B + r*sin BETA) tmp_p1.X := obj.X - comboCenter_original.X + ( (obj.Rozmer1/2) * cos(DegToRad(obj.Rozmer2)) ); tmp_p1.Y := obj.Y - comboCenter_original.Y + ( (obj.Rozmer1/2) * sin(DegToRad(obj.Rozmer2)) ); tmp_p2.X := obj.X - comboCenter_original.X + ( (obj.Rozmer1/2) * cos(DegToRad(obj.Rozmer3)) ); tmp_p2.Y := obj.Y - comboCenter_original.Y + ( (obj.Rozmer1/2) * sin(DegToRad(obj.Rozmer3)) ); // samotne vykreslenie canv.Arc( PX(obj.X - comboCenter_original.X - (obj.Rozmer1/2),'x'), PX(obj.Y - comboCenter_original.Y - (obj.Rozmer1/2),'y'), PX(obj.X - comboCenter_original.X + (obj.Rozmer1/2),'x')+1, PX(obj.Y - comboCenter_original.Y + (obj.Rozmer1/2),'y')-1, PX(tmp_p1.X, 'x'), PX(tmp_p1.Y, 'y'), PX(tmp_p2.X, 'x'), PX(tmp_p2.Y, 'y') ); // ak treba spojit zaciatok s koncom if obj.Param1 = 'S' then begin canv.MoveTo( PX(tmp_p1.X, 'x'), PX(tmp_p1.Y, 'y') ); canv.LineTo( PX(tmp_p2.X, 'x'), PX(tmp_p2.Y, 'y') ); end; end; end; end; end; end; procedure TfFeaCombo.ShowComponentName(arr_index: integer); begin // vypise do TEditu nazov komponentu comba podla parametra - indexu v poli FeaturesArr // ak je UpDown v specialnej polohe "0" a combo uz bolo nahrate, ponukne speci moznost if (UpDownComponent.Position = 0) AND ( Assigned(featuresArr[1]) ) then edComboComponent.Text := TransTxt('Center of the combo'); // inak ponukne niektoru z komponent comba if (UpDownComponent.Position > 0) AND ( Assigned(featuresArr[arr_index]) ) then edComboComponent.Text := featuresArr[arr_index].GetFeatureInfo(true, false, true); end; procedure TfFeaCombo.UpDownComponentChanging(Sender: TObject; var AllowChange: Boolean); begin // tu je to preto, aby preskakovali nazvy featurov ked drzim stlacenu mys na UpDown komponente... ShowComponentName( UpDownComponent.Position ); PreviewCombo; end; procedure TfFeaCombo.UpDownComponentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // ...a tu je to preto, aby po pusteni mysi sa nahral ten feature, ktory ma index ako je pozicia UpDown-u (v evente Changing ani Click poziciu nepozname, lebo sa aktualizuje az po tomto evente) ShowComponentName( UpDownComponent.Position ); PreviewCombo; end; procedure TfFeaCombo.edComboComponentKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // ked stlaca sipku dole a hore, ovlada tym komponentu UpDown if (Key = 38) AND (UpDownComponent.Position < UpDownComponent.Max) then UpDownComponent.Position := UpDownComponent.Position+1; if (Key = 40) AND (UpDownComponent.Position > 0) then UpDownComponent.Position := UpDownComponent.Position-1; ShowComponentName( UpDownComponent.Position ); PreviewCombo; if (Key = 13) then btnSave.Click; end; procedure TfFeaCombo.DecimalPoint(Sender: TObject; var Key: Char); begin fMain.CheckDecimalPoint(sender, key, btnSave); end; procedure TfFeaCombo.EditCombo(combo_id: integer); var features: TPoleIntegerov; i: integer; boundbox: TMyRect; combo: TComboObject; begin is_editing := true; edited_combo_ID := combo_id; btnBrowse.Enabled := false; rbFile.Enabled := false; rbLocalLibrary.Enabled := false; rbInternetLibrary.Enabled := false; lbComboName.Caption := '- - -'; lbComboSize.Caption := '- - -'; combo := _PNL.GetComboByID(combo_id); comboName := combo.Name; comboPolohaObject_original := combo.PolohaObject; boundbox := _PNL.GetComboBoundingBox(combo_id); comboSizeX := boundbox.BtmR.X - boundbox.TopL.X; comboSizeY := boundbox.TopL.Y - boundbox.BtmR.Y; if (combo.PolohaObject = -1) then begin // ak je polohovany vzhladom na svoj stred comboPoloha_original := combo.Poloha; comboCenter_original := comboPoloha_original; UpDownComponent.Position := 0; end else begin // ak je polohovane vzhladom na nejaky svoj komponent, musime jeho stred zistit (koli kresleniu v Preview) comboPoloha_original := _PNL.getFeatureByID( combo.PolohaObject ).Poloha; comboCenter_original.X := boundbox.TopL.X + (comboSizeX / 2); comboCenter_original.Y := boundbox.BtmR.y + (comboSizey / 2); end; edComboX.Text := FormatFloat('0.###', comboPoloha_original.X); edComboY.Text := FormatFloat('0.###', comboPoloha_original.Y); for i:=1 to High(featuresArr) do FreeAndNil( featuresArr[i] ); _PNL.GetComboFeatures(features, combo_id); UpDownComponent.Max := Length(features); // prekopirovanie featurov comba z panela do lokalneho pola for i := 1 to Length(features) do begin featuresArr[i] := TFeatureObject.Create(nil, _PNL.StranaVisible); featuresArr[i].ID := features[i-1]; featuresArr[i].CopyFrom( _PNL.GetFeatureByID(features[i-1]) ); // ak sme nasli prave ten komponent, podla ktoreho je polohovane combo, // nastavime nanho aj poziciu UpDown komponentu - nech ho ukazuje if (featuresArr[i].ID = combo.PolohaObject) then UpDownComponent.Position := i; end; ShowComponentName( UpDownComponent.Position ); PreviewCombo; end; end.
unit ProtectUnit; interface uses System.SysUtils, System.Win.Registry, Winapi.Windows, System.DateUtils, Soap.EncdDecd; type TProtect = class(TObject) private class var Instance: TProtect; protected function CreateKey(ADate1, ADate2: TDateTime; AOldKey: String = '') : Boolean; function DecodeDate(const Str: String; var ADate1, ADate2: TDateTime): Boolean; function DropKey(const AKey: String): Boolean; function EncodeDate(ADate1, ADate2: TDateTime): String; function SearchKey: String; public class function NewInstance: TObject; override; function Check: Boolean; function Unlock: Boolean; end; implementation uses System.Classes, System.NetEncoding, System.Contnrs; var SingletonList: TObjectList; const d1: Integer = 0; d2: Integer = 0; KEYPATH: String = 'SOFTWARE\{A6B78162-D43E-4867-B931-A68BC7075C2E}'; MYKEY: String = 'XPT_CE2.Interop.'; DemoDays: Integer = 30; function TProtect.DecodeDate(const Str: String; var ADate1, ADate2: TDateTime): Boolean; var m: TArray<String>; S: String; begin Result := False; if Str.IsEmpty then Exit; S := DecodeString(Str); m := S.Split(['_']); if Length(m) <> 2 then Exit; try ADate1 := StrToDateTime(m[0]); ADate2 := StrToDateTime(m[1]); Result := True; except ; end; end; function TProtect.EncodeDate(ADate1, ADate2: TDateTime): String; var S: string; begin S := Format('%s_%s', [DateTimeToStr(ADate1), DateTimeToStr(ADate2)]); Result := EncodeString(S); end; class function TProtect.NewInstance: TObject; begin if not Assigned(Instance) then begin Instance := TProtect(inherited NewInstance); SingletonList.Add(Instance); end; Result := Instance; end; function TProtect.Check: Boolean; var ADate1: TDateTime; ADate2: TDateTime; S: string; AKeyName: string; ANow: TDateTime; x: Integer; begin AKeyName := SearchKey; // Такого ключа вообще нет - считаем что программа загрузилась впервые if AKeyName.IsEmpty then begin Result := CreateKey(Now, Now); end else begin // Получаем хвостик ключа S := AKeyName.Substring(MYKEY.Length); // Декодируем даты Result := DecodeDate(S, ADate1, ADate2); if not Result then Exit; ADate1 := ADate1 - d1; ADate2 := ADate2 - d2; ANow := Now; // Текущая дата должна быть больше чем дата первого и последнео запуска Result := (ADate1 < ANow) and (ADate2 < ANow); if not Result then Exit; //x := MinutesBetween(ADate1, ANow); x := DaysBetween(ADate1, ANow); Result := x < DemoDays; if not Result then Exit; Result := CreateKey(ADate1, ANow, AKeyName); end; end; function TProtect.CreateKey(ADate1, ADate2: TDateTime; AOldKey: String = ''): Boolean; var AKeyName: string; r: TRegistry; S: String; begin ADate1 := ADate1 + d1; ADate2 := ADate2 + d2; S := EncodeDate(ADate1, ADate2); // Формируем имя ключа AKeyName := Format('%s\%s%s', [KEYPATH, MYKEY, S]); r := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY); try r.RootKey := HKEY_CURRENT_USER; Result := r.CreateKey(AKeyName); if not Result then Exit; if not AOldKey.IsEmpty then begin AKeyName := Format('%s\%s', [KEYPATH, AOldKey]); // Удаляем из реестра старый ключ Result := r.DeleteKey(AKeyName); end; finally FreeAndNil(r); end; end; function TProtect.DropKey(const AKey: String): Boolean; var AKeyName: string; r: TRegistry; begin //Result := False; r := TRegistry.Create(KEY_WRITE OR KEY_WOW64_64KEY); try r.RootKey := HKEY_CURRENT_USER; AKeyName := Format('%s\%s', [KEYPATH, AKey]); // Удаляем из реестра старый ключ Result := r.DeleteKey(AKeyName); finally FreeAndNil(r); end; end; function TProtect.SearchKey: String; var ASL: TStringList; r: TRegistry; S: String; begin Result := ''; r := TRegistry.Create(); try r.RootKey := HKEY_CURRENT_USER; if not r.OpenKeyReadOnly(KEYPATH) then Exit; ASL := TStringList.Create; try r.GetKeyNames(ASL); for S in ASL do begin if S.StartsWith(MYKEY) then begin Result := S; break; end; end; finally FreeAndNil(ASL); end; finally FreeAndNil(r); end; end; function TProtect.Unlock: Boolean; var AKeyName: String; begin AKeyName := SearchKey; Result := AKeyName.IsEmpty; if Result then Exit; Result := DropKey(AKeyName); end; initialization SingletonList := TObjectList.Create(True); finalization FreeAndNil(SingletonList); end.
unit ServerContainerUnit; interface uses SysUtils, Classes, SvcMgr, DSTCPServerTransport, DSServer, DSCommonServer, DSAuth, AppserverMainUnit; type THPDService = class(TService) procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceCreate(Sender: TObject); private FAppserverMain : TServerMain; protected function DoStop: Boolean; override; function DoPause: Boolean; override; function DoContinue: Boolean; override; procedure DoInterrogate; override; public function GetServiceController: TServiceController; override; end; var HPDService: THPDService; implementation uses Windows; {$R *.dfm} procedure ServiceController(CtrlCode: DWord); stdcall; begin HPDService.Controller(CtrlCode); end; function THPDService.GetServiceController: TServiceController; begin Result := ServiceController; end; function THPDService.DoContinue: Boolean; begin Result := inherited; FAppserverMain.DSServer.Start; end; procedure THPDService.DoInterrogate; begin inherited; end; function THPDService.DoPause: Boolean; begin FAppserverMain.DSServer.Stop; Result := inherited; end; function THPDService.DoStop: Boolean; begin FAppserverMain.DSServer.Stop; Result := inherited; end; procedure THPDService.ServiceCreate(Sender: TObject); begin FAppserverMain := TServerMain.Create(Self); end; procedure THPDService.ServiceStart(Sender: TService; var Started: Boolean); begin FAppserverMain.DSServer.Start; end; end.
unit uHeritageScreen; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, Vcl.ComCtrls, Vcl.ExtCtrls, uDTMConnection, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uEnum; type TfrmHeritageScreen = class(TForm) pgcMain: TPageControl; pnlFooter: TPanel; tabListing: TTabSheet; tabMaintenance: TTabSheet; btnNew: TBitBtn; btnAlter: TBitBtn; btnCancel: TBitBtn; btnSave: TBitBtn; btnDelete: TBitBtn; btnClose: TBitBtn; btnNavigator: TDBNavigator; qryListing: TFDQuery; dtsListing: TDataSource; pnlListingTop: TPanel; lblIndex: TLabel; mskSearch: TMaskEdit; btnSearch: TBitBtn; grdListing: TDBGrid; procedure FormCreate(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnNewClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnAlterClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure grdListingTitleClick(Column: TColumn); procedure mskSearchChange(Sender: TObject); procedure grdListingDblClick(Sender: TObject); private { Private declarations } procedure ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete : TBitBtn; btnNavigator : TDBNavigator; pgcMain : TPageControl; Flag : Boolean); procedure PageControl(pgcMain: TPageControl; CurrentIndex: Integer); function ReturnField(Field: String): String; procedure ShowLabelIndex(Field: String; aLabel: TLabel); function MandatoryField: Boolean; procedure DisableEditPK; procedure CleanFields; public { Public declarations } Status : TStatus; CurrentIndex : String; function Delete : Boolean; virtual; function Save(Status:TStatus): Boolean; virtual; end; var frmHeritageScreen: TfrmHeritageScreen; implementation {$R *.dfm} {$region 'OBSERVATIONS} //COMPONENT TAG: 1 - PRIMARY KEY (PK); //COMPONENT TAG: 2 - MANDATORY FIELD; {$endregion} {$region 'BUTTONS'} procedure TfrmHeritageScreen.btnNewClick(Sender: TObject); begin Try ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete, btnNavigator, pgcMain, False); Finally Status := ecInsert; CleanFields; QryListing.Refresh; End; end; procedure TfrmHeritageScreen.btnSaveClick(Sender: TObject); begin if (MandatoryField) then Abort; Try if Save(Status) then begin ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete, btnNavigator, pgcMain, True); PageControl(pgcMain, 0); Status := ecNone; CleanFields; QryListing.Refresh; end else begin MessageDlg('Error on saving process.', mtError, [mbOK], 0); end; Finally End; end; procedure TfrmHeritageScreen.btnAlterClick(Sender: TObject); begin Try ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete, btnNavigator, pgcMain, False); Finally Status := ecAlter; QryListing.Refresh; End; end; procedure TfrmHeritageScreen.btnCancelClick(Sender: TObject); begin Try ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete, btnNavigator, pgcMain, True); PageControl(pgcMain, 0); Finally Status := ecNone; CleanFields; End; end; procedure TfrmHeritageScreen.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmHeritageScreen.btnDeleteClick(Sender: TObject); begin Try if Delete then begin ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete, btnNavigator, pgcMain, True); PageControl(pgcMain, 0); end else begin MessageDlg('Error on delete process.', mtError, [mbOK], 0); end Finally Status := ecNone; CleanFields; QryListing.Refresh; End; end; {$endregion} {$region 'EVENTS'} procedure TfrmHeritageScreen.FormClose(Sender: TObject; var Action: TCloseAction); begin QryListing.Close; end; procedure TfrmHeritageScreen.FormCreate(Sender: TObject); begin qryListing.Connection := DTMConnection.dbConnection; dtsListing.DataSet := QryListing; grdListing.DataSource := dtsListing; grdListing.Options := [dgTitles,dgIndicator,dgColumnResize,dgColLines ,dgRowLines,dgTabs,dgRowSelect,dgAlwaysShowSelection, dgCancelOnExit,dgTitleClick,dgTitleHotTrack]; end; procedure TfrmHeritageScreen.FormShow(Sender: TObject); begin PageControl(pgcMain, 0); lblIndex.Caption:=CurrentIndex; DisableEditPK; if (QryListing.SQL.Text <> EmptyStr) then begin QryListing.IndexFieldNames := CurrentIndex; ShowLabelIndex(CurrentIndex, lblIndex); QryListing.Open; end; ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete, btnNavigator, pgcMain, True); end; procedure TfrmHeritageScreen.grdListingDblClick(Sender: TObject); begin btnAlter.Click; end; procedure TfrmHeritageScreen.grdListingTitleClick(Column: TColumn); begin CurrentIndex := Column.FieldName; QryListing.IndexFieldNames := CurrentIndex; ShowLabelIndex(CurrentIndex, lblIndex); end; {$endregion} {$region 'Screen Control'} procedure TfrmHeritageScreen.ButtonControl(btnNew, btnAlter, btnCancel, btnSave, btnDelete : TBitBtn; btnNavigator : TDBNavigator; pgcMain : TPageControl; Flag : Boolean); begin btnNew.Enabled := Flag; btnDelete.Enabled := Flag; btnAlter.Enabled := Flag; btnNavigator.Enabled := Flag; pgcMain.Pages[0].TabVisible := Flag; btnCancel.Enabled := not(Flag); btnSave.Enabled := not (Flag); end; {$region 'VIRTUAL METHODS'} function TfrmHeritageScreen.Delete: Boolean; begin ShowMessage('DELETED'); Result := True; end; {$endregion} procedure TfrmHeritageScreen.PageControl(pgcMain : TPageControl; CurrentIndex : Integer); begin if (pgcMain.Pages[CurrentIndex].TabVisible) then pgcMain.TabIndex := CurrentIndex; end; {$endregion} {$region 'FUNCTIONS & PROCEDURES'} procedure TfrmHeritageScreen.mskSearchChange(Sender: TObject); begin QryListing.Locate(CurrentIndex, TMaskEdit(Sender).Text, [loPartialKey]); end; function TfrmHeritageScreen.ReturnField(Field:String):String; var i : integer; begin for I := 0 to grdListing.Columns.Count-1 do begin if lowercase(grdListing.Columns[i].FieldName) = lowercase(Field) then begin Result := grdListing.Columns[i].Title.Caption; Break; end; end; end; function TfrmHeritageScreen.Save(Status: TStatus): Boolean; begin if (Status = ecInsert) then ShowMessage('Inserted') else if (Status = ecAlter) then ShowMessage('Altered'); Result := True; end; function TfrmHeritageScreen.MandatoryField : Boolean; var i : integer; begin Result := False; for i := 0 to ComponentCount -1 do begin if (Components[i] is TLabeledEdit) then if (TLabeledEdit(Components[i]).Tag = 2) and (TLabeledEdit(Components[i]).Text = EmptyStr) then begin MessageDlg(TLabeledEdit(Components[i]).EditLabel.Caption + ' is a mandatory field.', mtInformation,[mbOK],0); TLabeledEdit(Components[i]).SetFocus; Result := True; Break; end; end; end; procedure TfrmHeritageScreen.ShowLabelIndex(Field:String; aLabel: TLabel); begin aLabel.Caption := ReturnField(Field); end; procedure TfrmHeritageScreen.DisableEditPK; var i : integer; begin for i := 0 to ComponentCount -1 do begin if (Components[i] is TLabeledEdit) then if (TLabeledEdit(Components[i]).Tag = 1) then begin TLabeledEdit(Components[i]).Enabled := False; Break; end; end; end; procedure TfrmHeritageScreen.CleanFields; var i : integer; begin for i := 0 to ComponentCount -1 do begin if (Components[i] is TLabeledEdit) then begin TLabeledEdit(Components[i]).Text := EmptyStr end else if (Components[i] is TEdit) then TEdit(Components[i]).Text := EmptyStr; end; end; {$endregion} end.
{ 25/05/2007 10:24:05 (GMT+1:00) > [Akadamia] checked in } { 25/05/2007 10:22:39 (GMT+1:00) > [Akadamia] checked out /} { 25/05/2007 10:20:58 (GMT+1:00) > [Akadamia] checked in Add note to display } { 25/05/2007 09:27:39 (GMT+1:00) > [Akadamia] checked out /Add note to display} { 21/05/2007 17:03:07 (GMT+1:00) > [Akadamia] checked in Updates for SP1A } { 21/05/2007 16:56:34 (GMT+1:00) > [Akadamia] checked out /Updates for SP1A} { 14/02/2007 08:24:20 (GMT+0:00) > [Akadamia] checked out /} { 12/02/2007 10:10:09 (GMT+0:00) > [Akadamia] checked in } {----------------------------------------------------------------------------- Unit Name: AOU Author: ken.adam Date: 15-Jan-2007 Purpose: Translation of AI Objects and Waypoints example to Delphi Adds Non ATC controlled simulation objects. With the default flight (Cessna at Seatac) - turn off the engine and watch the antics. Press z to create the objects Press x to load them with their waypoint lists History: -----------------------------------------------------------------------------} unit AOU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls, ActnList, ComCtrls, SimConnect, StdActns; const // Define a user message for message driven version of the example WM_USER_SIMCONNECT = WM_USER + 2; var BalloonID : DWORD = SIMCONNECT_OBJECT_ID_USER; BellID : DWORD = SIMCONNECT_OBJECT_ID_USER; MooneyID : DWORD = SIMCONNECT_OBJECT_ID_USER; TruckID : DWORD = SIMCONNECT_OBJECT_ID_USER; type // Use enumerated types to create unique IDs as required TEventID = (EventSimStart, EventZ, EventX, EventC, EventV); TDataRequestId = ( REQUEST_BALLOON1, REQUEST_BELL, REQUEST_MOONEY, REQUEST_DOUGLAS, REQUEST_TRUCK, REQUEST_WHALE); TGroupId = (GroupZX); TInputId = (InputZX); TDataDefineId = (DefinitionWaypoint, DefinitionThrottle); TBallonControl = packed record ThrottlePercent: double; end; // The form TAIObjectsForm = class(TForm) StatusBar: TStatusBar; ActionManager: TActionManager; ActionToolBar: TActionToolBar; Images: TImageList; Memo: TMemo; StartPoll: TAction; FileExit: TFileExit; StartEvent: TAction; procedure StartPollExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure SimConnectMessage(var Message: TMessage); message WM_USER_SIMCONNECT; procedure StartEventExecute(Sender: TObject); private { Private declarations } RxCount: integer; // Count of Rx messages Quit: boolean; // True when signalled to quit hSimConnect: THandle; // Handle for the SimConection PlansSent: boolean; ObjectsCreated: boolean; bc: TBallonControl; public { Public declarations } procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); procedure SendFlightPlans; procedure SetUpSimObjects; end; var AIObjectsForm : TAIObjectsForm; implementation uses SimConnectSupport; resourcestring StrRx6d = 'Rx: %6d'; {$R *.dfm} {----------------------------------------------------------------------------- Procedure: MyDispatchProc Wraps the call to the form method in a simple StdCall procedure Author: ken.adam Date: 11-Jan-2007 Arguments: pData: PSimConnectRecv cbData: DWORD pContext: Pointer -----------------------------------------------------------------------------} procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); stdcall; begin AIObjectsForm.DispatchHandler(pData, cbData, pContext); end; {----------------------------------------------------------------------------- Procedure: DispatchHandler Handle the Dispatched callbacks in a method of the form. Note that this is used by both methods of handling the interface. Author: ken.adam Date: 11-Jan-2007 Arguments: pData: PSimConnectRecv cbData: DWORD pContext: Pointer -----------------------------------------------------------------------------} procedure TAIObjectsForm.DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer); var hr : HRESULT; Evt : PSimconnectRecvEvent; OpenData : PSimConnectRecvOpen; pObjData : PSimConnectRecvAssignedObjectID; begin // Maintain a display of the message count Inc(RxCount); StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]); // Only keep the last 200 lines in the Memo while Memo.Lines.Count > 200 do Memo.Lines.Delete(0); // Handle the various types of message case TSimConnectRecvId(pData^.dwID) of SIMCONNECT_RECV_ID_EXCEPTION: Memo.Lines.Add( SimConnectExceptionNames[TSimConnectException(PSimConnectRecvException(pData)^.dwException)]); SIMCONNECT_RECV_ID_OPEN: begin StatusBar.Panels[0].Text := 'Opened'; OpenData := PSimConnectRecvOpen(pData); with OpenData^ do begin Memo.Lines.Add(''); Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName, dwApplicationVersionMajor, dwApplicationVersionMinor, dwApplicationBuildMajor, dwApplicationBuildMinor])); Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect', dwSimConnectVersionMajor, dwSimConnectVersionMinor, dwSimConnectBuildMajor, dwSimConnectBuildMinor])); Memo.Lines.Add(''); end; end; SIMCONNECT_RECV_ID_EVENT: begin evt := PSimconnectRecvEvent(pData); case TEventId(evt^.uEventID) of EventSimStart: begin // Sim has started so turn the input events on hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputZX), Ord(SIMCONNECT_STATE_ON)); end; EventZ: if not ObjectsCreated then begin SetUpSimObjects; objectsCreated := True; end; EventX: if not plansSent and ObjectsCreated then begin SendFlightPlans; PlansSent := True; end; EventC: begin Memo.Lines.Add('EventC'); // Give the balloon some throttle // SDK actually uses SIMCONNECT_OBJECT_ID_USER, which is own ship // Yet to find a SimObject that will respond to "Throttle" if bc.ThrottlePercent < 100.0 then bc.throttlePercent := bc.throttlePercent + 5.0; hr := SimConnect_SetDataOnSimObject(hSimConnect, Ord(DefinitionThrottle), SIMCONNECT_OBJECT_ID_USER, 0, 1, sizeof(bc), @bc); end; EventV: begin Memo.Lines.Add('EventV'); // Give the balloon some throttle // SDK actually uses SIMCONNECT_OBJECT_ID_USER, which is own ship // Yet to find a SimObject that will respond to "Throttle" if bc.throttlePercent > 0.0 then bc.throttlePercent := bc.throttlePercent - 5.0; hr := SimConnect_SetDataOnSimObject(hSimConnect, Ord(DefinitionThrottle), SIMCONNECT_OBJECT_ID_USER, 0, 1, sizeof(bc), @bc); end; end; end; SIMCONNECT_RECV_ID_ASSIGNED_OBJECT_ID: begin pObjData := PSimConnectRecvAssignedObjectID(pData); case TDataRequestId(pObjData^.dwRequestID) of REQUEST_BALLOON1: begin BalloonID := pObjData^.dwObjectID; Memo.Lines.Add(Format('Created "Balloon 1" id = %d', [BalloonID])); end; REQUEST_BELL: begin BellID := pObjData^.dwObjectID; Memo.Lines.Add(Format('Created Bell Helicopter id = %d', [BellID])); end; REQUEST_MOONEY: begin MooneyID := pObjData^.dwObjectID; Memo.Lines.Add(Format('Created Mooney Bravo id = %d', [MooneyID])); end; REQUEST_DOUGLAS: Memo.Lines.Add(Format('Created stationary Douglas DC3 id = %d', [pObjData^.dwObjectID])); REQUEST_TRUCK: begin TruckID := pObjData^.dwObjectID; Memo.Lines.Add(Format('Created truck id = %d', [TruckID])); end; REQUEST_WHALE: Memo.Lines.Add(Format('Created humpback whale id = %d', [pObjData^.dwObjectID])); else Memo.Lines.Add(Format('Unknown creation %d', [pObjData^.dwRequestID])); end; end; SIMCONNECT_RECV_ID_QUIT: begin Quit := True; StatusBar.Panels[0].Text := 'FS X Quit'; end else Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID])); end; end; {----------------------------------------------------------------------------- Procedure: FormCloseQuery Ensure that we can signal "Quit" to the busy wait loop Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject var CanClose: Boolean Result: None -----------------------------------------------------------------------------} procedure TAIObjectsForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin Quit := True; CanClose := True; end; {----------------------------------------------------------------------------- Procedure: FormCreate We are using run-time dynamic loading of SimConnect.dll, so that the program will execute and fail gracefully if the DLL does not exist. Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject Result: None -----------------------------------------------------------------------------} procedure TAIObjectsForm.FormCreate(Sender: TObject); begin if InitSimConnect then StatusBar.Panels[2].Text := 'SimConnect.dll Loaded' else begin StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND'; StartPoll.Enabled := False; StartEvent.Enabled := False; end; Quit := False; PlansSent := False; ObjectsCreated := False; hSimConnect := 0; StatusBar.Panels[0].Text := 'Not Connected'; RxCount := 0; StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]); end; {----------------------------------------------------------------------------- Procedure: SimConnectMessage This uses CallDispatch, but could probably avoid the callback and use SimConnect_GetNextDispatch instead. Author: ken.adam Date: 11-Jan-2007 Arguments: var Message: TMessage -----------------------------------------------------------------------------} procedure TAIObjectsForm.SendFlightPlans; var hr : HRESULT; wp : array[0..2] of TSimConnectDataWaypoint; // Mooney waypoint list ft : array[0..1] of TSimConnectDataWaypoint; // Truck waypoint list begin // Mooney aircraft should fly in circles across the North end of the runway wp[0].Flags := SIMCONNECT_WAYPOINT_SPEED_REQUESTED; wp[0].Altitude := 800; wp[0].Latitude := 47 + (27.79 / 60); wp[0].Longitude := -122 - (18.46 / 60); wp[0].ktsSpeed := 100; wp[1].Flags := SIMCONNECT_WAYPOINT_SPEED_REQUESTED; wp[1].Altitude := 600; wp[1].Latitude := 47 + (27.79 / 60); wp[1].Longitude := -122 - (17.37 / 60); wp[1].ktsSpeed := 100; wp[2].Flags := SIMCONNECT_WAYPOINT_WRAP_TO_FIRST or SIMCONNECT_WAYPOINT_SPEED_REQUESTED; wp[2].Altitude := 800; wp[2].Latitude := 47 + (27.79 / 60); wp[2].Longitude := -122 - (19.92 / 60); wp[2].ktsSpeed := 100; // Send the three waypoints to the Mooney // ** Note that this call has changed with SP1A to match the documentation ** hr := SimConnect_SetDataOnSimObject(hSimConnect, Ord(DefinitionWayPoint), MooneyID, 0, Length(wp), SizeOf(wp[0]), @wp[0]); // Truck goes down the runway ft[0].Flags := SIMCONNECT_WAYPOINT_SPEED_REQUESTED; ft[0].Altitude := 433; ft[0].Latitude := 47 + (25.93 / 60); ft[0].Longitude := -122 - (18.46 / 60); ft[0].ktsSpeed := 75; ft[1].Flags := SIMCONNECT_WAYPOINT_WRAP_TO_FIRST or SIMCONNECT_WAYPOINT_SPEED_REQUESTED; ft[1].Altitude := 433; ft[1].Latitude := 47 + (26.25 / 60); ft[1].Longitude := -122 - (18.46 / 60); ft[1].ktsSpeed := 55; // Send the two waypoints to the truck // ** updated for SP1A ** hr := SimConnect_SetDataOnSimObject(hSimConnect, Ord(DefinitionWayPoint), TruckID, 0, Length(ft), SizeOf(ft[0]), @ft[0]); end; procedure TAIObjectsForm.SetUpSimObjects; var Init : TSimConnectDataInitPosition; hr : HRESULT; begin // Add a parked museum aircraft, just west of the runway Init.Altitude := 433.0; // Altitude of Sea-tac is 433 feet Init.Latitude := 47 + (25.97 / 60); // Convert from 47 25.97 N Init.Longitude := -122 - (18.51 / 60); // Convert from 122 18.51 W Init.Pitch := 0.0; Init.Bank := 0.0; Init.Heading := 90.0; Init.OnGround := 1; Init.Airspeed := 0; hr := SimConnect_AICreateSimulatedObject(hSimConnect, 'Douglas DC-3', Init, Ord(REQUEST_DOUGLAS)); // Add a hot air balloon // Except Hot Air ballons are scenery, not simobjects, so you can't add one // Using an "ANI_elephant_walk01_sm" instead.... // Need to use (exactly) the name that is in the "sim.cfg" file for the SimObject // Not the name of the directory, which may not be the same. Init.Altitude := 500.0; // Altitude of Sea-tac is 433 feet Init.Latitude := 47 + (25.97 / 60); // Convert from 47 26.22 N Init.Longitude := -122 - (18.45 / 60); // Convert from 122 18.45 W Init.Pitch := 0.0; Init.Bank := 0.0; Init.Heading := 0.0; Init.OnGround := 0; Init.Airspeed := 0; hr := SimConnect_AICreateSimulatedObject(hSimConnect, 'ANI_elephant_walk01_sm', Init, Ord(REQUEST_BALLOON1)); // Add a helicopter Init.Altitude := 433.0; // Altitude of Sea-tac is 433 feet Init.Latitude := 47 + (26.22 / 60); // Convert from 47 26.22 N Init.Longitude := -122 - (18.48 / 60); // Convert from 122 18.48 W Init.Pitch := 0.0; Init.Bank := 0.0; Init.Heading := 0.0; Init.OnGround := 1; Init.Airspeed := 100; //hr = SimConnect_AICreateNonATCAircraft(hSimConnect, 'Bell 206B JetRanger', 'H1000', Init, Ord(REQUEST_BELL)); // Initialize Mooney aircraft just in front of user aircraft // User aircraft is at 47 25.89 N, 122 18.48 W Init.Altitude := 433.0; // Altitude of Sea-tac is 433 feet Init.Latitude := 47 + (25.91 / 60); // Convert from 47 25.90 N Init.Longitude := -122 - (18.48 / 60); // Convert from 122 18.48 W Init.Pitch := 0.0; Init.Bank := 0.0; Init.Heading := 360.0; Init.OnGround := 1; Init.Airspeed := 1; hr := SimConnect_AICreateNonATCAircraft(hSimConnect, 'Mooney Bravo', 'N1001', Init, Ord(REQUEST_MOONEY)); // Initialize truck just in front of user aircraft // User aircraft is at 47 25.89 N, 122 18.48 W Init.Altitude := 433.0; // Altitude of Sea-tac is 433 feet Init.Latitude := 47 + (25.91 / 60); // Convert from 47 25.90 N Init.Longitude := -122 - (18.47 / 60); // Convert from 122 18.48 W Init.Pitch := 0.0; Init.Bank := 0.0; Init.Heading := 360.0; Init.OnGround := 1; Init.Airspeed := 0; hr := SimConnect_AICreateSimulatedObject(hSimConnect, 'VEH_jetTruck', Init, Ord(REQUEST_TRUCK)); // Add a humpback whale // This is in the view over your left shoulder, and is actually underground. Init.Altitude := 433.0; // Altitude of Sea-tac is 433 feet Init.Latitude := 47 + (25.89 / 60); // Convert from 47 25.89 N Init.Longitude := -122 - (18.51 / 60); // Convert from 122 18.51 W Init.Pitch := 0.0; Init.Bank := 0.0; Init.Heading := 0.0; Init.OnGround := 1; Init.Airspeed := 0; hr := SimConnect_AICreateSimulatedObject(hSimConnect, 'Humpbackwhale', Init, Ord(REQUEST_WHALE)); end; {----------------------------------------------------------------------------- Procedure: SimConnectMessage Author: ken.adam Date: 19-Jan-2007 Arguments: var Message: TMessage Result: None -----------------------------------------------------------------------------} procedure TAIObjectsForm.SimConnectMessage(var Message: TMessage); begin SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil); end; {----------------------------------------------------------------------------- Procedure: StartEventExecute Opens the connection for Event driven handling. If successful sets up the data requests and hooks the system event "SimStart". Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject -----------------------------------------------------------------------------} procedure TAIObjectsForm.StartEventExecute(Sender: TObject); var hr : HRESULT; begin if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', Handle, WM_USER_SIMCONNECT, 0, 0))) then begin StatusBar.Panels[0].Text := 'Connected'; // Create some private events hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventZ)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventX)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventC)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventV)); // Link the private events to keyboard keys, and ensure the input events are off hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'Z', Ord(EventZ)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'X', Ord(EventX)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'C', Ord(EventC)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'V', Ord(EventV)); hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputZX), Ord(SIMCONNECT_STATE_OFF)); // Sign up for notifications hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventZ)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventX)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventC)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventV)); // Set up a definition for a waypoint list hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionWaypoint), 'AI Waypoint List', 'number', SIMCONNECT_DATATYPE_WAYPOINT); // Set up a definition for the balloon throttle bc.throttlePercent := 0.0; hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionThrottle), 'GENERAL ENG THROTTLE LEVER POSITION:1', 'percent'); // Request a simulation start event hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart), 'SimStart'); StartEvent.Enabled := False; StartPoll.Enabled := False; end; end; {----------------------------------------------------------------------------- Procedure: StartPollExecute Opens the connection for Polled access. If successful sets up the data requests and hooks the system event "SimStart", and then loops indefinitely on CallDispatch. Author: ken.adam Date: 11-Jan-2007 Arguments: Sender: TObject -----------------------------------------------------------------------------} procedure TAIObjectsForm.StartPollExecute(Sender: TObject); var hr : HRESULT; begin if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then begin StatusBar.Panels[0].Text := 'Connected'; // Create some private events hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventZ)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventX)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventC)); hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EventV)); // Link the private events to keyboard keys, and ensure the input events are off hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'Z', Ord(EventZ)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'X', Ord(EventX)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'C', Ord(EventC)); hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(InputZX), 'V', Ord(EventV)); hr := SimConnect_SetInputGroupState(hSimConnect, Ord(InputZX), Ord(SIMCONNECT_STATE_OFF)); // Sign up for notifications hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventZ)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventX)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventC)); hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GroupZX), Ord(EventV)); // Set up a definition for a waypoint list hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionWaypoint), 'AI Waypoint List', 'number', SIMCONNECT_DATATYPE_WAYPOINT); // Set up a definition for the balloon throttle bc.throttlePercent := 0.0; hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionThrottle), 'MASTER IGNITION SWITCH', 'bool', SIMCONNECT_DATATYPE_FLOAT32); hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionThrottle), 'GENERAL ENG THROTTLE LEVER POSITION:1', 'percent', SIMCONNECT_DATATYPE_FLOAT64); // Request a simulation start event hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart), 'SimStart'); StartEvent.Enabled := False; StartPoll.Enabled := False; while not Quit do begin SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil); Application.ProcessMessages; Sleep(1); end; hr := SimConnect_Close(hSimConnect); end; end; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Authenticator.Simple; interface uses System.Classes, Data.Bind.ObjectScope, Data.Bind.Components, REST.Types, REST.Client, REST.Consts, REST.BindSource; type TSubSimpleAuthenticationBindSource = class; /// <summary> /// implements a simple authentication using an username and a password as /// GET or POST - parameters /// </summary> TSimpleAuthenticator = class(TCustomAuthenticator) private FBindSource: TSubSimpleAuthenticationBindSource; FUsernameKey: string; FUsername: string; FPasswordKey: string; FPassword: string; procedure SetPassword(const AValue: string); procedure SetPasswordKey(const AValue: string); procedure SetUsername(const AValue: string); procedure SetUsernameKey(const AValue: string); protected procedure DoAuthenticate(ARequest: TCustomRESTRequest); override; function CreateBindSource: TBaseObjectBindSource; override; public constructor Create(const AUsernameKey, AUsername, APasswordKey, APassword: string); reintroduce; overload; /// <summary> /// Resets a request to default values and clears all entries. /// </summary> procedure ResetToDefaults; override; published property UsernameKey: string read FUsernameKey write SetUsernameKey; property Username: string read FUsername write SetUsername; property PasswordKey: string read FPasswordKey write SetPasswordKey; property Password: string read FPassword write SetPassword; property BindSource: TSubSimpleAuthenticationBindSource read FBindSource; end; /// <summary> /// LiveBindings bindsource for TSimpleAuthenticator. Publishes subcomponent properties. /// </summary> TSubSimpleAuthenticationBindSource = class(TRESTAuthenticatorBindSource<TSimpleAuthenticator>) protected function CreateAdapterT: TRESTAuthenticatorAdapter<TSimpleAuthenticator>; override; end; /// <summary> /// LiveBindings adapter for TSimpleAuthenticator. Create bindable members. /// </summary> TSimpleAuthenticatorAdapter = class(TRESTAuthenticatorAdapter<TSimpleAuthenticator>) protected procedure AddFields; override; end; implementation { TSimpleAuthenticator } constructor TSimpleAuthenticator.Create(const AUsernameKey, AUsername, APasswordKey, APassword: string); begin Create(NIL); FUsernameKey := AUsernameKey; FUsername := AUsername; FPasswordKey := APasswordKey; FPassword := APassword; end; function TSimpleAuthenticator.CreateBindSource: TBaseObjectBindSource; begin FBindSource := TSubSimpleAuthenticationBindSource.Create(Self); FBindSource.Name := 'BindSource'; { Do not localize } FBindSource.SetSubComponent(True); FBindSource.Authenticator := Self; result := FBindSource; end; procedure TSimpleAuthenticator.DoAuthenticate(ARequest: TCustomRESTRequest); begin inherited; ARequest.Params.BeginUpdate; try ARequest.AddAuthParameter(FUsernameKey, FUsername, TRESTRequestParameterKind.pkGETorPOST); ARequest.AddAuthParameter(FPasswordKey, FPassword, TRESTRequestParameterKind.pkGETorPOST); finally ARequest.Params.EndUpdate; end; end; procedure TSimpleAuthenticator.ResetToDefaults; begin inherited; UsernameKey := ''; Username := ''; PasswordKey := ''; Password := ''; end; procedure TSimpleAuthenticator.SetPassword(const AValue: string); begin if (AValue <> FPassword) then begin FPassword := AValue; PropertyValueChanged; end; end; procedure TSimpleAuthenticator.SetPasswordKey(const AValue: string); begin if (AValue <> FPasswordKey) then begin FPasswordKey := AValue; PropertyValueChanged; end; end; procedure TSimpleAuthenticator.SetUsername(const AValue: string); begin if (AValue <> FUsername) then begin FUsername := AValue; PropertyValueChanged; end; end; procedure TSimpleAuthenticator.SetUsernameKey(const AValue: string); begin if (AValue <> FUsernameKey) then begin FUsernameKey := AValue; PropertyValueChanged; end; end; { TSubSimpleAuthenticationBindSource } function TSubSimpleAuthenticationBindSource.CreateAdapterT: TRESTAuthenticatorAdapter<TSimpleAuthenticator>; begin result := TSimpleAuthenticatorAdapter.Create(Self); end; { TSimpleAuthenticatorAdapter } procedure TSimpleAuthenticatorAdapter.AddFields; const sUserName = 'UserName'; sUserNameKey = 'UserNameKey'; sPassword = 'Password'; sPasswordKey = 'PasswordKey'; var LGetMemberObject: IGetMemberObject; begin CheckInactive; ClearFields; if Authenticator <> nil then begin LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self); CreateReadWriteField<string>(sUserName, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.Username; end, procedure(AValue: string) begin Authenticator.Username := AValue; end); CreateReadWriteField<string>(sUserNameKey, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.UsernameKey; end, procedure(AValue: string) begin Authenticator.UsernameKey := AValue; end); CreateReadWriteField<string>(sPassword, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.Password; end, procedure(AValue: string) begin Authenticator.Password := AValue; end); CreateReadWriteField<string>(sPasswordKey, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.PasswordKey; end, procedure(AValue: string) begin Authenticator.PasswordKey := AValue; end); end; end; end.
{ X2Software XML Data Binding Generated on: 6-9-2017 16:58:58 Generated from: P:\x2xmldatabinding\XSD\DataBindingSettings.xsd } unit DataBindingSettingsXML; interface uses Classes, SysUtils, XMLDoc, XMLIntf, XMLDataBindingUtils; type { Forward declarations for DataBindingSettings } IXMLDataBindingSettings = interface; IXMLDataBindingOutput = interface; IXMLOutputSingle = interface; IXMLOutputMultiple = interface; TXMLDataBindingOutputType = (DataBindingOutputType_Single, DataBindingOutputType_Multiple); { Interfaces for DataBindingSettings } { Contains the settings and hints for the Delphi XML Data Binding. } IXMLDataBindingSettings = interface(IXMLNode) ['{90C0CA10-A7AD-4418-98B6-D03469DB8913}'] procedure XSDValidateDocument(AStrict: Boolean = False); function GetHasOutput: Boolean; function GetOutput: IXMLDataBindingOutput; property HasOutput: Boolean read GetHasOutput; property Output: IXMLDataBindingOutput read GetOutput; end; { Contains the user-defined output settings last used } IXMLDataBindingOutput = interface(IXMLNode) ['{166F0975-2D2F-4CDB-B911-005163A0761F}'] procedure XSDValidate; procedure XSDValidateStrict(AResult: IXSDValidateStrictResult); function GetOutputTypeText: WideString; function GetOutputType: TXMLDataBindingOutputType; function GetHasOutputSingle: Boolean; function GetOutputSingle: IXMLOutputSingle; function GetHasOutputMultiple: Boolean; function GetOutputMultiple: IXMLOutputMultiple; function GetHasHasChecksEmpty: Boolean; function GetHasChecksEmpty: Boolean; function GetHasGenerateGetOptionalOrDefault: Boolean; function GetGenerateGetOptionalOrDefault: Boolean; procedure SetOutputTypeText(const Value: WideString); procedure SetOutputType(const Value: TXMLDataBindingOutputType); procedure SetHasChecksEmpty(const Value: Boolean); procedure SetGenerateGetOptionalOrDefault(const Value: Boolean); property OutputTypeText: WideString read GetOutputTypeText write SetOutputTypeText; property OutputType: TXMLDataBindingOutputType read GetOutputType write SetOutputType; property HasOutputSingle: Boolean read GetHasOutputSingle; property OutputSingle: IXMLOutputSingle read GetOutputSingle; property HasOutputMultiple: Boolean read GetHasOutputMultiple; property OutputMultiple: IXMLOutputMultiple read GetOutputMultiple; property HasHasChecksEmpty: Boolean read GetHasHasChecksEmpty; property HasChecksEmpty: Boolean read GetHasChecksEmpty write SetHasChecksEmpty; property HasGenerateGetOptionalOrDefault: Boolean read GetHasGenerateGetOptionalOrDefault; property GenerateGetOptionalOrDefault: Boolean read GetGenerateGetOptionalOrDefault write SetGenerateGetOptionalOrDefault; end; IXMLOutputSingle = interface(IXMLNode) ['{77AE2C19-333F-4335-872E-659AE17C4701}'] procedure XSDValidate; procedure XSDValidateStrict(AResult: IXSDValidateStrictResult); function GetFileName: WideString; procedure SetFileName(const Value: WideString); property FileName: WideString read GetFileName write SetFileName; end; IXMLOutputMultiple = interface(IXMLNode) ['{8C1E7817-DBF1-4125-B29A-F7279006C7FB}'] procedure XSDValidate; procedure XSDValidateStrict(AResult: IXSDValidateStrictResult); function GetPath: WideString; function GetPrefix: WideString; function GetPostfix: WideString; procedure SetPath(const Value: WideString); procedure SetPrefix(const Value: WideString); procedure SetPostfix(const Value: WideString); property Path: WideString read GetPath write SetPath; property Prefix: WideString read GetPrefix write SetPrefix; property Postfix: WideString read GetPostfix write SetPostfix; end; { Classes for DataBindingSettings } TXMLDataBindingSettings = class(TX2XMLNode, IXMLDataBindingSettings) public procedure AfterConstruction; override; protected procedure XSDValidateDocument(AStrict: Boolean = False); function GetHasOutput: Boolean; function GetOutput: IXMLDataBindingOutput; end; TXMLDataBindingOutput = class(TX2XMLNode, IXSDValidate, IXSDValidateStrict, IXMLDataBindingOutput) public procedure AfterConstruction; override; protected procedure XSDValidate; procedure XSDValidateStrict(AResult: IXSDValidateStrictResult); function GetOutputTypeText: WideString; function GetOutputType: TXMLDataBindingOutputType; function GetHasOutputSingle: Boolean; function GetOutputSingle: IXMLOutputSingle; function GetHasOutputMultiple: Boolean; function GetOutputMultiple: IXMLOutputMultiple; function GetHasHasChecksEmpty: Boolean; function GetHasChecksEmpty: Boolean; function GetHasGenerateGetOptionalOrDefault: Boolean; function GetGenerateGetOptionalOrDefault: Boolean; procedure SetOutputTypeText(const Value: WideString); procedure SetOutputType(const Value: TXMLDataBindingOutputType); procedure SetHasChecksEmpty(const Value: Boolean); procedure SetGenerateGetOptionalOrDefault(const Value: Boolean); end; TXMLOutputSingle = class(TX2XMLNode, IXSDValidate, IXSDValidateStrict, IXMLOutputSingle) protected procedure XSDValidate; procedure XSDValidateStrict(AResult: IXSDValidateStrictResult); function GetFileName: WideString; procedure SetFileName(const Value: WideString); end; TXMLOutputMultiple = class(TX2XMLNode, IXSDValidate, IXSDValidateStrict, IXMLOutputMultiple) protected procedure XSDValidate; procedure XSDValidateStrict(AResult: IXSDValidateStrictResult); function GetPath: WideString; function GetPrefix: WideString; function GetPostfix: WideString; procedure SetPath(const Value: WideString); procedure SetPrefix(const Value: WideString); procedure SetPostfix(const Value: WideString); end; { Document functions } function GetDataBindingSettings(ADocument: XMLIntf.IXMLDocument): IXMLDataBindingSettings; function LoadDataBindingSettings(const AFileName: String): IXMLDataBindingSettings; function LoadDataBindingSettingsFromStream(AStream: TStream): IXMLDataBindingSettings; function LoadDataBindingSettingsFromString(const AString: String{$IF CompilerVersion >= 20}; AEncoding: TEncoding = nil; AOwnsEncoding: Boolean = True{$IFEND}): IXMLDataBindingSettings; function NewDataBindingSettings: IXMLDataBindingSettings; const TargetNamespace = 'http://www.x2software.net/xsd/databinding/DataBindingSettings.xsd'; const DataBindingOutputTypeValues: array[TXMLDataBindingOutputType] of WideString = ( 'Single', 'Multiple' ); { Enumeration conversion helpers } function StringToDataBindingOutputType(const AValue: WideString): TXMLDataBindingOutputType; implementation uses Variants; { Document functions } function GetDataBindingSettings(ADocument: XMLIntf.IXMLDocument): IXMLDataBindingSettings; begin Result := ADocument.GetDocBinding('DataBindingSettings', TXMLDataBindingSettings, TargetNamespace) as IXMLDataBindingSettings end; function LoadDataBindingSettings(const AFileName: String): IXMLDataBindingSettings; begin Result := LoadXMLDocument(AFileName).GetDocBinding('DataBindingSettings', TXMLDataBindingSettings, TargetNamespace) as IXMLDataBindingSettings end; function LoadDataBindingSettingsFromStream(AStream: TStream): IXMLDataBindingSettings; var doc: XMLIntf.IXMLDocument; begin doc := NewXMLDocument; doc.LoadFromStream(AStream); Result := GetDataBindingSettings(doc); end; function LoadDataBindingSettingsFromString(const AString: String{$IF CompilerVersion >= 20}; AEncoding: TEncoding; AOwnsEncoding: Boolean{$IFEND}): IXMLDataBindingSettings; var stream: TStringStream; begin {$IF CompilerVersion >= 20} if Assigned(AEncoding) then stream := TStringStream.Create(AString, AEncoding, AOwnsEncoding) else {$IFEND} stream := TStringStream.Create(AString); try Result := LoadDataBindingSettingsFromStream(stream); finally FreeAndNil(stream); end; end; function NewDataBindingSettings: IXMLDataBindingSettings; begin Result := NewXMLDocument.GetDocBinding('DataBindingSettings', TXMLDataBindingSettings, TargetNamespace) as IXMLDataBindingSettings end; { Enumeration conversion helpers } function StringToDataBindingOutputType(const AValue: WideString): TXMLDataBindingOutputType; var enumValue: TXMLDataBindingOutputType; begin Result := TXMLDataBindingOutputType(-1); for enumValue := Low(TXMLDataBindingOutputType) to High(TXMLDataBindingOutputType) do if DataBindingOutputTypeValues[enumValue] = AValue then begin Result := enumValue; break; end; end; { Implementation for DataBindingSettings } procedure TXMLDataBindingSettings.AfterConstruction; begin RegisterChildNode('Output', TXMLDataBindingOutput); inherited; end; procedure TXMLDataBindingSettings.XSDValidateDocument(AStrict: Boolean); begin if AStrict then XMLDataBindingUtils.XSDValidateStrict(Self) else XMLDataBindingUtils.XSDValidate(Self); end; function TXMLDataBindingSettings.GetHasOutput: Boolean; begin Result := Assigned(ChildNodes.FindNode('Output')); end; function TXMLDataBindingSettings.GetOutput: IXMLDataBindingOutput; begin Result := (ChildNodes['Output'] as IXMLDataBindingOutput); end; procedure TXMLDataBindingOutput.AfterConstruction; begin RegisterChildNode('OutputSingle', TXMLOutputSingle); RegisterChildNode('OutputMultiple', TXMLOutputMultiple); inherited; end; procedure TXMLDataBindingOutput.XSDValidate; begin GetOutputType; SortChildNodes(Self, ['OutputType', 'OutputSingle', 'OutputMultiple', 'HasChecksEmpty', 'GenerateGetOptionalOrDefault']); end; procedure TXMLDataBindingOutput.XSDValidateStrict(AResult: IXSDValidateStrictResult); begin GetOutputType; SortChildNodes(Self, ['OutputType', 'OutputSingle', 'OutputMultiple', 'HasChecksEmpty', 'GenerateGetOptionalOrDefault']); end; function TXMLDataBindingOutput.GetOutputTypeText: WideString; begin Result := ChildNodes['OutputType'].Text; end; function TXMLDataBindingOutput.GetOutputType: TXMLDataBindingOutputType; begin Result := StringToDataBindingOutputType(GetOutputTypeText); end; function TXMLDataBindingOutput.GetHasOutputSingle: Boolean; begin Result := Assigned(ChildNodes.FindNode('OutputSingle')); end; function TXMLDataBindingOutput.GetOutputSingle: IXMLOutputSingle; begin Result := (ChildNodes['OutputSingle'] as IXMLOutputSingle); end; function TXMLDataBindingOutput.GetHasOutputMultiple: Boolean; begin Result := Assigned(ChildNodes.FindNode('OutputMultiple')); end; function TXMLDataBindingOutput.GetOutputMultiple: IXMLOutputMultiple; begin Result := (ChildNodes['OutputMultiple'] as IXMLOutputMultiple); end; function TXMLDataBindingOutput.GetHasHasChecksEmpty: Boolean; begin Result := Assigned(ChildNodes.FindNode('HasChecksEmpty')); end; function TXMLDataBindingOutput.GetHasChecksEmpty: Boolean; begin Result := ChildNodes['HasChecksEmpty'].NodeValue; end; function TXMLDataBindingOutput.GetHasGenerateGetOptionalOrDefault: Boolean; begin Result := Assigned(ChildNodes.FindNode('GenerateGetOptionalOrDefault')); end; function TXMLDataBindingOutput.GetGenerateGetOptionalOrDefault: Boolean; begin Result := ChildNodes['GenerateGetOptionalOrDefault'].NodeValue; end; procedure TXMLDataBindingOutput.SetOutputTypeText(const Value: WideString); begin ChildNodes['OutputType'].NodeValue := Value; end; procedure TXMLDataBindingOutput.SetOutputType(const Value: TXMLDataBindingOutputType); begin ChildNodes['OutputType'].NodeValue := DataBindingOutputTypeValues[Value]; end; procedure TXMLDataBindingOutput.SetHasChecksEmpty(const Value: Boolean); begin ChildNodes['HasChecksEmpty'].NodeValue := BoolToXML(Value); end; procedure TXMLDataBindingOutput.SetGenerateGetOptionalOrDefault(const Value: Boolean); begin ChildNodes['GenerateGetOptionalOrDefault'].NodeValue := BoolToXML(Value); end; procedure TXMLOutputSingle.XSDValidate; begin CreateRequiredElements(Self, ['FileName']); end; procedure TXMLOutputSingle.XSDValidateStrict(AResult: IXSDValidateStrictResult); begin ValidateRequiredElements(AResult, Self, ['FileName']); end; function TXMLOutputSingle.GetFileName: WideString; begin Result := ChildNodes['FileName'].Text; end; procedure TXMLOutputSingle.SetFileName(const Value: WideString); begin ChildNodes['FileName'].NodeValue := GetValidXMLText(Value); end; procedure TXMLOutputMultiple.XSDValidate; begin CreateRequiredElements(Self, ['Path', 'Prefix', 'Postfix']); SortChildNodes(Self, ['Path', 'Prefix', 'Postfix']); end; procedure TXMLOutputMultiple.XSDValidateStrict(AResult: IXSDValidateStrictResult); begin ValidateRequiredElements(AResult, Self, ['Path', 'Prefix', 'Postfix']); SortChildNodes(Self, ['Path', 'Prefix', 'Postfix']); end; function TXMLOutputMultiple.GetPath: WideString; begin Result := ChildNodes['Path'].Text; end; function TXMLOutputMultiple.GetPrefix: WideString; begin Result := ChildNodes['Prefix'].Text; end; function TXMLOutputMultiple.GetPostfix: WideString; begin Result := ChildNodes['Postfix'].Text; end; procedure TXMLOutputMultiple.SetPath(const Value: WideString); begin ChildNodes['Path'].NodeValue := GetValidXMLText(Value); end; procedure TXMLOutputMultiple.SetPrefix(const Value: WideString); begin ChildNodes['Prefix'].NodeValue := GetValidXMLText(Value); end; procedure TXMLOutputMultiple.SetPostfix(const Value: WideString); begin ChildNodes['Postfix'].NodeValue := GetValidXMLText(Value); end; end.
unit classe.sistema; interface uses StrUtils,SysUtils, DateUtils, System.Variants, System.Classes, Winapi.Windows; type TSistema = class private FDiretorioPadrao, pVersao : string; FDataBase: TDate; FPathArqIni, FServidorBanco, FIPServidor, FNomeBanco, FLoginBanco, FSenhaBAnco : String; FAno: word; FAnoAnterior: word; FDataAtual: TDateTime; FMes: word; procedure CarregarArqIni; public Constructor Create; function CapturarVersaoExe: string; procedure AtualizarParametrosData; property DiretorioPadrao : string read FDiretorioPadrao; property PathArquivoIni : string read FPathArqIni; property Versao : String read pVersao; property AnoAtual : word read FAno; property AnoAnterior : word read FAnoAnterior; property MesAtual : word read FMes; property DataAtual : TDateTime read FDataAtual; end; implementation { TSistema } uses Dados.Firebird, UnVariaveisGlobais, UnFuncoesAuxiliares; procedure TSistema.AtualizarParametrosData; begin FAno := YearOf(Date); FMes := MonthOf(Date); FAnoAnterior := YearOf(Date) - 1; FDataAtual := Date; end; function TSistema.CapturarVersaoExe: string; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; aVersao : string; begin VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy); GetMem(VerInfo, VerInfoSize); GetFileVersionInfo(PChar(ParamStr(0)), 0,VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue),VerValueSize); with VerValue^ do begin aVersao := IntToStr(dwFileVersionMS shr 16); aVersao := aVersao + '.' + IntToStr(dwFileVersionMS and $FFFF); aVersao := aVersao + '.' + IntToStr(dwFileVersionLS shr 16); // aVersao := aVersao + '.' + IntToStr(dwFileVersionLS and $FFFF); end; Result := aVersao; FreeMem(VerInfo, VerInfoSize); end; procedure TSistema.CarregarArqIni; begin FPathArqIni := FDiretorioPadrao+'\Config.ini'; pPathArquivoIni := FPathArqIni; FServidorBanco := LerArquivoIni('CONEXAO','Servidor'); FIPServidor := LerArquivoIni('CONEXAO','IP Servidor'); FNomeBanco := LerArquivoIni('CONEXAO','Banco'); FLoginBanco := LerArquivoIni('CONEXAO','Usuario'); FSenhaBAnco := LerArquivoIni('CONEXAO','Senha'); end; constructor TSistema.Create; begin FDiretorioPadrao := GetCurrentDir; CarregarArqIni; pVersao := CapturarVersaoExe; AtualizarParametrosData; try DadosFirebird.Conectar(FServidorBanco, FNomeBanco,FLoginBanco, FSenhaBAnco); except on E: Exception do begin raise Exception.Create('Problemas na conex„o com o banco! '+E.Message); end; end; end; end.
unit uYunJingAlarm; interface uses System.SysUtils, System.Classes, IniFiles, uLogger, SyncObjs, IOUtils, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, IdContext, IdHttp, IdUri, Types, Generics.Collections, uHik86Sender, uGlobal, uTypes, NetEncoding; type TYunJingPass = record HPHM, HPYS, IMEI, Longitude, Latitude: string; end; TYunJingThread = class(TThread) private FPass: TYunJingPass; procedure GetAlarm; protected procedure Execute; override; public constructor Create(pass: TYunJingPass); overload; end; TYunJingAlarm = class private IdHTTPServerIn: TIdHTTPServer; procedure IdHTTPServerInCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); public constructor Create; destructor Destroy; override; end; var YunJingAlarm: TYunJingAlarm; ALarmUrl: string; implementation constructor TYunJingAlarm.Create; var ini: TIniFile; port: integer; begin ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini'); AlarmUrl := ini.ReadString('YunJingAlarm', 'AlarmUrl', ''); port := ini.ReadInteger('YunJingAlarm', 'PORT', 18009); ini.Free; IdHTTPServerIn := TIdHTTPServer.Create(nil); IdHTTPServerIn.Bindings.Clear; IdHTTPServerIn.DefaultPort := port; IdHTTPServerIn.OnCommandGet := self.IdHTTPServerInCommandGet; try IdHTTPServerIn.Active := True; logger.logging('YunJingAlarm start', 2); except on e: Exception do begin logger.logging(e.Message, 4); end; end; end; procedure TYunJingAlarm.IdHTTPServerInCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var pass: TYunJingPass; begin try pass.HPHM := ARequestInfo.Params.Values['HPHM']; pass.HPHM := TNetEncoding.URL.Decode(pass.HPHM); pass.HPYS := ARequestInfo.Params.Values['HPYS']; pass.IMEI := ARequestInfo.Params.Values['IMEI']; pass.Longitude := ARequestInfo.Params.Values['Longitude']; pass.Latitude := ARequestInfo.Params.Values['Latitude']; if pass.HPHM <> '' then TYunJingThread.Create(pass); AResponseInfo.ContentText := 'OK'; except on e: Exception do begin logger.Error(e.Message); end; end; end; destructor TYunJingAlarm.Destroy; begin idHttpServerIn.Active := false; idHttpServerIn.Free; logger.Info('YunJingAlarm stoped'); end; { TYunJingThread } constructor TYunJingThread.Create(pass: TYunJingPass); begin self.FreeOnTerminate := true; FPass := pass; inherited Create(false); end; procedure TYunJingThread.Execute; begin inherited; GetAlarm; end; procedure TYunJingThread.GetAlarm; function IsValid(HPHM, HPZL: string): boolean; var s: string; begin s := '';//TQTZHelper.GetVehInfo(HPHM, HPZL); result := not s.Contains('"ZT":"A"'); end; function IsYunJing(kdbh: string): boolean; begin result := IMEIDic.ContainsKey(kdbh); end; procedure HttpPost(pass: TYunJingPass; bklx: string); var data: TStringList; http: TIdHttp; first: boolean; s: string; begin http := TIdHttp.Create(nil); data := TStringList.Create; first := true; s := ALarmUrl + '?data=[{"jybh":"' + pass.IMEI + '","hphm":"' + pass.hphm + '","hpzl":"' + '02' + '","csys":"' + pass.hpys + '","yjlx":"' + bklx + '"}]'; s := IdUri.TIdURI.URLEncode(s); try s := http.Post(s, data); logger.Debug('[TYunJingThread.GetAlarm.HttpPost]' + s); except on e: exception do begin logger.Error('[TYunJingThread.GetAlarm.HttpPost]' + e.Message); end; end; data.Free; http.Free; end; var alarm: TAlarm; begin if IsYunJing(FPass.IMEI) and AlarmDic.ContainsKey(FPass.HPHM) then begin alarm := AlarmDic[FPass.HPHM]; if alarm.ZT and IsValid(FPass.HPHM, '02') then begin HttpPost(FPass, alarm.BKLX); logger.Info('[YunJingAlarm]:' + FPass.HPHM); end else if alarm.ZT then begin alarm.ZT := false; AlarmDic[FPass.HPHM] := alarm; end; end; end; end.
unit record_fields_init_test; interface implementation type TRec = record a: int32 = 11; b: int32 = 22; end; var G1, G2: Int32; procedure Test; var R: TRec; begin G1 := R.a; G2 := R.b; end; initialization Test(); finalization Assert(G1 = 11); Assert(G2 = 22); end.
{ *************************************************************************** } { } { Audio Tools Library (Freeware) } { Class TID3v2 - for manipulating with ID3v2 tags } { } { Copyright (c) 2001,2002 by Jurgen Faul } { E-mail: jfaul@gmx.de } { http://jfaul.de/atl } { } { Version 1.4 (24 March 2002) } { - Reading support for ID3v2.2.x & ID3v2.4.x tags } { } { Version 1.3 (16 February 2002) } { - Fixed bug with property Comment } { - Added info: composer, encoder, copyright, language, link } { } { Version 1.2 (17 October 2001) } { - Writing support for ID3v2.3.x tags } { - Fixed bug with track number detection } { - Fixed bug with tag reading } { } { Version 1.1 (31 August 2001) } { - Added public procedure ResetData } { } { Version 1.0 (14 August 2001) } { - Reading support for ID3v2.3.x tags } { - Tag info: title, artist, album, track, year, genre, comment } { } { *************************************************************************** } unit ID3v2; interface uses Classes, SysUtils; const TAG_VERSION_2_2 = 2; { Code for ID3v2.2.x tag } TAG_VERSION_2_3 = 3; { Code for ID3v2.3.x tag } TAG_VERSION_2_4 = 4; { Code for ID3v2.4.x tag } type { Class TID3v2 } TID3v2 = class(TObject) private { Private declarations } FExists: Boolean; FVersionID: Byte; FSize: Integer; FTitle: string; FArtist: string; FAlbum: string; FTrack: Byte; FYear: string; FGenre: string; FComment: string; FComposer: string; FEncoder: string; FCopyright: string; FLanguage: string; FLink: string; procedure FSetTitle(const NewTitle: string); procedure FSetArtist(const NewArtist: string); procedure FSetAlbum(const NewAlbum: string); procedure FSetTrack(const NewTrack: Byte); procedure FSetYear(const NewYear: string); procedure FSetGenre(const NewGenre: string); procedure FSetComment(const NewComment: string); procedure FSetComposer(const NewComposer: string); procedure FSetEncoder(const NewEncoder: string); procedure FSetCopyright(const NewCopyright: string); procedure FSetLanguage(const NewLanguage: string); procedure FSetLink(const NewLink: string); public { Public declarations } constructor Create; { Create object } procedure ResetData; { Reset all data } function ReadFromFile(const FileName: string): Boolean; { Load tag } function SaveToFile(const FileName: string): Boolean; { Save tag } function RemoveFromFile(const FileName: string): Boolean; { Delete tag } property Exists: Boolean read FExists; { True if tag found } property VersionID: Byte read FVersionID; { Version code } property Size: Integer read FSize; { Total tag size } property Title: string read FTitle write FSetTitle; { Song title } property Artist: string read FArtist write FSetArtist; { Artist name } property Album: string read FAlbum write FSetAlbum; { Album title } property Track: Byte read FTrack write FSetTrack; { Track number } property Year: string read FYear write FSetYear; { Release year } property Genre: string read FGenre write FSetGenre; { Genre name } property Comment: string read FComment write FSetComment; { Comment } property Composer: string read FComposer write FSetComposer; { Composer } property Encoder: string read FEncoder write FSetEncoder; { Encoder } property Copyright: string read FCopyright write FSetCopyright; { (c) } property Language: string read FLanguage write FSetLanguage; { Language } property Link: string read FLink write FSetLink; { URL link } end; implementation const { ID3v2 tag ID } ID3V2_ID = 'ID3'; { Max. number of supported tag frames } ID3V2_FRAME_COUNT = 16; { Names of supported tag frames (ID3v2.3.x & ID3v2.4.x) } ID3V2_FRAME_NEW: array [1..ID3V2_FRAME_COUNT] of string = ('TIT2', 'TPE1', 'TALB', 'TRCK', 'TYER', 'TCON', 'COMM', 'TCOM', 'TENC', 'TCOP', 'TLAN', 'WXXX', 'TDRC', 'TOPE', 'TIT1', 'TOAL'); { Names of supported tag frames (ID3v2.2.x) } ID3V2_FRAME_OLD: array [1..ID3V2_FRAME_COUNT] of string = ('TT2', 'TP1', 'TAL', 'TRK', 'TYE', 'TCO', 'COM', 'TCM', 'TEN', 'TCR', 'TLA', 'WXX', 'TOR', 'TOA', 'TT1', 'TOT'); type { Frame header (ID3v2.3.x & ID3v2.4.x) } FrameHeaderNew = record ID: array [1..4] of Char; { Frame ID } Size: Integer; { Size excluding header } Flags: Word; { Flags } end; { Frame header (ID3v2.2.x) } FrameHeaderOld = record ID: array [1..3] of Char; { Frame ID } Size: array [1..3] of Byte; { Size excluding header } end; { ID3v2 header data - for internal use } TagInfo = record { Real structure of ID3v2 header } ID: array [1..3] of Char; { Always "ID3" } Version: Byte; { Version number } Revision: Byte; { Revision number } Flags: Byte; { Flags of tag } Size: array [1..4] of Byte; { Tag size excluding header } { Extended data } FileSize: Integer; { File size (bytes) } Frame: array [1..ID3V2_FRAME_COUNT] of string; { Information from frames } end; { ********************* Auxiliary functions & procedures ******************** } function ReadHeader(const FileName: string; var Tag: TagInfo): Boolean; var SourceFile: file; Transferred: Integer; begin try Result := true; { Set read-access and open file } AssignFile(SourceFile, FileName); FileMode := 0; Reset(SourceFile, 1); { Read header and get file size } BlockRead(SourceFile, Tag, 10, Transferred); Tag.FileSize := FileSize(SourceFile); CloseFile(SourceFile); { if transfer is not complete } if Transferred < 10 then Result := false; except { Error } Result := false; end; end; { --------------------------------------------------------------------------- } function GetTagSize(const Tag: TagInfo): Integer; begin { Get total tag size } Result := Tag.Size[1] * $200000 + Tag.Size[2] * $4000 + Tag.Size[3] * $80 + Tag.Size[4] + 10; if Tag.Flags and $10 > 0 then Inc(Result, 10); if Result > Tag.FileSize then Result := 0; end; { --------------------------------------------------------------------------- } procedure SetTagItem(const ID, Data: string; var Tag: TagInfo); var Iterator: Byte; FrameID: string; begin { Set tag item if supported frame found } for Iterator := 1 to ID3V2_FRAME_COUNT do begin if Tag.Version > TAG_VERSION_2_2 then FrameID := ID3V2_FRAME_NEW[Iterator] else FrameID := ID3V2_FRAME_OLD[Iterator]; if FrameID = ID then Tag.Frame[Iterator] := Data; end; end; { --------------------------------------------------------------------------- } function Swap32(const Figure: Integer): Integer; var ByteArray: array [1..4] of Byte absolute Figure; begin { Swap 4 bytes } Result := ByteArray[1] * $1000000 + ByteArray[2] * $10000 + ByteArray[3] * $100 + ByteArray[4]; end; { --------------------------------------------------------------------------- } procedure ReadFramesNew(const FileName: string; var Tag: TagInfo); var SourceFile: file; Frame: FrameHeaderNew; Data: array [1..250] of Char; DataPosition, DataSize: Integer; begin { Get information from frames (ID3v2.3.x & ID3v2.4.x) } try { Set read-access, open file } AssignFile(SourceFile, FileName); FileMode := 0; Reset(SourceFile, 1); Seek(SourceFile, 10); while (FilePos(SourceFile) < GetTagSize(Tag)) and (not EOF(SourceFile)) do begin FillChar(Data, SizeOf(Data), 0); { Read frame header and check frame ID } BlockRead(SourceFile, Frame, 10); if not (Frame.ID[1] in ['A'..'Z']) then break; { Note data position and determine significant data size } DataPosition := FilePos(SourceFile); if Swap32(Frame.Size) > SizeOf(Data) then DataSize := SizeOf(Data) else DataSize := Swap32(Frame.Size); { Read frame data and set tag item if frame supported } BlockRead(SourceFile, Data, DataSize); SetTagItem(Frame.ID, Data, Tag); Seek(SourceFile, DataPosition + Swap32(Frame.Size)); end; CloseFile(SourceFile); except end; end; { --------------------------------------------------------------------------- } procedure ReadFramesOld(const FileName: string; var Tag: TagInfo); var SourceFile: file; Frame: FrameHeaderOld; Data: array [1..250] of Char; DataPosition, FrameSize, DataSize: Integer; begin { Get information from frames (ID3v2.2.x) } try { Set read-access, open file } AssignFile(SourceFile, FileName); FileMode := 0; Reset(SourceFile, 1); Seek(SourceFile, 10); while (FilePos(SourceFile) < GetTagSize(Tag)) and (not EOF(SourceFile)) do begin FillChar(Data, SizeOf(Data), 0); { Read frame header and check frame ID } BlockRead(SourceFile, Frame, 6); if not (Frame.ID[1] in ['A'..'Z']) then break; { Note data position and determine significant data size } DataPosition := FilePos(SourceFile); FrameSize := Frame.Size[1] shl 16 + Frame.Size[2] shl 8 + Frame.Size[3]; if FrameSize > SizeOf(Data) then DataSize := SizeOf(Data) else DataSize := FrameSize; { Read frame data and set tag item if frame supported } BlockRead(SourceFile, Data, DataSize); SetTagItem(Frame.ID, Data, Tag); Seek(SourceFile, DataPosition + FrameSize); end; CloseFile(SourceFile); except end; end; { --------------------------------------------------------------------------- } function GetContent(const Content1, Content2: string): string; begin { Get content preferring the first content } Result := Trim(Content1); if Result = '' then Result := Trim(Content2); end; { --------------------------------------------------------------------------- } function ExtractTrack(const TrackString: string): Byte; var Index, Value, Code: Integer; begin { Extract track from string } Index := Pos('/', Trim(TrackString)); if Index = 0 then Val(Trim(TrackString), Value, Code) else Val(Copy(Trim(TrackString), 1, Index - 1), Value, Code); if Code = 0 then Result := Value else Result := 0; end; { --------------------------------------------------------------------------- } function ExtractYear(const YearString, DateString: string): string; begin { Extract year from strings } Result := Trim(YearString); if Result = '' then Result := Copy(Trim(DateString), 1, 4); end; { --------------------------------------------------------------------------- } function ExtractGenre(const GenreString: string): string; begin { Extract genre from string } Result := Trim(GenreString); if Pos(')', Result) > 0 then Delete(Result, 1, LastDelimiter(')', Result)); end; { --------------------------------------------------------------------------- } function ExtractComment(const CommentString: string): string; var Comment: string; begin { Extract comment from string } Comment := CommentString; Delete(Comment, 1, 4); Delete(Comment, 1, Pos(#0, Comment)); Result := Trim(Comment); end; { --------------------------------------------------------------------------- } function ExtractLink(const LinkString: string): string; var Link: string; begin { Extract URL link from string } Link := LinkString; Delete(Link, 1, 1); Delete(Link, 1, Pos(#0, Link)); Result := Trim(Link); end; { --------------------------------------------------------------------------- } procedure BuildHeader(var Tag: TagInfo); var Iterator, TagSize: Integer; begin { Build tag header } Tag.ID := ID3V2_ID; Tag.Version := TAG_VERSION_2_3; Tag.Revision := 0; Tag.Flags := 0; TagSize := 0; for Iterator := 1 to ID3V2_FRAME_COUNT do if Tag.Frame[Iterator] <> '' then Inc(TagSize, Length(Tag.Frame[Iterator]) + 11); { Convert tag size } Tag.Size[1] := TagSize div $200000; Tag.Size[2] := TagSize div $4000; Tag.Size[3] := TagSize div $80; Tag.Size[4] := TagSize mod $80; end; { --------------------------------------------------------------------------- } function RebuildFile(const FileName: string; TagData: TStream): Boolean; var Tag: TagInfo; Source, Destination: TFileStream; BufferName: string; begin { Rebuild file with old file data and new tag data (optional) } Result := false; if (not FileExists(FileName)) or (FileSetAttr(FileName, 0) <> 0) then exit; if not ReadHeader(FileName, Tag) then exit; if (TagData = nil) and (Tag.ID <> ID3V2_ID) then exit; try { Create file streams } BufferName := FileName + '~'; Source := TFileStream.Create(FileName, fmOpenRead or fmShareExclusive); Destination := TFileStream.Create(BufferName, fmCreate); { Copy data blocks } if Tag.ID = ID3V2_ID then Source.Seek(GetTagSize(Tag), soFromBeginning); if TagData <> nil then Destination.CopyFrom(TagData, 0); Destination.CopyFrom(Source, Source.Size - Source.Position); { Free resources } Source.Free; Destination.Free; { Replace old file and delete temporary file } if (DeleteFile(FileName)) and (RenameFile(BufferName, FileName)) then Result := true else raise Exception.Create(''); except { Access error } if FileExists(BufferName) then DeleteFile(BufferName); end; end; { --------------------------------------------------------------------------- } function SaveTag(const FileName: string; Tag: TagInfo): Boolean; var TagData: TStringStream; Iterator, FrameSize: Integer; begin { Build and write tag header and frames to stream } TagData := TStringStream.Create(''); BuildHeader(Tag); TagData.Write(Tag, 10); for Iterator := 1 to ID3V2_FRAME_COUNT do if Tag.Frame[Iterator] <> '' then begin TagData.WriteString(ID3V2_FRAME_NEW[Iterator]); FrameSize := Swap32(Length(Tag.Frame[Iterator]) + 1); TagData.Write(FrameSize, SizeOf(FrameSize)); TagData.WriteString(#0#0#0 + Tag.Frame[Iterator]); end; { Rebuild file with new tag data } Result := RebuildFile(FileName, TagData); TagData.Free; end; { ********************** Private functions & procedures ********************* } procedure TID3v2.FSetTitle(const NewTitle: string); begin { Set song title } FTitle := Trim(NewTitle); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetArtist(const NewArtist: string); begin { Set artist name } FArtist := Trim(NewArtist); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetAlbum(const NewAlbum: string); begin { Set album title } FAlbum := Trim(NewAlbum); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetTrack(const NewTrack: Byte); begin { Set track number } FTrack := NewTrack; end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetYear(const NewYear: string); begin { Set release year } FYear := Trim(NewYear); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetGenre(const NewGenre: string); begin { Set genre name } FGenre := Trim(NewGenre); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetComment(const NewComment: string); begin { Set comment } FComment := Trim(NewComment); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetComposer(const NewComposer: string); begin { Set composer name } FComposer := Trim(NewComposer); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetEncoder(const NewEncoder: string); begin { Set encoder name } FEncoder := Trim(NewEncoder); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetCopyright(const NewCopyright: string); begin { Set copyright information } FCopyright := Trim(NewCopyright); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetLanguage(const NewLanguage: string); begin { Set language } FLanguage := Trim(NewLanguage); end; { --------------------------------------------------------------------------- } procedure TID3v2.FSetLink(const NewLink: string); begin { Set URL link } FLink := Trim(NewLink); end; { ********************** Public functions & procedures ********************** } constructor TID3v2.Create; begin { Create object } inherited; ResetData; end; { --------------------------------------------------------------------------- } procedure TID3v2.ResetData; begin { Reset all variables } FExists := false; FVersionID := 0; FSize := 0; FTitle := ''; FArtist := ''; FAlbum := ''; FTrack := 0; FYear := ''; FGenre := ''; FComment := ''; FComposer := ''; FEncoder := ''; FCopyright := ''; FLanguage := ''; FLink := ''; end; { --------------------------------------------------------------------------- } function TID3v2.ReadFromFile(const FileName: string): Boolean; var Tag: TagInfo; begin { Reset data and load header from file to variable } ResetData; Result := ReadHeader(FileName, Tag); { Process data if loaded and header valid } if (Result) and (Tag.ID = ID3V2_ID) then begin FExists := true; { Fill properties with header data } FVersionID := Tag.Version; FSize := GetTagSize(Tag); { Get information from frames if version supported } if (FVersionID in [TAG_VERSION_2_2..TAG_VERSION_2_4]) and (FSize > 0) then begin if FVersionID > TAG_VERSION_2_2 then ReadFramesNew(FileName, Tag) else ReadFramesOld(FileName, Tag); FTitle := GetContent(Tag.Frame[1], Tag.Frame[15]); FArtist := GetContent(Tag.Frame[2], Tag.Frame[14]); FAlbum := GetContent(Tag.Frame[3], Tag.Frame[16]); FTrack := ExtractTrack(Tag.Frame[4]); FYear := ExtractYear(Tag.Frame[5], Tag.Frame[13]); FGenre := ExtractGenre(Tag.Frame[6]); FComment := ExtractComment(Tag.Frame[7]); FComposer := Trim(Tag.Frame[8]); FEncoder := Trim(Tag.Frame[9]); FCopyright := Trim(Tag.Frame[10]); FLanguage := Trim(Tag.Frame[11]); FLink := ExtractLink(Tag.Frame[12]); end; end; end; { --------------------------------------------------------------------------- } function TID3v2.SaveToFile(const FileName: string): Boolean; var Tag: TagInfo; begin { Prepare tag data and save to file } FillChar(Tag, SizeOf(Tag), 0); Tag.Frame[1] := FTitle; Tag.Frame[2] := FArtist; Tag.Frame[3] := FAlbum; if FTrack > 0 then Tag.Frame[4] := IntToStr(FTrack); Tag.Frame[5] := FYear; Tag.Frame[6] := FGenre; if FComment <> '' then Tag.Frame[7] := 'eng' + #0 + FComment; Tag.Frame[8] := FComposer; Tag.Frame[9] := FEncoder; Tag.Frame[10] := FCopyright; Tag.Frame[11] := FLanguage; if FLink <> '' then Tag.Frame[12] := #0 + FLink; Result := SaveTag(FileName, Tag); end; { --------------------------------------------------------------------------- } function TID3v2.RemoveFromFile(const FileName: string): Boolean; begin { Remove tag from file } Result := RebuildFile(FileName, nil); end; end.
program minZahl; const X = 5; type tIndex = 1..X; var Minimum : integer; Feld : array [tIndex] of integer; i : tIndex; minPos : tIndex; begin writeln ('Bitte geben Sie ', X, ' Werte ein: '); for i := 1 to X do readln (Feld[i]); Minimum := Feld[1]; minPos := 1; for i := 2 to X do if Feld[i] < Minimum then begin Minimum := Feld[i]; minPos := i end; writeln ('Die kleinste Zahl ist: ', Minimum, ' an Position ', minPos, '.'); end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 本单元是工程数据集窗体的基本单元 // //主要实现: // 1、EasyUtilADOConn // 发布数据连接:所有与数据库通信的模块均从此单元获得ADO连接 // 2、初始化指定控件的IME //-----------------------------------------------------------------------------} unit untEasyPlateDBBaseForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ADODB, ExtCtrls, untEasyGroupBox, untEasyWaterImage, DBClient, untEasyPlateBaseForm, EasyPlateServer_TLB, untEasyClasssysUser, untEasyClasshrEmployee; type TfrmEasyPlateDBBaseForm = class(TfrmEasyPlateBaseForm) procedure FormCreate(Sender: TObject); private { Private declarations } FEasyDBConn: TADOConnection; function GetUtilADOConn: TADOConnection; procedure SetUtilADOConn(const Value: TADOConnection); function GetRDMEasyPlateServerDisp: IRDMEasyPlateServerDisp; function GetEasyCurrLoginSysUser: TEasysysUser; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; //发布ADO数据连接 property EasyUtilADOConn: TADOConnection read GetUtilADOConn write SetUtilADOConn; //发布远程数据服务接口 //客户端调用服务端函数均使用此属性 property EasyRDMDisp: IRDMEasyPlateServerDisp read GetRDMEasyPlateServerDisp; //当前登录用户 property EasyCurrLoginSysUser: TEasysysUser read GetEasyCurrLoginSysUser; end; var frmEasyPlateDBBaseForm: TfrmEasyPlateDBBaseForm; implementation {$R *.dfm} uses untEasyDBConnection; constructor TfrmEasyPlateDBBaseForm.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TfrmEasyPlateDBBaseForm.Destroy; begin inherited; end; procedure TfrmEasyPlateDBBaseForm.FormCreate(Sender: TObject); begin inherited; FEasyDBConn := DMEasyDBConnection.EasyADOConn; end; function TfrmEasyPlateDBBaseForm.GetEasyCurrLoginSysUser: TEasysysUser; begin Result := DMEasyDBConnection.EasyCurrLoginSysUser; end; function TfrmEasyPlateDBBaseForm.GetRDMEasyPlateServerDisp: IRDMEasyPlateServerDisp; begin //获取COM接口 Result := DMEasyDBConnection.EasyIRDMEasyPlateServerDisp; end; function TfrmEasyPlateDBBaseForm.GetUtilADOConn: TADOConnection; begin Result := FEasyDBConn; end; procedure TfrmEasyPlateDBBaseForm.SetUtilADOConn( const Value: TADOConnection); begin FEasyDBConn := Value; end; end.
//grantadminaccess unit //Update : 08/04/2019 10.30 WIB //Dev : mk //v1.0.0 unit grantadminaccess; interface uses banana_csvparser; var user_data:banana_csvdoc; function grantaccess(row:integer):boolean; //Mengembalikan nilai true bila username merupakan admin, dan sebaliknya procedure accessdenied(); //Mengeluarkan pesan error bila pengunjung hendak mengakses function admin function return_user(row:integer):string; //Mengembalikan username yang bersesuaian dengan kolom yang dipilih implementation function grantaccess(row:integer):boolean; begin //Load CSV user_data:=load_csv('user_tmp.csv'); //Return true/false berdasarkan flag admin if(user_data[row,5]='admin') then grantaccess:=true else grantaccess:=false; end; procedure accessdenied(); begin //Mengeluarkan pesan writeln('Access Denied!'); writeln('Hubungi admin untuk informasi lebih lanjut.'); end; function return_user(row:integer):string; begin //Load CSV user_data:=load_csv('user_tmp.csv'); //Return username di row tersebut return_user:=user_data[row,3]; end; end.
unit UFrmWorkerInfoEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmModal, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, ActnList, StdCtrls, cxButtons, ExtCtrls, DBClient, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxMaskEdit, cxCalendar, cxTextEdit, DateUtils, DB; type TFrmWorkerInfoEdit = class(TFrmModal) lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; lbl6: TLabel; lbl7: TLabel; edtWorkerID: TcxTextEdit; edtWorkerName: TcxTextEdit; edtWorkerPass: TcxTextEdit; edtBeginTime: TcxDateEdit; edtEndTime: TcxDateEdit; cbbWorkerClass: TcxLookupComboBox; dsWorkerClass: TDataSource; procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); private FDataSet: TClientDataSet; FAction: string; FGuid: string; function BeforeExecute: Boolean; function DoExecute: Boolean; public class function ShowWorkerInfoEdit(DataSet, WorkerClass: TClientDataSet; AAction: string): Boolean; end; var FrmWorkerInfoEdit: TFrmWorkerInfoEdit; implementation uses UDBAccess, UMsgBox, UPubFunLib; {$R *.dfm} { TFrmWorkerInfoEdit } function TFrmWorkerInfoEdit.BeforeExecute: Boolean; const cCheckIDExistsSQL = 'select * from WorkerInfo where WorkerID=''%s'''; var lStrSql: string; iResult: Integer; begin Result := False; if Trim(edtWorkerID.Text) = '' then begin edtWorkerID.SetFocus; ShowMsg('用户编码不能为空,请输入!'); Exit; end; if Trim(edtWorkerName.Text) = '' then begin edtWorkerName.SetFocus; ShowMsg('用户名称不能为空,请输入!'); Exit; end; if Trim(edtWorkerPass.Text) = '' then begin edtWorkerPass.SetFocus; ShowMsg('用户密码不能为空,请输入!'); Exit; end; if cbbWorkerClass.ItemIndex = -1 then begin cbbWorkerClass.SetFocus; ShowMsg('所属角色不能为空,请选择!'); Exit; end; // 判断用户编码是否重复 if FAction = 'Append' then lStrSql := Format(cCheckIDExistsSQL, [Trim(edtWorkerID.Text)]) else lStrSql := Format(cCheckIDExistsSQL + ' and Guid <> ''%s''', [Trim(edtWorkerID.Text), FGuid]); iResult := DBAccess.DataSetIsEmpty(lStrSql); if iResult = -1 then begin ShowMsg('获取用户编码是否重复失败!'); Exit; end; if iResult = 0 then begin ShowMsg('当前用户编码已经存在,请重新输入!'); Exit; end; Result := True; end; procedure TFrmWorkerInfoEdit.btnOkClick(Sender: TObject); begin inherited; if not BeforeExecute then Exit; if not DoExecute then Exit; ModalResult := mrOk; end; function TFrmWorkerInfoEdit.DoExecute: Boolean; begin Result := False; with FDataSet do begin if FAction = 'Append' then begin Append; FindField('Guid').AsString := CreateGuid; end else Edit; FindField('WorkerID').AsString := edtWorkerID.Text; FindField('WorkerName').AsString := edtWorkerName.Text; FindField('WorkerPass').AsString := edtWorkerPass.Text; FindField('ClassGuid').AsString := cbbWorkerClass.EditValue; FindField('BeginTime').AsDateTime := edtBeginTime.Date; FindField('EndTime').AsDateTime := edtEndTime.Date; Post; end; if FDataSet.ChangeCount > 0 then begin if DBAccess.ApplyUpdates('WorkerInfo', FDataSet.Delta) then begin FDataSet.MergeChangeLog; end else begin FDataSet.CancelUpdates; ShowMsg('保存用户信息失败,请重新操作!'); Exit; end; end; Result := True; end; procedure TFrmWorkerInfoEdit.FormShow(Sender: TObject); begin inherited; if FAction = 'Edit' then begin with FDataSet do begin edtWorkerID.Text := FindField('WorkerID').AsString; edtWorkerName.Text := FindField('WorkerName').AsString; edtWorkerPass.Text := FindField('WorkerPass').AsString; cbbWorkerClass.EditValue := FindField('ClassGuid').AsString; edtBeginTime.Date := FindField('BeginTime').AsDateTime; edtEndTime.Date := FindField('EndTime').AsDateTime; FGuid := FindField('Guid').AsString; end; end else begin edtBeginTime.Date := Date; edtEndTime.Date := IncYear(Date, 1); end; end; class function TFrmWorkerInfoEdit.ShowWorkerInfoEdit(DataSet, WorkerClass: TClientDataSet; AAction: string): Boolean; begin with TFrmWorkerInfoEdit.Create(nil) do begin try FDataSet := DataSet; FAction := AAction; dsWorkerClass.DataSet := WorkerClass; Result := ShowModal = mrOk; finally Free; end; end; end; end.
unit IDELocale; interface uses Classes, StdCtrls, ResourceStrings; procedure LoadTranslations(cb: TComboBox); function GetLangIDFromLanguage(Language: string): string; implementation procedure LoadTranslations(cb: TComboBox); begin cb.Items.Add(rsSystemLanguage); cb.Items.Add(rsChineseZh_CN); cb.Items.Add(rsDutchNl_NL); cb.Items.Add(rsEnglishEn_US); cb.Items.Add(rsFrenchFr_FR); cb.Items.Add(rsGermanDe_DE); cb.Items.Add(rsItalianIt_IT); cb.Items.Add(rsPolishPl_PL); cb.Items.Add(rsSpanishEs_ES); cb.Sorted := True; end; function GetLangIDFromLanguage(Language: string): string; var i: integer; begin i := pos('(', Language); //no parentheses found so revert to default if i = -1 then exit(''); exit(copy(Language, i + 1, pos(')', Language) - i - 1)); end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Ani, FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Media, System.Beacon, System.Beacon.Components; type TForm1 = class(TForm) ToolBar1: TToolBar; Label1: TLabel; Switch1: TSwitch; Image1: TImage; StatusBar1: TStatusBar; Label2: TLabel; Rectangle1: TRectangle; FloatAnimation1: TFloatAnimation; MediaPlayer1: TMediaPlayer; Beacon1: TBeacon; Timer1: TTimer; procedure Switch1Switch(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Beacon1BeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); procedure Beacon1BeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); procedure Timer1Timer(Sender: TObject); private { Private declarations } FBeacon: IBeacon; procedure StartAlert; procedure StopAlert; // Ctrl + Shift + C: 자도완성 public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses System.IOUtils; { TForm1 } procedure TForm1.Beacon1BeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); begin FBeacon := ABeacon; end; procedure TForm1.Beacon1BeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList); begin FBeacon := nil; end; procedure TForm1.FormCreate(Sender: TObject); begin StopAlert; end; procedure TForm1.StartAlert; var Path: string; begin Rectangle1.Visible := True; FloatAnimation1.Enabled := True; {$IFNDEF MSWINDOWS} // MSWINDOWS가 아닌경우 실행 Path := TPath.Combine(TPath.GetDocumentsPath, 'alert.mp3'); MediaPlayer1.FileName := Path; {$ENDIF} MediaPlayer1.Play; end; procedure TForm1.StopAlert; begin Rectangle1.Visible := False; FloatAnimation1.Enabled := False; MediaPlayer1.Stop; end; procedure TForm1.Switch1Switch(Sender: TObject); begin Beacon1.Enabled := Switch1.IsChecked; end; procedure TForm1.Timer1Timer(Sender: TObject); begin if Assigned(FBeacon) then begin Label2.Text := Format('위험지역과의 거리: %2.1f', [FBeacon.Distance]); if FBeacon.Distance <= 1 then StartAlert else StopAlert; end; end; end.
{ ----------------------------------------------------------------------------- Unit Name: ufrmFindNewSheets Author: 黄伟 Date: 14-十月-2019 Purpose: 本单元用于查找新增仪器计算表,从已知的工作簿中。但无法从未知的新 工作簿中查找。 History: ----------------------------------------------------------------------------- } unit ufrmFindNewSheets; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, uHJX.Classes.Meters; type TfrmFindNewSheets = class(TForm) Panel1: TPanel; btnFindNew: TButton; mmoResult: TMemo; procedure btnFindNewClick(Sender: TObject); private { Private declarations } procedure FindNewSheets; public { Public declarations } end; var frmFindNewSheets: TfrmFindNewSheets; implementation uses nExcel, uHJX.Excel.IO; {$R *.dfm} procedure TfrmFindNewSheets.btnFindNewClick(Sender: TObject); begin FindNewSheets; end; procedure TfrmFindNewSheets.FindNewSheets; var i, j: Integer; wbks: TStrings; nBK:IXLSWorkBook; begin mmoResult.Clear; wbks := TStringList.Create; try // 首先将现有仪器过一遍,找出现有工作簿及其对应的工作表: for i := 0 to ExcelMeters.Count - 1 do begin if ExcelMeters.Items[i].DataBook = '' then Continue; if ExcelMeters.Items[i].DataSheet = '' then Continue; j := wbks.IndexOf(ExcelMeters.Items[i].DataBook); if j = -1 then // 如果工作簿没添加,则添加工作簿及仪器的工作表 begin wbks.Add(ExcelMeters.Items[i].DataBook); wbks.Objects[wbks.Count - 1] := TStringList.Create; TStrings(wbks.Objects[wbks.Count - 1]).Add(ExcelMeters.Items[i].DataSheet); end else // 如果有工作簿,检查工作表是否存在,不存在则添加之 begin if (wbks.Objects[j] as TStrings).IndexOf(ExcelMeters.Items[i].DataSheet) = -1 then (wbks.Objects[j] as TStrings).Add(ExcelMeters.Items[i].DataSheet); end; end; //逐一打开工作簿,枚举所有工作表,核对是否在已知表中,不在则列出 for i := 0 to wbks.Count -1 do begin if Trim(wbks[i])='' then Continue; ExcelIO.OpenWorkbook(nBK, wbks.Strings[i]); for j := 1 to nbk.WorkSheets.Count do if (wbks.Objects[i] as TStrings).IndexOf(nbk.WorkSheets[j].Name)=-1 then mmoResult.Lines.Add(wbks.Strings[i]+':'+nbk.WorkSheets[j].Name); end; finally for i := 0 to wbks.Count - 1 do wbks.Objects[i].Free; wbks.Free; end; end; end.
unit xTrainQuestionAction; interface uses xDBActionBase, xTrainQuestionInfo, System.Classes, System.SysUtils, FireDAC.Stan.Param, xFunction; type /// <summary> /// 练习题数据库操作 /// </summary> TTrainQuestionAction = class(TDBActionBase) public /// <summary> /// 获取最大编号 /// </summary> function GetMaxSN : Integer; /// <summary> /// 添加 /// </summary> procedure AddInfo(AInfo : TTrainQuestion); /// <summary> /// 删除 /// </summary> procedure DelInfo(nID: Integer); overload; /// <summary> /// 删除 /// </summary> /// <param name="bIsDelPath">如果是目录,是否删除目录</param> procedure DelInfo(AInfo : TTrainQuestion; bIsDelPath: Boolean); overload; /// <summary> /// 修改 /// </summary> procedure EditInfo(AInfo : TTrainQuestion); /// <summary> /// 清空 /// </summary> procedure ClearInfo; /// <summary> /// 加载 /// </summary> procedure LoadInfo(slList :TStringList); end; implementation { TTrainQuestionAction } procedure TTrainQuestionAction.AddInfo(AInfo: TTrainQuestion); const C_SQL ='insert into TrainQuestion ( TQID, TQType, TQPath, TQQName,' + 'TQCode1, TQCode2, TQRemark ) values ( %d, %d, :TQPath,' + ':TQQName, :TQCode1, :TQCode2, :TQRemark )'; begin if Assigned(AInfo) then begin with AInfo, FQuery.Params do begin FQuery.Sql.Text := Format( C_SQL, [ Tqid, Tqtype ] ); ParamByName( 'TQPath' ).Value := Tqpath ; ParamByName( 'TQQName' ).Value := Tqqname ; ParamByName( 'TQCode1' ).Value := Tqcode1 ; ParamByName( 'TQCode2' ).Value := Tqcode2 ; ParamByName( 'TQRemark' ).Value := Tqremark; end; ExecSQL; end; end; procedure TTrainQuestionAction.ClearInfo; begin FQuery.Sql.Text := 'delete from TrainQuestion'; ExecSQL; end; procedure TTrainQuestionAction.DelInfo(AInfo: TTrainQuestion; bIsDelPath: Boolean); const C_SQL = 'delete from TrainQuestion where TQPath LIKE ' ; begin if Assigned(AInfo) then begin // 目录 if AInfo.TQtype = 0 then begin FQuery.Sql.Text := C_SQL + AInfo.TQPath + '''\%'''; ExecSQL; if bIsDelPath then begin DelInfo(AInfo.TQId); end; end else // 文件 begin DelInfo(AInfo.TQId); end; end; end; procedure TTrainQuestionAction.DelInfo(nID: Integer); const C_SQL = 'delete from TrainQuestion where TQID = %d '; begin FQuery.Sql.Text := Format( C_SQL, [ nID ] ); ExecSQL; end; procedure TTrainQuestionAction.EditInfo(AInfo: TTrainQuestion); const C_SQL = 'update TrainQuestion set TQType = %d,' + 'TQPath = :TQPath, TQQName = :TQQName, TQCode1 = :TQCode1,' + 'TQCode2 = :TQCode2, TQRemark = :TQRemark where TQID = %d'; begin if Assigned(AInfo) then begin with AInfo, FQuery.Params do begin FQuery.Sql.Text := Format( C_SQL, [ Tqtype, Tqid ] ); ParamByName( 'TQPath' ).Value := Tqpath ; ParamByName( 'TQQName' ).Value := Tqqname ; ParamByName( 'TQCode1' ).Value := Tqcode1 ; ParamByName( 'TQCode2' ).Value := Tqcode2 ; ParamByName( 'TQRemark' ).Value := Tqremark; end; ExecSQL; end; end; function TTrainQuestionAction.GetMaxSN: Integer; const C_SQL = 'select max(TQID) as MaxSN from TrainQuestion'; begin FQuery.Open(C_SQL); if FQuery.RecordCount = 1 then Result := FQuery.FieldByName('MaxSN').AsInteger else Result := 0; FQuery.Close; end; procedure TTrainQuestionAction.LoadInfo(slList: TStringList); const C_SQL = 'select * from TrainQuestion'; var AInfo : TTrainQuestion; begin if Assigned(slList) then begin ClearStringList(slList); FQuery.Open(C_SQL); while not FQuery.Eof do begin AInfo := TTrainQuestion.Create; with AInfo, FQuery do begin Tqid := FieldByName( 'TQID' ).AsInteger; Tqtype := FieldByName( 'TQType' ).AsInteger; Tqpath := FieldByName( 'TQPath' ).AsString; Tqqname := FieldByName( 'TQQName' ).AsString; Tqcode1 := FieldByName( 'TQCode1' ).AsString; Tqcode2 := FieldByName( 'TQCode2' ).AsString; Tqremark := FieldByName( 'TQRemark' ).AsString; end; slList.AddObject('', AInfo); FQuery.Next; end; FQuery.Close; end; end; end.
unit Ths.Erp.Constants; interface {$I ThsERP.inc} const SURUM = 'A'; EPSILON = 0.00009; EPSILON_ISLEMLER = 0.009;//2 haneye bakılır PREFIX_LABEL = 'lbl'; PREFIX_CHECKBOX = 'chk'; PREFIX_EDIT = 'edt'; PREFIX_MEMO = 'mmo'; PREFIX_COMBOBOX = 'cbb'; PREFIX_RADIOGROUP = 'rg'; PREFIX_BUTTON = 'btn'; PREFIX_TABSHEET = 'ts'; DefaultFontName = 'Tahoma'; LngSystem = 'System'; LngGeneral = 'General'; LngButton = 'Button'; LngDGridFieldCaption = 'DGrid.FieldCaption'; LngSGridFieldCaption = 'SGrid.FieldCaption'; LngLabelCaption = 'LabelCaption'; LngFormCaption = 'FormCaption'; LngMsgTitle = 'MsgTitle'; LngMsgError = 'MsgError'; LngMsgData = 'MsgData'; LngMsgWarning = 'MsgWarning'; LngMainTable = 'Main'; LngFilter = 'Filter'; LngPopup = 'Popup'; LngStatus = 'Status'; LngLogin = 'Login'; LngTab = 'Tab'; LngMenu = 'Menu'; LngApplication = 'Application'; IMG_ACCEPT = 0; IMG_ADD = 1; IMG_ADD_DATA = 2; IMG_APPLICATION = 3; IMG_ARCHIVE = 4; IMG_ATTACHMENT = 5; IMG_BACK = 6; IMG_CALCULATOR = 7; IMG_CALENDAR = 8; IMG_CHART = 9; IMG_CLOCK = 10; IMG_CLOSE = 11; IMG_COL_WIDTH = 12; IMG_COMMENT = 13; IMG_COMMUNITY_USERS = 14; IMG_COMPUTER = 15; IMG_COPY = 16; IMG_CUSTOMER = 17; IMG_DATABASE = 18; IMG_DOWN = 19; IMG_EXCEL_EXPORTS = 20; IMG_EXCEL_IMPORTS = 21; IMG_FAVORITE = 22; IMG_FILE_DOC = 23; IMG_FILE_PDF = 24; IMG_FILE_XLS = 25; IMG_FILTER = 26; IMG_FILTER_ADD = 27; IMG_FILTER_CLEAR = 28; IMG_FOLDER = 29; IMG_FORWARD_NEW_MAIL = 30; IMG_HELP = 31; IMG_HOME = 32; IMG_IMAGE = 33; IMG_INFO = 34; IMG_LANG = 35; IMG_LOCK = 36; IMG_MAIL = 37; IMG_MONEY = 38; IMG_MOVIE = 39; IMG_NEXT = 40; IMG_NOTE = 41; IMG_PAGE = 42; IMG_PAGE_SEARCH = 43; IMG_PAUSE = 44; IMG_PLAY = 45; IMG_PORT = 46; IMG_PREVIEW = 47; IMG_PRINT = 48; IMG_PROCESS = 49; IMG_RECORD = 50; IMG_REMOVE = 51; IMG_REPEAT = 52; IMG_RSS = 53; IMG_SEARCH = 54; IMG_SERVER = 55; IMG_STOCK = 56; IMG_STOCK_ADD = 57; IMG_STOCK_DELETE = 58; IMG_SUM = 59; IMG_UP = 60; IMG_USER_HE = 61; IMG_USER_PASSWORD = 62; IMG_USER_SHE = 63; IMG_USERS = 64; IMG_WARNING = 65; IMG_PERIOD = 66; IMG_QUALITY = 67; IMG_EXCHANGE_RATE = 68; IMG_BANK = 69; IMG_BANK_BRANCH = 70; IMG_CITY = 71; IMG_COUNTRY = 72; IMG_STOCK_ROOM = 73; IMG_MEASURE_UNIT = 74; IMG_DURATION_FINANCE = 75; IMG_SETTINGS = 76; IMG_SORT_ASC = 77; IMG_SORT_DESC = 78; FILE_EXTENSION_XLS = 'xls'; FILE_EXTENSION_DOC = 'doc'; FILE_EXTENSION_PDF = 'pdf'; FILE_EXTENSION_XML = 'xml'; FILE_EXTENSION_PNG = 'png'; FILE_EXTENSION_BMP = 'bmp'; PATH_SETTINGS = 'Settings'; PATH_ICONS_32 = 'Resource/themeIcons/32x32/'; PATH_ICONS_16 = 'Resource/themeIcons/16x16/'; PATH_PRINT_FORMS = ''; STATUS_SQL_SERVER = 0; STATUS_DATE = 1; STATUS_USERNAME = 2; STATUS_KEY_F4 = 3; STATUS_KEY_F5 = 4; STATUS_KEY_F6 = 5; STATUS_KEY_F7 = 6; QUERY_PARAM_CHAR = ':'; implementation end.
unit UnRetorno; interface Uses classes, SysUtils, UnDados, ComCtrls, UnContasAPagar, UnContasAReceber, UnComissoes, UnDadosCR, unCaixa, SqlExpr,tabela, DB,Provider,DBClient; type TRBDLocalizacaoRetorno = class public procedure PosDuplicata(VpaTabela : TDataSet;VpaNumDuplicata :String); procedure PosNossoNumero(VpaTabela : TDataSet;VpaCodFilial : Integer;VpaNossoNumero : string); end; TRBDFuncoesRetorno = class(TRBDLocalizacaoRetorno) private Aux : TSQLQuery; Cadastro : TSQL; VprBarraStatus : TStatusBar; FunComissoes : TFuncoesComissao; procedure TextoStatus(VpaTexto : String); function IncrementaRetornosEfetuados(VpaDRetorno : TRBDRetornoCorpo):string; function RSeqRetornoDisponivel(VpaCodFilial : Integer):Integer; function RNomClienteContasReceber(VpaCodFilial,VpaLanReceber:Integer) : String; function RNumContaCorrente(VpaNumContrato : String) : string; function RErroBradesco(VpaCodErro : Integer):String; function RErroCNAB240(VpaCodErro : Integer):String; procedure AtualizaTotalTarifas(VpaTabela : TDataSet); function ConfirmaItemRemessa(VpaCodFilial,VpaLanReceber,VpaNumParcela : Integer):Boolean; procedure CarLanReceber(VpaDesIdentificacao : String; VpaDRetornoItem : TRBDREtornoItem); procedure CarLanReceberNossoNumeroItau(VpaDesIdentificacao : String; VpaDRetornoItem : TRBDREtornoItem); procedure CarLanReceberItem(VpaDRetorno : TRBDRetornoCorpo; VpaDItem : TRBDRetornoItem); function ContaCorrenteRetornoValida(VpaDRetorno : TRBDRetornoCorpo):string; procedure CarDesLiquidacao(VpaDItem : TRBDRetornoItem); function GravaDRetornoItem(VpaDRetorno : TRBDRetornoCorpo):String; function GravaDRetorno(VpaDRetorno : TRBDRetornoCorpo) : String; procedure processaEntradaConfirmada(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure processaDescontoDuplicata(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaEntradaRejeitadaItau(VpaDRetorno : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaLiquidacaoNormal(VpaDRetorno : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaEnvioCartorio(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaSustacaoProtesto(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaDebitoTarifas(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaBaixaSimples(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaCancelamentoProtesto(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaRetornoCorpoItau(VpaLinha : String;VpaDRetorno : TRBDRetornoCorpo); procedure ProcessaRetornoCorpoCNAB400(VpaLinha : String;VpaDRetorno : TRBDRetornoCorpo); procedure ProcessaRetornoCorpoCNAB240(VpaLinha : String;VpaDRetorno : TRBDRetornoCorpo); procedure ProcessaOcorrenciaItemItau(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); procedure ProcessaRetornoItemCNAB240(VpaArquivo : TStringList;VpaDRetorno : TRBDRetornoCorpo); procedure ProcessaRetornoItemTCNAB240(VpfLinha : String;VpaDItemRetorno : TRBDRetornoItem); procedure ProcessaRetornoItemUCNAB240(VpfLinha : String;VpaDItemRetorno : TRBDRetornoItem); procedure LocalizaParcelaCNAB240(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItemRetorno : TRBDRetornoItem); procedure ProcessaRetornoItemItau(VpaArquivo : TStringList;VpaDRetorno : TRBDRetornoCorpo); procedure ProcessaRetornoItemCNAB400(VpaArquivo : TStringList;VpaDRetorno : TRBDRetornoCorpo); function processaRetornoItau(VpaArquivo : TStringList):String; function ProcessaRetornoCNAB240(VpaNomArquivo : String;VpaArquivo : TStringList):String; function ProcessaRetornoCNAB400(VpaNomArquivo : String;VpaArquivo : TStringList):String; public constructor cria(VpaBaseDados : TSQLConnection); destructor destroy;override; function processaRetorno(VpaNomArquivo :String;VpaBarraStatus : TStatusBar):String; procedure MarcaRetornoImpresso(VpaCodFilial, VpaSeqRetorno : Integer); end; implementation Uses FunSql, Constantes, FunString, fundata, funarquivos, constmsg; {******************************************************************************} procedure TRBDLocalizacaoRetorno.PosDuplicata(VpaTabela : TDataSet;VpaNumDuplicata :String); begin AdicionaSqlAbreTabela(VpaTabela,'Select * from MOVCONTASARECEBER '+ ' Where C_NRO_DUP = '''+VpaNumDuplicata+'''' ); end; {******************************************************************************} procedure TRBDLocalizacaoRetorno.PosNossoNumero(VpaTabela : TDataSet;VpaCodFilial : Integer; VpaNossoNumero : string); begin AdicionaSqlAbreTabela(VpaTabela,'Select * from MOVCONTASARECEBER '+ ' Where C_NOS_NUM = '''+VpaNossoNumero+''''+ ' and I_EMP_FIL = '+IntToStr(VpaCodFilial)); end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos das Funcoes )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} constructor TRBDFuncoesRetorno.cria(VpaBaseDados : TSQLConnection); begin inherited create; Aux := TSQLQuery.create(nil); Aux.SQLConnection := VpaBaseDados; Cadastro := TSQL.Create(nil); Cadastro.ASQLConnection := VpaBaseDados; FunComissoes := TFuncoesComissao.cria(VpaBaseDados); end; {******************************************************************************} destructor TRBDFuncoesRetorno.destroy; begin Aux.free; FunComissoes.free; Cadastro.free; inherited destroy; end; {******************************************************************************} procedure TRBDFuncoesRetorno.TextoStatus(VpaTexto : String); begin if VprBarraStatus <> nil then begin VprBarraStatus.Panels[0].Text := VpaTexto; VprBarraStatus.refresh; end; end; {******************************************************************************} function TRBDFuncoesRetorno.RSeqRetornoDisponivel(VpaCodFilial : Integer):Integer; begin AdicionaSQLAbreTabela(Aux,'Select max(SEQRETORNO) ULTIMO from RETORNOCORPO '+ ' Where CODFILIAL = '+IntToStr(VpaCodFilial)); result := Aux.FieldByName('ULTIMO').AsInteger +1; aux.close; end; {******************************************************************************} function TRBDFuncoesRetorno.RNomClienteContasReceber(VpaCodFilial,VpaLanReceber : Integer) : String; begin AdicionaSQLAbreTabela(Aux,'Select CLI.C_NOM_CLI from CADCONTASARECEBER CR, CADCLIENTES CLI '+ ' Where CR.I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' and CR.I_LAN_REC = '+IntToStr(VpaLanReceber)+ ' and CR.I_COD_CLI = CLI.I_COD_CLI'); result := Aux.FieldByName('C_NOM_CLI').AsString; Aux.close; end; {******************************************************************************} function TRBDFuncoesRetorno.RNumContaCorrente(VpaNumContrato : String) : string; begin AdicionaSQLAbreTabela(Aux,'Select C_NRO_CON from CADCONTAS '+ ' Where C_NUM_CON = '''+VpaNumContrato +''''); result := Aux.FieldByName('C_NRO_CON').AsString; Aux.close; end; {******************************************************************************} function TRBDFuncoesRetorno.RErroBradesco(VpaCodErro : Integer):String; begin case VpaCodErro of 2 : result := 'CODIGO DO REGISTRO DETLHE INVÁLIDO.'; 3 : result := 'CODIGO DA OCORRÊNCIA INVÁLIDA.'; 4 : result := 'CODIGO DA OCORRÊNCIA NÃO PERMITIDA PARA A CARTEIRA.'; 5 : result := 'CODIGO DA OCRRÊNCIA NÃO NUMERICO.'; 7 : result := 'AGENCIA/CONTA/DIGITO - INVALIDO.'; 8 : result := 'NOSSO NUMERO INVALIDO.'; 9 : result := 'NOSSO NUMERO DUPLICADO'; 10 : result := 'CARTEIRA INVALIDA'; 13 : result := 'IDENTIFICACAO DA EMISSAO DO BOLETO INVALIDA'; 16 : result := 'DATA DE VENCIMENTO INVALIDA'; 18 : result := 'VENCIMENTO FORA DO PRAZO DE OPERACAO'; 20 : result := 'VALOR DO TITULO INVALIDO'; 21 : result := 'ESPECIE DO TITULO INVALIDA'; 22 : result := 'ESPECIE NAO PERMITIDA PARA A CARTEIRA'; 24 : result := 'DATA DE EMISSAO INVALIDA'; 28 : result := 'CODIGO DO DESCONTO INVALIDO'; 38 : result := 'PRAZO PARA PROTESTO INVALIDO'; 44 : result := 'AGENCIA CEDENTE NAO PREVISTA'; 45 : result := 'NOME DO SACADO NAO INFORMADO'; 46 : result := 'TIPO/NUMERO DE INSCRICAO DO SACADO INVALIDA'; 47 : result := 'ENDERECO DO SACADO NAO INFORMADO'; 48 : result := 'CEP INVALIDO'; 50 : result := 'CEP IRREGULAR - BANCO CORRESPONDENTE'; 63 : result := 'ENTRADA PARA TITULO JA CADASTRADO'; 65 : result := 'LIMITE EXCEDIDO'; 66 : result := 'NUMERO AUTORIZACAO INEXISTENTE'; 68 : result := 'DEBITO NAO AGENDADO - ERRO NOS DADOS DE REMESSA'; 69 : result := 'DEBITO NAO AGENDADO - SACADO NAO CONSTA NO CADAS DE AUTORIZANTE'; 70 : result := 'DEBITO NAO AGENDADO - CEDENTE NAO AUTORIZADO PELO SACADO'; 71 : result := 'DEBITO NAO AGENDADO - CEDENTE NAO PARTICIPA DO DEBITO AUTOMATICO'; 72 : result := 'DEBITO NAO AGENDADO - CODIGO DA MOEDA DIFERENTE DE R$'; 73 : result := 'DEBITO NAO AGENDADO - DATA DE VENCIMENTO INVALIDO'; 74 : result := 'DEBITO NAO AGENDADO - CONFORME SEU PEDIDO, TITULO NAO REGISTRADO'; 75 : result := 'DEBITO NAO AGENDADO - TIPO DE NUMERO DE INSCRICAO DO DEBITADO INVALIDO'; else result := 'CODIGO DA REJEICAO NAO CADASTRADO!!!'+IntToStr(VpaCodErro); end; end; {******************************************************************************} function TRBDFuncoesRetorno.RErroCNAB240(VpaCodErro : Integer):String; begin case VpaCodErro of 3 : result := 'CEP INVÁLIDO!!! Não foi possivel atribuir a agência cobradora pelo CEP.'; 4 : result := 'UF INVÁLIDA!!! Sigla do estado inválida.'; 5 : result := 'DATA VENCIMENTO INVÁLIDA!!! Prazo da operação menor que prazo mínimo ou maior que o máximo.'; 7 : result := 'VALOR DO TÍTULO INVÁLIDO!!! Valor do título maior que 10.000.000,00.'; 8 : result := 'NOME DO SACADO INVÁLIDO!!! Não informado ou deslocado.'; 9 : result := 'CONTA INVÁLIDA INVÁLIDA!!! Agencia ou conta corrente encerrada.'; 10 : result := 'ENDEREÇO INVÁLIDO!!! Não informado ou deslocado.'; 11 : result := 'CEP INVÁLIDO!!! CEP não numérico.'; 12 : result := 'SACADOR/AVALISTA INVÁLIDO!!! Não informado ou deslocado.'; 13 : result := 'CEP INVÁLIDO!!! Incompatível com a sigla do estado.'; 14 : result := 'NOSSO NÚMERO INVÁLIDO!!! Já registrado no cadastro do bancou ou fora da faixa.'; 15 : result := 'NOSSO NÚMERO INVÁLIDO!!! Em duplicidade no mesmo movimento.'; 18 : result := 'DATA DE ENTRADA INVÁLIDA!!! Data de entrada inválida para operar com essa carteira.'; 19 : result := 'OCORRÊNCIA INVÁLIDA!!! Ocorrência inválida.'; 21 : result := 'AGENCIA COBRADORA INVÁLIDA!!!'; 27 : result := 'CNPJ INVÁLIDO INVÁLIDA!!!CNPJ do cedente inapto'; 48 : result := 'CEP INVÁLIDO!!! CEP não numérico.'; 54 : result := 'DATA DE VENCIMENTO INVÁLIDO!!!A data de vencimento não pode ser inferior a 15 dias.'; 60 : result := 'TITULO NÃO CADATRADO NO BANCO!!!Movimento para título não Cadastrado.'; 63 : result := 'TITULO JÁ CADASTRADO!!! Esse título já foi cadastrado no banco anteriormente'; else result := 'CODIGO DA REJEICAO NAO CADASTRADO!!!'+IntToStr(VpaCodErro); end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.AtualizaTotalTarifas(VpaTabela : TDataSet); begin VpaTabela.FieldByName('N_TOT_TAR').AsFloat := VpaTabela.FieldByName('N_VLR_ECA').AsFloat + VpaTabela.FieldByName('N_VLR_CAR').AsFloat + VpaTabela.FieldByName('N_VLR_EPR').AsFloat + VpaTabela.FieldByName('N_VLR_PRT').AsFloat + VpaTabela.FieldByName('N_VLR_TMA').AsFloat + VpaTabela.FieldByName('N_VLR_TBS').AsFloat + VpaTabela.FieldByName('N_VLR_CPR').AsFloat + VpaTabela.FieldByName('N_VLR_BPR').AsFloat ; end; {******************************************************************************} function TRBDFuncoesRetorno.ConfirmaItemRemessa(VpaCodFilial,VpaLanReceber,VpaNumParcela : Integer):Boolean; begin AdicionaSQLAbreTabela(Cadastro,'Select * from REMESSAITEM '+ ' Where CODFILIAL = '+IntToStr(VpaCodFilial)+ ' and LANRECEBER = '+IntToStr(VpaLanReceber)+ ' and NUMPARCELA = '+IntToStr(VpaNumParcela)); result := not Cadastro.eof; while not Cadastro.eof do begin Cadastro.edit; Cadastro.FieldByName('INDCONFIRMADA').AsString := 'S'; Cadastro.post; cadastro.next; end; ExecutaComandoSql(Aux,'update MOVCONTASARECEBER '+ ' SET C_IND_RET = ''S'''+ ' Where I_EMP_FIL = '+ IntToStr(VpaCodFilial)+ ' and I_LAN_REC = '+IntToStr(VpaLanReceber) + ' and I_NRO_PAR = '+IntToStr(VpaNumParcela)); Cadastro.close; end; {******************************************************************************} procedure TRBDFuncoesRetorno.CarLanReceber(VpaDesIdentificacao : String; VpaDRetornoItem : TRBDREtornoItem); begin if (DeletaChars(VpaDesIdentificacao,'0') <> '') then begin if CopiaAteChar(VpaDesIdentificacao,'=') = 'FL' then begin VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'='); if ExisteLetraString('|',VpaDesIdentificacao) then begin VpaDRetornoItem.CodFilialRec := StrToInt(CopiaAteChar(VpaDesIdentificacao,'|')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'|') end else if ExisteLetraString('/',VpaDesIdentificacao) then begin VpaDRetornoItem.CodFilialRec := StrToInt(CopiaAteChar(VpaDesIdentificacao,'/')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'/') end else begin VpaDRetornoItem.CodFilialRec := StrToInt(CopiaAteChar(VpaDesIdentificacao,' ')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,' ') end; end; if CopiaAteChar(VpaDesIdentificacao,'=') = 'LR' then begin VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'='); if ExisteLetraString('|',VpaDesIdentificacao) then begin VpaDRetornoItem.LanReceber := StrToInt(CopiaAteChar(VpaDesIdentificacao,'|')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'|') end else if ExisteLetraString('/',VpaDesIdentificacao) then begin VpaDRetornoItem.LanReceber := StrToInt(CopiaAteChar(VpaDesIdentificacao,'/')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'/') end else begin VpaDRetornoItem.LanReceber := StrToInt(CopiaAteChar(VpaDesIdentificacao,' ')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,' ') end; end; if CopiaAteChar(VpaDesIdentificacao,'=') = 'PC' then begin VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'='); if ExisteLetraString('|',VpaDesIdentificacao) then begin VpaDRetornoItem.NumParcela := StrToInt(DeletaChars(CopiaAteChar(VpaDesIdentificacao,'|'),' ')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'|') end else if ExisteLetraString('/',VpaDesIdentificacao) then begin VpaDRetornoItem.NumParcela := StrToInt(DeletaChars(CopiaAteChar(VpaDesIdentificacao,'/'),' ')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,'/') end else begin VpaDRetornoItem.NumParcela := StrToInt(DeletaChars(CopiaAteChar(VpaDesIdentificacao,' '),' ')); VpaDesIdentificacao := DeleteAteChar(VpaDesIdentificacao,' ') end; end; if VpaDRetornoItem.NomSacado = '' then VpaDRetornoItem.NomSacado := RNomClienteContasReceber(VpaDRetornoItem.CodFilialRec,VpaDRetornoItem.LanReceber); end else begin VpaDRetornoItem.CodFilialRec := 0; VpaDRetornoItem.LanReceber := 0; VpaDRetornoItem.NumParcela := 0; end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.CarLanReceberNossoNumeroItau(VpaDesIdentificacao : String; VpaDRetornoItem : TRBDREtornoItem); begin VpaDesIdentificacao := DeletaChars(VpaDesIdentificacao,' '); VpaDRetornoItem.CodFilialRec := varia.CodigoEmpFil; VpaDRetornoItem.LanReceber := StrToInt(copy(VpaDesIdentificacao,1,length(VpaDesIdentificacao)-2)); VpaDRetornoItem.NumParcela := StrToInt(copy(VpaDesIdentificacao,length(VpaDesIdentificacao)-1,2)); AdicionaSQLAbreTabela(Aux,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDRetornoItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDRetornoItem.LanReceber)+ ' and I_NRO_PAR = '+IntToStr(VpaDRetornoItem.NumParcela)); if Aux.FieldByName('N_VLR_PAR').AsFloat <> VpaDRetornoItem.ValTitulo then begin VpaDRetornoItem.CodFilialRec := 0; VpaDRetornoItem.LanReceber := 0; VpaDRetornoItem.NumParcela := 0; end else begin VpaDRetornoItem.NumDuplicata := Aux.FieldByName('C_NRO_DUP').AsString; VpaDRetornoItem.DatVencimento := Aux.FieldByName('D_DAT_VEN').AsDateTime; end; Aux.Close; end; {******************************************************************************} procedure TRBDFuncoesRetorno.CarLanReceberItem(VpaDRetorno : TRBDRetornoCorpo; VpaDItem : TRBDRetornoItem); var vpfNumDuplicata : String; begin IF (VpaDItem.NumDuplicata <> '') or (VpaDItem.DesNossoNumero <> '') then begin if VpaDItem.DesNossoNumero <> '' then PosNossoNumero(Aux,VpaDRetorno.CodFilial,VpaDItem.DesNossoNumero) else begin vpfNumDuplicata := VpaDItem.NumDuplicata; PosDuplicata(Aux,vpfNumDuplicata); if aux.Eof then begin vpfNumDuplicata := vpfNumDuplicata + '-01'; PosDuplicata(Aux,vpfNumDuplicata); end; end; if not aux.eof then begin if (VpaDItem.DatVencimento = Aux.FieldByName('D_DAT_VEN').AsDateTime) or (VpaDItem.DatVencimento < MontaData(1,1,1900)) then begin VpaDItem.CodFilialRec := Aux.FieldByName('I_EMP_FIL').AsInteger; VpaDItem.LanReceber := Aux.FieldByName('I_LAN_REC').AsInteger; VpaDItem.NumParcela := Aux.FieldByName('I_NRO_PAR').AsInteger; end; end; end; end; {******************************************************************************} function TRBDFuncoesRetorno.ContaCorrenteRetornoValida(VpaDRetorno : TRBDRetornoCorpo):string; begin result := ''; if VpaDRetorno.CodBanco = 104 then begin AdicionaSQLAbreTabela(Aux,'Select * from CADCONTAS '+ ' Where C_NUM_CON = '''+DeletaChars(VpaDRetorno.NumConta,'-')+''''); VpaDRetorno.NumConta := Aux.FieldByname('C_NRO_CON').AsString; if Aux.Eof then begin AdicionaSQLAbreTabela(Aux,'Select * from CADCONTAS '+ ' Where C_CON_BAN = '''+DeletaChars(VpaDRetorno.NumConvenio,'-')+''''); VpaDRetorno.NumConta := Aux.FieldByname('C_NRO_CON').AsString; end; end else AdicionaSQLAbreTabela(Aux,'Select * from CADCONTAS '+ ' Where C_NRO_CON = '''+VpaDRetorno.NumConta+''''); VpaDRetorno.CodFornecedorBancario := Aux.FieldByName('I_COD_CLI').AsInteger; if Aux.eof then result := 'CONTA CORRENTE NÃO CADASTRADA!!!'#13'A conta corrente "'+VpaDRetorno.NumConta+''' não existe cadastrada no sistema.' else begin if Aux.FieldByName('I_EMP_FIL').AsInteger <> varia.CodigoEmpFil then result := 'FILIAL INVÁLIDA!!!'#13'A conta corrente "'+VpaDRetorno.NumConta+''' não pertence a filial ativa. Altere a filial ativa para a '+Aux.FieldByName('I_EMP_FIL').AsString; end; if result = '' then begin if config.Somente1RetornoporCaixa then if Aux.FieldByName('I_QTD_RET').AsInteger >= 1 then result := 'JÁ FOI EFETUADO RETORNO BANCÁRIO NESSE CAIXA!!!'#13'É permitido fazer apenas 1 retorno bancário por caixa'; end; if result = '' then begin if ConfigModulos.Caixa then if not FunCaixa.ContaCaixaAberta(VpaDRetorno.NumConta) then result := 'CONTA CAIXA NÃO ABERTA!!!'#13'Antes de processar o retorno é necessário abrir o caixa dessa conta.'; end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.CarDesLiquidacao(VpaDItem : TRBDRetornoItem); begin if (VpaDItem.CodLiquidacao = 'AA') or (VpaDItem.CodLiquidacao = 'BC') or (VpaDItem.CodLiquidacao = 'BF') or (VpaDItem.CodLiquidacao = 'BL') or (VpaDItem.CodLiquidacao = 'CK') or (VpaDItem.CodLiquidacao = 'CP') or (VpaDItem.CodLiquidacao = 'DG')then VpaDItem.DesLiquidacao := 'DISPONIVEL' else if (VpaDItem.CodLiquidacao = 'AC') or (VpaDItem.CodLiquidacao = 'B0') or (VpaDItem.CodLiquidacao = 'B1') or (VpaDItem.CodLiquidacao = 'B2') or (VpaDItem.CodLiquidacao = 'B3') or (VpaDItem.CodLiquidacao = 'B4') or (VpaDItem.CodLiquidacao = 'CC') or (VpaDItem.CodLiquidacao = 'LC') then VpaDItem.DesLiquidacao := 'A COMPENSAR'; end; {******************************************************************************} function TRBDFuncoesRetorno.GravaDRetornoItem(VpaDRetorno : TRBDRetornoCorpo ):String; var VpfDItem : TRBDREtornoItem; VpfLaco : Integer; begin for VpfLaco := 0 to VpaDRetorno.Itens.count - 1 do begin VpfDItem := TRBDREtornoItem(VpaDRetorno.Itens.Items[VpfLaco]); Aux.close; Aux.Sql.clear; Aux.sql.add('INSERT INTO RETORNOITEM (CODFILIAL,SEQRETORNO,SEQITEM,INDPROCESSADO,INDPOSSUIERRO, CODOCORRENCIA,'+ ' DATOCORRENCIA,NOMSACADO,DESDUPLICATA,DESNOSSONUMERO,DATVENCIMENTO,VALTITULO,'); Aux.sql.add(' VALTARIFA,VALMULTA,VALOUTRASDESPESAS,DATCREDITO,CODCANCELADA,DESCODERRO,'+ 'DESERRO,CODLIQUIDACAO,DESDISPONIVEL,CODUSUARIO,NOMOCORRENCIA)VALUES(' ); Aux.sql.add(InttoStr(VpaDRetorno.CodFilial)+ ','+ InttoStr(VpaDRetorno.SeqRetorno)+ ','+ InttoStr(VpfLaco+1)+ ','); if VpfDItem.IndProcessada then Aux.sql.add('''S'',') else Aux.sql.add('''N'','); if VpfDItem.IndPOSSUIERRO then Aux.sql.add('''S'',') else Aux.sql.add('''N'','); Aux.sql.add(IntToStr(VpfDItem.CodOcorrencia)+','+ SqlTextoDataAAAAMMMDD(VpfDItem.DatOcorrencia)+','''+ DeletaChars(copy(VpfDItem.NomSacado,1,30),'''') +''','''+ VpfDItem.NumDuplicata+''','''+ VpfDItem.DesNossoNumero+''','); if VpfDItem.DatVencimento > MontaData(1,1,1900) then Aux.sql.add(SqlTextoDataAAAAMMMDD(VpfDItem.DatVencimento)+',') else Aux.sql.add('null,'); Aux.sql.add(SQLRetornaValorTipoCampo(VpfDItem.ValTitulo)+','+ SQLRetornaValorTipoCampo(VpfDItem.ValTarifa)+','+ SQLRetornaValorTipoCampo(VpfDItem.ValJuros)+','+ SQLRetornaValorTipoCampo(VpfDItem.ValOutrasDespesas)+','+ SQLRetornaValorTipoCampo(VpfDItem.DatCredito)+','); if VpfDItem.CodCancelada <> 0 then Aux.sql.add(SQLRetornaValorTipoCampo(VpfDItem.CodCancelada)+',') else Aux.sql.add('null,'); Aux.sql.add(''''+copy(VpfDItem.CodErros,1,8)+''','''+ copy(RetiraAcentuacao(VpfDItem.DesErro),1,100)+''','''+ VpfDItem.CodLiquidacao+''','''+ VpfDItem.DesLiquidacao+''','+ SQLRetornaValorTipoCampo(varia.CodigoUsuario)+','''+ VpfDItem.NomOcorrencia+''')'); Aux.execsql; end; end; {******************************************************************************} function TRBDFuncoesRetorno.IncrementaRetornosEfetuados(VpaDRetorno: TRBDRetornoCorpo): string; begin result := ''; AdicionaSQLAbreTabela(Cadastro,'Select * from CADCONTAS ' + 'Where C_NRO_CON = '''+VpaDRetorno.NumConta+''''); Cadastro.edit; Cadastro.FieldByName('I_QTD_RET').AsInteger := Cadastro.FieldByName('I_QTD_RET').AsInteger +1; Cadastro.Post; result := Cadastro.AMensagemErroGravacao; end; {******************************************************************************} function TRBDFuncoesRetorno.GravaDRetorno(VpaDRetorno : TRBDRetornoCorpo) : String; begin result := ''; AdicionaSQLAbreTabela(Cadastro,'Select * from RETORNOCORPO'); Cadastro.Insert; Cadastro.FieldByName('CODFILIAL').AsInteger := VpaDRetorno.CodFilial; Cadastro.FieldByName('SEQARQUIVO').AsInteger := VpaDRetorno.SeqArquivo; Cadastro.FieldByName('NUMCONTA').AsString := VpaDRetorno.NumConta; Cadastro.FieldByName('NOMARQUIVO').AsString := VpaDRetorno.NomArquivo; Cadastro.FieldByName('CODUSUARIO').AsInteger := VpaDRetorno.CodUsuario; Cadastro.FieldByName('DATRETORNO').AsDateTime := VpaDRetorno.DatRetorno; Cadastro.FieldByName('DATGERACAO').AsDateTime := VpaDRetorno.DatGeracao; Cadastro.FieldByName('INDIMPRESSO').AsString := 'N'; if VpaDRetorno.DatCredito > MontaData(1,1,1900) then Cadastro.FieldByName('DATCREDITO').AsDateTime := VpaDRetorno.DatCredito; if VpaDRetorno.SeqRetorno = 0 then VpaDRetorno.SeqRetorno := RSeqRetornoDisponivel(VpaDRetorno.CodFilial); Cadastro.FieldByName('SEQRETORNO').AsInteger := VpaDRetorno.SeqRetorno; try Cadastro.post; except on e : exception do result := 'ERRO NA GRAVAÇÃO DO RETORNO CORPO!!!'#13+e.message; end; if result = '' then result := GravaDRetornoItem(VpaDRetorno); if result = '' then result :=IncrementaRetornosEfetuados(VpaDRetorno); end; {******************************************************************************} procedure TRBDFuncoesRetorno.processaEntradaConfirmada(VpaDRetornoCorpo : TRBDRetornoCorpo; VpaDItem : TRBDREtornoItem); begin VpaDItem.DesErro := ''; VpaDItem.NomOcorrencia := 'ENTRADA CONFIRMADA'; if (VpaDItem.LanReceber = 0) then VpaDItem.DesErro := 'NAO FOI POSSIVEL CONFIRMAR A ENTRADA!!!LANREC = 0.' else begin if not ConfirmaItemRemessa(VpaDItem.CodFilialRec,VpaDItem.LanReceber,VpaDItem.NumParcela) then VpaDItem.DesErro := 'NAO FOI POSSIVEL CONFIRMAR A ENTRADA!!! Lançamento nao encontrado.' else begin if VpaDItem.ValTarifa <> 0 then FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValTarifa,'TARIFA REGISTRO DUPLICATA',''); VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.processaDescontoDuplicata(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); begin VpaDItem.NomOcorrencia := 'DESCONTO DUPLICATA'; if VpaDItem.LanReceber = 0 then CarLanReceberItem(VpaDRetornoCorpo,VpaDItem); if VpaDItem.LanReceber <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDItem.LanReceber)+ ' AND I_NRO_PAR = '+IntToStr(VpadItem.NumParcela)); if not Cadastro.Eof then begin if Cadastro.FieldByName('C_DUP_DES').AsString = '' then begin Cadastro.Edit; Cadastro.FieldByName('C_DUP_DES').AsString := 'S'; Cadastro.Post; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValJuros,'TARIFA DESCONTO DUPLICATA',varia.PlanoDescontoDuplicata); VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou o envio para cartorio dessa duplicata em outro retorno.' end else VpaDItem.DesErro:= 'DUPLICATA EXCLUIDA!!!O sistema nao envio para cartorio o titulo pois o mesmo foi excluido do sistema.' end else VpaDItem.DesErro:= 'DUPLICATA NAO ENCONTRADA NO SISTEMA!!!O sistema nao localizou o titulo para enviar para marcar como enviado para cartorio.' end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaEntradaRejeitadaItau(VpaDRetorno : TRBDRetornoCorpo; VpaDItem : TRBDREtornoItem); var VpfAux : String; VpfCodErro : Integer; begin VpaDItem.NomOcorrencia := 'ENTRADA REJEITADA'; VpfAux := DeletaChars(VpaDItem.CodErros,' '); while length(VpfAux) > 1 do begin VpfCodErro := StrToInt(copy(VpfAux,1,2)); VpfAux := copy(VpfAux,3,10); if VpfCodErro <> 0 then begin case VpaDRetorno.CodBanco of 237 : VpaDItem.DesErro := RErroBradesco(VpfCodErro); else VpaDItem.DesErro := RErroCNAB240(VpfCodErro); end; end; end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaLiquidacaoNormal(VpaDRetorno : TRBDRetornoCorpo; VpaDItem : TRBDREtornoItem); var VpfDBaixa : TRBDBaixaCR; VpfDParela : TRBDParcelaBaixaCR; VpfVAlor : Double; begin if VpaDItem.CodOcorrencia = 16 then VpaDItem.NomOcorrencia := 'TITULO PAGO EM CHEQUE - VINCULADO' else if VpaDItem.CodOcorrencia = 17 then VpaDItem.NomOcorrencia := 'LIQ TITULO NAO REGISTRADO' ELSE if VpaDItem.CodOcorrencia = 8 then VpaDItem.NomOcorrencia := 'LIQUIDACAO EM CARTORIO' ELSE VpaDItem.NomOcorrencia := 'LIQUIDACAO NORMAL'; if VpaDItem.LanReceber = 0 then CarLanReceberItem(VpaDRetorno,VpaDItem); if VpaDItem.LanReceber <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDItem.LanReceber)+ ' AND I_NRO_PAR = '+IntToStr(VpadItem.NumParcela)); if not Cadastro.Eof then begin if Cadastro.FieldByName('N_VLR_PAG').AsFLOAT = 0 then begin VpfVAlor :=(VpaDItem.ValTitulo + VpaDItem.ValJuros); if (Cadastro.FieldByName('N_VLR_PAR').AsFLOAT <= VpfVAlor) then begin VpfDBaixa := TRBDBaixaCR.Cria; VpfDBaixa.CodFormaPagamento := varia.FormaPagamentoBoleto; VpfDBaixa.TipFormaPagamento := fpCobrancaBancaria; VpfDBaixa.NumContaCaixa := VpaDRetorno.NumConta; VpfDBaixa.ValorAcrescimo := VpaDItem.ValJuros; VpfDBaixa.ValorPago := VpaDItem.ValTitulo + VpaDItem.ValJuros; VpfDBaixa.DatPagamento := VpaDItem.DatOcorrencia; VpfDBaixa.IndPagamentoParcial := false; VpfDBaixa.IndBaixaRetornoBancario := true; VpfDParela := VpfDBaixa.AddParcela; FunContasAReceber.CarDParcelaBaixa(VpfDParela,VpaDItem.CodFilialRec,VpaDItem.LanReceber,VpaDItem.NumParcela); VpfDParela.ValAcrescimo := VpaDItem.ValJuros; if VpfDParela.DesObservacoes <> '' then VpfDParela.DesObservacoes := VpfDParela.DesObservacoes+#13; VpfDParela.DesObservacoes := VpfDParela.DesObservacoes + ' Baixa automatica pelo retorno do banco '+DeletaEspacoD(VpaDRetorno.NomBanco)+' ('+VpaDRetorno.NumConta+')'; FunContasAReceber.BaixaContasAReceber(VpfDBaixa); if VpaDItem.ValTarifa <> 0 then FunContasAPagar.GeraCPTarifasRetorno(VpaDRetorno,VpaDItem,VpaDItem.ValTarifa,'TARIFA REGISTRO DUPLICATA',''); VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end else VpaDItem.DesErro:= 'VALOR PAGO MENOR QUE O VALOR DA DUPLICATA!!!O sistema nao baixou o titulo por detectar diferenca nos valores.' end else VpaDItem.DesErro:= 'DUPLICATA JA PAGA!!!O sistema nao baixou o titulo pois o mesmo ja se encontrava baixado.' end else VpaDItem.DesErro:= 'DUPLICATA EXCLUIDA!!!O sistema nao baixou o titulo pois o mesmo foi excluido do sistema.' end else VpaDItem.DesErro:= 'DUPLICATA NAO ENCONTRADA NO SISTEMA!!!O sistema nao localizou o titulo do contas a receber para baixar.' end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaEnvioCartorio(VpaDRetornoCorpo : TRBDRetornoCorpo; VpaDItem : TRBDREtornoItem); begin VpaDItem.NomOcorrencia := 'ENVIO CARTORIO'; if VpaDItem.LanReceber = 0 then CarLanReceberItem(VpaDRetornoCorpo, VpaDItem); if VpaDItem.LanReceber <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDItem.LanReceber)+ ' AND I_NRO_PAR = '+IntToStr(VpadItem.NumParcela)); if not Cadastro.Eof then begin if Cadastro.FieldByName('N_VLR_ECA').AsFloat = 0 then begin Cadastro.Edit; Cadastro.FieldByName('D_ENV_CAR').AsDateTime := VpaDItem.DatOcorrencia; Cadastro.FieldByName('N_VLR_ECA').AsFloat := VpaDItem.ValTarifa; AtualizaTotalTarifas(Cadastro); Cadastro.Post; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValTarifa,'TARIFA ENVIO CARTORIO',''); VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou o envio para cartorio dessa duplicata em outro retorno.' end else VpaDItem.DesErro:= 'DUPLICATA EXCLUIDA!!!O sistema nao envio para cartorio o titulo pois o mesmo foi excluido do sistema.' end else VpaDItem.DesErro:= 'DUPLICATA NAO ENCONTRADA NO SISTEMA!!!O sistema nao localizou o titulo para enviar para marcar como enviado para cartorio.' end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaDebitoTarifas(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); begin VpaDItem.NomOcorrencia := 'DEBITO DE TARIFAS'; if VpaDItem.LanReceber = 0 then CarLanReceberItem(VpaDRetornoCorpo, VpaDItem); if VpaDItem.LanReceber <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDItem.LanReceber)+ ' AND I_NRO_PAR = '+IntToStr(VpadItem.NumParcela)); if not Cadastro.Eof then begin Cadastro.Edit; VpaDItem.CodErros := copy(VpaDItem.CodErros,1,2); // duplicata em cartorio if VpaDItem.CodErros = '08' then begin if Cadastro.FieldByName('N_VLR_CAR').AsFloat = 0 then begin Cadastro.FieldByName('N_VLR_CAR').AsFloat := VpaDItem.ValOutrasDespesas; Cadastro.FieldByName('D_ENV_CAR').AsDateTime := VpaDItem.DatOcorrencia; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValOutrasDespesas,'DUPLICATA EM CARTORIO',''); end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou o envio para cartorio dessa duplicata em outro retorno.' end //sustacao de protesto else if VpaDItem.CodErros = '09' then begin if Cadastro.FieldByName('N_VLR_BPR').AsFloat = 0 then begin Cadastro.FieldByName('N_VLR_BPR').AsFloat := VpaDItem.ValOutrasDespesas; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValOutrasDespesas,'SUSTACAO DE PROTESTO',''); end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou o envio para cartorio dessa duplicata em outro retorno.' end else //TARIFA DE MANUTENCAO DE TITULO VENCIDO if VpaDItem.CodErros = '02' then begin if Cadastro.FieldByName('N_VLR_TMA').AsFloat = 0 then begin Cadastro.FieldByName('N_VLR_TMA').AsFloat := VpaDItem.ValTarifa; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValTarifa,'TARIFA MANUTENCAO TITULO VENCIDO',''); end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou a tarifa de manutencao de titulo vencido desta duplicata em outro retorno.' end; AtualizaTotalTarifas(Cadastro); Cadastro.Post; if VpaDItem.DesErro = '' then begin VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; end else VpaDItem.DesErro:= 'DUPLICATA EXCLUIDA!!!O sistema nao envio para cartorio o titulo pois o mesmo foi excluido do sistema.' end else VpaDItem.DesErro:= 'DUPLICATA NAO ENCONTRADA NO SISTEMA!!!O sistema nao localizou o titulo.' end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaBaixaSimples(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); begin VpaDItem.NomOcorrencia := 'BAIXA SIMPLES'; if VpaDItem.LanReceber = 0 then CarLanReceberItem(VpaDRetornoCorpo,VpaDItem); if VpaDItem.LanReceber <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDItem.LanReceber)+ ' AND I_NRO_PAR = '+IntToStr(VpadItem.NumParcela)); if not Cadastro.Eof then begin if Cadastro.FieldByName('N_VLR_TBS').AsFloat = 0 then begin Cadastro.Edit; Cadastro.FieldByName('N_VLR_TBS').AsFloat := VpaDItem.ValTarifa; AtualizaTotalTarifas(Cadastro); Cadastro.Post; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValTarifa,'BAIXA SIMPLES',''); VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou a instrução de cancelamento de envio para protesto dessa duplicata em outro retorno.' end else VpaDItem.DesErro:= 'DUPLICATA EXCLUIDA!!!O sistema nao processou o titulo pois o mesmo foi excluido do sistema.' end else VpaDItem.DesErro:= 'DUPLICATA NAO ENCONTRADA NO SISTEMA!!!O sistema nao localizou o titulo para processar.' end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaCancelamentoProtesto(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); begin VpaDItem.NomOcorrencia := 'CANCELAMENTO PROTESTO'; if VpaDItem.LanReceber = 0 then CarLanReceberItem(VpaDRetornoCorpo,VpaDItem); if VpaDItem.LanReceber <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDItem.LanReceber)+ ' AND I_NRO_PAR = '+IntToStr(VpadItem.NumParcela)); if not Cadastro.Eof then begin if Cadastro.FieldByName('N_VLR_CPR').AsFloat = 0 then begin Cadastro.Edit; Cadastro.FieldByName('N_VLR_CPR').AsFloat := VpaDItem.ValTarifa; AtualizaTotalTarifas(Cadastro); Cadastro.Post; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValTarifa,'INSTRUCAO DE CANCELAMENTO PROTESTO',''); VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou a instrução de cancelamento de envio para protesto dessa duplicata em outro retorno.' end else VpaDItem.DesErro:= 'DUPLICATA EXCLUIDA!!!O sistema nao processou o titulo pois o mesmo foi excluido do sistema.' end else VpaDItem.DesErro:= 'DUPLICATA NAO ENCONTRADA NO SISTEMA!!!O sistema nao localizou o titulo para processar.' end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoCorpoItau(VpaLinha : String;VpaDRetorno : TRBDRetornoCorpo); begin TextoStatus('Carregando Header do Banco "'+copy(VpaLinha,80,15)+'"'); VpaDRetorno.CodBanco := StrToInt(copy(VpaLinha,77,3)); VpaDRetorno.NomBanco := copy(VpaLinha,80,15); VpaDRetorno.CodFilial := varia.CodigoEmpFil; if (varia.CNPJFilial = CNPJ_INFORMARE) or (varia.CNPJFilial = CNPJ_INFORWAP) or (varia.CNPJFilial = CNPJ_INFORMANET) then VpaDRetorno.NumConta := '206490' else VpaDRetorno.NumConta := DeletaCharE(copy(VpaLinha,33,6),'0'); insert('-',VpaDRetorno.NumConta,length(VpadRetorno.Numconta)); VpaDRetorno.DatRetorno := now; VpaDRetorno.DatGeracao := MontaData(StrToInt(copy(VpaLinha,95,2)),strtoint(copy(VpaLinha,97,2)),StrToInt('20'+copy(VpaLinha,99,2))); VpaDRetorno.SeqArquivo := StrToIntDef(copy(VpaLinha,109,5),0); try VpaDRetorno.DatCredito := MontaData(StrToInt(copy(VpaLinha,114,2)),strtoint(copy(VpaLinha,116,2)),StrToInt('20'+copy(VpaLinha,118,2))); except VpaDRetorno.DatCredito := MontaData(StrToInt(copy(VpaLinha,95,2)),strtoint(copy(VpaLinha,97,2)),StrToInt('20'+copy(VpaLinha,99,2))); end; VpaDRetorno.CodUsuario := varia.CodigoUsuario; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoCorpoCNAB400(VpaLinha : String;VpaDRetorno : TRBDRetornoCorpo); begin TextoStatus('Carregando Header do Banco "'+copy(VpaLinha,80,15)+'"'); VpaDRetorno.CodBanco := StrToInt(copy(VpaLinha,77,3)); VpaDRetorno.NomBanco := copy(VpaLinha,80,15); VpaDRetorno.CodFilial := varia.CodigoEmpFil; VpaDRetorno.NumConta := RNumContaCorrente(copy(VpaLinha,40,7)); VpaDRetorno.DatRetorno := now; VpaDRetorno.DatGeracao := MontaData(StrToInt(copy(VpaLinha,95,2)),strtoint(copy(VpaLinha,97,2)),StrToInt('20'+copy(VpaLinha,99,2))); VpaDRetorno.SeqArquivo := StrToInt(copy(VpaLinha,109,5)); VpaDRetorno.DatCredito := MontaData(StrToInt(copy(VpaLinha,380,2)),strtoint(copy(VpaLinha,382,2)),StrToInt('20'+copy(VpaLinha,384,2))); VpaDRetorno.CodUsuario := varia.CodigoUsuario; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoCorpoCNAB240(VpaLinha : String;VpaDRetorno : TRBDRetornoCorpo); begin TextoStatus('Carregando Header do Banco "'+copy(VpaLinha,103,30)+'"'); VpaDRetorno.CodBanco := StrToInt(Copy(VpaLinha,1,3)); VpaDRetorno.NomBanco := copy(VpaLinha,103,30); VpaDRetorno.CodFilial := varia.CodigoEmpFil; if varia.CNPJFilial = CNPJ_AGZ then VpaDRetorno.NumConta := copy(VpaLinha,66,5)+'-'+copy(VpaLinha,71,2) else begin VpaDRetorno.NumConta := DeletaCharE(copy(VpaLinha,59,12),'0'); if VpaDRetorno.CodBanco = 399 then VpaDRetorno.NumConta := AdicionaCharE('0',copy(VpaDRetorno.NumConta,1,length(VpaDRetorno.NumConta)-2)+'-'+copy(VpaDRetorno.NumConta,length(VpaDRetorno.NumConta)-1,2),8) else VpaDRetorno.NumConta := VpaDRetorno.NumConta+'-'+copy(VpaLinha,71,1); end; VpaDRetorno.DatRetorno := now; VpaDRetorno.DatGeracao := MontaData(StrToInt(copy(VpaLinha,144,2)),strtoint(copy(VpaLinha,146,2)),StrToInt(copy(VpaLinha,148,4))); VpaDRetorno.SeqArquivo := StrToInt(copy(VpaLinha,158,6)); VpaDRetorno.DatCredito := VpaDRetorno.DatGeracao; VpaDRetorno.NumConvenio := copy(VpaLinha,33,16); VpaDRetorno.CodUsuario := varia.CodigoUsuario; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaOcorrenciaItemItau(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItem : TRBDREtornoItem); begin if VpaDRetornoCorpo.CodBanco = 341 then begin case VpaDItem.CodOcorrencia of 2 : processaEntradaConfirmada(VpaDRetornoCorpo,VpaDItem); //entradaConfirmada; 3 : ProcessaEntradaRejeitadaItau(VpaDRetornoCorpo,VpaDItem); //entrada rejeitada 6,8 : ProcessaLiquidacaoNormal(VpaDRetornoCorpo,VpaDItem); //liquidação normal; 9 : ProcessaBaixaSimples(VpaDRetornoCorpo, VpaDItem); 14,29 : begin VpaDItem.DesErro := '';// VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; 15 :begin VpaDItem.NomOcorrencia := 'BAIXA REJEITADA'; VpaDItem.DesErro := '';// VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; 19 :begin VpaDItem.NomOcorrencia := 'CONFIRMACAO RECEBIMENTO PROTESTO'; VpaDItem.DesErro := '';// VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; 20 : ProcessaSustacaoProtesto(VpaDRetornoCorpo, VpaDItem); 24 : ProcessaCancelamentoProtesto(VpaDRetornoCorpo, VpaDItem); 23 : ProcessaEnvioCartorio(VpaDRetornoCorpo, VpaDItem); 28 : ProcessaDebitoTarifas(VpaDRetornoCorpo, VpaDItem); 47 : processaDescontoDuplicata(VpaDRetornoCorpo,VpaDItem); else VpaDItem.DesErro:= 'OCORRÊNCIA NAO CADASTRADA!!!'; end; end else if VpaDRetornoCorpo.CodBanco = 104 then begin case VpaDItem.CodOcorrencia of 2 : processaEntradaConfirmada(VpaDRetornoCorpo,VpaDItem); //entradaConfirmada; 3 : ProcessaEntradaRejeitadaItau(VpaDRetornoCorpo,VpaDItem); //entrada rejeitada 6 : ProcessaLiquidacaoNormal(VpaDRetornoCorpo,VpaDItem); //liquidação normal; 9 : ProcessaBaixaSimples(VpaDRetornoCorpo, VpaDItem); 14: begin VpaDItem.DesErro := '';// VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; 24 : ProcessaCancelamentoProtesto(VpaDRetornoCorpo, VpaDItem); 23 : ProcessaEnvioCartorio(VpaDRetornoCorpo, VpaDItem); 28 : ProcessaDebitoTarifas(VpaDRetornoCorpo, VpaDItem); else VpaDItem.DesErro:= 'OCORRÊNCIA NAO CADASTRADA!!!'; end; end else if VpaDRetornoCorpo.CodBanco = 237 then begin case VpaDItem.CodOcorrencia of 2 : processaEntradaConfirmada(VpaDRetornoCorpo,VpaDItem); //entradaConfirmada; 3 : ProcessaEntradaRejeitadaItau(VpaDRetornoCorpo,VpaDItem); //entrada rejeitada 6 : ProcessaLiquidacaoNormal(VpaDRetornoCorpo,VpaDItem); //liquidação normal; 10 : ProcessaBaixaSimples(VpaDRetornoCorpo, VpaDItem); 14: begin VpaDItem.DesErro := '';// VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; 24 : ProcessaCancelamentoProtesto(VpaDRetornoCorpo, VpaDItem); 23 : ProcessaEnvioCartorio(VpaDRetornoCorpo, VpaDItem); 28 : ProcessaDebitoTarifas(VpaDRetornoCorpo, VpaDItem); else VpaDItem.DesErro:= 'OCORRÊNCIA NAO CADASTRADA!!!'; end; end else begin case VpaDItem.CodOcorrencia of 2 : processaEntradaConfirmada(VpaDRetornoCorpo,VpaDItem); //entradaConfirmada; 3 : ProcessaEntradaRejeitadaItau(VpaDRetornoCorpo,VpaDItem); //entrada rejeitada 4 : processaDescontoDuplicata(VpaDRetornoCorpo,VpaDItem); 6,16,17 : ProcessaLiquidacaoNormal(VpaDRetornoCorpo,VpaDItem); //liquidação normal; 9 : ProcessaBaixaSimples(VpaDRetornoCorpo, VpaDItem); 14,29 : begin VpaDItem.DesErro := '';// VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end; 20 : ProcessaCancelamentoProtesto(VpaDRetornoCorpo, VpaDItem); 23 : ProcessaEnvioCartorio(VpaDRetornoCorpo, VpaDItem); 28 : ProcessaDebitoTarifas(VpaDRetornoCorpo, VpaDItem); else VpaDItem.DesErro:= 'OCORRÊNCIA NAO CADASTRADA!!!'; end; end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoItemCNAB240(VpaArquivo : TStringList;VpaDRetorno : TRBDRetornoCorpo); var VpfDItem : TRBDREtornoItem; VpfLaco : Integer; VpfLinha : String; begin for VpfLaco := 2 to VpaArquivo.Count-3 do begin VpfLinha := VpaArquivo.Strings[VpfLaco]; if copy(VpfLinha,14,1) = 'T' then begin VpfDItem := VpaDRetorno.addItem; ProcessaRetornoItemTCNAB240(VpfLinha,VpfDItem) end else if copy(VpfLinha,14,1) = 'U' then begin ProcessaRetornoItemUCNAB240(VpfLinha,VpfDItem); if VpfDItem.CodFilialRec = 0 then LocalizaParcelaCNAB240(VpaDRetorno,VpfDItem); ProcessaOcorrenciaItemItau(VpaDRetorno,VpfDItem); end; end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoItemTCNAB240(VpfLinha : String;VpaDItemRetorno : TRBDRetornoItem); begin VpaDItemretorno.NomSacado := DeletaCharD(DeletaCharD(copy(VpfLinha,149,40),' '),'0'); CarLanReceber(Copy(VpfLinha,106,25),VpaDItemretorno); VpaDItemretorno.CodOcorrencia := StrToInt(copy(vpfLinha,16,2)); VpaDItemretorno.NumDuplicata := DeletaCharD(copy(vpfLinha,59,15),' '); if copy(VpfLinha,75,1) <> '0' then VpaDItemretorno.DatVencimento := MontaData(StrToInt(copy(VpfLinha,74,2)),StrToInt(copy(VpfLinha,76,2)),StrToInt(copy(VpfLinha,78,4))); VpaDItemretorno.ValTitulo := StrToFloat(copy(VpfLinha,82,15))/100 ; VpaDItemretorno.ValTarifa := StrToFloat(copy(VpfLinha,199,15))/100 ; VpaDItemRetorno.DesNossoNumero := DeletaCharE(DeletaChars(DeletaCharD(copy(vpfLinha,38,20),' '),' '),'0'); // VpaDItemretorno.CodLiquidacao := copy(VpfLinha,393,2); VpaDItemretorno.CodErros := copy(VpfLinha,214,10); end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoItemUCNAB240(VpfLinha : String;VpaDItemRetorno : TRBDRetornoItem); begin VpaDItemretorno.DatOcorrencia := MontaData(StrToInt(copy(VpfLinha,138,2)),StrToInt(copy(VpfLinha,140,2)),StrToInt(copy(VpfLinha,142,4))); VpaDItemretorno.ValJuros := StrToFloat(copy(VpfLinha,18,15))/100 ; if (copy(vpflinha,146,1) <> ' ') and (copy(vpflinha,146,1) <> '0') then VpaDItemretorno.DatCredito := MontaData(StrToInt(copy(VpfLinha,146,2)),StrToInt(copy(VpfLinha,148,2)),StrToInt(copy(VpfLinha,150,4))); VpaDItemretorno.ValOutrasDespesas := StrToFloat(copy(VpfLinha,108,15))/100 ; VpaDItemretorno.ValLiquido := StrToFloat(copy(VpfLinha,93,15))/100 ; // VpaDItemretorno.CodCancelada := StrToInt(copy(vpfLinha,302,4)); end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaSustacaoProtesto(VpaDRetornoCorpo: TRBDRetornoCorpo; VpaDItem: TRBDREtornoItem); begin VpaDItem.NomOcorrencia := 'SUSTACAO CARTORIO'; if VpaDItem.LanReceber = 0 then CarLanReceberItem(VpaDRetornoCorpo, VpaDItem); if VpaDItem.LanReceber <> 0 then begin AdicionaSQLAbreTabela(Cadastro,'Select * from MOVCONTASARECEBER '+ ' Where I_EMP_FIL = '+IntToStr(VpaDItem.CodFilialRec)+ ' and I_LAN_REC = '+IntToStr(VpaDItem.LanReceber)+ ' AND I_NRO_PAR = '+IntToStr(VpadItem.NumParcela)); if not Cadastro.Eof then begin if Cadastro.FieldByName('N_VLR_BPR').AsFloat = 0 then begin Cadastro.Edit; Cadastro.FieldByName('N_VLR_BPR').AsFloat := VpaDItem.ValTarifa; AtualizaTotalTarifas(Cadastro); Cadastro.Post; FunContasAPagar.GeraCPTarifasRetorno(VpaDRetornoCorpo,VpaDItem,VpaDItem.ValTarifa,'SUSTACAO PROTESTO',''); VpaDItem.IndProcessada := true; VpaDItem.IndPossuiErro := false; end else VpaDItem.DesErro:= 'DUPLICATA JÁ PROCESSADA PELO SISTEMA!!!O sistema já processou o envio para cartorio dessa duplicata em outro retorno.' end else VpaDItem.DesErro:= 'DUPLICATA EXCLUIDA!!!O sistema nao envio para cartorio o titulo pois o mesmo foi excluido do sistema.' end else VpaDItem.DesErro:= 'DUPLICATA NAO ENCONTRADA NO SISTEMA!!!O sistema nao localizou o titulo para enviar para marcar como enviado para cartorio.' end; {******************************************************************************} procedure TRBDFuncoesRetorno.LocalizaParcelaCNAB240(VpaDRetornoCorpo : TRBDRetornoCorpo;VpaDItemRetorno : TRBDRetornoItem); var vpfNumDuplicata : String; begin if VpaDItemRetorno.NumDuplicata <>'' then begin VpaDItemRetorno.NumDuplicata := DeletaChars(VpaDItemRetorno.NumDuplicata,' '); VpaDItemRetorno.NumDuplicata := DeletaChars(VpaDItemRetorno.NumDuplicata,'V'); VpaDItemRetorno.NumDuplicata := DeletaChars(VpaDItemRetorno.NumDuplicata,'S'); if length(VpaDItemRetorno.NumDuplicata) < 6 then vpfNumDuplicata := VpaDItemRetorno.NumDuplicata +'/1' else vpfNumDuplicata := copy(VpaDItemRetorno.NumDuplicata,1,length(VpaDItemRetorno.NumDuplicata)-3)+'/'+DeletaCharE(copy(VpaDItemRetorno.NumDuplicata,length(VpaDItemRetorno.NumDuplicata)-2,4),'0'); AdicionaSQLAbreTabela(Aux,'Select * from MOVCONTASARECEBER '+ ' Where C_NRO_DUP = '''+vpfNumDuplicata+''''); if not Aux.Eof then begin if (Aux.FieldByName('D_DAT_VEN').AsDateTime = VpaDItemRetorno.DatVencimento) and (Aux.FieldByName('N_VLR_PAR').AsFloat = VpaDItemRetorno.ValTitulo) then begin VpaDItemRetorno.CodFilialRec := Aux.FieldByName('I_EMP_FIL').AsInteger; VpaDItemRetorno.LanReceber := Aux.FieldByName('I_LAN_REC').AsInteger; VpaDItemRetorno.NumParcela := Aux.FieldByName('I_NRO_PAR').AsInteger; end; end; end else if (VpaDItemRetorno.DesNossoNumero <> '') and (VpaDRetornoCorpo.CodBanco = 104) then begin AdicionaSQLAbreTabela(Aux,'Select * from MOVCONTASARECEBER '+ ' Where C_NOS_NUM = '''+copy(DeletaCharE(VpaDItemRetorno.DesNossoNumero,' '),1,10)+''''+ ' AND I_EMP_FIL = '+ IntToStr(VpaDRetornoCorpo.CodFilial)); if not Aux.Eof then begin if (Aux.FieldByName('D_DAT_VEN').AsDateTime >= VpaDItemRetorno.DatVencimento) and (Aux.FieldByName('N_VLR_PAR').AsFloat = VpaDItemRetorno.ValTitulo) then begin VpaDItemRetorno.CodFilialRec := Aux.FieldByName('I_EMP_FIL').AsInteger; VpaDItemRetorno.LanReceber := Aux.FieldByName('I_LAN_REC').AsInteger; VpaDItemRetorno.NumParcela := Aux.FieldByName('I_NRO_PAR').AsInteger; end; end; end; Aux.Close; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoItemItau(VpaArquivo : TStringList;VpaDRetorno : TRBDRetornoCorpo); var VpfDItem : TRBDREtornoItem; VpfLaco : Integer; VpfLinha : String; begin for VpfLaco := 1 to VpaArquivo.Count-2 do begin VpfLinha := VpaArquivo.Strings[VpfLaco]; VpfDItem := VpaDRetorno.addItem; VpfDItem.NomSacado := copy(VpfLinha,325,30); CarLanReceber(Copy(VpfLinha,38,25),VpfDItem); VpfDItem.CodOcorrencia := StrToInt(copy(vpfLinha,109,2)); VpfDItem.DesNossoNumero := copy(vpfLinha,63,8); VpfDItem.DatOcorrencia := MontaData(StrToInt(copy(VpfLinha,111,2)),StrToInt(copy(VpfLinha,113,2)),StrToInt('20'+copy(VpfLinha,115,2))); VpfDItem.NumDuplicata := DeletaCharD(copy(vpfLinha,117,10),' '); if StrToInt(copy(VpfLinha,147,2)) <> 0 then // so monta da data se o dia for diferente de zero. VpfDItem.DatVencimento := MontaData(StrToInt(copy(VpfLinha,147,2)),StrToInt(copy(VpfLinha,149,2)),StrToInt('20'+copy(VpfLinha,151,2))); VpfDItem.ValTitulo := StrToFloat(copy(VpfLinha,153,13))/100 ; VpfDItem.ValTarifa := StrToFloat(copy(VpfLinha,176,13))/100 ; VpfDItem.ValJuros := StrToFloat(copy(VpfLinha,267,13))/100 ; VpfDItem.ValLiquido := VpfDItem.ValTitulo + VpfDItem.ValJuros ; if copy(vpflinha,296,1) <> ' ' then VpfDItem.DatCredito := MontaData(StrToInt(copy(VpfLinha,296,2)),StrToInt(copy(VpfLinha,298,2)),StrToInt('20'+copy(VpfLinha,300,2))); VpfDItem.CodCancelada := StrToInt(copy(vpfLinha,302,4)); VpfDItem.CodErros := copy(VpfLinha,378,8); VpfDItem.CodLiquidacao := copy(VpfLinha,393,2); CarDesLiquidacao(VpfDItem); if VpfDItem.LanReceber = 0 then CarLanReceberNossoNumeroItau(Copy(VpfLinha,63,8),VpfDItem); ProcessaOcorrenciaItemItau(VpaDRetorno, VpfDItem); end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.ProcessaRetornoItemCNAB400(VpaArquivo : TStringList;VpaDRetorno : TRBDRetornoCorpo); var VpfDItem : TRBDREtornoItem; VpfLaco : Integer; VpfLinha : String; begin for VpfLaco := 1 to VpaArquivo.Count-2 do begin VpfLinha := VpaArquivo.Strings[VpfLaco]; VpfDItem := VpaDRetorno.addItem; CarLanReceber(Copy(VpfLinha,38,25),VpfDItem); VpfDItem.CodOcorrencia := StrToInt(copy(vpfLinha,109,2)); VpfDItem.DesNossoNumero := copy(vpfLinha,71,12); VpfDItem.DatOcorrencia := MontaData(StrToInt(copy(VpfLinha,111,2)),StrToInt(copy(VpfLinha,113,2)),StrToInt('20'+copy(VpfLinha,115,2))); VpfDItem.NumDuplicata := DeletaCharD(copy(vpfLinha,117,10),' '); if StrToInt(copy(VpfLinha,147,2)) <> 0 then // so monta da data se o dia for diferente de zero. VpfDItem.DatVencimento := MontaData(StrToInt(copy(VpfLinha,147,2)),StrToInt(copy(VpfLinha,149,2)),StrToInt('20'+copy(VpfLinha,151,2))); VpfDItem.ValTitulo := StrToFloat(copy(VpfLinha,153,13))/100 ; VpfDItem.ValTarifa := StrToFloat(copy(VpfLinha,176,13))/100 ; VpfDItem.ValJuros := StrToFloat(copy(VpfLinha,267,13))/100 ; VpfDItem.ValLiquido := VpfDItem.ValTitulo + VpfDItem.ValJuros ; if (copy(vpflinha,296,1) <> ' ') and (copy(vpflinha,296,2) <> '00')then VpfDItem.DatCredito := MontaData(StrToInt(copy(VpfLinha,296,2)),StrToInt(copy(VpfLinha,298,2)),StrToInt('20'+copy(VpfLinha,300,2))); VpfDItem.CodErros := copy(VpfLinha,319,10); ProcessaOcorrenciaItemItau(VpaDRetorno, VpfDItem); end; end; {******************************************************************************} function TRBDFuncoesRetorno.processaRetornoItau(VpaArquivo : TStringList):String; var VpfDRetorno : TRBDRetornoCorpo; begin result := ''; VpfDRetorno := TRBDRetornoCorpo.cria; ProcessaRetornoCorpoItau(VpaArquivo.Strings[0],VpfDRetorno); Result := ContaCorrenteRetornoValida(VpfDRetorno); if result = '' then begin ProcessaRetornoItemItau(VpaArquivo,VpfDRetorno); if result = '' then result := GravaDRetorno(VpfDRetorno); end; VpfDRetorno.free; end; {******************************************************************************} function TRBDFuncoesRetorno.ProcessaRetornoCNAB240(VpaNomArquivo : String;VpaArquivo : TStringList):String; var VpfDRetorno : TRBDRetornoCorpo; begin result := ''; VpfDRetorno := TRBDRetornoCorpo.cria; VpfDRetorno.NomArquivo := VpaNomArquivo; ProcessaRetornoCorpoCNAB240(VpaArquivo.Strings[0],VpfDRetorno); Result := ContaCorrenteRetornoValida(VpfDRetorno); if result = '' then begin ProcessaRetornoItemCNAB240(VpaArquivo,VpfDRetorno); if result = '' then result := GravaDRetorno(VpfDRetorno); end; VpfDRetorno.free; end; {******************************************************************************} function TRBDFuncoesRetorno.ProcessaRetornoCNAB400(VpaNomArquivo : String;VpaArquivo : TStringList):String; var VpfDRetorno : TRBDRetornoCorpo; begin result := ''; VpfDRetorno := TRBDRetornoCorpo.cria; VpfDRetorno.NomArquivo := VpaNomArquivo; ProcessaRetornoCorpoCNAB400(VpaArquivo.Strings[0],VpfDRetorno); Result := ContaCorrenteRetornoValida(VpfDRetorno); if result = '' then begin ProcessaRetornoItemCNAB400(VpaArquivo,VpfDRetorno); if result = '' then result := GravaDRetorno(VpfDRetorno); end; VpfDRetorno.free; end; {******************************************************************************} function TRBDFuncoesRetorno.processaRetorno(VpaNomArquivo :String;VpaBarraStatus : TStatusBar):String; var VpfArquivo : TStringList; begin result := ''; VprBarraStatus := VpaBarraStatus; VpfArquivo := TStringList.Create; TextoStatus('Abrindo arquivo de retorno "'+VpaNomArquivo+'"'); VpfArquivo.loadFromfile(VpaNomArquivo); TextoStatus('Verificando o Banco do arquivo.'); if (copy(VpfArquivo.Strings[0],77,3) ='341')or (copy(VpfArquivo.Strings[0],77,3) ='001') then //itau result := processaRetornoItau(VpfArquivo) else if (copy(VpfArquivo.Strings[0],1,3) ='001') or (copy(VpfArquivo.Strings[0],1,3) ='409') or (copy(VpfArquivo.Strings[0],1,3) ='399')or (copy(VpfArquivo.Strings[0],1,3) ='104') or (copy(VpfArquivo.Strings[0],1,3) ='356') then result := ProcessaRetornoCNAB240(VpaNomArquivo,VpfArquivo) else if (copy(VpfArquivo.Strings[0],77,3) ='237') then //bradesco result := ProcessaRetornoCNAB400(VpaNomArquivo,VpfArquivo); VpfArquivo.free; if result = '' then begin TextoStatus('Retorno efetuado com sucesso.'); CopiaArquivo(VpaNomArquivo,RetornaDiretorioArquivo(VpaNomArquivo)+'Backup\'+RetornaNomArquivoSemDiretorio(VpaNomArquivo)); DeletaArquivo(VpaNomArquivo); end; end; {******************************************************************************} procedure TRBDFuncoesRetorno.MarcaRetornoImpresso(VpaCodFilial, VpaSeqRetorno : Integer); begin ExecutaComandoSql(Aux,'Update RETORNOCORPO '+ ' SET INDIMPRESSO = ''S'''+ ' Where CODFILIAL = '+IntToStr(VpaCodFilial)+ ' and SEQRETORNO = '+ InttoStr(VpaSeqRetorno)); end; end.
{ "Memory Heap Manager" - Copyright (c) Danijel Tkalcec @exclude } unit memManager; {$INCLUDE rtcDefs.inc} interface uses SysUtils, rtcSyncObjs, memBinTree; type THeapInfo=packed record minsize, // Minimum Heap Block Size blocksize, // Heap Block Size Increment alloc, // Memory Allocation Unit pool:cardinal; // Free blocks Pool Size free, // want to free empty Heap blocks? freeany, // want to free empty Heap Block even if it is not the last block? (could unused memory holes) organize, // want to reorganize empty Heap blocks? sysmem:boolean; // want to use SysGetMem? end; const Min_MemFreeBlockSize = 6; // Blocks smaller than this will be "swallowed" by neighbouring block, to minimize fragmentation MaxHeaps=1048; // Maximum number of heaps to use. 1024 heaps give us at least 1 GB allocation space MinAllocUnit=1024; HeapAllocUnit=1024; StdHeap_Info:THeapInfo = (minsize:2024; blocksize:1024; alloc:4; pool:128; Free:True; FreeAny:True; Organize:True; SysMem:True); type tHeapDataStreamHandle=packed record TotalSize:cardinal; // Data size in File UnusedSize:cardinal; // Unused bytes in "Data" Fragments:cardinal; // Number of Unused Fragments end; tHeapDataBlockHeader=packed record BlockSize:cardinal; // Real Data Block size Unused:byte; end; { ... Heap management ... A Heap is a managed chunk of memory. Heap bock is internally allocated as 1 memory block and has the ability to reserve and free smaller blocks inside it, providing memory mamangement for the memory allocated in that block. } tMyMemory = array[1 .. MaxLongInt] of byte; pMyMemory = ^tMyMemory; tHeap_Manager=class private fSysMem:boolean; FFree:tBinTree; FSS:pMyMemory; procedure CheckDataBlock(Block:cardinal;var FDataHead:tHeapDataBlockHeader); procedure SetBlockIsUsed(Block:cardinal;FDataHead:tHeapDataBlockHeader); procedure AddFreeBlock(Block,Size:cardinal); procedure DelFreeBlock(Block:cardinal); procedure EditFreeBlock(Block,Size:cardinal); procedure ChangeFreeBlock(Old_Block,New_Block,Size:cardinal); procedure SetBlockIsFree(Block,Size:cardinal); function GetFirstFreeBlock(MinSize,MaxSize:cardinal;var Size:cardinal):cardinal; protected FHead:tHeapDataStreamHandle; public FSS_Size:cardinal; FSS2:cardinal; constructor Create(Size,FreeBlocksPool:cardinal; UseSysGetMem:boolean); destructor Destroy; override; function GetTotalSize:cardinal; function GetUnusedSize:cardinal; function GetBufferSize:cardinal; function GetFragmentCount:cardinal; function GetTotalFree:cardinal; function GetBlock(Size:cardinal):pointer; function FreeBlock(Loc:pointer):cardinal; function isBlock(Loc:pointer):boolean; function BlockSize(Loc:pointer):cardinal; end; { ... Memory management ... Memory Manager's job is to manages a number of Heaps to make memory allocation and deallocation dynamic and still transparent to the user. Memory manager will create heeps when needed and free them when they are not needed. } tMem_Manager=class private MM:array[1..MaxHeaps] of tHeap_Manager; public HeapInfo:THeapInfo; NumHeaps:cardinal; Total_Alloc, Total_AddrSpace:cardinal; constructor Create(UseSysGetMem:boolean); destructor Destroy; override; function Free_Mem(p:pointer):boolean; function Get_Mem(size:cardinal):pointer; function Check_Mem(P: Pointer):cardinal; function GetTotalFree(Heap:byte):cardinal; function GetBufferSize(Heap:byte):cardinal; function GetTotalSize(Heap:byte):cardinal; function GetUnusedSize(Heap:byte):cardinal; function GetFragmentCount(Heap:byte):cardinal; function Clear:boolean; end; implementation const DS_DSize=SizeOf(tHeapDataBlockHeader); {$IFDEF MSWINDOWS} const kernel = 'kernel32.dll'; function LocalAlloc(flags, size: cardinal): Pointer; stdcall; external kernel name 'LocalAlloc'; function LocalFree(addr: Pointer): Pointer; stdcall; external kernel name 'LocalFree'; function myGetMem(size:cardinal):pointer; begin Result:=LocalAlloc(0,size); end; procedure myFreeMem(p:pointer); begin LocalFree(p); end; {$ELSE} function myGetMem(size:cardinal):pointer; begin Result:=SysGetMem(size); end; procedure myFreeMem(p:pointer); begin SysFreeMem(size); end; {$ENDIF} { MemoryManager } constructor tHeap_Manager.Create(Size,FreeBlocksPool:cardinal;UseSysGetMem:boolean); begin inherited Create; if UseSysGetMem then FSS:=MyGetMem(Size) else FSS:=SysGetMem(Size); if FSS=nil then OutOfMemoryError; fSysMem:=UseSysGetMem; FSS_Size:=Size; FillChar(FHead,SizeOf(FHead),0); FSS2:=cardinal(FSS); FFree:=tBinTree.Create(FreeBlocksPool); end; destructor tHeap_Manager.Destroy; begin FFree.Free; if assigned(FSS) and (FSS_Size>0) then begin if fSysMem then myFreeMem(FSS) else SysFreeMem(FSS); FSS:=nil; FSS_Size:=0; end; inherited; end; (* PRIVATE METHODS *) procedure tHeap_Manager.CheckDataBlock(Block:cardinal;var FDataHead:tHeapDataBlockHeader); begin Move(FSS^[Block],FDataHead,DS_DSize); end; procedure tHeap_Manager.SetBlockIsUsed(Block:cardinal;FDataHead:tHeapDataBlockHeader); begin Move(FDataHead,FSS^[Block],DS_DSize); end; (****************************************************************************) procedure tHeap_Manager.AddFreeBlock(Block,Size:cardinal); begin if FFree.search(Block)<>0 then raise Exception.Create('Access Violation: Memory block to be released allready free.'); FFree.insert(Block,Size); Inc(FHead.Fragments); end; procedure tHeap_Manager.DelFreeBlock(Block:cardinal); begin if FFree.search(Block)=0 then raise Exception.Create('Access Violation: Memory block to be reserved is not free.'); FFree.remove(Block); Dec(FHead.Fragments); end; procedure tHeap_Manager.EditFreeBlock(Block,Size:cardinal); begin if FFree.search(Block)=0 then raise Exception.Create('Access Violation: Memory block to be resized is not free.'); FFree.remove(Block); FFree.insert(Block,Size); end; procedure tHeap_Manager.ChangeFreeBlock(Old_Block,New_Block,Size:cardinal); begin if FFree.search(Old_Block)=0 then raise Exception.Create('Access Violation: Memory block to be resized is not free.'); FFree.remove(Old_Block); FFree.insert(New_Block,Size); end; (*************************************************************************) procedure tHeap_Manager.SetBlockIsFree(Block,Size:cardinal); var FE_NextBlock,FE_BlockSize:cardinal; s,Tmp:cardinal; Loc,Blck:cardinal; procedure SetNewFreeSize; begin Inc(Size,FE_BlockSize); if Blck+Size>FHead.TotalSize then begin DelFreeBlock(Blck); Dec(FHead.UnusedSize,Size); Dec(FHead.TotalSize,Size); end; end; procedure AddTheBlock; begin Blck:=Block; AddFreeBlock(Block,Size); Inc(FHead.UnusedSize,Size); SetNewFreeSize; end; begin if FHead.Fragments>0 then begin Blck:=FFree.search_le(Block,FE_BlockSize); if (FE_BlockSize>0) and (Blck+FE_BlockSize=Block) then // There is a block Left from us (linked) begin FE_NextBlock:=FFree.search_g(Blck,Tmp); s:=Size; if FE_NextBlock=Block+Size then // There's a Block Right to us (linked) begin Inc(Size,FE_BlockSize); Loc:=FE_NextBlock; FE_BlockSize:=Tmp; DelFreeBlock(Loc); end; EditFreeBlock(Blck,Size+FE_BlockSize); Inc(FHead.UnusedSize,s); SetNewFreeSize; end else if (FE_BlockSize>0) and (Blck+FE_BlockSize>Block) then // Memory allready freed begin raise Exception.Create('Memory allready released.'); end else begin Blck:=Block; FE_NextBlock:=FFree.search_g(Blck,FE_BlockSize); if FE_NextBlock=Block+Size then // There's a block Right to us (linked) begin ChangeFreeBlock(FE_NextBlock,Blck,Size+FE_BlockSize); Inc(FHead.UnusedSize,Size); SetNewFreeSize; end else // No blocks near us. begin FE_BlockSize:=0; AddTheBlock; end; end; end else begin FE_BlockSize:=0; AddTheBlock; end; end; function tHeap_Manager.GetFirstFreeBlock(MinSize,MaxSize:cardinal;var Size:cardinal):cardinal; var Block,Loc:cardinal; Size_X,Siz:cardinal; FE_BlockSize:cardinal; myBlock:tHeapDataBlockHeader; function GetTheBlock:cardinal; begin Size:=MaxSize; Size_X:=MaxSize+DS_DSize; Block:=FHead.TotalSize+1; if FSS_Size<Block+Size_X then Result:=0 else begin Inc(FHead.TotalSize,Size_X); myBlock.BlockSize:=Size; myBlock.Unused:=0; SetBlockIsUsed(Block,myBlock); Result:=Block+DS_DSize; end; end; begin if FHead.Fragments>0 then begin if MinSize>MaxSize then MinSize:=MaxSize; Size_X:=MinSize+DS_DSize; Siz:=FFree.isearch_ge(Size_X,Loc); if Siz>=Size_X then begin Block:=Loc; FE_BlockSize:=Siz; Dec(FHead.UnusedSize,FE_BlockSize); DelFreeBlock(Block); if FE_BlockSize>=MaxSize+DS_DSize+Min_MemFreeBlockSize then begin Size:=MaxSize; Size_X:=Size+DS_DSize; SetBlockIsFree(Block+Size_X,FE_BlockSize-Size_X); end else begin Size_X:=FE_BlockSize; Size:=Size_X-DS_DSize; if Size>MaxSize then Size:=MaxSize; end; myBlock.BlockSize:=Size; myBlock.Unused:=Size_X-Size-DS_DSize; SetBlockIsUsed(Block,myBlock); Result:=Block+DS_DSize; end else Result:=GetTheBlock; end else Result:=GetTheBlock; end; (* GLOBAL METHODS *) function tHeap_Manager.GetTotalSize:cardinal; begin Result:=FHead.TotalSize; end; function tHeap_Manager.GetUnusedSize:cardinal; begin Result:=FHead.UnusedSize; end; function tHeap_Manager.GetBufferSize:cardinal; begin Result:=FSS_Size-FHead.TotalSize; end; function tHeap_Manager.GetTotalFree:cardinal; begin Result:=GetBufferSize+GetUnusedSize; end; function tHeap_Manager.GetFragmentCount:cardinal; begin Result:=FHead.Fragments; end; function tHeap_Manager.GetBlock(Size:cardinal):pointer; var Block:cardinal; begin Block:=GetFirstFreeBlock(Size,Size,Size); if Block>0 then Result:=Addr(FSS^[Block]) else Result:=nil; end; function tHeap_Manager.FreeBlock(Loc:pointer):cardinal; var FD:tHeapDataBlockHeader; Block:cardinal; begin if (cardinal(Loc)<FSS2) or (cardinal(Loc)>=FSS2+FSS_Size) then begin Result:=0; Exit; end; Block:=cardinal(Loc)-cardinal(FSS)+1; Dec(Block,DS_DSize); CheckDataBlock(Block,FD); SetBlockIsFree(Block,FD.BlockSize+DS_DSize+FD.Unused); Result:=FD.BlockSize; end; function tHeap_Manager.isBlock(Loc:pointer):boolean; begin Result:=(cardinal(Loc)>=FSS2) and (cardinal(Loc)<FSS2+FSS_Size); end; function tHeap_Manager.BlockSize(Loc:pointer):cardinal; var FD:tHeapDataBlockHeader; Block:cardinal; begin Block:=cardinal(Loc)-cardinal(FSS2)+1; CheckDataBlock(Block-DS_DSize,FD); Result:=FD.BlockSize; end; { tMem_Manager } function roundto(a,b:cardinal):cardinal; begin Result:=(a+(b-1)) div b * b; end; constructor tMem_Manager.Create(UseSysGetMem:boolean); begin inherited Create; Total_Alloc:=0; Total_AddrSpace:=0; HeapInfo:=StdHeap_Info; NumHeaps:=0; end; destructor tMem_Manager.Destroy; begin Clear; inherited; end; function tMem_Manager.Clear:boolean; begin while NumHeaps>0 do begin MM[NumHeaps].Free; Dec(NumHeaps); end; Result:=True; end; function tMem_Manager.GetBufferSize(Heap: byte): cardinal; var a:cardinal; begin if Heap=0 then begin Result:=0; for a:=1 to NumHeaps do Result:=Result+MM[a].GetBufferSize; end else if Heap<=NumHeaps then Result:=MM[Heap].GetBufferSize else Result:=0; end; function tMem_Manager.GetTotalFree(Heap: byte): cardinal; var a:cardinal; begin if Heap=0 then begin Result:=0; for a:=1 to NumHeaps do Result:=Result+MM[a].GetTotalFree; end else if Heap<=NumHeaps then Result:=MM[Heap].GetTotalFree else Result:=0; end; function tMem_Manager.GetFragmentCount(Heap: byte): cardinal; var a:cardinal; begin if Heap=0 then begin Result:=0; for a:=1 to NumHeaps do Result:=Result+MM[a].GetFragmentCount; end else if Heap<=NumHeaps then Result:=MM[Heap].GetFragmentCount else Result:=0; end; function tMem_Manager.GetTotalSize(Heap: byte): cardinal; var a:cardinal; begin if Heap=0 then begin Result:=0; for a:=1 to NumHeaps do Result:=Result+MM[a].GetTotalSize; end else if Heap<=NumHeaps then Result:=MM[Heap].GetTotalSize else Result:=0; end; function tMem_Manager.GetUnusedSize(Heap: byte): cardinal; var a:cardinal; begin if Heap=0 then begin Result:=0; for a:=1 to NumHeaps do Result:=Result+MM[a].GetUnusedSize; end else if Heap<=NumHeaps then Result:=MM[Heap].GetUnusedSize else Result:=0; end; function tMem_Manager.Free_Mem(p: pointer): boolean; var a,b:cardinal; TMM:tHeap_Manager; begin if p=nil then Result:=True else begin Result:=False; for a:=NumHeaps downto 1 do begin if MM[a].isBlock(p) then begin Total_Alloc := Total_Alloc - MM[a].FreeBlock(p); if NumHeaps>1 then // using NumHeaps>1 instead of NumHeaps<=0 will leave at least one heap block open, to speed up memory allocation. begin if (HeapInfo.free and (HeapInfo.freeany or (a=NumHeaps))) and (MM[a].GetTotalSize=0) then begin Total_AddrSpace := Total_AddrSpace - MM[a].FSS_Size; MM[a].Free; if NumHeaps>a then for b:=a+1 to NumHeaps do MM[b-1]:=MM[b]; Dec(NumHeaps); end else if HeapInfo.organize then begin b:=a; while (b<NumHeaps) and (MM[b].GetBufferSize>MM[b+1].GetBufferSize) do begin TMM:=MM[b]; MM[b]:=MM[b+1]; MM[b+1]:=TMM; Inc(b); end; end; end; Result:=True; Break; end; end; end; end; function tMem_Manager.Get_Mem(size: cardinal): pointer; var a,mbsize:cardinal; TMM:tHeap_Manager; begin Result:=nil; if Size<=0 then Exit; Size:=roundto(Size,HeapInfo.alloc); a:=1; while a<=NumHeaps do begin Result:=MM[a].GetBlock(Size); if Result<>nil then begin if HeapInfo.organize then while (a>1) and (MM[a-1].GetBufferSize>MM[a].GetBufferSize) do begin TMM:=MM[a]; MM[a]:=MM[a-1]; MM[a-1]:=TMM; Dec(a); end; Break; end else Inc(a); end; if (Result=nil) and (NumHeaps<MaxHeaps) then begin mbsize:=roundto(size+MinAllocUnit,HeapInfo.blocksize*HeapAllocUnit); if mbsize<HeapInfo.minsize*HeapAllocUnit then mbsize:=HeapInfo.minsize*HeapAllocUnit; try MM[NumHeaps+1]:=tHeap_Manager.Create(mbsize,HeapInfo.pool,HeapInfo.sysmem); except Exit; // Out of Memory end; Inc(NumHeaps); Total_AddrSpace := Total_AddrSpace + MM[NumHeaps].FSS_Size; Result:=MM[NumHeaps].GetBlock(roundto(Size,HeapInfo.alloc)); if HeapInfo.organize and (Result<>nil) then begin a:=NumHeaps; while (a>1) and (MM[a-1].GetBufferSize>MM[a].GetBufferSize) do begin TMM:=MM[a]; MM[a]:=MM[a-1]; MM[a-1]:=TMM; Dec(a); end; end; end; Total_Alloc := Total_Alloc + size; end; function tMem_Manager.Check_Mem(P: Pointer):cardinal; var a:cardinal; begin Result:=0; for a:=1 to NumHeaps do if MM[a].isBlock(p) then begin Result:=MM[a].BlockSize(p); Break; end; end; end.
unit VA508AccessibilityRouter; interface uses SysUtils, Windows, Registry, StrUtils, Classes, Controls, Dialogs, Contnrs, DateUtils, Forms, ExtCtrls; type TComponentDataNeededEvent = procedure(const WindowHandle: HWND; var DataStatus: LongInt; var Caption: PChar; var Value: PChar; var Data: PChar; var ControlType: PChar; var State: PChar; var Instructions: PChar; var ItemInstructions: PChar) of object; TKeyMapProcedure = procedure; TVA508ScreenReader = class(TObject) protected procedure RegisterCustomClassBehavior(Before, After: string); virtual; abstract; procedure RegisterClassAsMSAA(ClassName: string); virtual; abstract; procedure AddComponentDataNeededEventHandler(event: TComponentDataNeededEvent); virtual; abstract; procedure RemoveComponentDataNeededEventHandler(event: TComponentDataNeededEvent); virtual; abstract; public procedure Speak(Text: string); virtual; abstract; procedure RegisterDictionaryChange(Before, After: string); virtual; abstract; procedure RegisterCustomKeyMapping(Key: string; proc: TKeyMapProcedure; shortDescription, longDescription: string); virtual; abstract; end; function GetScreenReader: TVA508ScreenReader; { TODO -oJeremy Merrill -c508 : if ScreenReaderSystemActive is false, but there are valid DLLs, add a recheck every 30 seconds to see if the screen reader is running. in the timer event, see if DLL.IsRunning is running is true. if it is then pop up a message to the user (only once) and inform them that if they restart the app with the screen reader running it will work better. After the popup disable the timer event. } function ScreenReaderSystemActive: boolean; // Only guaranteed to be valid if called in an initialization section // all other components stored as .dfm files will be registered as a dialog // using the RegisterCustomClassBehavior procedure SpecifyFormIsNotADialog(FormClass: TClass); // do not call this routine - called by screen reader DLL procedure ComponentDataRequested(WindowHandle: HWND; DataRequest: LongInt); stdcall; implementation uses VAUtils, VA508ScreenReaderDLLLinker, VAClasses, VA508AccessibilityConst, Generics.Collections, Generics.Defaults; type TNullScreenReader = class(TVA508ScreenReader) public procedure Speak(Text: string); override; procedure RegisterDictionaryChange(Before, After: string); override; procedure RegisterCustomClassBehavior(Before, After: string); override; procedure RegisterClassAsMSAA(ClassName: string); override; procedure RegisterCustomKeyMapping(Key: string; proc: TKeyMapProcedure; shortDescription, longDescription: string); override; procedure AddComponentDataNeededEventHandler(event: TComponentDataNeededEvent); override; procedure RemoveComponentDataNeededEventHandler(event: TComponentDataNeededEvent); override; end; TMasterScreenReader = class(TVA508ScreenReader) strict private FEventHandlers: TVAMethodList; FCustomBehaviors: TStringList; FInternalRegistration: boolean; FDataHasBeenRegistered: boolean; FTrying2Register: boolean; FKeyProc: TList; private function EncodeBehavior(Before, After: string; Action: integer): string; procedure DecodeBehavior(code: string; var Before, After: string; var Action: integer); function RegistrationAllowed: boolean; procedure RegisterCustomData; protected procedure RegisterCustomBehavior(Str1, Str2: String; Action: integer; CheckIR: boolean = FALSE); procedure ProcessCustomKeyCommand(DataRequest: integer); property EventHandlers: TVAMethodList read FEventHandlers; public constructor Create; destructor Destroy; override; procedure HandleSRException(E: Exception); procedure Speak(Text: string); override; procedure RegisterDictionaryChange(Before, After: string); override; procedure RegisterCustomClassBehavior(Before, After: string); override; procedure RegisterClassAsMSAA(ClassName: string); override; procedure RegisterCustomKeyMapping(Key: string; proc: TKeyMapProcedure; shortDescription, longDescription: string); override; procedure AddComponentDataNeededEventHandler(event: TComponentDataNeededEvent); override; procedure RemoveComponentDataNeededEventHandler(event: TComponentDataNeededEvent); override; end; var ActiveScreenReader: TVA508ScreenReader = nil; MasterScreenReader: TMasterScreenReader = nil; uNonDialogClassNames: TStringList = nil; SaveInitProc: Pointer = nil; Need2RegisterData: boolean = FALSE; OK2RegisterData: boolean = FALSE; CheckScreenReaderSystemActive: boolean = TRUE; uScreenReaderSystemActive: boolean = FALSE; uPostScreenReaderActivationTimer: TTimer = nil; const // number of seconds between checks for a screen reader POST_SCREEN_READER_ACTIVATION_CHECK_SECONDS = 30; POST_SCREEN_READER_INFO_MESSAGE = ERROR_INTRO + 'The Accessibility Framework can only communicate with the screen' + CRLF + 'reader if the screen reader is running before you start this application.'+ CRLF + 'Please restart %s to take advantage of the enhanced'+ CRLF + 'accessibility features offered by the Accessibility Framework.'; procedure VA508RouterInitProc; begin if assigned(SaveInitProc) then TProcedure(SaveInitProc); OK2RegisterData := TRUE; if Need2RegisterData then begin Need2RegisterData := FALSE; if ScreenReaderSystemActive then begin TMasterScreenReader(GetScreenreader).RegisterCustomData; end; end; end; function GetScreenReader: TVA508ScreenReader; begin if not assigned(ActiveScreenReader) then begin if ScreenReaderSystemActive then begin MasterScreenReader := TMasterScreenReader.Create; ActiveScreenReader := MasterScreenReader; end else ActiveScreenReader := TNullScreenReader.Create; end; Result := ActiveScreenReader; end; procedure PostScreenReaderCheckEvent(Self: TObject; Sender: TObject); var AppName, ext, error: string; begin if ScreenReaderActive then begin FreeAndNil(uPostScreenReaderActivationTimer); if IsScreenReaderSupported(TRUE) then begin AppName := ExtractFileName(ParamStr(0)); ext := ExtractFileExt(AppName); AppName := LeftStr(AppName, length(AppName) - Length(ext)); error := Format(POST_SCREEN_READER_INFO_MESSAGE, [AppName]); MessageBox(0, PChar(error), 'Accessibility Component Information', MB_OK or MB_ICONINFORMATION or MB_TASKMODAL or MB_TOPMOST); end; end; end; function ScreenReaderSystemActive: boolean; procedure CreateTimer; var ptr: TMethod; begin uPostScreenReaderActivationTimer := TTimer.Create(nil); with uPostScreenReaderActivationTimer do begin Enabled := FALSE; Interval := 1000 * POST_SCREEN_READER_ACTIVATION_CHECK_SECONDS; ptr.Code := @PostScreenReaderCheckEvent; ptr.Data := @ptr; OnTimer := TNotifyEvent(ptr); Enabled := TRUE; end; end; begin if CheckScreenReaderSystemActive then begin CheckScreenReaderSystemActive := FALSE; // prevent Delphi IDE from running DLL if LowerCase(ExtractFileName(ParamStr(0))) <> 'bds.exe' then uScreenReaderSystemActive := ScreenReaderDLLsExist; if uScreenReaderSystemActive then begin if CheckForJaws and ScreenReaderSupportEnabled then begin if IsScreenReaderSupported(FALSE) then uScreenReaderSystemActive := InitializeScreenReaderLink else uScreenReaderSystemActive := FALSE; end else begin uScreenReaderSystemActive := FALSE; CreateTimer; end; end; end; Result := uScreenReaderSystemActive; end; procedure SpecifyFormIsNotADialog(FormClass: TClass); var lc: string; begin if ScreenReaderSystemActive then begin lc := lowercase(FormClass.ClassName); if not assigned(uNonDialogClassNames) then uNonDialogClassNames := TStringList.Create; if uNonDialogClassNames.IndexOf(lc) < 0 then uNonDialogClassNames.Add(lc); if assigned(MasterScreenReader) then MasterScreenReader.RegisterCustomBehavior(FormClass.ClassName, '', BEHAVIOR_REMOVE_COMPONENT_CLASS, TRUE); end; end; { TMasterScreenReader } procedure TMasterScreenReader.AddComponentDataNeededEventHandler(event: TComponentDataNeededEvent); begin FEventHandlers.Add(TMethod(event)); end; constructor TMasterScreenReader.Create; begin FEventHandlers := TVAMethodList.Create; FCustomBehaviors := TStringList.Create; FInternalRegistration := FALSE; FDataHasBeenRegistered := FALSE; FKeyProc := TList.Create; end; procedure TMasterScreenReader.DecodeBehavior(code: string; var Before, After: string; var Action: integer); function Decode(var MasterString: string): string; var CodeLength: integer; hex: string; begin Result := ''; if length(MasterString) > 1 then begin hex := copy(MasterString,1,2); CodeLength := FastHexToByte(hex); Result := copy(MasterString, 3, CodeLength); delete(MasterString, 1, CodeLength + 2); end; end; begin Action := StrToIntDef(Decode(code), 0); Before := Decode(code); After := Decode(code); if code <> '' then Raise TVA508Exception.Create('Corrupted Custom Behavior'); end; destructor TMasterScreenReader.Destroy; begin CloseScreenReaderLink; FreeAndNil(FEventHandlers); FreeAndNil(FCustomBehaviors); FreeAndNil(FKeyProc); inherited; end; function TMasterScreenReader.EncodeBehavior(Before, After: string; Action: integer): string; function Coded(str: string): string; var len: integer; begin len := length(str); if len > 255 then Raise TVA508Exception.Create('RegisterCustomBehavior parameter can not be more than 255 characters long'); Result := HexChars[len] + str; end; begin Result := Coded(IntToStr(Action)) + Coded(Before) + Coded(After); end; procedure TMasterScreenReader.HandleSRException(E: Exception); begin if not E.ClassNameIs(TVA508Exception.ClassName) then raise E; end; procedure TMasterScreenReader.ProcessCustomKeyCommand(DataRequest: integer); var idx: integer; proc: TKeyMapProcedure; begin idx := (DataRequest AND DATA_CUSTOM_KEY_COMMAND_MASK) - 1; if (idx < 0) or (idx >= FKeyProc.count) then exit; proc := TKeyMapProcedure(FKeyProc[idx]); proc; end; procedure TMasterScreenReader.RegisterClassAsMSAA(ClassName: string); begin RegisterCustomBehavior(ClassName, '', BEHAVIOR_ADD_COMPONENT_MSAA, TRUE); RegisterCustomBehavior(ClassName, '', BEHAVIOR_REMOVE_COMPONENT_CLASS, TRUE); end; procedure TMasterScreenReader.RegisterCustomBehavior(Str1, Str2: String; Action: integer; CheckIR: boolean = FALSE); var code: string; idx: integer; p2: PChar; ok: boolean; begin code := EncodeBehavior(Str1, Str2, Action); idx := FCustomBehaviors.IndexOf(code); if idx < 0 then begin FCustomBehaviors.add(code); ok := RegistrationAllowed; if ok and CheckIR then ok := (not FInternalRegistration); if ok then begin try if Str2 = '' then p2 := nil else p2 := PChar(Str2); SRRegisterCustomBehavior(Action, PChar(Str1), P2); except on E: Exception do HandleSRException(E); end; end; end; end; procedure TMasterScreenReader.RegisterCustomClassBehavior(Before, After: string); begin RegisterCustomBehavior(Before, After, BEHAVIOR_ADD_COMPONENT_CLASS, TRUE); RegisterCustomBehavior(Before, After, BEHAVIOR_REMOVE_COMPONENT_MSAA, TRUE); end; function EnumResNameProc(module: HMODULE; lpszType: PChar; lpszName: PChar; var list: TStringList): BOOL; stdcall; var name: string; begin name := lpszName; list.Add(name); Result := TRUE; end; procedure TMasterScreenReader.RegisterCustomData; // DEV SECTION ONLY.... Add to this list to ignore resource items. handled exception will be thrown if not const IgnoreArray: array [1 .. 6] of string = ('DESCRIPTION', 'DVCLAL', 'PACKAGEINFO', 'PLATFORMTARGETS', 'TEELCDFONT', 'TEELEDFONT'); // Resource to ignore rErrMsg = 'READ ERROR try adding %s to the IgnoreArray constant to bypass this exception'; var i, Action: integer; Before, After, code: string; procedure EnsureDialogAreSpecified; var list: TStringList; i: integer; stream: TResourceStream; Reader: TReader; ChildPos: integer; Flags: TFilerFlags; clsName: string; ok: boolean; FoundIndex: integer; begin FInternalRegistration := TRUE; try list := TStringList.Create; try if EnumResourceNames(HInstance, RT_RCDATA, @EnumResNameProc, integer(@list)) then begin for i := 0 to list.count - 1 do begin stream := TResourceStream.Create(HInstance, list[i], RT_RCDATA); try if not TArray.BinarySearch<string>(IgnoreArray, list[i], FoundIndex, TStringComparer.Ordinal) then begin Reader := TReader.Create(stream, 512); try try Reader.ReadSignature; Reader.ReadPrefix(Flags, ChildPos); clsName := Reader.ReadStr; ok := not assigned(uNonDialogClassNames); if not ok then ok := (uNonDialogClassNames.IndexOf (LowerCase(clsName)) < 0); if ok then RegisterCustomClassBehavior(clsName, CLASS_BEHAVIOR_DIALOG); except {$WARN SYMBOL_PLATFORM OFF} if DebugHook <> 0 then OutputDebugString(PwideChar(Format(rErrMsg, [list[i]]))); {$WARN SYMBOL_PLATFORM ON} end; finally Reader.Free; end; end; finally stream.Free; end; end; end; finally list.Free; end; finally FInternalRegistration := FALSE; end; end; begin if FTrying2Register then exit; FTrying2Register := TRUE; try if OK2RegisterData then begin try EnsureDialogAreSpecified; RegisterCustomBehavior('', '', BEHAVIOR_PURGE_UNREGISTERED_KEY_MAPPINGS); for i := 0 to FCustomBehaviors.count - 1 do begin code := FCustomBehaviors[i]; DecodeBehavior(code, Before, After, Action); SRRegisterCustomBehavior(Action, PChar(Before), PChar(After)); end; FDataHasBeenRegistered := TRUE; except on E: Exception do HandleSRException(E); end; end else Need2RegisterData := TRUE; finally FTrying2Register := FALSE; end; end; procedure TMasterScreenReader.RegisterCustomKeyMapping(Key: string; proc: TKeyMapProcedure; shortDescription, longDescription: string); var idx: string; procedure AddDescription(DescType, Desc: string); var temp: string; begin temp := DescType + idx + '=' + Desc; if length(temp) > 255 then raise TVA508Exception.Create('Key Mapping description for ' + Key + ' exceeds 255 characters'); RegisterCustomBehavior(DescType + idx, Desc, BEHAVIOR_ADD_CUSTOM_KEY_DESCRIPTION); end; begin FKeyProc.Add(@proc); idx := inttostr(FKeyProc.Count); RegisterCustomBehavior(Key, idx, BEHAVIOR_ADD_CUSTOM_KEY_MAPPING); AddDescription('short', shortDescription); AddDescription('long', longDescription); end; procedure TMasterScreenReader.RegisterDictionaryChange(Before, After: string); begin RegisterCustomBehavior(Before, After, BEHAVIOR_ADD_DICTIONARY_CHANGE); end; function TMasterScreenReader.RegistrationAllowed: boolean; begin Result := FDataHasBeenRegistered; if not Result then begin RegisterCustomData; Result := FDataHasBeenRegistered; end; end; procedure TMasterScreenReader.RemoveComponentDataNeededEventHandler(event: TComponentDataNeededEvent); begin FEventHandlers.Remove(TMethod(event)); end; procedure TMasterScreenReader.Speak(Text: string); begin if (not assigned(SRSpeakText)) or (Text = '') then exit; try SRSpeakText(PChar(Text)); except on E: Exception do HandleSRException(E); end; end; // need to post a message here - can't do direct call - this message is called before mouse // process messages are called that change a check box state procedure ComponentDataRequested(WindowHandle: HWND; DataRequest: LongInt); stdcall; var i: integer; Handle: HWND; Caption: PChar; Value: PChar; Data: PChar; ControlType: PChar; State: PChar; Instructions: PChar; ItemInstructions: PChar; DataStatus: LongInt; handler: TComponentDataNeededEvent; begin if assigned(MasterScreenReader) then begin try if (DataRequest AND DATA_CUSTOM_KEY_COMMAND) <> 0 then MasterScreenReader.ProcessCustomKeyCommand(DataRequest) else begin Handle := WindowHandle; Caption := nil; Value := nil; Data := nil; ControlType := nil; State := nil; Instructions := nil; ItemInstructions := nil; DataStatus := DataRequest; i := 0; while (i < MasterScreenReader.EventHandlers.Count) do begin handler := TComponentDataNeededEvent(MasterScreenReader.EventHandlers.Methods[i]); if assigned(handler) then handler(Handle, DataStatus, Caption, Value, Data, ControlType, State, Instructions, ItemInstructions); inc(i); end; SRComponentData(WindowHandle, DataStatus, Caption, Value, Data, ControlType, State, Instructions, ItemInstructions); end; except on E: Exception do MasterScreenReader.HandleSRException(E); end; end; end; { TNullScreenReader } procedure TNullScreenReader.AddComponentDataNeededEventHandler( event: TComponentDataNeededEvent); begin end; procedure TNullScreenReader.RegisterClassAsMSAA(ClassName: string); begin end; procedure TNullScreenReader.RegisterCustomClassBehavior(Before, After: string); begin end; procedure TNullScreenReader.RegisterCustomKeyMapping(Key: string; proc: TKeyMapProcedure; shortDescription, longDescription: string); begin end; procedure TNullScreenReader.RegisterDictionaryChange(Before, After: string); begin end; procedure TNullScreenReader.RemoveComponentDataNeededEventHandler( event: TComponentDataNeededEvent); begin end; procedure TNullScreenReader.Speak(Text: string); begin end; initialization SaveInitProc := InitProc; InitProc := @VA508RouterInitProc; finalization if assigned(ActiveScreenReader) then FreeAndNil(ActiveScreenReader); if assigned(uNonDialogClassNames) then FreeAndNil(uNonDialogClassNames); if assigned(uPostScreenReaderActivationTimer) then FreeAndNil(uPostScreenReaderActivationTimer); end.
unit LoanClassification; interface uses LoanClassCharge, LoanType, LoansAuxData, Group, LoanClassAdvance, SysUtils; type TLoanClassAction = (lcaNone, lcaCreating, lcaActivating, lcaDeactivating); TDiminishingType = (dtNone, dtScheduled, dtFixed); TLoanClassification = class private FClassificationId: integer; FGroup: TGroup; FClassificationName: string; FInterest: currency; FTerm: integer; FLoanType: TLoanType; FMaxLoan: currency; FComakersMin: integer; FComakersMax: integer; FValidFrom: TDate; FValidUntil: TDate; FClassCharges: array of TLoanClassCharge; FMaxAge: integer; FAction: TLoanClassAction; FInterestComputationMethod: string; FDiminishingType: TDiminishingType; FAdvancePayment: TLoanClassAdvance; FMaxAdvanceInterestPayment: currency; function GetComakersNotRequired: boolean; function GetClassCharge(const i: integer): TLoanClassCharge; function GetClassChargesCount: integer; function GetHasMaxAge: boolean; function GetHasConcurrent: boolean; function GetIsActive: boolean; function GetIsActivated: boolean; function GetIsDeactivated: boolean; function GetInterestInDecimal: currency; function GetIsDiminishing: boolean; function GetIsFixed: boolean; function GetHasAdvancePayment: boolean; public procedure Add; procedure Save; procedure AppendCharge; procedure AddClassCharge(cg: TLoanClassCharge); procedure RemoveClassCharge(const cgType: string); procedure EmptyClassCharges; procedure RemoveAdvancePayment; function ClassChargeExists(const cgType: string; const forNew, forRenewal, forRestructure, forReloan: boolean): boolean; property ClassificationId: integer read FClassificationId write FClassificationId; property Group: TGroup read FGroup write FGroup; property ClassificationName: string read FClassificationName write FClassificationName; property Interest: currency read FInterest write FInterest; property Term: integer read FTerm write FTerm; property LoanType: TLoanType read FLoanType write FLoanType; property MaxLoan: currency read FMaxLoan write FMaxLoan; property ComakersMin: integer read FComakersMin write FComakersMin; property ComakersMax: integer read FComakersMax write FComakersMax; property ValidFrom: TDate read FValidFrom write FVAlidFrom; property ValidUntil: TDate read FValidUntil write FValidUntil; property ComakersNotRequired: boolean read GetComakersNotRequired; property ClassCharge[const i: integer]: TLoanClassCharge read GetClassCharge; property ClassChargesCount: integer read GetClassChargesCount; property MaxAge: integer read FMaxAge write FMaxAge; property HasMaxAge: boolean read GetHasMaxAge; property HasConcurrent: boolean read GetHasConcurrent; property IsActive: boolean read GetIsActive; property IsActivated: boolean read GetIsActivated; property IsDeactivated: boolean read GetIsDeactivated; property Action: TLoanClassAction read FAction write FAction; property InterestInDecimal: currency read GetInterestInDecimal; property InterestComputationMethod: string write FInterestComputationMethod; property IsDiminishing: boolean read GetIsDiminishing; property IsFixed: boolean read GetIsFixed; property DiminishingType: TDiminishingType read FDiminishingType write FDiminishingType; property AdvancePayment: TLoanClassAdvance read FAdvancePayment write FAdvancePayment; property HasAdvancePayment: boolean read GetHasAdvancePayment; property MaxAdvanceInterestPayment: currency read FMaxAdvanceInterestPayment write FMaxAdvanceInterestPayment; constructor Create(const classificationId: integer; classificationName: string; const interest: real; const term: integer; const maxLoan: currency; const comakersMin, comakersMax: integer; const validFrom, validUntil: TDate; const age: integer; const lt: TLoanType; const gp: TGroup; const intCompMethod: string; const ADimType: TDiminishingType = dtNone); end; var lnc: TLoanClassification; implementation uses IFinanceGlobal; constructor TLoanClassification.Create(const classificationId: integer; classificationName: string; const interest: real; const term: integer; const maxLoan: currency; const comakersMin, comakersMax: integer; const validFrom, validUntil: TDate; const age: integer; const lt: TLoanType; const gp: TGroup; const intCompMethod: string; const ADimType: TDiminishingType); begin FClassificationId := classificationId; FClassificationName := classificationName; FInterest := interest; FTerm := term; FMaxLoan := maxLoan; FComakersMin := comakersMin; FComakersMax := comakersMax; FValidFrom := validFrom; FValidUntil := validUntil; FMaxAge := age; FLoanType := lt; FGroup := gp; FInterestComputationMethod := intCompMethod; FDiminishingType := ADimType; // set action if IsActive then FAction := lcaNone else FAction := lcaCreating; end; procedure TLoanClassification.AddClassCharge(cg: TLoanClassCharge); begin if not ClassChargeExists(cg.ChargeType,cg.ForNew,cg.ForRenewal,cg.ForRestructure,cg.ForReloan) then begin SetLength(FClassCharges,Length(FClassCharges) + 1); FClassCharges[Length(FClassCharges) - 1] := cg; end; end; procedure TLoanClassification.RemoveAdvancePayment; begin FreeAndNil(FAdvancePayment); end; procedure TLoanClassification.RemoveClassCharge(const cgType: string); var i, len: integer; cg: TLoanClassCharge; begin len := Length(FClassCharges); for i := 0 to len - 1 do begin cg := FClassCharges[i]; if cg.ChargeType <> cgType then FClassCharges[i] := cg; end; SetLength(FClassCharges,Length(FClassCharges) - 1); end; procedure TLoanClassification.EmptyClassCharges; begin FClassCharges := []; end; procedure TLoanClassification.Add; begin end; procedure TLoanClassification.Save; begin end; procedure TLoanClassification.AppendCharge; begin end; function TLoanClassification.GetComakersNotRequired: boolean; begin Result := (FComakersMin = 0) and (FComakersMax = 0); end; function TLoanClassification.GetClassCharge(const i: Integer): TLoanClassCharge; begin Result := FClassCharges[i]; end; function TLoanClassification.ClassChargeExists(const cgType: string; const forNew, forRenewal, forRestructure, forReloan: boolean): boolean; var i, len: integer; ch: TLoanClassCharge; begin Result := false; len := Length(FClassCharges); for i := 0 to len - 1 do begin ch := FClassCharges[i]; if ch.ChargeType = cgType then begin if (ch.ForNew = forNew) or (ch.ForRenewal = forRenewal) or (ch.ForRestructure = forRestructure) or (ch.ForReloan = forReloan) then begin Result := true; Exit; end; end; end; end; function TLoanClassification.GetClassChargesCount: integer; begin Result := Length(FClassCharges); end; function TLoanClassification.GetHasMaxAge: boolean; begin Result := FMaxAge > 0; end; function TLoanClassification.GetHasAdvancePayment: boolean; begin Result := Assigned(FAdvancePayment); end; function TLoanClassification.GetHasConcurrent: boolean; begin Result := FGroup.Attributes.MaxConcurrent > 0; end; function TLoanClassification.GetIsActive: boolean; begin Result := (FValidFrom <> 0) and ((FValidFrom > ifn.AppDate) and (FValidUntil < ifn.AppDate)); end; function TLoanClassification.GetInterestInDecimal: currency; begin Result := FInterest / 100; end; function TLoanClassification.GetIsActivated: boolean; begin Result := (FValidFrom <> 0) end; function TLoanClassification.GetIsDeactivated: boolean; begin Result := (FValidUntil <> 0) end; function TLoanClassification.GetIsDiminishing: boolean; begin Result := FInterestComputationMethod = 'D'; end; function TLoanClassification.GetIsFixed: boolean; begin Result := FInterestComputationMethod = 'F'; end; end.
unit Horse.BasicAuthentication; {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} {$ENDIF} interface uses {$IF DEFINED(FPC)} SysUtils, StrUtils, base64, Classes, {$ELSE} System.SysUtils, System.NetEncoding, System.Classes, System.StrUtils, {$ENDIF} Horse, Horse.Commons; const AUTHORIZATION = 'authorization'; REALM_MESSAGE = 'Enter credentials'; type IHorseBasicAuthenticationConfig = interface ['{DB16765F-156C-4BC1-8EDE-183CA9FE1985}'] function Header(const AValue: string): IHorseBasicAuthenticationConfig; overload; function Header: string; overload; function RealmMessage(const AValue: string): IHorseBasicAuthenticationConfig; overload; function RealmMessage: string; overload; function SkipRoutes(const AValues: TArray<string>): IHorseBasicAuthenticationConfig; overload; function SkipRoutes: TArray<string>; overload; end; THorseBasicAuthenticationConfig = class(TInterfacedObject, IHorseBasicAuthenticationConfig) private FHeader: string; FRealmMessage: string; FSkipRoutes: TArray<string>; function Header(const AValue: string): IHorseBasicAuthenticationConfig; overload; function Header: string; overload; function RealmMessage(const AValue: string): IHorseBasicAuthenticationConfig; overload; function RealmMessage: string; overload; function SkipRoutes(const AValues: TArray<string>): IHorseBasicAuthenticationConfig; overload; function SkipRoutes: TArray<string>; overload; public constructor Create; class function New: IHorseBasicAuthenticationConfig; end; type THorseBasicAuthentication = {$IF NOT DEFINED(FPC)} reference to {$ENDIF} function(const AUsername, APassword: string): Boolean; procedure Middleware(Req: THorseRequest; Res: THorseResponse; Next: {$IF DEFINED(FPC)} TNextProc {$ELSE} TProc {$ENDIF} ); function HorseBasicAuthentication(const AAuthenticate: THorseBasicAuthentication): THorseCallback; overload; function HorseBasicAuthentication(const AAuthenticate: THorseBasicAuthentication; const AConfig: IHorseBasicAuthenticationConfig): THorseCallback; overload; implementation var Config: IHorseBasicAuthenticationConfig; Authenticate: THorseBasicAuthentication; function HorseBasicAuthentication(const AAuthenticate: THorseBasicAuthentication): THorseCallback; begin Result := HorseBasicAuthentication(AAuthenticate, THorseBasicAuthenticationConfig.New); end; function HorseBasicAuthentication(const AAuthenticate: THorseBasicAuthentication; const AConfig: IHorseBasicAuthenticationConfig): THorseCallback; begin Config := AConfig; Authenticate := AAuthenticate; Result := Middleware; end; procedure Middleware(Req: THorseRequest; Res: THorseResponse; Next: {$IF DEFINED(FPC)} TNextProc {$ELSE} TProc {$ENDIF}); const BASIC_AUTH = 'basic '; var LBasicAuthenticationEncode: string; LBase64String: string; LBasicAuthenticationDecode: TStringList; LIsAuthenticated: Boolean; begin if MatchText(Req.RawWebRequest.PathInfo, Config.SkipRoutes) then begin Next(); Exit; end; LBasicAuthenticationEncode := Req.Headers[Config.Header]; if LBasicAuthenticationEncode.Trim.IsEmpty and not Req.Query.TryGetValue(Config.Header, LBasicAuthenticationEncode) then begin Res.Send('Authorization not found').Status(THTTPStatus.Unauthorized).RawWebResponse {$IF DEFINED(FPC)} .WWWAuthenticate := Format('Basic realm=%s', [Config.RealmMessage]); {$ELSE} .Realm := Config.RealmMessage; {$ENDIF} raise EHorseCallbackInterrupted.Create; end; if not LBasicAuthenticationEncode.ToLower.StartsWith(BASIC_AUTH) then begin Res.Send('Invalid authorization type').Status(THTTPStatus.Unauthorized); raise EHorseCallbackInterrupted.Create; end; LBasicAuthenticationDecode := TStringList.Create; try LBasicAuthenticationDecode.Delimiter := ':'; LBasicAuthenticationDecode.StrictDelimiter := True; LBase64String := LBasicAuthenticationEncode.Replace(BASIC_AUTH, '', [rfIgnoreCase]); LBasicAuthenticationDecode.DelimitedText := {$IF DEFINED(FPC)}DecodeStringBase64(LBase64String){$ELSE}TBase64Encoding.Base64.Decode(LBase64String){$ENDIF}; try LIsAuthenticated := Authenticate(LBasicAuthenticationDecode.Strings[0], LBasicAuthenticationDecode.Strings[1]); except on E: exception do begin Res.Send(E.Message).Status(THTTPStatus.InternalServerError); raise EHorseCallbackInterrupted.Create; end; end; finally LBasicAuthenticationDecode.Free; end; if not LIsAuthenticated then begin Res.Send('Unauthorized').Status(THTTPStatus.Unauthorized); raise EHorseCallbackInterrupted.Create; end; Next(); end; { THorseBasicAuthenticationConfig } constructor THorseBasicAuthenticationConfig.Create; begin FHeader := AUTHORIZATION; FRealmMessage := REALM_MESSAGE; FSkipRoutes := []; end; function THorseBasicAuthenticationConfig.Header: string; begin Result := FHeader; end; function THorseBasicAuthenticationConfig.Header(const AValue: string): IHorseBasicAuthenticationConfig; begin FHeader := AValue; Result := Self; end; class function THorseBasicAuthenticationConfig.New: IHorseBasicAuthenticationConfig; begin Result := THorseBasicAuthenticationConfig.Create; end; function THorseBasicAuthenticationConfig.RealmMessage(const AValue: string): IHorseBasicAuthenticationConfig; begin FRealmMessage := AValue; Result := Self; end; function THorseBasicAuthenticationConfig.RealmMessage: string; begin Result := FRealmMessage; end; function THorseBasicAuthenticationConfig.SkipRoutes(const AValues: TArray<string>): IHorseBasicAuthenticationConfig; var I: Integer; begin FSkipRoutes := AValues; for I := 0 to Pred(Length(FSkipRoutes)) do if Copy(Trim(FSkipRoutes[I]), 1, 1) <> '/' then FSkipRoutes[I] := '/' + FSkipRoutes[I]; Result := Self; end; function THorseBasicAuthenticationConfig.SkipRoutes: TArray<string>; begin Result := FSkipRoutes; end; end.
unit AnyTest_s; {This file was generated on 27 Oct 2000 17:40:35 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file } {C:\Examples\IDL2PA~1\Any\AnyTest.idl. } {Delphi Pascal unit : AnyTest_s } {derived from IDL module : default } interface uses CORBA, AnyTest_i, AnyTest_c; type TMyTestSkeleton = class; TMyTestSkeleton = class(CORBA.TCorbaObject, AnyTest_i.MyTest) private FImplementation : MyTest; public constructor Create(const InstanceName: string; const Impl: MyTest); destructor Destroy; override; function GetImplementation : MyTest; function GetAny : ANY; published procedure _GetAny(const _Input: CORBA.InputStream; _Cookie: Pointer); end; implementation constructor TMyTestSkeleton.Create(const InstanceName : string; const Impl : AnyTest_i.MyTest); begin inherited; inherited CreateSkeleton(InstanceName, 'MyTest', 'IDL:MyTest:1.0'); FImplementation := Impl; end; destructor TMyTestSkeleton.Destroy; begin FImplementation := nil; inherited; end; function TMyTestSkeleton.GetImplementation : AnyTest_i.MyTest; begin result := FImplementation as AnyTest_i.MyTest; end; function TMyTestSkeleton.GetAny : ANY; begin Result := FImplementation.GetAny; end; procedure TMyTestSkeleton._GetAny(const _Input: CORBA.InputStream; _Cookie: Pointer); var _Output : CORBA.OutputStream; _Result : ANY; begin _Result := GetAny; GetReplyBuffer(_Cookie, _Output); _Output.WriteAny(_Result); end; initialization end.
unit osShellAPI; interface uses SysUtils, WinTypes, WinProcs, ShlObj, Windows, ComObj, ActiveX, ShellApi, Registry, Forms; function ShGetTempPathFileName(p_sPrefix : string) : string; { obtem um nome de arquivo temporario com o caminho do diretorio padrao de arquivos temporarios (se houver) ou a raiz } function ShGetTempPath : string; { retorna o caminho do diretorio padrao de arquivos temporarios ou ''} function BrowseForFolder(p_sRootFolder, p_selectionFolder, p_sTitle : string) : string; { Browse por um diretorio tendo como raiz p_sRootFolder. Se p_sRootFolder = '' entao a raiz é Meu Computador } procedure AddToRecentDocs(p_sFileName : string); { Adiciona um atalho para p_sFileName na menu Documentos do menu iniciar} procedure CopyFiles(p_sFrom, p_sTo : string); procedure MoveFiles(p_sFrom, p_sTo : string); procedure DeleteFiles(p_sFiles : string); procedure SilentDeleteFiles(p_sFiles : string); { O mesmo que DeleteFiles mas sem confirmaçao ou janela de progresso } function GetSpecialFolderPath(p_iFolder : Integer) : string; function GetMyDocumentsPath : string; { Retorna o caminho para a pasta Meus Documentos do usuario atual } function GetDesktopPath : string; { Retorna o caminho para a pasta Desktop do usuario atual } function GetProgramsMenuPath : string; { Retorna o caminho para a pasta Iniciar|Programas do usuario atual } function GetStartMenuPath : string; { Retorna o caminho para a pasta Iniciar do usuario atual } function GetStartUpMenuPath : string; { Retorna o caminho para a pasta Iniciar|Programas|Iniciar do usuario atual } function GetApplicationDataPath : string; procedure CreateLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); { Cria um atalho do arquivo p_sLinkFile com o nome p_sLinkPath, diretorio p_sWorkingFolder Ex.: CreateLink('C:\Windows\Notepad.exe', 'C:\Windows', 'C:\Notepad.lnk'); } procedure CreateDesktopLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); { Cria um atalho do arquivo p_sLinkFile no desktop CreateDesktopLink('C:\Windows\Notepad.exe', 'C:\Windows', 'Notepad.lnk'); } procedure CreateProgramsMenuLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); { Cria um atalho do arquivo p_sLinkFile no menu Iniciar|Programas CreateProgramsMenuLink('C:\Windows\Notepad.exe', 'C:\Windows', 'Notepad.lnk'); CreateProgramsMenuLink('C:\Windows\Notepad.exe', GetMyDocumentsPath, 'Utilitários\Notepad.lnk'); } procedure CreateStartMenuLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); { Cria um atalho no menu Iniciar } procedure CreateStartUpMenuLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); { Cria um atalho no menu Iniciar|Programas|Iniciar } type TShMessageStyle = (msStandard, msQuestion, msWarning, msError); function ShShowMessage(Mensagem : String; msStyle : TShMessageStyle = msStandard) : boolean; function VersionInfo(p_exeName : String; p_key : String) : String; function VersionInfoCompanyName(p_exeName : String) : String; function VersionInfoFileDescription(p_exeName : String) : String; function VersionInfoFileVersion(p_exeName : String) : String; function VersionInfoInternalName(p_exeName : String) : String; function VersionInfoLegalCopyright(p_exeName : String) : String; function VersionInfoLegalTrademarks(p_exeName : String) : String; function VersionInfoOriginalFilename(p_exeName : String) : String; function VersionInfoProductName(p_exeName : String) : String; function VersionInfoProductVersion(p_exeName : String) : String; function VersionInfoComments(p_exeName : String) : String; function ExecuteWait(const p_commandLine : string; const p_commandShow: Word) : integer; { Executa uma aplicação e espera até que ela termine Retorna: Codigo de Erro ou o ExitCode retornado pela aplicação executada } function GetFolder(aRoot: integer; aCaption :string): string; implementation function ShGetTempPath : string; var sFilePath : string; begin sFilePath := StringOfChar(' ', 1024); if GetTempPath(1024, PChar(sFilePath)) = 0 then sFilePath := ''; ShGetTempPath := Trim(sFilePath); end; function ShGetTempPathFileName(p_sPrefix : string) : string; var sFilePath : string; sFileName : string; begin sFilePath := StringOfChar(' ', 1024); sFileName := StringOfChar(' ', 1024); if GetTempPath(1024, PChar(sFilePath)) = 0 then sFilePath := '\'; GetTempFileName(PChar(sFilePath), PChar(p_sPrefix), 1, PChar(sFileName)); ShGetTempPathFileName := Trim(sFileName); end; function GetSpecialFolderPath(p_iFolder : Integer) : string; var sPath : string; ppidl : PItemIDList; begin sPath := StringOfChar(' ', 1024); { SHGetSpecialFolderPath(0, PChar(sPath), p_iFolder, FALSE); } SHGetSpecialFolderLocation(0, p_iFolder, ppidl); SHGetPathFromIDList(ppidl, PChar(sPath)); GetSpecialFolderPath := Trim(sPath); end; function GetMyDocumentsPath : string; begin GetMyDocumentsPath := GetSpecialFolderPath(CSIDL_PERSONAL); end; function GetDesktopPath : string; begin GetDesktopPath := GetSpecialFolderPath(CSIDL_DESKTOP); end; function GetProgramsMenuPath : string; begin GetProgramsMenuPath := GetSpecialFolderPath(CSIDL_PROGRAMS); end; function GetStartMenuPath : string; begin GetStartMenuPath := GetSpecialFolderPath(CSIDL_STARTMENU); end; function GetStartUpMenuPath : string; begin GetStartUpMenuPath := GetSpecialFolderPath(CSIDL_STARTUP); end; function GetApplicationDataPath : string; begin GetApplicationDataPath := GetSpecialFolderPath(CSIDL_APPDATA); end; // -- BrowseForFolder var g_selectionFolder : string; // -- nao pode ser local a funcao (i.e. nao pode estar no stack) function BrowseForFolder(p_sRootFolder, p_selectionFolder, p_sTitle : string) : string; var lpbi : TBrowseInfo; lpidl : PItemIDList; lpidlroot : PItemIDList; pszDisplayName : string; pszResult : string; psl : IShellLink; function BrowserFolderCallback(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer; stdcall; begin if uMsg = BFFM_INITIALIZED then SendMessage(Wnd, BFFM_SETSELECTION, 1, LongInt(PChar(g_selectionFolder))); BrowserFolderCallback := 0; end; begin g_selectionFolder := p_selectionFolder; pszDisplayName := StringOfChar(' ', 1024); lpidlroot := nil; if p_sRootFolder <> '' then begin psl := CreateComObject(CLSID_ShellLink) as IShellLink; psl.SetPath(PChar(p_sRootFolder)); psl.GetIDList(lpidlroot); end; lpbi.hwndOwner := 0; lpbi.pidlRoot := lpidlroot; lpbi.pszDisplayName := PChar(pszDisplayName); lpbi.lpszTitle := PChar(p_sTitle); lpbi.ulFlags := 0; lpbi.lpfn := @BrowserFolderCallback; lpbi.lParam := 0; lpbi.iImage := 0; lpidl := SHBrowseForFolder(lpbi); pszResult := StringOfChar(' ', 1024); if lpidl <> nil then SHGetPathFromIDList(lpidl, PChar(pszResult)); BrowseForFolder := Trim(pszResult); end; procedure CopyFiles(p_sFrom, p_sTo : string); var lpFileOp : ^TSHFileOpStruct; begin lpFileOp := AllocMem(Sizeof(TSHFileOpStruct)); lpFileOp.Wnd := 0; lpFileOp.wFunc := FO_COPY; lpFileOp.pFrom := PChar(p_sFrom); lpFileOp.pTo := PChar(p_sTo); lpFileOp.fFlags := FOF_NOCONFIRMMKDIR; SHFileOperation(lpFileOp^); FreeMem(lpFileOp); end; procedure MoveFiles(p_sFrom, p_sTo : string); var lpFileOp : ^TSHFileOpStruct; begin lpFileOp := AllocMem(Sizeof(TSHFileOpStruct)); lpFileOp.Wnd := 0; lpFileOp.wFunc := FO_MOVE; lpFileOp.pFrom := PChar(p_sFrom); lpFileOp.pTo := PChar(p_sTo); lpFileOp.fFlags := FOF_NOCONFIRMMKDIR; SHFileOperation(lpFileOp^); FreeMem(lpFileOp); end; procedure DeleteFiles(p_sFiles : string); var lpFileOp : ^TSHFileOpStruct; begin lpFileOp := AllocMem(Sizeof(TSHFileOpStruct)); lpFileOp.Wnd := 0; lpFileOp.wFunc := FO_DELETE; lpFileOp.pFrom := PChar(p_sFiles); lpFileOp.fFlags := FOF_ALLOWUNDO; SHFileOperation(lpFileOp^); FreeMem(lpFileOp); end; procedure SilentDeleteFiles(p_sFiles : string); var lpFileOp : ^TSHFileOpStruct; begin lpFileOp := AllocMem(Sizeof(TSHFileOpStruct)); lpFileOp.Wnd := 0; lpFileOp.wFunc := FO_DELETE; lpFileOp.pFrom := PChar(p_sFiles); lpFileOp.fFlags := FOF_ALLOWUNDO + FOF_SILENT + FOF_NOCONFIRMATION; SHFileOperation(lpFileOp^); FreeMem(lpFileOp); end; procedure AddToRecentDocs(p_sFileName : string); begin SHAddToRecentDocs(SHARD_PATH, PChar(p_sFileName)); end; procedure CreateLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); const IID_IPersistFile: TGUID = ( D1:$0000010B;D2:$0000;D3:$0000;D4:($C0,$00,$00,$00,$00,$00,$00,$46)); var psl : IShellLink; ppf : IPersistFile; wsz: array[0..1024] of WideChar; begin psl := CreateComObject(CLSID_ShellLink) as IShellLink; psl.SetPath(PChar(p_sLinkFile)); psl.SetWorkingDirectory(PChar(p_sWorkingFolder)); psl.QueryInterface(IID_IPersistFile, ppf); StringToWideChar(p_sLinkPath, wsz, SizeOf(wsz) div 2); ppf.Save(wsz, False); end; procedure CreateDesktopLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); begin CreateLink(p_sLinkFile, p_sWorkingFolder, GetDesktopPath + '\' + p_sLinkPath); end; procedure CreateProgramsMenuLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); begin CreateLink(p_sLinkFile, p_sWorkingFolder, GetProgramsMenuPath + '\' + p_sLinkPath); end; procedure CreateStartMenuLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); begin CreateLink(p_sLinkFile, p_sWorkingFolder, GetStartMenuPath + '\' + p_sLinkPath); end; procedure CreateStartUpMenuLink(p_sLinkFile, p_sWorkingFolder, p_sLinkPath : string); begin CreateLink(p_sLinkFile, p_sWorkingFolder, GetStartUpMenuPath + '\' + p_sLinkPath); end; function ShShowMessage(Mensagem : String; msStyle : TShMessageStyle) : boolean; var s : String; Flags : LongInt; begin Flags := 0; s := Application.ExeName; if Application.Title <> '' then s := Application.Title; case msStyle of msStandard: Flags := MB_ICONINFORMATION; msQuestion: Flags := MB_ICONQUESTION; msWarning: Flags := MB_ICONWARNING; msError: Flags := MB_ICONSTOP; end; Result := Application.MessageBox(PChar(Mensagem), PChar(s), MB_OKCANCEL + MB_DEFBUTTON1 + Flags) = IDOK; end; function VersionInfo(p_exeName : String; p_key : String) : String; var InfoSize, Wnd: DWORD; VerBuf: Pointer; VerSize: DWORD; VersionS : String; VersionPtr : PChar; begin VersionS := StringOfChar(' ', 1024); VersionPtr := PChar(VersionS); VerSize := StrLen(VersionPtr); InfoSize := GetFileVersionInfoSize(PChar(p_exeName), Wnd); if InfoSize <> 0 then begin GetMem(VerBuf, InfoSize); try if GetFileVersionInfo(PChar(p_exeName), Wnd, InfoSize, VerBuf) then if VerQueryValue(VerBuf, PChar('\StringFileInfo\041604E4\' + p_key), Pointer(VersionPtr), VerSize) then VersionS := VersionPtr; finally FreeMem(VerBuf); end; end; VersionInfo := Trim(VersionS); end; function VersionInfoCompanyName(p_exeName : String) : String; begin VersionInfoCompanyName := VersionInfo(p_exeName, 'CompanyName'); end; function VersionInfoFileDescription(p_exeName : String) : String; begin VersionInfoFileDescription := VersionInfo(p_exeName, 'FileDescription'); end; function VersionInfoFileVersion(p_exeName : String) : String; begin VersionInfoFileVersion := VersionInfo(p_exeName, 'FileVersion'); end; function VersionInfoInternalName(p_exeName : String) : String; begin VersionInfoInternalName := VersionInfo(p_exeName, 'InternalName'); end; function VersionInfoLegalCopyright(p_exeName : String) : String; begin VersionInfoLegalCopyright := VersionInfo(p_exeName, 'LegalCopyright'); end; function VersionInfoLegalTrademarks(p_exeName : String) : String; begin VersionInfoLegalTrademarks := VersionInfo(p_exeName, 'LegalTrademarks'); end; function VersionInfoOriginalFilename(p_exeName : String) : String; begin VersionInfoOriginalFilename := VersionInfo(p_exeName, 'OriginalFilename'); end; function VersionInfoProductName(p_exeName : String) : String; begin VersionInfoProductName := VersionInfo(p_exeName, 'ProductName'); end; function VersionInfoProductVersion(p_exeName : String) : String; begin VersionInfoProductVersion := VersionInfo(p_exeName, 'ProductVersion'); end; function VersionInfoComments(p_exeName : String) : String; begin VersionInfoComments := VersionInfo(p_exeName, 'Comments'); end; // With a big Help from my Theodoros Bebekis - Thessaloniki, Greece function ExecuteWait(const p_commandLine : string; const p_commandShow: Word) : integer; var pCommandLine : array[0..MAX_PATH] of char; StartupInfo : TStartupInfo; ProcessInfo : TProcessInformation; hAppProcess, hAppThread : THandle; dwExitCode : DWORD; bRet : boolean; begin StrPCopy(pCommandLine, p_commandLine); hAppThread := 0; hAppProcess := 0; TRY { Prepare StartupInfo structure } FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; StartupInfo.wShowWindow := p_commandShow; StartupInfo.hStdOutput := 0; StartupInfo.hStdInput := 0; dwExitCode := $FFFFFFFF; { Create the app } bRet := CreateProcess( nil, { pointer to name of executable module } pCommandLine, { pointer to command line string } nil, { pointer to process security attributes } nil, { pointer to thread security attributes } True, { handle inheritance flag } HIGH_PRIORITY_CLASS,{ creation flags } nil, { pointer to new environment block } nil, { pointer to current directory name } StartupInfo, { pointer to STARTUPINFO } ProcessInfo); { pointer to PROCESS_INF } { wait for the app to finish its job and take the handles to free them later } if bRet then begin WaitforSingleObject(ProcessInfo.hProcess, INFINITE); hAppProcess := ProcessInfo.hProcess; hAppThread := ProcessInfo.hThread; GetExitCodeProcess (hAppProcess, dwExitCode); end else dwExitCode := GetLastError; FINALLY { Close the handles. Kernel objects, like the process and the files we created in this case, are maintained by a usage count. So, for cleaning up purposes, we have to close the handles to inform the system that we don't need the objects anymore } if hAppThread <> 0 then CloseHandle(hAppThread); if hAppProcess <> 0 then CloseHandle(hAppProcess); end; Result := dwExitCode; end; function GetFolder(aRoot: integer; aCaption :string): string; var pPrograms,pBrowse: PItemIDList; hBrowseInfo: TBROWSEINFO; hPChar: PChar; begin Result := ''; if (not SUCCEEDED(SHGetSpecialFolderLocation(Getactivewindow, aRoot, pPrograms))) then Exit; hPChar := StrAlloc(100); try with hBrowseInfo do begin hwndOwner := Getactivewindow; pidlRoot := pPrograms; pszDisplayName := hPChar; lpszTitle := pChar(aCaption); ulFlags := BIF_RETURNONLYFSDIRS; lpfn := nil; lParam := 0; end; pBrowse := SHBrowseForFolder(hBrowseInfo); if (pBrowse <> nil) then if (SHGetPathFromIDList(pBrowse, hPChar)) then Result:= hPChar; finally StrDispose(hPChar); end; end; end.
unit Destinfo; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DB, DBTables, Types; type TEnterDestinationParcelInformationForm = class(TForm) GroupBox1: TGroupBox; OKButton: TBitBtn; CancelButton: TBitBtn; Name1: TLabel; Name1Edit: TEdit; Name2: TLabel; Name2Edit: TEdit; Address1: TLabel; Addr1Edit: TEdit; Address2: TLabel; Addr2Edit: TEdit; Street: TLabel; StreetEdit: TEdit; City: TLabel; CityEdit: TEdit; RemapOldSBL: TLabel; PriorSBLKeyEdit: TEdit; State: TLabel; Zip: TLabel; ZipPlus4: TLabel; StateEdit: TEdit; ZipEdit: TEdit; ZipPlus4Edit: TEdit; LegalAddrNo: TLabel; LegalAddr: TLabel; LegalAddrNoEdit: TEdit; LegalAddrStreetEdit: TEdit; Depth: TLabel; Frontage: TLabel; Acreage: TLabel; GridCordNorth: TLabel; GridCordEast: TLabel; EditFrontage: TEdit; EditDepth: TEdit; EditGridCoordNorth: TEdit; EditAcreage: TEdit; EditGridCoordEast: TEdit; ParcelTable: TTable; AssessmentYearControlTable: TTable; SwisCodeTable: TTable; procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } SourceSwisSBLKey : String; _GridLine : Integer; AssessmentYear : String; Procedure InitializeForm(DestinationSwisSBLKey : String; DestParcelInfoList : TList; ProcessingType : Integer); Function GetValueForField(DestinationSwisSBLKey : String; DestParcelInfoList : TList; _FieldName : String) : String; Procedure AddDefaultInformationItem(DestinationSwisSBLKey : String; DestParcelInfoList : TList; ProcessingType : Integer); end; var EnterDestinationParcelInformationForm: TEnterDestinationParcelInformationForm; implementation {$R *.DFM} uses PasUtils, GlblCnst, PASTypes, WinUtils, GlblVars, Utilitys; {==============================================================} Procedure TEnterDestinationParcelInformationForm.AddDefaultInformationItem(DestinationSwisSBLKey : String; DestParcelInfoList : TList; ProcessingType : Integer); var DestParcelInfoPtr : DestinationParcelInformationPointer; I : Integer; Quit, ValidEntry : Boolean; begin OpenTableForProcessingType(ParcelTable, ParcelTableName, ProcessingType, Quit); OpenTableForProcessingType(SwisCodeTable, SwisCodeTableName, ProcessingType, Quit); OpenTableForProcessingType(AssessmentYearControlTable, AssessmentYearControlTableName, ProcessingType, Quit); {First clear out any entries for this SBL.} For I := (DestParcelInfoList.Count - 1) downto 0 do If (DestinationParcelInformationPointer(DestParcelInfoList[I])^.SwisSBLKey = DestinationSwisSBLKey) then DestParcelInfoList.Delete(I); {Now put the new ones in.} For I := 0 to (ComponentCount - 1) do If (Components[I] is TLabel) then with Components[I] as TLabel do begin New(DestParcelInfoPtr); with DestParcelInfoPtr^ do begin FieldName := Name; TableName := 'TParcelTable'; SwisSBLKey := DestinationSwisSBLKey; (*GridLine := _GridLine; *) {The FocusControl of the label points to the corresponding edit.} {FXX03292002-2: Not getting the old ID correctly.} If (GlblLocateByOldParcelID and (FieldName = 'RemapOldSBL') and (Deblank(TEdit(FocusControl).Text) <> '')) then FieldValue := ConvertOldSwisDashDotSBLToSwisSBL(TEdit(FocusControl).Text, AssessmentYearControlTable, SwisCodeTable, ValidEntry) else FieldValue := TEdit(FocusControl).Text; end; {with DestParcelInfoPtr^ do} DestParcelInfoList.Add(DestParcelInfoPtr); end; {with Components[I] as TLabel do} CloseTablesForForm(Self); end; {AddDefaultInformationItem} {==============================================================} Function TEnterDestinationParcelInformationForm.GetValueForField(DestinationSwisSBLKey : String; DestParcelInfoList : TList; _FieldName : String) : String; {FXX03292002-3: Check for information that already exists.} var I : Integer; begin Result := ''; For I := 0 to (DestParcelInfoList.Count - 1) do with DestinationParcelInformationPointer(DestParcelInfoList[I])^ do If ((SwisSBLKey = DestinationSwisSBLKey) and (Take(30, FieldName) = Take(30, _FieldName))) then Result := FieldValue; end; {GetValueForField} {==============================================================} Procedure TEnterDestinationParcelInformationForm.InitializeForm(DestinationSwisSBLKey : String; DestParcelInfoList : TList; ProcessingType : Integer); var SBLRec : SBLRecord; I : Integer; Quit, InformationFound : Boolean; TempStr : String; begin OpenTableForProcessingType(ParcelTable, ParcelTableName, ProcessingType, Quit); OpenTableForProcessingType(SwisCodeTable, SwisCodeTableName, ProcessingType, Quit); OpenTableForProcessingType(AssessmentYearControlTable, AssessmentYearControlTableName, ProcessingType, Quit); GroupBox1.Caption := ' Enter information for ' + ConvertSwisSBLToDashDot(DestinationSwisSBLKey) + ' '; Caption := 'Enter information for ' + ConvertSwisSBLToDashDot(DestinationSwisSBLKey); SBLRec := ExtractSwisSBLFromSwisSBLKey(SourceSwisSBLKey); with SBLRec do FindKeyOld(ParcelTable, ['TaxRollYr', 'SwisCode', 'Section', 'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'], [AssessmentYear, SwisCode, Section, Subsection, Block, Lot, Sublot, Suffix]); {FXX03292002-3: Check for information that already exists.} InformationFound := False; For I := 0 to (DestParcelInfoList.Count - 1) do If (DestinationParcelInformationPointer(DestParcelInfoList[I])^.SwisSBLKey = DestinationSwisSBLKey) then InformationFound := True; {Fill in the default info.} If InformationFound then begin Name1Edit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Name1'); Name2Edit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Name2'); Addr1Edit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Address1'); Addr2Edit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Address2'); StreetEdit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Street'); CityEdit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'City'); StateEdit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'State'); ZipEdit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Zip'); ZipPlus4Edit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'ZipPlus4'); LegalAddrNoEdit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'LegalAddrNo'); LegalAddrStreetEdit.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'LegalAddr'); try EditFrontage.Text := FormatFloat(DecimalEditDisplay_BlankZero, StrToFloat(GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Frontage'))); except EditFrontage.Text := ''; end; try EditDepth.Text := FormatFloat(DecimalEditDisplay_BlankZero, StrToFloat(GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Depth'))); except EditDepth.Text := ''; end; try EditAcreage.Text := FormatFloat(DecimalEditDisplay_BlankZero, StrToFloat(GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'Acreage'))); except EditAcreage.Text := ''; end; EditGridCoordNorth.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'GridCordNorth'); EditGridCoordEast.Text := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'GridCordEast'); TempStr := GetValueForField(DestinationSwisSBLKey, DestParcelInfoList, 'RemapOldSBL'); PriorSBLKeyEdit.Text := ConvertSwisSBLToOldDashDot(TempStr, AssessmentYearControlTable); end else begin with ParcelTable do begin Name1Edit.Text := FieldByName('Name1').Text; Name2Edit.Text := FieldByName('Name2').Text; Addr1Edit.Text := FieldByName('Address1').Text; Addr2Edit.Text := FieldByName('Address2').Text; StreetEdit.Text := FieldByName('Street').Text; CityEdit.Text := FieldByName('City').Text; StateEdit.Text := FieldByName('State').Text; ZipEdit.Text := FieldByName('Zip').Text; ZipPlus4Edit.Text := FieldByName('ZipPlus4').Text; LegalAddrNoEdit.Text := FieldByName('LegalAddrNo').Text; LegalAddrStreetEdit.Text := FieldByName('LegalAddr').Text; EditFrontage.Text := FormatFloat(DecimalEditDisplay_BlankZero, FieldByName('Frontage').AsFloat); EditDepth.Text := FormatFloat(DecimalEditDisplay_BlankZero, FieldByName('Depth').AsFloat); EditAcreage.Text := FormatFloat(DecimalEditDisplay_BlankZero, FieldByName('Acreage').AsFloat); EditGridCoordNorth.Text := FieldByName('GridCordNorth').Text; EditGridCoordEast.Text := FieldByName('GridCordEast').Text; end; {with ParcelTable do} end; {else of If InformationFound} CloseTablesForForm(Self); end; {InitializeForm} {==========================================================================} Procedure TEnterDestinationParcelInformationForm.FormKeyPress( Sender: TObject; var Key: Char); begin If (Key = #13) then begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); end; end; {FormKeyPress} {==========================================================================} end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Datasnap.DSClientRest; interface uses System.Classes, System.Contnrs, Data.DB, Data.DBXCommon, Data.DBXJSON, Data.DBXJSONReflect, Datasnap.DSCommonProxy, Datasnap.DSHTTP, System.Generics.Collections, System.SysUtils; type ///<summary> /// Provides information about a server method parameter type or return type needed by /// TDSRestCommand ///</summary> TDSRestParameterMetaData = record ///<summary> /// Name of the parameter or blank if a return type. ///</summary> Name: string; ///<summary> /// Direction of the parameter or return type. See TDBXParameterDirections. ///</summary> Direction: Integer; ///<summary> /// Parameter type or return type. See TDBXDataTypes. ///</summary> DBXType: Integer; ///<summary> /// Parameter or return type name. ///</summary> TypeName: string; end; ///<summary> /// Stores login information on behalf of TDSCustomRestConnection and TDSRestLoginEvent ///</summary> TDSRestLoginProperties = class(TPersistent) protected ///<summary> /// Copies login information to another instance ///</summary> procedure AssignTo(Dest: TPersistent); override; public ///<summary> /// Username or blank. ///</summary> UserName: string; ///<summary> /// Password or blank. ///</summary> Password: string; ///<summary> /// Indicates whether the user should be prompted for the username and password when connecting ///</summary> LoginPrompt: Boolean; end; TDSRestCommand = class; ///<summary> /// Declares the event procedure that can provide the username and password when connecting ///</summary> TDSRestLoginEvent = procedure(Sender: TObject; LoginProperties: TDSRestLoginProperties; var Cancel: Boolean) of object; ///<summary> /// Possible values for the TDSTextConnectionOptions ///</summary> TDSTestConnectionOption = (toNoLoginPrompt); ///<summary> /// Options to control the behavior of the TDSCustomRestConnection.TestConnection method ///</summary> TDSTestConnectionOptions = set of TDSTestConnectionOption; ///<summary> /// RestConnection component with no published properties. ///</summary> TDSCustomRestConnection = class(TComponent) strict private FProtocol: string; FHost: string; FPort: Integer; FUrlPath: string; FUserName: string; FPassword: string; FUniqueID: string; FContext: string; FLoginProperties: TDSRestLoginProperties; FHTTP: TDSHTTP; FSessionID: string; FProxyHost: string; FProxyPort: Integer; FProxyUsername: string; FProxyPassword: string; FIPImplementationID: string; FConnectionKeepAlive: string; private FLoginPrompt: Boolean; FOnLogin: TDSRestLoginEvent; FOnValidateCertificate: TValidateCertificate; FBeforeExecute: TNotifyEvent; FAfterExecute: TNotifyEvent; FPreserveSessionID: Boolean; procedure ReadUniqueId(Reader: TReader); procedure WriteUniqueId(Writer: TWriter); function GetPassword: string; function GetUserName: string; procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); procedure SetLoginPrompt(const Value: Boolean); function GetLoginPrompt: Boolean; procedure LoginDialogTestConnection; procedure SetContext(const Value: string); function GetHTTP: TDSHTTP; function GetOnValidatePeerCertificate: TValidateCertificate; procedure SetOnValidatePeerCertificate(const Value: TValidateCertificate); procedure SetProtocol(const Value: string); protected function Login: Boolean; virtual; procedure BeforeExecute; virtual; procedure AfterExecute; virtual; procedure DefineProperties(Filer: TFiler); override; procedure AssignTo(Dest: TPersistent); override; procedure SessionExpired; virtual; procedure SetConnection(const KeepAlive: String); virtual; function GetConnection: String; virtual; function GetProxyHost: String; virtual; procedure SetProxyHost(const Value: String); virtual; function GetProxyPort: Integer; virtual; procedure SetProxyPort(const Value: Integer); function GetProxyUsername: String; virtual; procedure SetProxyUsername(const Value: String); virtual; function GetProxyPassword: String; virtual; procedure SetProxyPassword(const Value: String); virtual; function GetIPImplementationID: string; virtual; procedure SetIPImplementationID(const Value: string); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure TestConnection(AOptions: TDSTestConnectionOptions = []); function CreateCommand: TDSRestCommand; function DefaultProtocol: string; procedure Reset; property Protocol: string read FProtocol write SetProtocol; property Host: string read FHost write FHost; property Port: Integer read FPort write FPort; property UrlPath: string read FUrlPath write FUrlPath; property Context: string read FContext write SetContext; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property UniqueID: string read FUniqueID write FUniqueID; property LoginPrompt: Boolean read GetLoginPrompt write SetLoginPrompt default True; property OnLogin: TDSRestLoginEvent read FOnLogin write FOnLogin; property SessionID: string read FSessionID write FSessionID; property LoginProperties: TDSRestLoginProperties read FLoginProperties; property PreserveSessionID: Boolean read FPreserveSessionID write FPreserveSessionID default True; property OnValidatePeerCertificate: TValidateCertificate read GetOnValidatePeerCertificate write SetOnValidatePeerCertificate; property OnBeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute; property OnAfterExecute: TNotifyEvent read FAfterExecute write FAfterExecute; property HTTP: TDSHTTP read GetHTTP; property Connection: String read GetConnection write SetConnection; property ProxyHost: String read GetProxyHost write SetProxyHost; property ProxyPort: Integer read GetProxyPort write SetProxyPort default 8888; property ProxyUsername: String read GetProxyUsername write SetProxyUsername; property ProxyPassword: String read GetProxyPassword write SetProxyPassword; property IPImplementationID: string read GetIPImplementationID write SetIPImplementationID; end; ///<summary> /// RestConnection component with with published properties. ///</summary> TDSRestConnection = class(TDSCustomRestConnection) published property Protocol; property Host; property Port; property UrlPath; property Context; property UserName; property Password; property LoginPrompt; property PreserveSessionID; property Connection; property ProxyHost; property ProxyPort; property ProxyUsername; property ProxyPassword; property OnLogin; property OnValidatePeerCertificate; property OnBeforeExecute; property OnAfterExecute; property IPImplementationID; end; TDSRestParameterMetaDataArray = array of TDSRestParameterMetaData; TDSRestCommand = class strict private FDBXContext: TDBXContext; FConnection: TDSCustomRestConnection; FText: string; FParameters: TDBXParameterList; FRequestType: string; FFreeOnExecuteList: TObjectList; function CreateParameters(AMetaData: array of TDSRestParameterMetaData): TDBXParameterList; private procedure AfterExecute; procedure BeforeExecute; function BuildParameterMetaDataArray: TArray<TDSRestParameterMetaData>; overload; function BuildParameterMetaDataArray(AProxyMetaData: TDSProxyMetadata): TArray<TDSRestParameterMetaData>; overload; function DetermineRequestType( AMetaData: array of TDSRestParameterMetaData): string; public constructor Create(AConnection: TDSCustomRestConnection); destructor Destroy; override; procedure Prepare(AMetaData: array of TDSRestParameterMetaData); overload; procedure Prepare(AProxyMetaData: TDSProxyMetadata); overload; procedure Prepare; overload; procedure Execute(const ARequestFilter: string = ''); procedure ExecuteCache(const ARequestFilter: string = ''); property Text: string read FText write FText; property Parameters: TDBXParameterList read FParameters; property RequestType: string read FRequestType write FRequestType; property Connection: TDSCustomRestConnection read FConnection; function GetJSONMarshaler: TJSONMarshal; function GetJSONUnMarshaler: TJSONUnMarshal; procedure FreeOnExecute(Value: TObject); end; TDSRestResponseStreamProc = reference to procedure(AStream: TStream; const AResponseCharSet: string; var AOwnsStream: Boolean); TDSRestCacheCommand = class strict private FParameterPath: string; FConnection: TDSCustomRestConnection; procedure Execute(const ARequestType, ACachePath: string; AResponseStreamProc: TDSRestResponseStreamProc; const ARequestFilter: string = ''); function GetCommandPath: string; public constructor Create(AConnection: TDSCustomRestConnection); destructor Destroy; override; procedure GetParameter(AResponseStreamProc: TDSRestResponseStreamProc; const ARequestFilter: string = ''); overload; procedure GetParameter(out AJSONValue: TJSONValue; const ARequestFilter: string = ''); overload; procedure GetParameter(out AStream: TStream; AOwnsObject: Boolean; const ARequestFilter: string = ''); overload; procedure GetCommand(AResponseStreamProc: TDSRestResponseStreamProc); overload; ///<summary> /// Retrieve JSONObject that represents a cached command ///</summary> function GetCommand(AOwnsObject: Boolean = True): TJSONObject; overload; procedure DeleteCommand; property Connection: TDSCustomRestConnection read FConnection; property ParameterPath: string read FParameterPath write FParameterPath; property CommandPath: string read GetCommandPath; end; IDSRestCachedCommand = interface ['{16B2E1F2-436B-45D8-A17D-5B1617F65BD6}'] function GetCommand(AConnection: TDSRestConnection; AOwnsObject: Boolean = True): TJSONObject; procedure DeleteCommand(AConnection: TDSRestConnection); end; IDSRestCachedItem = interface ['{CCCDC036-04F0-4CF6-A74F-D2759F1E635A}'] function GetItemPath: string; property ItemPath: string read GetItemPath; end; IDSRestCachedJSONObject = interface(IDSRestCachedItem) ['{3C45664B-BAAB-42AA-8FD9-9D3AB0198455}'] function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TJSONObject; end; IDSRestCachedJSONArray = interface(IDSRestCachedItem) ['{38E0EFCC-A1B6-4E11-BD9D-F640B7822D44}'] function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TJSONArray; end; IDSRestCachedJSONValue = interface(IDSRestCachedItem) ['{12458118-91A1-4A67-87AB-947CB8970D7B}'] function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TJSONValue; end; IDSRestCachedDBXReader = interface(IDSRestCachedItem) ['{567DBA1E-2CAE-4C15-824B-0B678FBBD5B1}'] function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TDBXReader; end; IDSRestCachedDataSet = interface(IDSRestCachedItem) ['{54D0BA3F-9159-4DD5-802A-0097BA842D91}'] function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TDataSet; end; IDSRestCachedParams = interface(IDSRestCachedItem) ['{FD14E67B-D225-4FED-8B45-451B6627962C}'] function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TParams; end; IDSRestCachedStream = interface(IDSRestCachedItem) ['{0E09C8A7-11A5-4CD5-B175-A35C9B0BEDF5}'] function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TStream; end; IDSRestCachedObject<T: class> = interface function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): T; end; TGetJSONValueCallback = reference to function(AValue: TJSONValue): Boolean; TDSRestCachedItem = class(TInterfacedObject, IDSRestCachedItem, IDSRestCachedCommand) strict private FItemPath: string; FOwnedObjects: TList; protected function GetItemPath: string; function GetJSONValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TJSONValue; function GetJSONValueCallback(AConnection: TDSRestConnection; ACallBack: TGetJSONValueCallback; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TJSONValue; function UnmarshalValue<T: class>(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): T; property OwnedObjects: TList read FOwnedObjects; public constructor Create(const AItemPath: string); destructor Destroy; override; procedure DeleteCommand(AConnection: TDSRestConnection); function GetCommand(AConnection: TDSRestConnection; AOwnsObject: Boolean = True): TJSONObject; property ItemPath: string read GetItemPath; end; TDSRestCachedJSONObject = class(TDSRestCachedItem, IDSRestCachedJSONObject, IDSRestCachedCommand) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TJSONObject; end; TDSRestCachedJSONArray = class(TDSRestCachedItem, IDSRestCachedJSONArray, IDSRestCachedCommand) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TJSONArray; end; TDSRestCachedJSONValue = class(TDSRestCachedItem, IDSRestCachedJSONValue, IDSRestCachedCommand) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TJSONValue; end; TDSRestCachedStream = class(TDSRestCachedItem, IDSRestCachedStream, IDSRestCachedCommand) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TStream; end; TDSRestCachedDataSet = class(TDSRestCachedItem, IDSRestCachedDataSet, IDSRestCachedCommand) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TDataSet; end; TDSRestCachedParams = class(TDSRestCachedItem, IDSRestCachedParams, IDSRestCachedCommand) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TParams; end; TDSRestCachedDBXReader = class(TDSRestCachedItem, IDSRestCachedDBXReader, IDSRestCachedCommand) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): TDBXReader; end; TDSRestCachedObject<T: class> = class(TDSRestCachedItem) public function GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean = True; const ARequestFilter: string = ''): T; end; TDSRestClientCallback = class; TDSRestClientChannel = class; TDSRestCallbackLoop = class; /// <summary> User event type for notification of callback channel events, such as create and close. /// </summary> TDSRESTChannelEventType = (rChannelCreate, rChannelClose, rChannelClosedByServer, rCallbackAdded, rCallbackRemoved); /// <summary> Event Item passed in through the TDSRESRChannelEvent, for providing tunnel event info. /// </summary> TDSRESTChannelEventItem = record ///<summary>The type of event occurring for a tunnel (channel.)</summary> EventType: TDSRESTChannelEventType; ///<summary>The channel being acted on.</summary> ClientChannel: TDSRestClientChannel; ///<summary>The ID of the channel being acted on.</summary> ClientChannelId: String; ///<summary>The ServerChannelName of the tunnel (Channel) being acted on.</summary> ClientChannelName: String; ///<summary>The ID of the callback being added or removed.</summary> CallbackId: String; ///<summary>The callback being added or removed, or nil if the channel is being closed.</summary> Callback: TDSRestClientCallback; end; /// <summary> User event for notification of callback tunnel, such as create and close.</summary> TDSRESRChannelEvent = procedure(const EventItem: TDSRESTChannelEventItem) of object; TDSRestClientChannel = class private FConnection: TDSCustomRestConnection; FCallbackLoop: TDSRestCallbackLoop; FOnDisconnect: TNotifyEvent; FChannelEvent: TDSRESRChannelEvent; FStopped: Boolean; FCallbacks: TList<TDSRestClientCallback>; procedure EnumerateCallbacks(AMethod: TFunc<TDSRestClientCallback, Boolean>); overload; procedure EnumerateCallbacks(AMethod: TProc<TDSRestClientCallback>); overload; procedure UnregisterAllCallbacks; procedure NotifyEvent(EventType: TDSRESTChannelEventType; Callback: TDSRestClientCallback); strict private FChannelId: string; FServerChannelName: string; function GetConnected: Boolean; function GetSessionId: String; public constructor Create(const AChannelId, AServerChannelName: string; AConnection: TDSCustomRestConnection); destructor Destroy; override; procedure RegisterCallback(AClientCallback: TDSRestClientCallback); procedure Connect(AFirstCallback: TDSRestClientCallback); procedure UnregisterCallback(AClientCallback: TDSRestClientCallback); function Broadcast(AMessage: TJSONValue; AChannelName: String = ''): Boolean; procedure Disconnect; function Notify(const AClientId, ACallbackId: string; AMessage: TJSONValue): Boolean; property Connected: Boolean read GetConnected; property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect; property ServerChannelName: string read FServerChannelName; property ChannelId: string read FChannelId; property SessionId: String read GetSessionId; /// <summary>Returns the list of callbacks held by this client channel.</summary> property Callbacks: TList<TDSRestClientCallback> read FCallbacks; /// <summary>Event that gets notified when changes are made to the callbacks held by this /// channel or to the channel itself. /// </summary> property OnChannelStateChange: TDSRESRChannelEvent read FChannelEvent write FChannelEvent; end; TDSRestCallbackLoop = class strict private FClientChannel: TDSRestClientChannel; FConnection: TDSCustomRestConnection; FThread: TThread; FStopping: Boolean; procedure OnThreadTerminateDirect; function GetStopped: Boolean; function GetSessionId: String; public constructor Create(AClientChannel: TDSRestClientChannel; AConnection: TDSCustomRestConnection); destructor Destroy; override; procedure Callback(responseValue: TJSONValue; var AStatus: Boolean; var AStop: Boolean); procedure Start(AFirstCallback: TDSRestClientCallback); procedure Stop; property Stopped: Boolean read GetStopped; property ClientChannel: TDSRestClientChannel read FClientChannel; property SessionId: String read GetSessionId; end; TDSRestClientCallbackFunction = TFunc<TJSONValue, string, Boolean>; TDSRestClientCallback = class strict private FCallbackId: string; FChannelNames: TStrings; FClientCallbackFunction: TDSRestClientCallbackFunction; FClientChannel: TDSRestClientChannel; public constructor Create(AClientChannel: TDSRestClientChannel; const ACallbackId: string; AClientCallbackFunction: TDSRestClientCallbackFunction; AChannelNames: TStrings = nil); destructor Destroy; override; property CallbackId: string read FCallbackId; property ClientCallbackFunction: TDSRestClientCallbackFunction read FClientCallbackFunction; property ChannelNames: TStrings read FChannelNames; end; TTestConnectionMethod = procedure of object; TDSRestException = class(Exception); TDSRestProtocolException = class(TDSRestException) private FStatus: Integer; FResponseText: string; public constructor Create(AStatus: Integer; const AMessage, AResponseText: string); property Status: Integer read FStatus; property ResponseText: string read FResponseText; end; var DSRestLoginDialogProc: function (ASender: TObject; var LoginProperties: TDSRestLoginProperties; ATestConnectionMethod: TTestConnectionMethod): Boolean; implementation uses Data.DBXCommonTable, Data.DBXDBReaders, Data.DBXJSONCommon, Data.DBXMemoryRow, Data.DBXPlatform, Datasnap.DSClientResStrs, Datasnap.DSProxyRest, IPPeerAPI, Data.SqlExpr, System.StrUtils; const sDSSessionEquals = 'dssession='; type TDSRestRequestResponse = class strict private FFreeStreamValue: Boolean; FStringValue: string; FStreamValue: TStream; FHaveString: Boolean; FSessionID: string; FSessionExpired: Boolean; FResponseCharSet: string; private FIPImplementationID: string; function GetStringValue: string; public function GetStream(AObjectOwner: Boolean = True): TStream; property StringValue: string read GetStringValue; property SessionExpired: Boolean read FSessionExpired; property SessionID: string read FSessionID; constructor Create(const AStream: TStream; const AResponseCharSet, ASessionID: string; ASessionExpired: Boolean); destructor Destroy; override; property ResponseCharSet: string read FResponseCharSet; end; TDSRestRequest = class strict private FHeaders: TDictionary<string, string>; FResponseStream: TStream; FResponseCharSet: string; FResponseSessionID: string; FResponseSessionExpired: Boolean; FStatus: Integer; FRequestType: string; FUrl: string; FPassword: string; FUsername: string; FHTTP: TDSHTTP; FRequestPragma: string; FFreeResponseStream: Boolean; procedure SendDeleteRequest(var response: string; out responseCode: Integer; out errorMessage: string); procedure SendGetRequest(var response: string; out responseCode: Integer; out errorMessage: string); procedure SendPostRequest(datastream: TStream; var response: string; out responseCode: Integer; out errorMessage: string); procedure SendPutRequest(datastream: TStream; var response: string; out responseCode: Integer; out errorMessage: string); function GetResponseStream(AOwnsObject: Boolean): TStream; private FAccept: string; function GetHTTP: TDSHTTP; procedure DoRequest(var response: string; out responseCode: Integer; out errorMessage: string; ACallback: TProc<TDSHTTP>); public constructor Create(AHTTP: TDSHTTP); destructor Destroy; override; procedure open(const requestType, url, userName, password: string); procedure setRequestHeader(const AName, AValue: string); procedure setRequestPragma(const AValue: string); function send(const paramToSend: string): TDSRestRequestResponse; overload; property Status: Integer read FStatus; property SessionExpired: Boolean read FResponseSessionExpired; property Accept: string read FAccept write FAccept; end; constructor TDSRestCommand.Create(AConnection: TDSCustomRestConnection); begin FConnection := AConnection; end; destructor TDSRestCommand.Destroy; begin FParameters.Free; FDBXContext.Free; FFreeOnExecuteList.Free; inherited; end; // Use "GET" unless parameters types require "POST". Use "POST" because request content, // rather than URL, must be used to pass complex input parameters. function TDSRestCommand.DetermineRequestType(AMetaData: array of TDSRestParameterMetaData): string; function IsKnownJSONTypeName(const Name: UnicodeString): Boolean; begin if not StringIsNil(Name) then begin if CompareText(Copy(Name,0+1,5-(0)), 'TJSON') = 0 then Exit(True); end; Result := False; end; var Item: TDSRestParameterMetaData; LRequiresRequestContent: Boolean; LTypeName: string; begin LRequiresRequestContent := False; for Item in AMetaData do begin case Item.Direction of TDBXParameterDirections.InParameter, TDBXParameterDirections.InOutParameter: begin case Item.DBXType of TDBXDataTypes.TableType, TDBXDataTypes.BinaryBlobType: LRequiresRequestContent := True; TDBXDataTypes.JsonValueType: begin LTypeName := Item.TypeName; if not IsKnownJSONTypeName(LTypeName) then LRequiresRequestContent := True else if SameText(LTypeName, 'TJSONValue') or SameText(LTypeName, 'TJSONObject') or SameText(LTypeName, 'TJSONArray') then // Do not localize LRequiresRequestContent := True; end; end; if LRequiresRequestContent then break; end; end; end; if LRequiresRequestContent then Result := 'POST' // Do not localize else Result := 'GET'; // Do not localize end; procedure TDSRestCommand.Prepare(AMetaData: array of TDSRestParameterMetaData); begin FreeAndNil(FParameters); FParameters := CreateParameters(AMetaData); // Set HTTP verb if not specified if Self.FRequestType = '' then Self.FRequestType := DetermineRequestType(AMetaData); end; procedure TDSRestCommand.Prepare(AProxyMetaData: TDSProxyMetadata); var DSRestParameterMetaDataArray: TArray<TDSRestParameterMetaData>; begin DSRestParameterMetaDataArray := BuildParameterMetaDataArray(AProxyMetaData); Self.Prepare(DSRestParameterMetaDataArray); end; procedure TDSRestCommand.Prepare; var DSRestParameterMetaDataArray: TArray<TDSRestParameterMetaData>; begin DSRestParameterMetaDataArray := BuildParameterMetaDataArray; Self.Prepare(DSRestParameterMetaDataArray); end; function TDSRestCommand.BuildParameterMetaDataArray(AProxyMetaData: TDSProxyMetadata): TArray<TDSRestParameterMetaData>; var MethodStr: string; Index: Integer; DSRestParameterMetaDataArray: TArray<TDSRestParameterMetaData>; ParamCount: Integer; DSProxyClass: TDSProxyClass; DSProxyMethod: TDSProxyMethod; DSProxyParameter: TDSProxyParameter; LClassName: string; LMethodName: string; begin MethodStr := ReplaceStr(Self.Text, '"', ''); Index := Pos('.', MethodStr); if Index < 0 then raise TDSRestException.CreateFmt(sInvalidServerMethodName, [Self.Text]); LClassName := AnsiLeftStr(MethodStr, Index-1); LMethodName := AnsiRightStr(MethodStr, Length(MethodStr)-Index); if MethodStr = Self.Text then // Not quoted begin //adjust method name for REST request storage methods if Self.RequestType = 'PUT' then // Do not localize LMethodName := 'Accept' + LMethodName // Do not localize else if Self.RequestType = 'POST' then // Do not localize LMethodName := 'Update' + LMethodName // Do not localize else if Self.RequestType = 'DELETE' then // Do not localize LMethodName := 'Cancel' + LMethodName; // Do not localize end; DSProxyClass := AProxyMetaData.Classes; while DSProxyClass <> nil do begin if SameText(DSProxyClass.ProxyClassName, LClassName) then begin DSProxyMethod := DSProxyClass.FirstMethod; while DSProxyMethod <> nil do begin if SameText(DSProxyMethod.ProxyMethodName, LMethodName) then begin DSProxyParameter := DSProxyMethod.Parameters; ParamCount := 0; while DSProxyParameter <> nil do begin Inc(ParamCount); SetLength(DSRestParameterMetaDataArray, ParamCount); DSRestParameterMetaDataArray[ParamCount-1].Name := DSProxyParameter.ParameterName; DSRestParameterMetaDataArray[ParamCount-1].Direction := DSProxyParameter.ParameterDirection; DSRestParameterMetaDataArray[ParamCount-1].DBXType := DSProxyParameter.DataType; DSRestParameterMetaDataArray[ParamCount-1].TypeName := DSProxyParameter.TypeName; DSProxyParameter := DSProxyParameter.Next; end; Exit(DSRestParameterMetaDataArray); end; DSProxyMethod := DSProxyMethod.Next; end; end; DSProxyClass := DSProxyClass.Next; end; end; function TDSRestCommand.BuildParameterMetaDataArray: TArray<TDSRestParameterMetaData>; var SessionID: string; DSProxyMetaDataLoaderIntf: IDSProxyMetaDataLoader; DSProxyMetadata: TDSProxyMetadata; begin //preserve original session SessionID := Connection.SessionID; try DSProxyMetaDataLoaderIntf := TDSRestProxyMetaDataLoader.Create(Connection); if DSProxyMetaDataLoaderIntf = nil then raise TDSRestException.Create(SUnableToRetrieveServerMethodParameters); DSProxyMetaData := TDSProxyMetaData.Create; try DSProxyMetaDataLoaderIntf.Load(DSProxyMetaData); Result := BuildParameterMetaDataArray(DSProxyMetaData); finally DSProxyMetaData.Free; end; finally //restore session Self.Connection.SessionID := SessionID; end; end; function TDSRestCommand.CreateParameters(AMetaData: array of TDSRestParameterMetaData): TDBXParameterList; var LParameter: TDBXParameter; LValueTypes: TDBXValueTypeArray; LMemoryRow: TDBXRow; LValueType: TDBXValueType; LMetaData: TDSRestParameterMetaData; I: Integer; LParameterList: TDBXParameterList; begin if FDBXContext = nil then FDBXContext := TDBXContext.Create; SetLength(LValueTypes, Length(AMetaData)); for I := 0 to Length(AMetaData) - 1 do begin LMetaData := AMetaData[I]; LParameter := TDBXParameter.Create(FDBXContext); LParameter.DataType := LMetaData.DBXType; LParameter.ParameterDirection := LMetaData.Direction; LParameter.Name := LMetaData.Name; LParameter.Ordinal := I; LParameter.ConnectionHandler := Self; LParameter.TypeName := LMetaData.TypeName; LValueTypes[I] := LParameter; end; LMemoryRow := TDBXMemoryRow.Create(FDBXContext, LValueTypes); LParameterList := TDBXParameterList.Create(nil, LMemoryRow); for LValueType in LValueTypes do LParameterList.AddParameter(TDBXParameter(LValueType)); Result := LParameterList; end; procedure ExecuteCommand(ACommand: TDSRestCommand; const ARequestFilter: string; const AAccept: string = ''); forward; procedure ExecuteCacheCommand(ACommand: TDSRestCacheCommand; const ARequestType: string; const ACachePath: string; AResponseStreamProc: TDSRestResponseStreamProc; const ARequestFilter: string ); forward; procedure TDSRestCommand.Execute(const ARequestFilter: string); begin BeforeExecute; try if Connection.LoginProperties.LoginPrompt then if not Connection.Login then System.SysUtils.Abort; ExecuteCommand(Self, ARequestFilter); finally AfterExecute; end; end; procedure TDSRestCommand.BeforeExecute; begin FreeAndNil(FFreeOnExecuteList); Connection.BeforeExecute; end; procedure TDSRestCommand.AfterExecute; begin Connection.AfterExecute; end; procedure TDSRestCommand.ExecuteCache(const ARequestFilter: string); begin Connection.BeforeExecute; try if Connection.LoginProperties.LoginPrompt then if not Connection.Login then System.SysUtils.Abort; ExecuteCommand(Self, ARequestFilter, 'application/rest'); finally Connection.AfterExecute; end; end; function TDSRestCommand.GetJSONMarshaler: TJSONMarshal; begin Result := TJSONConverters.GetJSONMarshaler; end; function TDSRestCommand.GetJSONUnMarshaler: TJSONUnMarshal; begin Result := TJSONConverters.GetJSONUnmarshaler; end; procedure TDSRestCommand.FreeOnExecute(Value: TObject); begin if FFreeOnExecuteList = nil then begin FFreeOnExecuteList := TObjectList.Create; FFreeOnExecuteList.OwnsObjects := true; end; if FFreeOnExecuteList.IndexOf(Value) < 0 then FFreeOnExecuteList.Add(Value); end; { TDSRestCacheCommand } constructor TDSRestCacheCommand.Create(AConnection: TDSCustomRestConnection); begin FConnection := AConnection; end; procedure TDSRestCacheCommand.DeleteCommand; begin // Note that the server doesn't support deleting a item associated with a command. So this // will generate an HTTP error. Only the entire cache item can be deleted. if CommandPath = '' then raise TDSRestException.Create(sMissingCommandPath); Execute('DELETE', CommandPath, nil); end; destructor TDSRestCacheCommand.Destroy; begin inherited; end; procedure TDSRestCacheCommand.Execute(const ARequestType, ACachePath: string; AResponseStreamProc: TDSRestResponseStreamProc; const ARequestFilter: string ); begin ExecuteCacheCommand(Self, ARequestType, ACachePath, AResponseStreamProc, ARequestFilter); end; procedure TDSRestCacheCommand.GetCommand(AResponseStreamProc: TDSRestResponseStreamProc); begin if CommandPath = '' then raise TDSRestException.Create(sMissingCommandPath); Execute('GET', CommandPath, AResponseStreamProc); end; function TDSRestCacheCommand.GetCommand(AOwnsObject: Boolean = True): TJSONObject; var LJSONValue: TJSONValue; LPair: TJSONPair; LResult: TJSONObject; begin LResult := nil; GetCommand( procedure(AStream: TStream; const AResponseCharSet: string; var AOwnsStream: Boolean) var LString: string; begin if AStream <> nil then begin AStream.Position := 0; LString := IPProcs(Connection.IPImplementationID).ReadStringAsCharset(AStream, AResponseCharSet); AOwnsStream := True; // Don't keep stream LJSONValue := TJSONObject.ParseJSONValue(BytesOf(LString), 0); try if LJSONValue is TJSONObject then begin LPair := TJSONObject(LJSONValue).Get('result'); if (LPair <> nil) and (LPair.JSONValue is TJSONObject) then begin LResult := TJSONObject(LPair.JSONValue); // TJSONArray(LPair.JSONValue); if LResult <> nil then LResult.Owned := False; end end; finally LJSONValue.Free; end; end; end ); Result := LResult; end; function TDSRestCacheCommand.GetCommandPath: string; var LLast: Integer; begin LLast := System.SysUtils.LastDelimiter('/', FParameterPath); if LLast > 0 then Result := Copy(FParameterPath, 1, LLast-1) else Result := ''; end; procedure TDSRestCacheCommand.GetParameter(out AJSONValue: TJSONValue; const ARequestFilter: string); var LJSONValue: TJSONValue; LResult: TJSONValue; LPair: TJSONPair; begin LResult := nil; GetParameter( procedure(AStream: TStream; const AResponseCharSet: string; var AOwnsStream: Boolean) var LString: string; begin if AStream <> nil then begin AStream.Position := 0; LString := IPProcs(Connection.IPImplementationID).ReadStringAsCharset(AStream, AResponseCharSet); AOwnsStream := True; // Don't keep stream LJSONValue := TJSONObject.ParseJSONValue(BytesOf(LString), 0); try if LJSONValue is TJSONObject then begin LPair := TJSONObject(LJSONValue).Get('result'); if (LPair <> nil) then //and (LPair.JSONValue is TJSONArray) then begin LResult := LPair.JSONValue; // TJSONArray(LPair.JSONValue); if LResult <> nil then LResult.Owned := False; end end; finally LJSONValue.Free; end; end; end, ARequestFilter); AJSONValue := LResult; end; procedure TDSRestCacheCommand.GetParameter(out AStream: TStream; AOwnsObject: Boolean; const ARequestFilter: string = ''); var LJSONValue: TJSONValue; LResult: TStream; LPair: TJSONPair; LString: string; LJSONArray: TJSONArray; begin LResult := nil; GetParameter( procedure(AStream: TStream; const AResponseCharSet: string; var AOwnsStream: Boolean) begin AStream.Position := 0; // ResponseCharSet should identify as binary stream LString := IPProcs(Connection.IPImplementationID).ReadStringAsCharset(AStream, AResponseCharSet); LJSONValue := TJSONObject.ParseJSONValue(BytesOf(LString), 0); try if LJSONValue is TJSONObject then begin LPair := TJSONObject(LJSONValue).Get('result'); if (LPair <> nil) and(LPair.JSONValue is TJSONArray) then begin LJSONArray := TJSONArray(LPair.JSONValue); LResult := TDBXJSONTools.JSONToStream(LJSONArray); end end else if LJSONValue = nil then begin // Assume binary AStream.Position := 0; LResult := AStream; if AOwnsObject then AOwnsStream := AOwnsObject; end; finally LJSONValue.Free; end; end, ARequestFilter); AStream := LResult; end; procedure TDSRestCacheCommand.GetParameter(AResponseStreamProc: TDSRestResponseStreamProc; const ARequestFilter: string); begin if FParameterPath = '' then raise TDSRestException.Create(sMissingParameterPath); Execute('GET', FParameterPath, AResponseStreamProc, ARequestFilter); end; function EncodeCharSet(const AStr: string; ACharSet: TSysCharSet): string; var Sp, Rp: PChar; begin SetLength(Result, Length(AStr) * 3); Sp := PChar(AStr); Rp := PChar(Result); while Sp^ <> #0 do begin if not System.SysUtils.CharInSet(Sp^, ACharSet) then Rp^ := Sp^ else begin FormatBuf(Rp, 3, '%%%.2x', 6, [Ord(Sp^)]); Inc(Rp,2); end; Inc(Rp); Inc(Sp); end; SetLength(Result, (Rp - PChar(Result))); end; function EncodeURIComponent(const AStr: string; const AIPImplementationID: string = ''): string; overload; const EncodeURIComponentCharSet = ['@', '$', '&', '=', ':', '/', ',', ';', '?', '+']; begin Result := EncodeCharSet(IPProcs(AIPImplementationID).ParamsEncode(AStr), EncodeURIComponentCharSet); end; function encodeURIComponent(const AValue: TDBXParameter; const AIPImplementationID: string = ''): string; overload; var LStringValue: string; begin case AValue.DataType of TDBXDataTypes.DoubleType, TDBXDataTypes.SingleType, TDBXDataTypes.CurrencyType, TDBXDataTypes.BcdType: // Use consistent decimal separator LStringValue := TDBXPlatform.JsonFloat(AValue.Value.AsDouble); else if AValue.Value.IsNull then LStringValue := 'null' else LStringValue := AValue.Value.AsString; end; Result := encodeURIComponent(LStringValue, AIPImplementationID); end; function IsUrlParameter(const AValue: TDBXParameter): Boolean; var LTypeName: string; begin LTypeName := AValue.TypeName; if AValue.DataType = TDBXDataTypes.TableType then Exit(False); if AValue.DataType = TDBXDataTypes.BinaryBlobType then Exit(False); if AValue.DataType = TDBXDataTypes.JSONValueType then if not SameText(Copy(LTypeName,0+1,5-(0)), 'TJSON') then Exit(False) else if SameText(LTypeName, 'TJSONValue') or SameText(LTypeName, 'TJSONObject') or SameText(LTypeName, 'TJSONArray') then Exit(False); Result := True; end; procedure ExecuteRequest(AHTTP: TDSHTTP; const AURL, LRequestType, LUserName, LPassword: string; LParameters: TDBXParameterList; const ARequestFilter, AAccept: string; var ASessionID: string; LSessionExpired: TProc; LSetSessionID: TProc<string>); forward; procedure ExecuteCommand(ACommand: TDSRestCommand; const ARequestFilter, AAccept: string); overload; var LPathPrefix: string; LPort: Integer; LHost: string; LPortString: string; LUrl: string; LMethodName: string; LContext: string; LProtocol: string; LSessionID: string; LIPImplementationID: string; begin LIPImplementationID := ACommand.Connection.IPImplementationID; LPathPrefix := ACommand.Connection.UrlPath; LPort := ACommand.Connection.Port; LHost := ACommand.Connection.Host; LMethodName := ACommand.Text; LProtocol := ACommand.Connection.HTTP.Protocol; if LProtocol = '' then LProtocol := 'http'; if LHost = '' then LHost := 'localhost'; if LPathPrefix <> '' then LPathPrefix := '/' + LPathPrefix; if LPort > 0 then LPortString := ':' + IntToStr(LPort); LMethodName := StringReplace(LMethodName, '.', '/', []); LMethodName := StringReplace(LMethodName, '"', '%22', [rfReplaceAll]); // Encode quotes LContext := ACommand.Connection.Context; if LContext = '' then LContext := 'datasnap/'; LUrl := LProtocol + '://' + encodeURIComponent(LHost, LIPImplementationID) + LPortString + LpathPrefix + '/' + LContext + 'rest/' + LMethodName + '/'; LSessionID := ACommand.Connection.SessionID; ExecuteRequest(ACommand.Connection.HTTP, LURL, ACommand.RequestType, ACommand.Connection.LoginProperties.UserName, ACommand.Connection.LoginProperties.Password, ACommand.Parameters, ARequestFilter, AAccept, LSessionID, procedure begin ACommand.Connection.SessionExpired; end, procedure(ASessionID: string) begin if ASessionID <> '' then ACommand.Connection.SessionID := ASessionID; end); end; procedure ExecuteRequest(AHTTP: TDSHTTP; const AURL, LRequestType, LUserName, LPassword: string; LParameters: TDBXParameterList; const ARequestFilter, AAccept: string; var ASessionID: string; LSessionExpired: TProc; LSetSessionID: TProc<string>); overload; function ParameterToJSon(AParameter: TDBXParameter; out ACanFree: Boolean): TJSONValue; begin ACanFree := True; if AParameter.Value = nil then Result := nil else if AParameter.Value.IsNull then Result := TJSONNull.Create else case AParameter.DataType of TDBXDataTypes.JsonValueType: begin Result := AParameter.Value.GetJSONValue; ACanFree := False; end; TDBXDataTypes.TableType: Result := TDBXJSONTools.TableToJSON(AParameter.Value.GetDBXReader, High(Integer), False); TDBXDataTypes.BlobType, TDBXDataTypes.BinaryBlobType: Result := TDBXJSONTools.StreamToJSON(AParameter.Value.GetStream, 0, High(Integer)); else Result := TDBXJSONTools.DBXToJSON(AParameter.Value, AParameter.DataType, True (* Local connection *)); end; end; var LUrl: string; LParametersToSend: TList<TDBXParameter>; LParametersToSendInContent: TList<TDBXParameter>; LParameter: TDBXParameter; LWritingUrl: Boolean; LOrdinal: Integer; LRequest: TDSRestRequest; LStringToSend: string; LJSONToSend: TJSONValue; LResponseText: TDSRestRequestResponse; LResponseJSON: TJSONValue; LJSONParameterValuePair: TJSONPair; LJSONParameterValue: TJSONValue; LJSONResultArray: TJSONArray; LJSONResultArrayIndex: Integer; LJSONArray: TJSONArray; LJSONObject: TJSONObject; LCanFree: Boolean; LValueToFree: TJSONValue; begin LURL := AURL; LParametersToSend := TList<TDBXParameter>.Create; LParametersToSendInContent := nil; try if LParameters <> nil then for LOrdinal := 0 to LParameters.Count - 1 do begin LParameter := LParameters[LOrdinal]; if (LParameter.ParameterDirection = TDBXParameterDirections.InParameter) or (LParameter.ParameterDirection = TDBXParameterDirections.InOutParameter) then LParametersToSend.Add(LParameter); end; if (LRequestType = 'GET') or (LRequestType = '') or (LRequestType = 'DELETE') then begin for LParameter in LParametersToSend do LUrl := LUrl + encodeURIComponent(LParameter, AHTTP.IPImplementationID) + '/'; end else begin LParametersToSendInContent := TList<TDBXParameter>.Create; LWritingUrl := True; for LParameter in LParametersToSend do begin if LWritingUrl then if IsUrlParameter(LParameter) then LUrl := LUrl + encodeURIComponent(LParameter, AHTTP.IPImplementationID) + '/' else begin LParametersToSendInContent.Add(LParameter); LWritingUrl := False end else LParametersToSendInContent.Add(LParameter); end; end; if ARequestFilter <> '' then begin if not System.StrUtils.EndsText('/', LUrl) then LUrl := LUrl + '/'; if ARequestFilter[1] = '?' then LUrl := LUrl + ARequestFilter else LUrl := LUrl + '?' + ARequestFilter; end; LRequest := TDSRestRequest.Create(AHTTP); try LRequest.open(LRequestType, LUrl, LUserName, LPassword); if (LParametersToSendInContent <> nil) and (LParametersToSendInContent.Count > 0) then begin LValueToFree := nil; try if LParametersToSendInContent.Count = 1 then begin LJSONToSend := ParameterToJSon(LParametersToSendInContent[0], LCanFree); if LCanFree then LValueToFree := LJSONToSend; end else begin LJSONArray := TJSONArray.Create; for LParameter in LParametersToSendInContent do begin LJSONToSend := ParameterToJSon(LParameter, LCanFree); LJSONArray.AddElement(LJSONToSend); if not LCanFree then LJSONToSend.Owned := False; end; LJSONObject := TJSONObject.Create; LJSONObject.AddPair('_parameters', LJSONArray); LJSONToSend := LJSONObject; LValueToFree := LJSONObject; end; LStringToSend := LJSONToSend.ToString; finally LValueToFree.Free; end; end; if AAccept <> '' then Lrequest.Accept := AAccept else Lrequest.Accept := 'application/JSON'; // Do not localize Lrequest.SetRequestHeader('Content-Type', 'text/plain;charset=UTF-8'); // Do not localize Lrequest.SetRequestHeader('If-Modified-Since', 'Mon, 1 Oct 1990 05:00:00 GMT'); // Do not localize if ASessionId <> '' then Lrequest.SetRequestPragma(sDSSessionEquals + ASessionId); LResponseText := LRequest.send(LStringToSend); try if LResponseText.SessionExpired then LSessionExpired else LSetSessionID(LResponseText.SessionID); LResponseJSON := TJSONObject.ParseJSONValue(BytesOf(LResponseText.StringValue), 0); try if LResponseJSON <> nil then begin LJSONParameterValuePair := TJSONObject(LResponseJSON).Get('result'); if LJSONParameterValuePair.JSONValue is TJSONArray then LJSONResultArray := TJSONArray(LJSONParameterValuePair.JSONValue) else LJSONResultArray := nil; if LJSONResultArray <> nil then begin LJSONResultArrayIndex := 0; if LParameters <> nil then for LOrdinal := 0 to LParameters.Count - 1 do begin LParameter := LParameters[LOrdinal]; LJSONParameterValue := nil; if (LParameter.ParameterDirection = TDBXParameterDirections.ReturnParameter) or (LParameter.ParameterDirection = TDBXParameterDirections.InOutParameter) or (LParameter.ParameterDirection = TDBXParameterDirections.OutParameter) then if LJSONResultArray.Size = 1 then LJSONParameterValue := LJSONResultArray.Get(0) else begin LJSONParameterValue := LJSONResultArray.Get(LJSONResultArrayIndex); Inc(LJSONResultArrayIndex); end; if LJSONParameterValue <> nil then begin // Must clone some types case LParameter.DataType of TDBXDataTypes.TableType: begin TDBXJSONTools.JSONToDBX(TJSONValue(LJSONParameterValue.Clone), LParameter.Value, LParameter.DataType, True (* Local connection *), True (* Owns Clone *)); end; TDBXDataTypes.JSONValueType: begin TDBXJSONTools.JSONToDBX(TJSONValue(LJSONParameterValue.Clone), LParameter.Value, LParameter.DataType, True (* Local connection *), True (* Owns Clone *)); end else TDBXJSONTools.JSONToDBX(LJSONParameterValue, LParameter.Value, LParameter.DataType, True (* Local connection *)); end; end; end; end; end else begin // Stream result if LParameters <> nil then for LOrdinal := 0 to LParameters.Count - 1 do begin LParameter := LParameters[LOrdinal]; if (LParameter.ParameterDirection = TDBXParameterDirections.ReturnParameter) or (LParameter.ParameterDirection = TDBXParameterDirections.InOutParameter) or (LParameter.ParameterDirection = TDBXParameterDirections.OutParameter) then if LParameter.DataType = TDBXDataTypes.BinaryBlobType then begin LParameter.Value.SetStream(LResponseText.GetStream(False), True); break; end; end; end; finally LResponseJSON.Free; end; finally LResponseText.Free; end; finally LRequest.Free; end; finally LParametersToSend.Free; LParametersToSendInContent.Free; end; end; procedure ExecuteCacheRequest(AHTTP: TDSHTTP; const LRequestType: string; const AURL, LUserName, LPassword: string; const ARequestFilter: string; const ACachePath: string; var ASessionID: string; LSessionExpired: TProc; LSetSessionID: TProc<string>; AResponseStreamProc: TDSRestResponseStreamProc ); forward; procedure ExecuteCacheCommand(ACommand: TDSRestCacheCommand; const ARequestType: string; const ACachePath: string; AResponseStreamProc: TDSRestResponseStreamProc; const ARequestFilter: string ); var LPathPrefix: string; LPort: Integer; LHost: string; LPortString: string; LUrl: string; // LMethodName: string; LContext: string; LProtocol: string; LSessionID: string; //LParameterPath: string; LIPImplementationID: string; begin LIPImplementationID := ACommand.Connection.IPImplementationID; LPathPrefix := ACommand.Connection.UrlPath; LPort := ACommand.Connection.Port; LHost := ACommand.Connection.Host; // LMethodName := ACommand.Text; LProtocol := ACommand.Connection.HTTP.Protocol; // LParameterPath := ACommand.ParameterPath; if LProtocol = '' then LProtocol := 'http'; if LHost = '' then LHost := 'localhost'; if LPathPrefix <> '' then LPathPrefix := '/' + LPathPrefix; if LPort > 0 then LPortString := ':' + IntToStr(LPort); // LMethodName := StringReplace(LMethodName, '.', '/', []); LContext := ACommand.Connection.Context; if LContext = '' then LContext := 'datasnap/'; LUrl := LProtocol + '://' + encodeURIComponent(LHost, LIPImplementationID) + LPortString + LpathPrefix + '/' + LContext + 'cache' + '/'; LSessionID := ACommand.Connection.SessionID; ExecuteCacheRequest(ACommand.Connection.HTTP, ARequestType, LURL, ACommand.Connection.LoginProperties.UserName, ACommand.Connection.LoginProperties.Password, ARequestFilter, ACachePath, LSessionID, procedure begin ACommand.Connection.SessionExpired; end, procedure(ASessionID: string) begin if ASessionID <> '' then ACommand.Connection.SessionID := ASessionID; end, AResponseStreamProc); end; procedure ExecuteCacheRequest(AHTTP: TDSHTTP; const LRequestType: string; const AURL, LUserName, LPassword: string; const ARequestFilter: string; const ACachePath: string; var ASessionID: string; LSessionExpired: TProc; LSetSessionID: TProc<string>; AResponseStreamProc: TDSRestResponseStreamProc ); var LUrl: string; LRequest: TDSRestRequest; LResponseText: TDSRestRequestResponse; LObjectOwner: Boolean; begin LURL := AURL; LURL := LURL + ACachePath; if ARequestFilter <> '' then begin if not System.StrUtils.EndsText('/', LUrl) then LUrl := LUrl + '/'; if ARequestFilter[1] = '?' then LUrl := LUrl + ARequestFilter else LUrl := LUrl + '?' + ARequestFilter; end; LRequest := TDSRestRequest.Create(AHTTP); try LRequest.open(LRequestType, LUrl, LUserName, LPassword); Lrequest.Accept := 'application/JSON'; // Do not localize Lrequest.SetRequestHeader('Content-Type', 'text/plain;charset=UTF-8'); // Do not localize Lrequest.SetRequestHeader('If-Modified-Since', 'Mon, 1 Oct 1990 05:00:00 GMT'); // Do not localize if ASessionId <> '' then Lrequest.SetRequestPragma(sDSSessionEquals + ASessionId); LResponseText := LRequest.send(''); try if LResponseText.SessionExpired then LSessionExpired else LSetSessionID(LResponseText.SessionID); if Assigned(AResponseStreamProc) then begin LObjectOwner := False; AResponseStreamProc(LResponseText.GetStream, LResponseText.ResponseCharSet, LObjectOwner); if not LObjectOwner then LResponseText.GetStream(False); end; finally LResponseText.Free; end; finally LRequest.Free; end; end; { TDSCustomRestConnection } procedure TDSCustomRestConnection.AfterExecute; begin if Assigned(OnAfterExecute) then OnAfterExecute(Self); end; procedure TDSCustomRestConnection.AssignTo(Dest: TPersistent); begin if Dest is TDSCustomRestConnection then begin TDSCustomRestConnection(Dest).Host := Host; TDSCustomRestConnection(Dest).Port := Port; TDSCustomRestConnection(Dest).UrlPath := UrlPath; TDSCustomRestConnection(Dest).UserName := UserName; TDSCustomRestConnection(Dest).Password := Password; TDSCustomRestConnection(Dest).Context := Context; TDSCustomRestConnection(Dest).SessionID := SessionID; TDSCustomRestConnection(Dest).PreserveSessionID := PreserveSessionID; TDSCustomRestConnection(Dest).OnLogin := OnLogin; TDSCustomRestConnection(Dest).OnValidatePeerCertificate := OnValidatePeerCertificate; end else inherited; end; procedure TDSCustomRestConnection.BeforeExecute; begin if not PreserveSessionID then SessionID := ''; if Assigned(OnBeforeExecute) then OnBeforeExecute(Self); end; constructor TDSCustomRestConnection.Create(AOwner: TComponent); begin inherited; FProxyPort := 8888; FLoginProperties := TDSRestLoginProperties.Create; FPreserveSessionID := True; LoginPrompt := True; FIPImplementationID := ''; FConnectionKeepAlive := 'Keep-Alive'; end; function TDSCustomRestConnection.CreateCommand: TDSRestCommand; begin Result := TDSRestCommand.Create(Self); end; procedure TDSCustomRestConnection.DefineProperties(Filer: TFiler); function DesignerDataStored: Boolean; begin if Filer.Ancestor <> nil then Result := TDSCustomRestConnection(Filer.Ancestor).UniqueId <> UniqueId else Result := UniqueId <> ''; end; begin inherited; Filer.DefineProperty('UniqueId', ReadUniqueId, WriteUniqueId, DesignerDataStored); end; destructor TDSCustomRestConnection.Destroy; begin FLoginProperties.Free; FHTTP.Free; inherited; end; function TDSCustomRestConnection.GetConnection: String; begin if Assigned(FHTTP) then Result := HTTP.Request.Connection else Result := FConnectionKeepAlive; end; function TDSCustomRestConnection.GetHTTP: TDSHTTP; var LProtocol: string; begin if FHTTP = nil then begin LProtocol := DefaultProtocol; FHTTP := TDSHTTP.ProtocolClass(LProtocol).Create(nil, FIPImplementationID); // call virtual constructor FHTTP.OnValidatePeerCertificate := FOnValidateCertificate; FHTTP.Request.Connection := FConnectionKeepAlive; FHTTP.HTTPOptions := [hoKeepOrigProtocol]; FHTTP.ProxyParams.ProxyServer := FProxyHost; FHTTP.ProxyParams.ProxyPort := FProxyPort; FHTTP.ProxyParams.ProxyUsername := FProxyUsername; FHTTP.ProxyParams.ProxyPassword := FProxyPassword; FHTTP.ProxyParams.BasicAuthentication := FProxyUsername <> EmptyStr; end; Result := FHTTP; end; function TDSCustomRestConnection.GetLoginPrompt: Boolean; begin if not (csDesigning in ComponentState) then Result := FLoginProperties.LoginPrompt else Result := FLoginPrompt; end; function TDSCustomRestConnection.GetPassword: string; begin if not (csDesigning in ComponentState) then Result := FLoginProperties.Password else Result := FPassword; end; function TDSCustomRestConnection.GetProxyHost: String; begin if Assigned(FHTTP) then Result := HTTP.ProxyParams.ProxyServer else Result := FProxyHost; end; function TDSCustomRestConnection.GetProxyPassword: String; begin if Assigned(FHTTP) then Result := HTTP.ProxyParams.ProxyPassword else Result := FProxyPassword; end; function TDSCustomRestConnection.GetIPImplementationID: string; begin if Assigned(FHTTP) then Result := HTTP.IPImplementationID else Result := FIPImplementationID; end; function TDSCustomRestConnection.GetProxyPort: Integer; begin if Assigned(FHTTP) then Result := HTTP.ProxyParams.ProxyPort else Result := FProxyPort; end; function TDSCustomRestConnection.GetProxyUsername: String; begin if Assigned(FHTTP) then Result := HTTP.ProxyParams.ProxyUsername else Result := FProxyUsername; end; function TDSCustomRestConnection.DefaultProtocol: string; begin if FProtocol = '' then Result := 'http' else Result := FProtocol; end; function TDSCustomRestConnection.GetUserName: string; begin if not (csDesigning in ComponentState) then Result := FLoginProperties.Username else Result := FUserName; end; function TDSCustomRestConnection.GetOnValidatePeerCertificate: TValidateCertificate; begin if FHTTP <> nil then Result := FHTTP.OnValidatePeerCertificate else Result := FOnValidateCertificate; end; procedure TDSCustomRestConnection.ReadUniqueId(Reader: TReader); begin FUniqueID := Reader.ReadString; end; procedure TDSCustomRestConnection.SessionExpired; begin FSessionID := ''; end; procedure TDSCustomRestConnection.SetConnection(const KeepAlive: String); begin FConnectionKeepAlive := KeepAlive; if Assigned(FHTTP) then HTTP.Request.Connection := KeepAlive; end; procedure TDSCustomRestConnection.SetContext(const Value: string); begin if (Value <> EmptyStr) and (Value[Length(Value)] <> '/') then FContext := FContext + '/' else FContext := Value; end; procedure TDSCustomRestConnection.SetLoginPrompt(const Value: Boolean); begin FLoginPrompt := Value; FLoginProperties.LoginPrompt := Value; end; procedure TDSCustomRestConnection.SetPassword(const Value: string); begin FPassword := Value; FLoginProperties.Password := Value; end; procedure TDSCustomRestConnection.SetProtocol(const Value: string); begin if FProtocol <> Value then Reset; FProtocol := Value; end; procedure TDSCustomRestConnection.SetProxyHost(const Value: String); begin FProxyHost := Value; if Assigned(FHTTP) then HTTP.ProxyParams.ProxyServer := Value end; procedure TDSCustomRestConnection.SetProxyPassword(const Value: String); begin FProxyPassword := Value; if Assigned(FHTTP) then HTTP.ProxyParams.ProxyPassword := Value end; procedure TDSCustomRestConnection.SetIPImplementationID(const Value: string); begin if FIPImplementationID <> Value then begin if Assigned(FHTTP) then raise TDSRestException.Create(sCannotChangeIPImplID); FIPImplementationID := Value; end; end; procedure TDSCustomRestConnection.SetProxyPort(const Value: Integer); begin FProxyPort := Value; if Assigned(FHTTP) then HTTP.ProxyParams.ProxyPort := Value; end; procedure TDSCustomRestConnection.SetProxyUsername(const Value: String); begin FProxyUsername := Value; if Assigned(FHTTP) then begin HTTP.ProxyParams.ProxyUsername := Value; HTTP.ProxyParams.BasicAuthentication := Value <> EmptyStr; end; end; procedure TDSCustomRestConnection.Reset; begin FreeAndNil(FHTTP); end; procedure TDSCustomRestConnection.SetUserName(const Value: string); begin if FUserName <> Value then begin SessionID := ''; FUserName := Value; FLoginProperties.UserName := Value; end; end; procedure TDSCustomRestConnection.SetOnValidatePeerCertificate( const Value: TValidateCertificate); begin FOnValidateCertificate := Value; if FHTTP <> nil then FHTTP.OnValidatePeerCertificate := Value; end; procedure TDSCustomRestConnection.TestConnection( AOptions: TDSTestConnectionOptions); var LSaveLoginPrompt: Boolean; LClient: TDSAdminRestClient; LPlatformName: string; begin LSaveLoginPrompt := LoginProperties.LoginPrompt; if toNoLoginPrompt in AOptions then LoginProperties.LoginPrompt := False; try LClient := TDSAdminRestClient.Create(Self); try LPlatformName := LClient.GetPlatformName; if LPlatformName = '' then raise TDSRestException.Create(sUnexpectedResult); finally LClient.Free; end; finally if toNoLoginPrompt in AOptions then LoginProperties.LoginPrompt := LSaveLoginPrompt; try Self.HTTP.Disconnect; except end; end; end; procedure TDSCustomRestConnection.WriteUniqueId(Writer: TWriter); begin Writer.WriteString(FUniqueID); end; function TDSCustomRestConnection.Login: Boolean; var LCancel: Boolean; function Login: Boolean; begin Result := (not (csDesigning in ComponentState)) and Assigned(FOnLogin); if Result then FOnLogin(Self, FLoginProperties, LCancel); end; begin LCancel := False; if not Login then begin if Assigned(DSRestLoginDialogProc) then begin if not DSRestLoginDialogProc(Self, FLoginProperties, LoginDialogTestConnection) then LCancel := True; end; end; Result := not LCancel; end; procedure TDSCustomRestConnection.LoginDialogTestConnection; begin TestConnection([toNoLoginPrompt]); end; { TDSRestRequest } procedure TDSRestRequest.open(const requestType, url, userName, password: string); begin FHeaders := TDictionary<string, string>.Create; FRequestType := UpperCase(requestType); FUrl := url; FUserName := userName; FPassword := password; end; destructor TDSRestRequest.Destroy; begin inherited; FHeaders.Free; if FFreeResponseStream then FResponseStream.Free; end; function TDSRestRequest.send(const paramToSend: string): TDSRestRequestResponse; var LStream: TStream; LResponseText: string; LJSONValue: TJSONValue; LErrorMessage: string; begin Result := nil; LStream := nil; try if FResponseStream = nil then FResponseStream := TMemoryStream.Create; if (FRequestType = 'GET') or (FRequestType = '') then SendGetRequest(LResponseText, FStatus, LErrorMessage) else if FRequestType = 'PUT' then begin LStream := TStringStream.Create(paramToSend, TEncoding.UTF8); SendPutRequest(LStream, LResponseText, FStatus, LErrorMessage); end else if FRequestType = 'POST' then begin LStream := TStringStream.Create(paramToSend, TEncoding.UTF8); SendPostRequest(LStream, LResponseText, FStatus, LErrorMessage); end else if FRequestType = 'DELETE' then SendDeleteRequest(LResponseText, FStatus, LErrorMessage) else raise TDSRestException.CreateFmt(SUnexpectedRequestType, [FRequestType]); //handle session timeouts (status = 403) and other session and authorization related errors if FStatus = 403 then begin Result := TDSRestRequestResponse.Create(GetResponseStream(False), FResponseCharSet, '', False); try Result.FIPImplementationID := FHTTP.IPImplementationID; LJSONValue := TJSONObject.ParseJSONValue(BytesOf(Result.StringValue), 0); if (LJSONValue <> nil) and (LJSONValue is TJSONObject) and (TJSONObject(LJSONValue).Get('SessionExpired') <> nil) then FResponseSessionExpired := True; finally FreeAndNil(Result); end; end; if (FStatus <> 200) and (FStatus <> 201) and (FStatus <> 202) then raise TDSRestProtocolException.Create(FStatus, LResponseText, LErrorMessage); Result := TDSRestRequestResponse.Create(GetResponseStream(False), FResponseCharSet, FResponseSessionID, FResponseSessionExpired); Result.FIPImplementationID := FHTTP.IPImplementationID; finally LStream.Free; end; end; procedure TDSRestRequest.setRequestHeader(const AName, AValue: string); begin if not FHeaders.ContainsKey(AName) then FHeaders.Add(AName, AValue) else FHeaders[AName] := AValue; end; procedure TDSRestRequest.setRequestPragma(const AValue: string); begin FRequestPragma := AValue; end; constructor TDSRestRequest.Create(AHTTP: TDSHTTP); begin FFreeResponseStream := True; FHTTP := AHTTP; end; function TDSRestRequest.GetHTTP: TDSHTTP; var P: TPair<string, string>; begin Result := FHTTP; Result.Request.Accept := Accept; if Result.Request.Authentication <> nil then begin Result.Request.Authentication.Username := FUserName; Result.Request.Authentication.Password := FPassword; end else Result.SetBasicAuthentication(FUserName, FPassword); FResponseStream.Size := 0; Result.Request.CustomHeaders.Clear; for P in FHeaders do Result.Request.CustomHeaders.AddValue(P.Key, P.Value); Result.Request.Pragma := FRequestPragma; end; function TDSRestRequest.GetResponseStream(AOwnsObject: Boolean): TStream; begin Result := FResponseStream; if (Result <> nil) and (not AOwnsObject) then FFreeResponseStream := False; end; procedure TDSRestRequest.DoRequest(var response: string; out responseCode: Integer; out errorMessage: string; ACallback: TProc<TDSHTTP>); var Http: TDSHTTP; LPragma: string; LPos: Integer; begin errorMessage := ''; Http := GetHTTP; try ACallback(Http); FResponseCharSet := Http.Response.Charset; responseCode := http.ResponseCode; //FResponseSessionID := Http.Response.CustomHeaders.Values['dssession']; LPragma := Http.Response.Pragma; LPos := Pos(sDSSessionEquals, LPragma); if LPos > 0 then begin LPragma := Copy(LPragma, LPos+Length(sDSSessionEquals), MaxInt); LPos := Pos(',', LPragma); if LPos > 0 then Delete(LPragma, LPos, MaxInt); FResponseSessionID := LPragma; end else FResponseSessionID := ''; except on PE: EIPHTTPProtocolExceptionPeer do begin responseCode := PE.ErrorCode; errorMessage := PE.ErrorMessage; response := PE.Message; end; on E: Exception do raise; end; end; procedure TDSRestRequest.SendGetRequest(var response: string; out responseCode: Integer; out errorMessage: string); begin DoRequest(response, responseCode, errorMessage, procedure(Http: TDSHTTP) begin Http.Get(FURL, FResponseStream); end ); end; procedure TDSRestRequest.SendPutRequest(datastream: TStream; var response: string; out responseCode: Integer; out errorMessage: string); begin DoRequest(response, responseCode, errorMessage, procedure(Http: TDSHTTP) begin Http.Put(FURL, dataStream, FResponseStream); end ); end; procedure TDSRestRequest.SendPostRequest(datastream: TStream; var response: string; out responseCode: Integer; out errorMessage: string); begin DoRequest(response, responseCode, errorMessage, procedure(Http: TDSHTTP) begin http.Post(FURL, dataStream, FResponseStream); end ); end; procedure TDSRestRequest.SendDeleteRequest(var response: string; out responseCode: Integer; out errorMessage: string); begin DoRequest(response, responseCode, errorMessage, procedure(Http: TDSHTTP) begin http.Delete(FURL, FResponseStream); end ); end; { TDSRestRequestResponse } constructor TDSRestRequestResponse.Create(const AStream: TStream; const AResponseCharSet, ASessionID: string; ASessionExpired: Boolean); begin FFreeStreamValue := True; AStream.Position := 0; FStreamValue := AStream; FResponseCharSet := AResponseCharSet; FSessionID := ASessionID; FSessionExpired := ASessionExpired; end; function TDSRestRequestResponse.GetStringValue: string; begin if not FHaveString then begin FHaveString := True; FStreamValue.Position := 0; FStringValue := IPProcs(FIPImplementationID).ReadStringAsCharset(FStreamValue, FResponseCharset); end; Result := FStringValue; end; destructor TDSRestRequestResponse.Destroy; begin if FFreeStreamValue then FreeAndNil(FStreamValue); inherited; end; function TDSRestRequestResponse.GetStream(AObjectOwner: Boolean): TStream; begin Result := FStreamValue; if not AObjectOwner then FFreeStreamValue := False; end; { TDSRestLoginProperties } procedure TDSRestLoginProperties.AssignTo(Dest: TPersistent); begin if Dest is TDSRestLoginProperties then begin TDSRestLoginProperties(Dest).UserName := UserName; TDSRestLoginProperties(Dest).Password := Password; TDSRestLoginProperties(Dest).LoginPrompt := LoginPrompt; end else inherited; end; (* * Class for registering a callback which will update callbacks on the client when invoked from * the server. A channel on the server is a manager for a specific object on the source which can * send out notifications. Registering a client callback hooks that callback in to be notified * of changes by the server. * @param AChannelId the unique identifier for this client channel (callback) * @param AServerChannelName the unique name of the server channel * @param AConnection TDSRestConnection *) constructor TDSRestClientChannel.Create(const AChannelId, AServerChannelName: string; AConnection: TDSCustomRestConnection); begin FConnection := AConnection; FCallbacks := TObjectList<TDSRestClientCallback>.Create(True (* Owns *)); FServerChannelName := AServerChannelName; FCallbackLoop := nil; FChannelId := AChannelId; FChannelEvent := nil; end; (* * Registers a client callback with the server. * @param AClientCallback an instance of TClientCallback *) procedure TDSRestClientChannel.RegisterCallback(AClientCallback: TDSRestClientCallback); var LClient: TDSAdminRestClient; begin if not Connected then begin Connect(AClientCallback); Exit; end; TMonitor.Enter(FCallbacks); try if (FCallbackLoop <> nil) then begin if not FCallbacks.Contains(AClientCallback) then FCallbacks.Add(AClientCallback); LClient := TDSAdminRestClient.Create(FConnection, False); try if LClient.RegisterClientCallbackServer(FchannelId, AClientCallback.callbackId, AClientCallback.ChannelNames.CommaText) then NotifyEvent(rCallbackAdded, AClientCallback); finally LClient.Free; end; end; finally TMonitor.Exit(FCallbacks); end; end; (* * Unregisters a client callback from the server. * @param AClientCallback the callback to unregister *) procedure TDSRestClientChannel.UnregisterCallback(AClientCallback: TDSRestClientCallback); var LClient: TDSAdminRestClient; LCallbackId: string; begin TMonitor.Enter(FCallbacks); try LCallbackId := AClientCallback.CallbackId; NotifyEvent(rCallbackRemoved, AClientCallback); // Frees AClientCallback FCallbacks.Remove(AClientCallback); LClient := TDSAdminRestClient.Create(FConnection, False); try LClient.UnregisterClientCallback(FchannelId, LCallbackId); finally LClient.Free; end; finally TMonitor.Exit(FCallbacks); end; end; (* * Connects the client channel, registering a callback, as the channel can only * be open if at least one callback is registered. * @param AFirstCallback an instance of TClientCallback *) procedure TDSRestClientChannel.Connect(AFirstCallback: TDSRestClientCallback); begin TMonitor.Enter(FCallbacks); try if (FCallbackLoop <> nil) then begin FCallbackLoop.Stop; FreeAndNil(FCallbackLoop); end; FCallbacks.Clear; FCallbacks.Add(AFirstCallback); FCallbackLoop := TDSRestCallbackLoop.Create(Self, FConnection); FCallbackLoop.Start(AFirstCallback); NotifyEvent(rChannelCreate, AFirstCallback); finally TMonitor.Exit(FCallbacks); end; end; (* * Unregisters all callbacks and disconnect the channel. *) procedure TDSRestClientChannel.Disconnect; begin try if (FCallbackLoop <> nil) and (not FCallbackLoop.Stopped) then begin FCallbackLoop.Stop; end; finally if FCallbacks <> nil then FCallbacks.Clear; end; end; procedure TDSRestClientChannel.UnregisterAllCallbacks; begin TMonitor.Enter(FCallbacks); try while FCallbacks.Count > 0 do UnregisterCallback(FCallbacks[0]); finally TMonitor.Exit(FCallbacks); end; end; procedure TDSRestClientChannel.EnumerateCallbacks(AMethod: TFunc<TDSRestClientCallback, Boolean>); var LCallback: TDSRestClientCallback; begin TMonitor.Enter(FCallbacks); try for LCallback in FCallbacks do if not AMethod(LCallback) then break; finally TMonitor.Exit(FCallbacks); end; end; procedure TDSRestClientChannel.EnumerateCallbacks(AMethod: TProc<TDSRestClientCallback>); var LCallback: TDSRestClientCallback; begin TMonitor.Enter(FCallbacks); try for LCallback in FCallbacks do AMethod(LCallback); finally TMonitor.Exit(FCallbacks); end; end; function TDSRestClientChannel.GetConnected: Boolean; begin Result := (FCallbackLoop <> nil) and (not FCallbackLoop.Stopped) end; function TDSRestClientChannel.GetSessionId: String; begin if FCallbackLoop <> nil then Result := FCallbackLoop.SessionId else if FConnection <> nil then Result := FConnection.SessionID; end; destructor TDSRestClientChannel.Destroy; begin if (FCallbackLoop <> nil) and (not FCallbackLoop.Stopped) then Disconnect; // Blocks until thread is terminated FreeAndNil(FCallbacks); FreeAndNil(FCallbackLoop); inherited; end; (* * Broadcasts a message to all registered callbacks of the server channel * this ClientChannel is registered with. * @param AMessage the message to broadcast * @param AChannelName the channel to broadcast to, or empty string to use ServerChannelName * @return true if the message was sent successfully to the server (but not neccessarally all callbacks,) * false otherwise *) function TDSRestClientChannel.Broadcast(AMessage: TJSONValue; AChannelName: String): Boolean; var LClient: TDSAdminRestClient; begin if AChannelName = EmptyStr then AChannelName := FServerChannelName; if (AMessage <> nil) and (AChannelName <> EmptyStr) then begin LClient := TDSAdminRestClient.Create(FConnection, False); try Result := LClient.BroadcastToChannel(AChannelName, AMessage) finally LClient.Free; end; end else Result := False; end; (* * Sends a notification message to a single callback of a specific ClientChannel. * Note that if you try to notify a callback of this ClientChannel no trip to the * server will be made to perform this. * @param AClientId the unique ID of ClientChannel the callback to notify is in * @param ACallbackId the unique ID of the callback to notify * @param AMessage the message to notify the callback with * @return true if notification was successful, * false otherwise *) function TDSRestClientChannel.Notify(const AClientId, ACallbackId: string; AMessage: TJSONValue): Boolean; var LResponse: TJSONValue; LClient: TDSAdminRestClient; LCurCallback: TDSRestClientCallback; begin if (AClientId = '') or (ACallbackId = '') or (AMessage = nil) then Exit(false); if AClientId = FChannelId then begin TMonitor.Enter(FCallbacks); try for LCurCallback in FCallbacks do begin if LCurCallback.CallbackId = ACallbackId then begin Exit(LCurCallback.ClientCallbackFunction(AMessage, '')); end; end; finally TMonitor.Exit(FCallbacks); end; Exit(False); end; LClient := TDSAdminRestClient.Create(FConnection, False); try Result := LClient.NotifyCallback(AClientId, ACallbackId, AMessage, LResponse); finally LClient.Free; end; end; procedure TDSRestClientChannel.NotifyEvent(EventType: TDSRESTChannelEventType; Callback: TDSRestClientCallback); var Event: TDSRESTChannelEventItem; begin //If the channel is stopped then only the channel create event should be sent if FStopped and (EventType <> rChannelCreate) then Exit; //if the current event is a stop event, then mark the channel as stopped FStopped := (EventType = rChannelClose) or (EventType = rChannelClosedByServer); if Assigned(FChannelEvent) then begin Event.EventType := EventType; Event.ClientChannelId := FChannelId; Event.ClientChannelName := FServerChannelName; Event.ClientChannel := Self; Event.Callback := Callback; if Callback <> nil then Event.CallbackId := Callback.CallbackId; try FChannelEvent(Event); except end; end; end; constructor TDSRestCallbackLoop.Create(AClientChannel: TDSRestClientChannel; AConnection: TDSCustomRestConnection); begin // Clone connection to use on a separate thread FConnection := TDSCustomRestConnection(TComponentClass(AConnection.ClassType).Create(nil)); FConnection.Assign(AConnection); if not FConnection.PreserveSessionID then FConnection.SessionID := ''; FClientChannel := AClientChannel; end; destructor TDSRestCallbackLoop.Destroy; begin FreeAndNil(FThread); FreeAndNil(FConnection); inherited; end; function TDSRestCallbackLoop.GetSessionId: String; begin if FConnection <> nil then Result := FConnection.SessionID; end; function TDSRestCallbackLoop.GetStopped: Boolean; begin Result := (FThread = nil) or (FThread.Finished); end; (* * The callback which will handle a value passed in from the server *) procedure TDSRestCallbackLoop.Callback(responseValue: TJSONValue; var AStatus: Boolean; var AStop: Boolean); var LParamArray: TJSONArray; LParamValue: TJSONValue; LDataType: string; LResponseObject: TJSONObject; LCallbackKey: string; LStatus: PBoolean; LBroadcastChannel: String; LDoForAll: Boolean; begin AStop := False; AStatus := True; if (not Self.Stopped) and (responseValue <> nil) then begin //code which resolves the true response object if (responseValue is TJSONObject) and (TJSONObject(responseValue).Get('result') <> nil) then responseValue := TJSONObject(responseValue).Get('result').JSONValue; if responseValue is TJSONArray then responseValue := TJSONArray(responseValue).Get(0); LResponseObject := TJSONObject(responseValue); //session expired, so notify local callbacks and then stop the loop if LResponseObject.Get('SessionExpired') <> nil then begin clientChannel.EnumerateCallbacks( procedure(ACallback: TDSRestClientCallback) begin ACallback.ClientCallbackFunction(LResponseObject,''); end); AStop := True; clientChannel.NotifyEvent(rChannelClosedByServer, nil); end //broadcast to all of the callbacks else if (LResponseObject.Get('broadcast') <> nil) then begin LParamArray := TJSONArray(LResponseObject.Get('broadcast').JSONValue); LParamValue := TJSONArray(LParamArray.Get(0)); if LResponseObject.Get('channel') <> nil then LBroadcastChannel := LResponseObject.Get('channel').JsonValue.Value else LBroadcastChannel := FClientChannel.ServerChannelName; //used to determine if the paramValue is (on the server) a JSONValue or a TObject LDataType := LParamArray.Get(1).Value; LDoForAll := LBroadcastChannel = FClientChannel.ServerChannelName; clientChannel.EnumerateCallbacks( procedure(ACallback: TDSRestClientCallback) begin if LDoForAll or (ACallback.ChannelNames.IndexOf(LBroadcastChannel) > -1) then ACallback.ClientCallbackFunction(LParamValue, LDataType); end); AStatus := True; end //Invoke the specified callback else if LResponseObject.Get('invoke') <> nil then begin LParamArray := TJSONArray(LResponseObject.Get('invoke').JSONValue); LCallbackKey := LParamArray.Get(0).Value; LParamValue := TJSONArray(LParamArray.Get(1)); //used to determine if the paramValue is (on the server) a JSONValue or a TObject LDataType := LParamArray.Get(2).Value; LStatus := @AStatus; clientChannel.EnumerateCallbacks( function(ACallback: TDSRestClientCallback): Boolean begin if ACallback.callbackId = LCallbackKey then begin LStatus^ := ACallback.ClientCallbackFunction(LParamValue, LDataType); Result := False; // Stop enumeration end else Result := True; // continue enumeration end); end //if an error has occured notify the callbacks and stop the loop else if LResponseObject.Get('error') <> nil then begin clientChannel.EnumerateCallbacks( procedure(ACallback: TDSRestClientCallback) begin ACallback.ClientCallbackFunction(LResponseObject, 'error'); end); AStop := True; clientChannel.NotifyEvent(rChannelClosedByServer, nil); end //If the result key is 'close' or 'closeChannel' then no response should be sent, which means //the recursion of this loop will end. Otherwise, send a response to the server with //a value of false so the loop will continue and the server will know the invocation failed else if (LResponseObject.Get('closeChannel') = nil) and (LResponseObject.Get('close') = nil) then begin AStatus := False; end else begin AStop := True; clientChannel.NotifyEvent(rChannelClose, nil); end end else begin if Self.Stopped then clientChannel.NotifyEvent(rChannelClosedByServer, nil); AStop := True; end; end; type TCallbackLoopWorker = procedure(AResponseValue: TJSONValue; var AStatus: Boolean; var AStop: Boolean) of object; TCallbackLoopThread = class(TThread) private FConnection: TDSCustomRestConnection; FChannelName: string; FClientManagerId: string; FCallbackId: string; FCallbackChannelNames: String; FWorker: TCallbackLoopWorker; FOnTerminateDirect: TProc; constructor Create(AWorker: TCallbackLoopWorker; AConnection: TDSCustomRestConnection; AChannelName, AClientManagerId, ACallbackId, ACallbackChannelNames: string); protected procedure Execute; override; end; constructor TCallbackLoopThread.Create(AWorker: TCallbackLoopWorker; AConnection: TDSCustomRestConnection; AChannelName, AClientManagerId, ACallbackId, ACallbackChannelNames: string); begin FWorker := AWorker; FConnection := AConnection; FChannelName := AChannelName; FClientManagerId := AClientManagerId; FCallbackId := ACallbackId; FCallbackChannelNames := ACallbackChannelNames; inherited Create(True); end; procedure TCallbackLoopThread.Execute; var LClient: TDSAdminRestClient; LJSONValue: TJSONValue; LStatus: Boolean; LStopped: Boolean; LStatusValue: TJSONValue; LTrue: TJSONTrue; LFalse: TJSONFalse; begin LTrue := TJSONTrue.Create; LFalse := TJSONFalse.Create; LClient := TDSAdminRestClient.Create(FConnection, False); try // Block until the server responds LJSONValue := LClient.ConsumeClientChannel(FChannelName, FClientManagerId, FCallbackId, FCallbackChannelNames, nil); try FWorker(LJSONValue, LStatus, LStopped); finally LJSONValue.Free; end; while not LStopped do begin if LStatus then LStatusValue := TJSONTrue.Create else LStatusValue := TJSONFalse.Create; try // Must pass '' when using an existing channel // Block until the server responds LJSONValue := LClient.ConsumeClientChannel(FChannelName, FClientManagerId, EmptyStr, EmptyStr, LStatusValue); try FWorker(LJSONValue, LStatus, LStopped); finally LJSONValue.Free; end; finally LStatusValue.Free; end; end; finally LClient.Free; LTrue.Free; LFalse.Free; if Assigned(FOnTerminateDirect) then FOnTerminateDirect; end; end; (* * Starts the loop, registering the client callback on the server and the initial client callback specified * @param firstCallback the first callback to register, as you can't register a client with the server without specifying the first callback *) procedure TDSRestCallbackLoop.Start(AFirstCallback: TDSRestClientCallback); begin if Stopped and (FClientChannel <> nil) then begin FreeAndNil(FThread); FThread := TCallbackLoopThread.Create(Self.Callback, FConnection, FClientChannel.ServerChannelName, FClientChannel.ChannelId, AFirstCallback.CallbackId, AFirstCallback.ChannelNames.CommaText); TCallbackLoopThread(FThread).FOnTerminateDirect := OnThreadTerminateDirect; FThread.FreeOnTerminate := False; FThread.Start; end; end; procedure TDSRestCallbackLoop.OnThreadTerminateDirect; begin FClientChannel.NotifyEvent(rChannelClosedByServer, nil); if Assigned(FClientChannel.FOnDisconnect) then FClientChannel.FOnDisconnect(FClientChannel); end; (* * Tells the thread to terminate. The thread will still be hung waiting for a response from the server, but * once it gets that it will disregard the server command and not send another http request. This also * sends a command to the server, telling it that the client wishes to be unregistered. *) procedure TDSRestCallbackLoop.Stop; var LClient: TDSAdminRestClient; LConnection: TDSCustomRestConnection; begin //insure stop is not called while another thread is already invoking stop. if not FStopping then begin FStopping := True; try if (not Stopped) and (FClientChannel <> nil) then begin // Must use another connection because FConnection is currently // waiting for a response LConnection := TDSCustomRestConnection(TComponentClass(FConnection.ClassType).Create(nil)); try LConnection.Assign(FConnection); if not LConnection.PreserveSessionID then LConnection.SessionId := ''; LClient := TDSAdminRestClient.Create(LConnection, False); try LClient.CloseClientChannel(FClientChannel.ChannelId); FClientChannel.FCallbacks.Clear; finally LClient.Free; end; finally LConnection.Free; end; end; try // Block until thread is terminated if (FThread <> nil) and (not FThread.Finished) then FThread.WaitFor; except end; finally FStopping := False; end; end; end; (* * AClientChannel is an instance of the ClientChannel class which is intended to contain the callback. It isn't * guaranteed this containment will actually exist. To do so, you will need to call either the * "connect" or "registerCallback" function of the ClientChannel instance with this callback * as a parameter to create the containment relationship. * ACallbackId is the unique ID of this callback. This only needs to be unique on this particular client, * in this instance of ClientChannel and not across all instances of ClientChannel or all clients. * AClientCallbackFunction is the function to call for updating the callback and returning a JSON Value response back to the server. * @param value a JSON Value instance containing the formatted JSON properties required for updating the callback * @return a JSON value response to deliver to the server. This response will reflect the current * state of the callback after the update. *) constructor TDSRestClientCallback.Create(AClientChannel: TDSRestClientChannel; const ACallbackId: string; AClientCallbackFunction: TDSRestClientCallbackFunction; AChannelNames: TStrings); begin FClientChannel := AClientChannel; FCallbackId := ACallbackId; FClientCallbackFunction := AClientCallbackFunction; FChannelNames := AChannelNames; if AChannelNames = nil then FChannelNames := TStringList.Create; end; // The above code is based on the javascript within CallbackFramework.js { TDSRestCachedItem } constructor TDSRestCachedItem.Create(const AItemPath: string); begin FItemPath := AItemPath; FOwnedObjects := TObjectList.Create(True); end; procedure TDSRestCachedItem.DeleteCommand(AConnection: TDSRestConnection); var LCommand: TDSRestCacheCommand; begin LCommand := TDSRestCacheCommand.Create(AConnection); try LCommand.ParameterPath := ItemPath; LCommand.DeleteCommand; finally LCommand.Free; end; end; destructor TDSRestCachedItem.Destroy; begin FOwnedObjects.Free; inherited; end; function TDSRestCachedItem.GetCommand(AConnection: TDSRestConnection; AOwnsObject: Boolean = True): TJSONObject; var LCommand: TDSRestCacheCommand; begin LCommand := TDSRestCacheCommand.Create(AConnection); try LCommand.ParameterPath := ItemPath; Result := LCommand.GetCommand(False); if AOwnsObject then FOwnedObjects.Add(Result); finally LCommand.Free; end; end; function TDSRestCachedItem.GetItemPath: string; begin Result := FItempath; end; function TDSRestCachedItem.GetJSONValueCallback(AConnection: TDSRestConnection; ACallback: TGetJSONValueCallback; AOwnsObject: Boolean; const ARequestFilter: string): TJSONValue; var LCommand: TDSRestCacheCommand; LAccept: Boolean; begin LAccept := False; Result := nil; LCommand := TDSRestCacheCommand.Create(AConnection); try LCommand.ParameterPath := ItemPath; LCommand.GetParameter(Result, ARequestFilter); try if Assigned(ACallback) then LAccept := ACallback(Result) else LAccept := True; if LAccept and AOwnsObject then OwnedObjects.Add(Result); finally if not LAccept then FreeAndNil(Result); end; finally LCommand.Free; end; end; function TDSRestCachedItem.UnmarshalValue<T>(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): T; var AJSONValue: TJSONValue; AUnmarshal: TJSONUnMarshal; begin Result := nil; AJSONValue := GetJSONValue(AConnection, True, ARequestFilter); if AJSONValue <> nil then begin AUnmarshal := TJSONConverters.GetJSONUnmarshaler; try Result := T(AUnmarshal.UnMarshal(AJSONValue)); if (Result <> nil) and AOwnsObject then OwnedObjects.Add(TObject(Result)); finally FreeAndNil(AUnmarshal) end end end; function TDSRestCachedItem.GetJSONValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TJSONValue; begin Result := (GetJSONValueCallback(AConnection, nil (* Callback *), AOwnsObject, ARequestFilter)); end; { TDSRestCachedJSONObject } function TDSRestCachedJSONObject.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TJSONObject; begin Result := TJSONObject (GetJSONValueCallback(AConnection, function(AValue: TJSONValue): Boolean begin Result := AValue is TJSONObject; end, AOwnsObject, ARequestFilter)); end; { TDSRestCachedJSONArray } function TDSRestCachedJSONArray.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TJSONArray; begin Result := TJSONArray (GetJSONValueCallback(AConnection, function(AValue: TJSONValue): Boolean begin Result := AValue is TJSONArray; end, AOwnsObject, ARequestFilter)); end; { TDSRestCachedJSONValue } function TDSRestCachedJSONValue.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TJSONValue; begin Result := (GetJSONValueCallback(AConnection, function(AValue: TJSONValue): Boolean begin Result := AValue is TJSONValue; end, AOwnsObject, ARequestFilter)); end; { TDSRestCachedStream } function TDSRestCachedStream.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TStream; var LCommand: TDSRestCacheCommand; begin Result := nil; LCommand := TDSRestCacheCommand.Create(AConnection); try LCommand.ParameterPath := ItemPath; LCommand.GetParameter(Result, False (* We own stream now *), ARequestFilter); if AOwnsObject and (Result <> nil) then OwnedObjects.Add(Result); finally LCommand.Free; end; end; { TDSRestCachedDataSet } function TDSRestCachedDataSet.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TDataSet; var LReader: TDBXReader; LJSONTable: TJSONObject; begin Result := nil; LJSONTable := TJSONObject (GetJSONValueCallback(AConnection, function(AValue: TJSONValue): Boolean begin Result := AValue is TJSONObject; end, False, ARequestFilter)); try if LJSONTable <> nil then begin LReader := TDBXJSONTableReader.Create(nil, LJSONTable, True); LJSONTable := nil; try if LReader <> nil then begin Result := TCustomSQLDataSet.Create(nil, LReader, True); LReader := nil; Result.Open; if AOwnsObject then OwnedObjects.Add(Result); end; finally LReader.Free; end; end; finally LJSONTable.Free; end; end; { TDSRestCachedParams } function TDSRestCachedParams.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TParams; var LReader: TDBXReader; LJSONTable: TJSONObject; begin Result := nil; LJSONTable := TJSONObject (GetJSONValueCallback(AConnection, function(AValue: TJSONValue): Boolean begin Result := AValue is TJSONObject; end, False (* Take ownership of JSONObject *), ARequestFilter)); try if LJSONTable <> nil then begin LReader := TDBXJSONTableReader.Create(nil, LJSONTable, True); LJSONTable := nil; try Result := TDBXParamsReader.ToParams(nil, LReader, True); LReader := nil; if AOwnsObject then OwnedObjects.Add(Result); finally LReader.Free; end; end; finally LJSONTable.Free; end; end; { TDSRestCachedDBXReader } function TDSRestCachedDBXReader.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): TDBXReader; var LJSONTable: TJSONObject; begin LJSONTable := TJSONObject (GetJSONValueCallback(AConnection, function(AValue: TJSONValue): Boolean begin Result := AValue is TJSONObject; end, False, ARequestFilter)); if LJSONTable <> nil then begin Result := TDBXJSONTableReader.Create(nil, LJSONTable, True); if (Result <> nil) and AOwnsObject then OwnedObjects.Add(Result); end else Result := nil; end; { TDSRestCachedObject<T> } function TDSRestCachedObject<T>.GetValue(AConnection: TDSRestConnection; AOwnsObject: Boolean; const ARequestFilter: string): T; begin Result := UnmarshalValue<T>(AConnection, AOwnsObject, ARequestFilter); end; { TDSRestProtocolException } constructor TDSRestProtocolException.Create(AStatus: Integer; const AMessage, AResponseText: string); begin inherited Create(AMessage); FStatus := AStatus; FResponseText := AResponseText; end; destructor TDSRestClientCallback.Destroy; begin try FreeAndNil(FChannelNames); except end; inherited; end; end.
unit FC.StockChart.UnitTask.Bars.DataGrid; interface {$I Compiler.inc} uses SysUtils,Classes, BaseUtils, Serialization, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation uses FC.StockChart.UnitTask.Bars.DataGridDialog; type //Специальный Unit Task для автоматического подбора размеров грани и длины периода. //Подюор оусщестьвляется прямым перебором. TStockUnitTaskBarsDataGrid = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskBarsDataGrid } function TStockUnitTaskBarsDataGrid.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorBars); if result then aOperationName:='Bars: DataGrid'; end; procedure TStockUnitTaskBarsDataGrid.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); begin TfmBarsDataGridDialog.Run(aIndicator as ISCIndicatorBars,aStockChart); end; initialization //Регистрируем Unit Task StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskBarsDataGrid.Create); end.
unit ScreenViewForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, rtcTypes, rtcThrPool, rtcInfo, rtcGateConst, rtcGateCli, rtcVImgPlayback; const HiddenCursor:TCursor=crNone; VisibleCursor:TCursor=crHandPoint; type TScreenViewFrm = class(TForm) sbMainBox: TScrollBox; pbScreenView: TPaintBox; pStartInfo: TPanel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pbScreenViewPaint(Sender: TObject); procedure pbScreenViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure pStartInfoClick(Sender: TObject); procedure pbScreenViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbScreenViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DeactivateControl(Sender: TObject); procedure sbMainBoxMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } SCLink:TRtcImageVCLPlayback; WasActive:boolean; procedure SCLinkLogOut(Sender: TObject); procedure SCLinkDisconnect(Sender: TObject); procedure SCLinkHostOffLine(Sender: TObject); procedure SCLinkHostConnect(Sender: TObject); procedure SCLinkHostDisconnect(Sender: TObject); procedure SCLinkHostClosed(Sender: TObject); procedure SCLinkControlEnabled(Sender: TObject); procedure SCLinkControlDisabled(Sender: TObject); procedure SCLinkStartReceive(Sender: TObject); procedure SCLinkImageRepaint(Sender: TObject); procedure SCLinkCursorShow(Sender: TObject); procedure SCLinkCursorHide(Sender: TObject); end; function NewScreenViewForm(Cli:TRtcHttpGateClient; UID,GID:TGateUID; const Key:RtcString):TScreenViewFrm; implementation {$R *.dfm} function NewScreenViewForm(Cli:TRtcHttpGateClient; UID,GID:TGateUID; const Key:RtcString):TScreenViewFrm; begin if not Cli.Ready then raise ERtcGateClient.Create('No connection'); Result:=TScreenViewFrm.Create(Application); Result.Caption:=IntToStr(Cli.MyUID)+': Screen from '+IntToStr(UID)+'/'+IntToStr(GID); Result.pStartInfo.Caption:='Waiting for the Host ...'; Result.pStartInfo.Color:=clYellow; Result.pStartInfo.Font.Color:=clRed; Result.pStartInfo.Visible:=True; Result.Show; Result.SCLink.Client:=Cli; Result.SCLink.HostInviteAccept(UID,GID,Key); end; procedure TScreenViewFrm.FormCreate(Sender: TObject); begin WasActive:=False; SCLink:=TRtcImageVCLPlayback.Create(nil); SCLink.OnImageRepaint:=SCLinkImageRepaint; SCLink.OnCursorShow:=SCLinkCursorShow; SCLink.OnCursorHide:=SCLinkCursorHide; SCLink.OnHostOffLine:=SCLinkHostOffLine; SCLink.OnHostConnect:=SCLinkHostConnect; SCLink.OnHostDisconnect:=SCLinkHostDisconnect; SCLink.OnHostClosed:=SCLinkHostClosed; SCLink.OnLogOut:=SCLinkLogOut; SCLink.OnDisconnect:=SCLinkDisconnect; SCLink.OnControlEnabled:=SCLinkControlEnabled; SCLink.OnControlDisabled:=SCLinkControlDisabled; SCLink.OnStartReceive:=SCLinkStartReceive; ClientWidth:=pbScreenView.Width; ClientHeight:=pbScreenView.Height; end; procedure TScreenViewFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin SCLink.Client:=nil; Action:=caFree; end; procedure TScreenViewFrm.FormDestroy(Sender: TObject); begin RtcFreeAndNil(SCLink); end; procedure TScreenViewFrm.SCLinkLogOut(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Logged out ('+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID)+')'; pStartInfo.Caption:='Logged out.'; pStartInfo.Color:=clRed; pStartInfo.Font.Color:=clYellow; pStartInfo.Visible:=True; end; procedure TScreenViewFrm.SCLinkHostOffLine(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Host is OFF-LINE ('+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID)+')'; pStartInfo.Caption:='Host is OFF-LINE'; pStartInfo.Color:=clRed; pStartInfo.Font.Color:=clYellow; pStartInfo.Visible:=True; end; procedure TScreenViewFrm.SCLinkHostConnect(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Connected to '+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID)+' as Viewer'; pStartInfo.Caption:='Connected to Host'; pStartInfo.Color:=clWhite; pStartInfo.Font.Color:=clBlack; pStartInfo.Visible:=True; end; procedure TScreenViewFrm.SCLinkHostDisconnect(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Disconnected from '+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID); pStartInfo.Caption:='Lost connection to Host'; pStartInfo.Color:=clRed; pStartInfo.Font.Color:=clYellow; pStartInfo.Visible:=True; end; procedure TScreenViewFrm.SCLinkHostClosed(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Session Closed ('+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID)+')'; pStartInfo.Caption:='Host Session closed'; pStartInfo.Color:=clRed; pStartInfo.Font.Color:=clYellow; pStartInfo.Visible:=True; end; procedure TScreenViewFrm.SCLinkDisconnect(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Disconnected from '+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID); pStartInfo.Caption:='Disconnected from Gateway'; pStartInfo.Color:=clRed; pStartInfo.Font.Color:=clYellow; pStartInfo.Visible:=True; end; procedure TScreenViewFrm.SCLinkControlEnabled(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Connected to ('+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID)+') as Control'; pStartInfo.Caption:='Control Enabled'; pStartInfo.Font.Color:=clBlack; end; procedure TScreenViewFrm.SCLinkControlDIsabled(Sender: TObject); begin Caption:=IntToStr(SCLink.Client.MyUID)+': Connected to ('+IntToStr(SCLink.HostUserID)+'/'+IntToStr(SCLink.HostGroupID)+') as Viewer'; pStartInfo.Caption:='Control Disabled'; pStartInfo.Font.Color:=clBlack; end; procedure TScreenViewFrm.SCLinkStartReceive(Sender: TObject); begin pStartInfo.Caption:='Receiving image ...'; pStartInfo.Font.Color:=clBlack; pStartInfo.Visible:=True; end; procedure TScreenViewFrm.SCLinkImageRepaint(Sender: TObject); begin if ( (pbScreenView.Width<>SCLink.ImageWidth) or (pbScreenView.Height<>SCLink.ImageHeight) ) then begin WasActive:=False; pbScreenView.Width:=SCLink.ImageWidth; pbScreenView.Height:=SCLink.ImageHeight; end; if pStartInfo.Visible or not WasActive then begin pStartInfo.Visible:=false; if not WasActive then begin WasActive:=True; if WindowState=wsNormal then begin if pbScreenView.Width<Screen.Width then ClientWidth:=pbScreenView.Width else Width:=Screen.Width; if pbScreenView.Height<Screen.Height then ClientHeight:=pbScreenView.Height else Height:=Screen.Height; if (Left>0) and (Left+Width>Screen.Width) then Left:=Screen.Width-Width; if (Top>0) and (Top+Height>Screen.Height) then Top:=Screen.Height-Height; end; end; end; pbScreenViewPaint(pbScreenView); end; procedure TScreenViewFrm.SCLinkCursorHide(Sender:TObject); begin pbScreenView.Cursor:=HiddenCursor; Screen.Cursor:=HiddenCursor; ShowCursor(False); Screen.Cursor:=crDefault; end; procedure TScreenViewFrm.SCLinkCursorShow(Sender:TObject); begin pbScreenView.Cursor:=VisibleCursor; Screen.Cursor:=VisibleCursor; ShowCursor(True); Screen.Cursor:=crDefault; end; procedure TScreenViewFrm.pbScreenViewPaint(Sender: TObject); begin SCLink.DrawBitmap(pbScreenView.Canvas); end; procedure TScreenViewFrm.pStartInfoClick(Sender: TObject); begin pStartInfo.Visible:=False; end; procedure TScreenViewFrm.pbScreenViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SCLink.MouseDown(X,Y,Ord(Button)); end; procedure TScreenViewFrm.pbScreenViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin SCLink.MouseMove(X,Y); end; procedure TScreenViewFrm.pbScreenViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SCLink.MouseUp(X,Y,Ord(Button)); end; procedure TScreenViewFrm.DeactivateControl(Sender: TObject); begin SCLink.MouseControl:=False; end; procedure TScreenViewFrm.sbMainBoxMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin SCLink.MouseWheel(WheelDelta); Handled:=True; end; procedure TScreenViewFrm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin SCLink.KeyDown(Key); Key:=0; end; procedure TScreenViewFrm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_TAB then // We don't get KeyDown events for TAB SCLink.KeyDown(Key); SCLink.KeyUp(Key); Key:=0; end; end.
unit IdLogStream; interface uses classes, IdLogBase; type TIdLogStream = class(TIdLogBase) protected FInputStream : TStream; FOutputStream : TStream; procedure LogStatus(const AText: string); override; procedure LogReceivedData(const AText: string; const AData: string); override; procedure LogSentData(const AText: string; const AData: string); override; public property InputStream : TStream read FInputStream write FInputStream; property OutputStream : TStream read FOutputStream write FOutputStream; end; implementation { TIdLogStream } procedure TIdLogStream.LogReceivedData(const AText, AData: string); begin if (Assigned(FInputStream)) and (Length(AData)>0) then begin FInputStream.Write(AData[1],Length(AData)); end; end; procedure TIdLogStream.LogSentData(const AText, AData: string); begin if (Assigned(FOutputStream)) and (Length(AData)>0) then begin FOutputStream.Write(AData[1],Length(AData)); end; end; procedure TIdLogStream.LogStatus(const AText: string); begin //we just leave this empty because the AText is not part of the stream and we don't {Do not Localize} //want to raise an abstract method exception. end; end.
unit install; {$mode ObjFPC}{$H+} interface uses Classes, Registry; procedure Install; procedure Uninstall; function Installed: Boolean; implementation procedure Install; var Reg: TRegistry; begin Reg := TRegistry.Create(KEY_WOW64_32KEY or KEY_WRITE); try Reg.RootKey := HKEY_LOCAL_MACHINE; if not Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run', False) then Exit; Reg.WriteString('NoadTalk', ParamStr(0)); finally Reg.Free; end; end; procedure Uninstall; var Reg: TRegistry; sName: unicodestring; begin Reg := TRegistry.Create(KEY_WOW64_32KEY or KEY_SET_VALUE or KEY_QUERY_VALUE); try Reg.RootKey := HKEY_LOCAL_MACHINE; if not Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run', False) then Exit; for sName in Reg.GetValueNames do begin if Reg.ReadString(sName) = unicodestring(ParamStr(0)) then begin Reg.DeleteValue(sName); end; end; finally Reg.Free; end; end; function Installed: Boolean; var Reg: TRegistry; sName: unicodestring; begin Result := False; Reg := TRegistry.Create(KEY_WOW64_32KEY or KEY_READ); try Reg.RootKey := HKEY_LOCAL_MACHINE; if not Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run', False) then Exit; for sName in Reg.GetValueNames do begin if Reg.ReadString(sName) = unicodestring(ParamStr(0)) then begin Result := True; Break; end; end; finally Reg.Free; end; end; end.
unit fAllSettings; { AFS 7 Sept 2K All settings on one form at once } {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is fAllSettings, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"). you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/NPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface uses { delphi } SysUtils, Classes, Controls, Forms, StdCtrls, Buttons, ExtCtrls, ComCtrls, ShellAPI, Dialogs, { local } JcfSettings, frmBaseSettingsFrame; type TFormAllSettings = class(TForm) tvFrames: TTreeView; pnlSet: TPanel; bbOK: TBitBtn; bbCancel: TBitBtn; BitBtn1: TBitBtn; procedure tvFramesChange(Sender: TObject; Node: TTreeNode); procedure FormCreate(Sender: TObject); procedure bbOKClick(Sender: TObject); procedure bbCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure bbHelpClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); procedure FormShow(Sender: TObject); private frLastFrame: TfrSettingsFrame; function GetTreeNodeByName(const psName: string): TTreeNode; procedure GetFrameForNode(const pcNode: TTreeNode); function GetCurrentFrame: TfrSettingsFrame; procedure RemoveAll(const pbSave: boolean); procedure BuildTree; protected function GetFrameType(const psName: string): TSettingsFrameClass; virtual; public procedure Execute; end; implementation {$ifdef FPC} {$R *.lfm} {$else} {$R *.dfm} {$endif} uses Windows, JcfRegistrySettings, JcfFontSetFunctions, JcfHelp, { contained frames } frFiles, frObfuscateSettings, frClarify, frClarifySpaces, frClarifyIndent, frClarifyReturns, frBlankLines, frClarifyLongLineBreaker, frClarifyBlocks, frClarifyCaseBlocks, frClarifyAlign, frReplace, frReservedCapsSettings, frAnyCapsSettings, frIdentifierCapsSettings, frNotIdentifierCapsSettings, frUnitCaps, frUses, frBasicSettings, frPreProcessor, frComments, frTransform, frCompilerDirectReturns, frWarnings, frAsm; type TFrameMapRecord = record FrameName: string; FrameClass: TsettingsFrameClass; end; const FrameMap: array[0..24] of TFrameMapRecord = ( (FrameName: 'Format File'; FrameClass: TfFiles), (FrameName: 'Obfuscate'; FrameClass: TfObfuscateSettings), (FrameName: 'Clarify'; FrameClass: TfClarify), (FrameName: 'Spaces'; FrameClass: TfClarifySpaces), (FrameName: 'Indentation'; FrameClass: TfClarifyIndent), (FrameName: 'Long Lines'; FrameClass: TfClarifyLongLineBreaker), (FrameName: 'Returns'; FrameClass: TfClarifyReturns), (FrameName: 'Blank Lines'; FrameClass: TfBlankLines), (FrameName: 'Blocks'; FrameClass: TfClarifyBlocks), (FrameName: 'Case Blocks'; FrameClass: TfClarifyCaseBlocks), (FrameName: 'Align'; FrameClass: TfClarifyAlign), (FrameName: 'Object Pascal'; FrameClass: TfrReservedCapsSettings), (FrameName: 'Any Word'; FrameClass: TfrAnyCapsSettings), (FrameName: 'Identifiers'; FrameClass: TfIdentifierCapsSettings), (FrameName: 'Not Identifiers'; FrameClass: TfNotIdentifierCapsSettings), (FrameName: 'Unit Name'; FrameClass: TfrUnitNameCaps), (FrameName: 'Find and replace'; FrameClass: TfReplace), (FrameName: 'Uses'; FrameClass: TfUses), (FrameName: 'Basic'; FrameClass: TfrBasic), (FrameName: 'PreProcessor'; FrameClass: TfPreProcessor), (FrameName: 'Comments'; FrameClass: TfComments), (FrameName: 'Transform'; FrameClass: TfTransform), (FrameName: 'Compiler Directives'; FrameClass: TfCompilerDirectReturns), (FrameName: 'Warnings'; FrameClass: TfWarnings), (FrameName: 'Asm'; FrameClass: TfAsm) ); { TFormAllSettings } procedure TFormAllSettings.Execute; begin BuildTree; ShowModal; if (ModalResult = mrOk) and JcfFormatSettings.Dirty then JcfFormatSettings.Write; end; procedure TFormAllSettings.GetFrameForNode(const pcNode: TTreeNode); var lcType: TSettingsFrameClass; lf: TfrSettingsFrame; begin if pcNode.Data <> nil then exit; lcType := GetFrameType(pcNode.Text); if lcType = nil then exit; lf := lcType.Create(self); lf.Parent := pnlSet; SetObjectFontToSystemFont(lf); { read } lf.Read; { show } lf.Left := 0; lf.Top := 0; lf.Width := pnlSet.ClientWidth; lf.Height := pnlSet.ClientHeight; pcNode.Data := lf; end; function TFormAllSettings.GetFrameType(const psName: string): TsettingsFrameClass; var liLoop: integer; begin Result := nil; // find the frame is the data? for liLoop := Low(FrameMap) to High(FrameMap) do begin if AnsiSameText(psName, FrameMap[liLoop].FrameName) then begin Result := FrameMap[liLoop].FrameClass; break; end; end; end; procedure TFormAllSettings.tvFramesChange(Sender: TObject; Node: TTreeNode); var lf: TfrSettingsFrame; begin GetFrameForNode(Node); if frLastFrame <> nil then frLastFrame.Visible := False; if Node.Data = nil then exit; lf := TfrSettingsFrame(Node.Data); lf.Visible := True; frLastFrame := lf; end; procedure TFormAllSettings.FormCreate(Sender: TObject); begin SetObjectFontToSystemFont(Self); Application.HelpFile := GetHelpFilePath; frLastFrame := nil; end; procedure TFormAllSettings.bbOKClick(Sender: TObject); begin { save settings } RemoveAll(True); { settings are now in need of saving } JcfFormatSettings.Dirty := True; { check consistency of settings } JcfFormatSettings.MakeConsistent; Close; ModalResult := mrOk; end; procedure TFormAllSettings.BuildTree; var lcClarifyNode: TTreeNode; lcLineBreakingNode: TTreeNode; lcCaptialisationNode: TTreeNode; lcFindReplaceNode: TTreeNode; begin tvFrames.Items.Clear; tvFrames.Items.AddChild(nil, 'Format File'); tvFrames.Items.AddChild(nil, 'Obfuscate'); lcClarifyNode := tvFrames.Items.AddChild(nil, 'Clarify'); tvFrames.Items.AddChild(lcClarifyNode, 'Spaces'); tvFrames.Items.AddChild(lcClarifyNode, 'Indentation'); tvFrames.Items.AddChild(lcClarifyNode, 'Blank Lines'); tvFrames.Items.AddChild(lcClarifyNode, 'Align'); lcLineBreakingNode := tvFrames.Items.AddChild(lcClarifyNode, 'Line Breaking'); tvFrames.Items.AddChild(lcLineBreakingNode, 'Long Lines'); tvFrames.Items.AddChild(lcLineBreakingNode, 'Returns'); tvFrames.Items.AddChild(lcLineBreakingNode, 'Case Blocks'); tvFrames.Items.AddChild(lcLineBreakingNode, 'Blocks'); tvFrames.Items.AddChild(lcLineBreakingNode, 'Compiler Directives'); tvFrames.Items.AddChild(lcClarifyNode, 'Comments'); tvFrames.Items.AddChild(lcClarifyNode, 'Warnings'); lcCaptialisationNode := tvFrames.Items.AddChild(lcClarifyNode, 'Capitalisation'); tvFrames.Items.AddChild(lcCaptialisationNode, 'Object Pascal'); tvFrames.Items.AddChild(lcCaptialisationNode, 'Any Word'); tvFrames.Items.AddChild(lcCaptialisationNode, 'Identifiers'); tvFrames.Items.AddChild(lcCaptialisationNode, 'Not Identifiers'); tvFrames.Items.AddChild(lcCaptialisationNode, 'Unit Name'); lcFindReplaceNode := tvFrames.Items.AddChild(lcClarifyNode, 'Find and Replace'); tvFrames.Items.AddChild(lcFindReplaceNode, 'Uses'); tvFrames.Items.AddChild(lcClarifyNode, 'Transform'); tvFrames.Items.AddChild(lcClarifyNode, 'Asm'); tvFrames.Items.AddChild(nil, 'PreProcessor'); end; procedure TFormAllSettings.bbCancelClick(Sender: TObject); begin RemoveAll(False); Close; end; procedure TFormAllSettings.RemoveAll(const pbSave: boolean); var liLoop: integer; lcItem: TTreeNode; lf: TfrSettingsFrame; begin { retrieve frames from the tree nodes and save them } for liLoop := 0 to tvFrames.Items.Count - 1 do begin lcItem := tvFrames.Items[liLoop]; if lcItem.Data <> nil then begin lf := lcItem.Data; lcItem.Data := nil; if pbSave then lf.Write; lf.Free; end; end; end; function TFormAllSettings.GetTreeNodeByName(const psName: string): TTreeNode; var liLoop: integer; lcNode: TTreeNode; begin Result := nil; if psName = '' then exit; for liLoop := 0 to tvFrames.Items.Count - 1 do begin lcNode := tvFrames.Items[liLoop]; if AnsiSameText(lcNode.Text, psName) then begin Result := lcNode; break; end; end; end; function TFormAllSettings.GetCurrentFrame: TfrSettingsFrame; begin Result := nil; if tvFrames.Selected = nil then exit; Result := tvFrames.Selected.Data; end; procedure TFormAllSettings.bbHelpClick(Sender: TObject); var lcFrame: TfrSettingsFrame; begin lcFrame := GetCurrentFrame; if lcFrame = nil then begin try Application.HelpContext(HELP_MAIN); except if FileExists(Application.HelpFile) then ShellExecute(Handle, 'open', PChar(Application.HelpFile), nil, nil, SW_SHOWNORMAL); end; end else lcFrame.ShowContextHelp; end; procedure TFormAllSettings.FormClose(Sender: TObject; var Action: TCloseAction); begin { save the last selected node } if tvFrames.Selected <> nil then GetRegSettings.LastSettingsPage := tvFrames.Selected.Text; end; procedure TFormAllSettings.FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); begin if Key = VK_F1 then bbHelpClick(nil); end; procedure TFormAllSettings.FormShow(Sender: TObject); var lcNode: TTreeNode; begin tvFrames.FullExpand; lcNode := GetTreeNodeByName(GetRegSettings.LastSettingsPage); if lcNode <> nil then lcNode.Selected := True; end; end.
unit record_props_indexed_2; interface type TRec = record function GetI(const Index: string): Int32; procedure SetI(const Index: string; Value: Int32); property Items[const Index: string]: Int32 read GetI write SetI; end; implementation var GR, GW: Int32; GS: string; function TRec.GetI(const Index: string): Int32; begin Result := Length(Index); end; procedure TRec.SetI(const Index: string; Value: Int32); begin GS := Index; GW := Value; end; procedure Test; var R: TRec; begin GR := R.Items['asdf']; R.Items['hello'] := 8; end; initialization Test(); finalization Assert(GR = 4); Assert(GW = 8); Assert(GS = 'hello'); end.
PROGRAM fxc (* display currency reciprocals over a range *); CONST defaultIncr = 0.1; ScreenLines = 23; DefaultFact = 100; VAR FX, Start, Center, Increment : REAL; Factor, n, err : WORD; (* --------------------------------------------------------- *) PROCEDURE ShowHelp; BEGIN Writeln('Usage: FXC ExchRate [Increment] [Factor]'); HALT; END (* ShowHelp *); (* --------------------------------------------------------- *) PROCEDURE GetParams(VAR ExchRate, incr : REAL; VAR Fact : WORD); BEGIN if paramcount > 0 THEN BEGIN val(paramstr(1),ExchRate,err); If err > 0 THEN ShowHelp; val(paramstr(2),incr,err); If err > 0 THEN incr := DefaultIncr; val(paramstr(3),Fact,err); If err > 0 THEN Fact := DefaultFact; END ELSE ShowHelp; END (* GetParams *); (* --------------------------------------------------------- *) BEGIN (* MAIN *) GetParams(Center, Increment, Factor); Start := Center - Increment * (ScreenLines DIV 2); FOR n := 0 to ScreenLines-1 DO BEGIN FX := Start + n*Increment; IF n = ScreenLines DIV 2 THEN Write('*'); Writeln(FX:10:3,1/FX*Factor:10:3); END; END (* FXC *). 
unit GroupList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, System.ImageList, Vcl.ImgList, Vcl.StdCtrls, Vcl.Mask, RzEdit, RzButton, RzTabs, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls, RzPanel, RzRadChk, RzDBChk, Vcl.DBCtrls, RzDBCmbo, RzDBEdit, Vcl.Imaging.pngimage, Vcl.ComCtrls, RzTreeVw, Group, Vcl.Menus, RzCmboBx; type TfrmGroupList = class(TfrmBaseGridDetail) edGroupName: TRzDBEdit; cbxPublic: TRzDBCheckBox; cbxActive: TRzDBCheckBox; dbluParentGroup: TRzDBLookupComboBox; tvGroup: TRzTreeView; cmbBranch: TRzComboBox; edMaxTotal: TRzDBNumericEdit; RzGroupBox1: TRzGroupBox; dbluLoanType: TRzDBLookupComboBox; edConcurrent: TRzDBEdit; edIdentityDocs: TRzDBEdit; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; dbluBranch: TRzDBLookupComboBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure tvGroupChange(Sender: TObject; Node: TTreeNode); procedure tvGroupDragDrop(Sender, Source: TObject; X, Y: Integer); procedure tvGroupDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure cmbBranchChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure sbtnNewClick(Sender: TObject); private { Private declarations } procedure PopulateTree; procedure PopulateGroupList; procedure FilterList; procedure UpdateTree; procedure EnableControls(const enable: boolean); procedure SaveAttributes; protected function EntryIsValid: boolean; override; function NewIsAllowed: boolean; override; function EditIsAllowed: boolean; override; procedure SearchList; override; procedure BindToObject; override; public { Public declarations } procedure New; override; function Save: boolean; override; end; implementation {$R *.dfm} uses EntitiesData, IFinanceDialogs, FormsUtil, AuxData; procedure TfrmGroupList.PopulateTree; var i, cnt: integer; function GetParentNode: TTreeNode; var n: integer; begin Result := nil; for n := 0 to tvGroup.Items.Count - 1 do if TGroup(tvGroup.Items[n].Data).GroupId = groups[i].ParentGroupId then begin Result := tvGroup.Items[n]; Exit; end; end; begin with tvGroup do begin Items.Clear; cnt := Length(groups) - 1; // loop through the list and insert items with no parent first for i := 0 to cnt do if not groups[i].HasParent then Items.AddObject(nil,groups[i].GroupName,groups[i]); // loop through the list and insert child items (with parent) for i := 0 to cnt do if groups[i].HasParent then Items.AddChildObject(GetParentNode,groups[i].GroupName,groups[i]); FullExpand; end; end; procedure TfrmGroupList.PopulateGroupList; var gp: TGroup; begin groups := []; with grList.DataSource.DataSet do begin DisableControls; First; while not Eof do begin gp := TGroup.Create; gp.GroupId := FieldByName('grp_id').AsString; gp.GroupName := FieldByName('grp_name').AsString; gp.ParentGroupId := FieldByName('par_grp_id').AsString; gp.IsActive := FieldByName('is_active').AsInteger; SetLength(groups,Length(groups) + 1); groups[Length(groups)-1] := gp; Next; end; First; EnableControls; end; end; procedure TfrmGroupList.FormClose(Sender: TObject; var Action: TCloseAction); begin dmEntities.Free; dmAux.Free; inherited; end; procedure TfrmGroupList.FormCreate(Sender: TObject); begin dmEntities := TdmEntities.Create(self); dmAux := TdmAux.Create(self); PopulateBranchComboBox(cmbBranch); inherited; end; procedure TfrmGroupList.FormShow(Sender: TObject); begin inherited; UpdateTree; end; procedure TfrmGroupList.New; begin inherited; TGroup.AddAttributes; end; function TfrmGroupList.NewIsAllowed: boolean; begin Result := true; end; procedure TfrmGroupList.UpdateTree; begin FilterList; PopulateGroupList; PopulateTree; if Length(groups) > 0 then begin EnableControls(not groups[0].HasParent); groups[0].GetAttributes; end; end; procedure TfrmGroupList.SearchList; begin grList.DataSource.DataSet.Locate('grp_name',edSearchKey.Text, [loPartialKey,loCaseInsensitive]); end; procedure TfrmGroupList.tvGroupChange(Sender: TObject; Node: TTreeNode); var groupId: string; begin groupId := TGroup(Node.Data).GroupId; grList.DataSource.DataSet.Locate('grp_id',groupId,[]); EnableControls(not TGroup(Node.Data).HasParent); TGroup(Node.Data).GetAttributes; end; procedure TfrmGroupList.tvGroupDragDrop(Sender, Source: TObject; X, Y: Integer); var src, dst: TTreeNode; begin src := tvGroup.Selected; dst := tvGroup.GetNodeAt(X,Y); src.MoveTo(dst, naAddChild); // apply destination properties to source TGroup(src.Data).ParentGroupId := TGroup(dst.Data).GroupId; TGroup(src.Data).IsActive := TGroup(dst.Data).IsActive; TGroup(src.Data).SaveChanges(src.Data); end; procedure TfrmGroupList.tvGroupDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var src, dst: TTreeNode; begin src := tvGroup.Selected; dst := tvGroup.GetNodeAt(X,Y); Accept := Assigned(dst) and (src<>dst); end; procedure TfrmGroupList.FilterList; var filterStr: string; begin if cmbBranch.ItemIndex > -1 then filterStr := 'loc_code = ''' + cmbBranch.Value + '''' else filterStr := ''; grList.DataSource.DataSet.Filter := filterStr; end; procedure TfrmGroupList.BindToObject; begin inherited; end; procedure TfrmGroupList.cmbBranchChange(Sender: TObject); begin inherited; UpdateTree; end; function TfrmGroupList.EditIsAllowed: boolean; begin Result := true; end; procedure TfrmGroupList.EnableControls(const enable: boolean); var i, cnt: integer; begin cnt := pnlDetail.ControlCount - 1; for i := 0 to cnt do begin if pnlDetail.Controls[i].Tag = 1 then begin if pnlDetail.Controls[i] is TRzDBNumericEdit then (pnlDetail.Controls[i] as TRzDBNumericEdit).Enabled := enable else if pnlDetail.Controls[i] is TRzDBLookupComboBox then (pnlDetail.Controls[i] as TRzDBLookupComboBox).Enabled := enable else if pnlDetail.Controls[i] is TRzDBEdit then (pnlDetail.Controls[i] as TRzDBEdit).Enabled := enable else if pnlDetail.Controls[i] is TRzDBCheckBox then (pnlDetail.Controls[i] as TRzDBCheckBox).ReadOnly := not enable; end; end; end; function TfrmGroupList.EntryIsValid: boolean; var error: string; begin if Trim(dbluBranch.Text) = '' then error := 'Please enter a group name.' else if Trim(edGroupName.Text) = '' then error := 'Please enter a group name.' else if Trim(edGroupName.Text) = (dbluParentGroup.Text) then error := 'Parent group cannot be the same as group.' // check attributes // only parent groups have attributes else if dbluParentGroup.KeyValue = null then begin if Trim(edMaxTotal.Text) = '' then error := 'Please enter maximum total.' else if edMaxTotal.Value < 0 then error := 'Invalid amount for maximum total.' else if dbluLoanType.Text = '' then error := 'Please select a loan type.'; end; if error <> '' then ShowErrorBox(error); Result := error = ''; end; function TfrmGroupList.Save: boolean; begin Result := false; if EntryIsValid then begin inherited Save; SaveAttributes; UpdateTree; Result := true; end; end; procedure TfrmGroupList.SaveAttributes; begin with dmEntities.dstGroupAttribute do begin if State in [dsInsert,dsEdit] then begin if dbluParentGroup.KeyValue = null then begin Post; UpdateBatch; end else CancelBatch; end; end; end; procedure TfrmGroupList.sbtnNewClick(Sender: TObject); begin inherited; grList.DataSource.DataSet.FieldByName('loc_code').AsString := cmbBranch.Value; end; end.
{ "DNS Query component" - Copyright (c) Danijel Tkalcec @html(<br>) @exclude } unit rtcDnsQuery; {$INCLUDE rtcDefs.inc} {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$R-} { Disable range checking } {$IFNDEF VER80} { Not for Delphi 1 } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF VER110} { C++ Builder V3.0 } {$ObjExportAll On} {$ENDIF} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, rtcConn, rtcUdpCli, WSocket_rtc; const DnsQueryVersion = 001; { Maximum answers (responses) count } MAX_ANCOUNT = 50; { Maximum number of MX records taken into account in responses } MAX_MX_RECORDS = 50; MAX_A_RECORDS = 50; { DNS Classes } DnsClassIN = 1; // The internet DnsClassCS = 2; // The CSNET class (obsolete, used only for examples) DnsClassCH = 3; // The CHAOS class DnsClassHS = 4; // Hesiod name service DnsClassALL = 255; // Any class { Type of query/response a DNS can handle } DnsQueryA = 1; // A HostAddress DnsQueryNS = 2; // NS Authoritative name server DnsQueryMD = 3; // MD MailDestination, obsolete, use Mail Exchange DnsQueryMF = 4; // MF MailForwarder, obsolete, use Mail Exchange DnsQueryCNAME = 5; // CNAME CanonicalName DnsQuerySOA = 6; // SOA Start of a Zone of Authority DnsQueryMB = 7; // MB MailBox, experimental DnsQueryMG = 8; // MG MailGroup, experimental DnsQueryMR = 9; // MR MailRename, experimental DnsQueryNULL = 10; // NULL Experimental DnsQueryWKS = 11; // WKS Well Known Service Description DnsQueryPTR = 12; // PTR Domain Name Pointer DnsQueryHINFO = 13; // HINFO Host Information DnsQueryMINFO = 14; // MINFO Mailbox information DnsQueryMX = 15; // MX Mail Exchange DnsQueryTXT = 16; // TXT Text Strings { Some additional type only allowed in queries } DnsQueryAXFR = 252; // Transfer for an entire zone DnsQueryMAILB = 253; // Mailbox related records (MB, MG or MR) DnsQueryMAILA = 254; // MailAgent, obsolete, use MX instead DnsQueryALL = 255; // Request ALL records { Opcode field in query flags } DnsOpCodeQUERY = 0; DnsOpCodeIQUERY = 1; DnsOpCodeSTATUS = 2; type TDnsAnswerNameArray = packed array [0..MAX_ANCOUNT - 1] of String; TDnsAnswerTypeArray = packed array [0..MAX_ANCOUNT - 1] of Integer; TDnsAnswerClassArray = packed array [0..MAX_ANCOUNT - 1] of Integer; TDnsAnswerTTLArray = packed array [0..MAX_ANCOUNT - 1] of LongInt; TDnsAnswerTagArray = packed array [0..MAX_ANCOUNT - 1] of Integer; TDnsMXPreferenceArray = packed array [0..MAX_MX_RECORDS - 1] of Integer; TDnsMXExchangeArray = packed array [0..MAX_MX_RECORDS - 1] of String; TDnsAddressArray = packed array [0..MAX_A_RECORDS - 1] of TInAddr; TDnsRequestDoneEvent = procedure (Sender : TObject; Error : WORD) of Object; TDnsRequestHeader = packed record ID : WORD; Flags : WORD; QDCount : WORD; ANCount : WORD; NSCount : WORD; ARCount : WORD; end; PDnsRequestHeader = ^TDnsRequestHeader; TRtcDnsQuery = class(TComponent) private { Déclarations privées } protected FWSocket : TRtcUdpClient; FPort : String; FAddr : String; FIDCount : WORD; FQueryBuf : array [0..511] of char; FQueryLen : Integer; FResponseBuf : array [0..511] of char; FResponseLen : Integer; FResponseID : Integer; FResponseCode : Integer; FResponseOpCode : Integer; FResponseAuthoritative : Boolean; FResponseTruncation : Boolean; FResponseRecursionAvailable : Boolean; FResponseQDCount : Integer; FResponseANCount : Integer; FResponseNSCount : Integer; FResponseARCount : Integer; FQuestionType : Integer; FQuestionClass : Integer; FQuestionName : String; FAnswerNameArray : TDnsAnswerNameArray; FAnswerTypeArray : TDnsAnswerTypeArray; FAnswerClassArray : TDnsAnswerClassArray; FAnswerTTLArray : TDnsAnswerTTLArray; FAnswerTagArray : TDnsAnswerTagArray; FMXRecordCount : Integer; FMXPreferenceArray : TDnsMXPreferenceArray; FMXExchangeArray : TDnsMXExchangeArray; FARecordCount : Integer; FAddressArray : TDnsAddressArray; FOnRequestDone : TDnsRequestDoneEvent; function GetMXPreference(nIndex : Integer) : Integer; function GetMXExchange(nIndex : Integer) : String; function GetAnswerName(nIndex : Integer) : String; function GetAnswerType(nIndex : Integer) : Integer; function GetAnswerClass(nIndex : Integer) : Integer; function GetAnswerTTL(nIndex : Integer) : LongInt; function GetAnswerTag(nIndex : Integer) : Integer; function GetAddress(nIndex : Integer) : TInAddr; procedure BuildRequestHeader(Dst : PDnsRequestHeader; ID : WORD; OPCode : BYTE; Recursion : Boolean; QDCount : WORD; ANCount : WORD; NSCount : WORD; ARCount : WORD); virtual; function BuildQuestionSection(Dst : PChar; const QName : String; QType : WORD; QClass : WORD) : Integer; virtual; procedure WSocketDataAvailable(Sender: TRtcConnection); virtual; procedure TriggerRequestDone(Error: WORD); virtual; function GetResponseBuf : PChar; procedure SendQuery; function ExtractName(Base : PChar; From : PChar; var Name : String) : PChar; function DecodeQuestion(Base : PChar; From : PChar; var Name : String; var QType : Integer; var QClass : Integer) : PChar; function DecodeAnswer(Base : PChar; From : PChar; var Name : String; var QType : Integer; var QClass : Integer; var TTL : LongInt; var RDataPtr : Pointer; var RDataLen : Integer) : PChar; function DecodeMXData(Base : PChar; From : PChar; var Preference : Integer; var Exchange : String) : PChar; function DecodeAData(Base : PChar; From : PChar; var Address : TInAddr) : PChar; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; operation: TOperation); override; function MXLookup(Domain : String) : Integer; function ALookup(Host : String) : Integer; property ResponseID : Integer read FResponseID; property ResponseCode : Integer read FResponseCode; property ResponseOpCode : Integer read FResponseOpCode; property ResponseAuthoritative : Boolean read FResponseAuthoritative; property ResponseTruncation : Boolean read FResponseTruncation; property ResponseRecursionAvailable : Boolean read FResponseRecursionAvailable; property ResponseQDCount : Integer read FResponseQDCount; property ResponseANCount : Integer read FResponseANCount; property ResponseNSCount : Integer read FResponseNSCount; property ResponseARCount : Integer read FResponseARCount; property ResponseBuf : PChar read GetResponseBuf; property ResponseLen : Integer read FResponseLen; property QuestionType : Integer read FQuestionType; property QuestionClass : Integer read FQuestionClass; property QuestionName : String read FQuestionName; property AnswerName[nIndex : Integer] : String read GetAnswerName; property AnswerType[nIndex : Integer] : Integer read GetAnswerType; property AnswerClass[nIndex : Integer] : Integer read GetAnswerClass; property AnswerTTL[nIndex : Integer] : LongInt read GetAnswerTTL; property AnswerTag[nIndex : Integer] : Integer read GetAnswerTag; property MXPreference[nIndex : Integer] : Integer read GetMXPreference; property MXExchange[nIndex : Integer] : String read GetMXExchange; property Address[nIndex : Integer] : TInAddr read GetAddress; published property Port : String read FPort write FPort; property Addr : String read FAddr write FAddr; property OnRequestDone : TDnsRequestDoneEvent read FOnRequestDone write FOnRequestDone; end; implementation type PWORD = ^WORD; PDWORD = ^DWORD; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TRtcDnsQuery.Create(AOwner : TComponent); begin inherited Create(AOwner); FWSocket := TRtcUdpClient.New; FPort := '53'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TRtcDnsQuery.Destroy; begin if Assigned(FWSocket) then begin FWSocket.Destroy; FWSocket := nil; end; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TRtcDnsQuery.Notification(AComponent: TComponent; operation: TOperation); begin inherited Notification(AComponent, operation); if operation = opRemove then begin if AComponent = FWSocket then FWSocket := nil; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetMXPreference(nIndex : Integer) : Integer; begin { Silently ignore index out of bounds error } if (nIndex < Low(FMXPreferenceArray)) or (nIndex > High(FMXPreferenceArray)) then Result := 0 else Result := FMXPreferenceArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetMXExchange(nIndex : Integer) : String; begin { Silently ignore index out of bounds error } if (nIndex < Low(FMXExchangeArray)) or (nIndex > High(FMXExchangeArray)) then Result := '' else Result := FMXExchangeArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetAnswerName(nIndex : Integer) : String; begin { Silently ignore index out of bounds error } if (nIndex < Low(FAnswerNameArray)) or (nIndex > High(FAnswerNameArray)) then Result := '' else Result := FAnswerNameArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetAnswerType(nIndex : Integer) : Integer; begin { Silently ignore index out of bounds error } if (nIndex < Low(FAnswerTypeArray)) or (nIndex > High(FAnswerTypeArray)) then Result := 0 else Result := FAnswerTypeArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetAnswerClass(nIndex : Integer) : Integer; begin { Silently ignore index out of bounds error } if (nIndex < Low(FAnswerClassArray)) or (nIndex > High(FAnswerClassArray)) then Result := 0 else Result := FAnswerClassArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetAnswerTTL(nIndex : Integer) : LongInt; begin { Silently ignore index out of bounds error } if (nIndex < Low(FAnswerTTLArray)) or (nIndex > High(FAnswerTTLArray)) then Result := 0 else Result := FAnswerTTLArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetAnswerTag(nIndex : Integer) : Integer; begin { Silently ignore index out of bounds error } if (nIndex < Low(FAnswerTagArray)) or (nIndex > High(FAnswerTagArray)) then Result := 0 else Result := FAnswerTagArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetAddress(nIndex : Integer) : TInAddr; begin { Silently ignore index out of bounds error } if (nIndex < Low(FAddressArray)) or (nIndex > High(FAddressArray)) then Result.S_addr := 0 else Result := FAddressArray[nIndex]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.GetResponseBuf : PChar; begin Result := @FResponseBuf; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.MXLookup(Domain : String) : Integer; begin Inc(FIDCount); BuildRequestHeader(PDnsRequestHeader(@FQueryBuf), FIDCount, DnsOpCodeQuery, TRUE, 1, 0, 0, 0); FQueryLen := BuildQuestionSection(@FQueryBuf[SizeOf(TDnsRequestHeader)], Domain, DnsQueryMX, DnsClassIN); FQueryLen := FQueryLen + SizeOf(TDnsRequestHeader); Result := FIDCount; SendQuery; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.ALookup(Host : String) : Integer; begin Inc(FIDCount); BuildRequestHeader(PDnsRequestHeader(@FQueryBuf), FIDCount, DnsOpCodeQuery, TRUE, 1, 0, 0, 0); FQueryLen := BuildQuestionSection(@FQueryBuf[SizeOf(TDnsRequestHeader)], Host, DnsQueryA, DnsClassIN); FQueryLen := FQueryLen + SizeOf(TDnsRequestHeader); Result := FIDCount; SendQuery; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TRtcDnsQuery.SendQuery; var s:string; begin FResponseLen := -1; FWSocket.OnDataReceived := WSocketDataAvailable; FWSocket.ServerPort := FPort; FWSocket.ServerAddr := FAddr; FWSocket.Connect; SetLength(s,FQueryLen); Move(FQueryBuf[0],s[1],FQueryLen); FWSocket.Write(s); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.BuildQuestionSection( Dst : PChar; const QName : String; QType : WORD; QClass : WORD) : Integer; var I : Integer; p : PChar; Ptr : PChar; begin Ptr := Dst; if Ptr = nil then begin Result := 0; Exit; end; I := 1; while I <= Length(QName) do begin p := Ptr; Inc(Ptr); while (I <= Length(QName)) and (QName[I] <> '.') do begin Ptr^ := QName[I]; Inc(Ptr); Inc(I); end; p^ := Chr(Ptr - p - 1); Inc(I); end; Ptr^ := #0; Inc(Ptr); PWORD(Ptr)^ := WSocket_htons(QType); Inc(Ptr, 2); PWORD(Ptr)^ := WSocket_htons(QClass); Inc(Ptr, 2); Result := Ptr - Dst; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TRtcDnsQuery.BuildRequestHeader( Dst : PDnsRequestHeader; ID : WORD; OPCode : BYTE; Recursion : Boolean; QDCount : WORD; ANCount : WORD; NSCount : WORD; ARCount : WORD); begin if Dst = nil then Exit; WinSockLoad; Dst^.ID := WSocket_htons(ID); Dst^.Flags := WSocket_htons((OpCode shl 11) + (Ord(Recursion) shl 8)); Dst^.QDCount := WSocket_htons(QDCount); Dst^.ANCount := WSocket_htons(ANCount); Dst^.NSCount := WSocket_htons(NSCount); Dst^.ARCount := WSocket_htons(ARCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TRtcDnsQuery.TriggerRequestDone(Error: WORD); begin if Assigned(FOnRequestDone) then FOnRequestDone(Self, Error); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TRtcDnsQuery.WSocketDataAvailable(Sender: TRtcConnection); var Len : Integer; Ans : PDnsRequestHeader; Flags : Integer; P : PChar; RDataPtr : Pointer; RDataLen : Integer; I : Integer; s:string; begin Ans := PDnsRequestHeader(@FResponseBuf); // Len := FWSocket.Receive(Ans, SizeOf(FResponseBuf)); {if Error <> 0 then begin TriggerRequestDone(Error); Exit; end;} s:=FWSocket.Read; Len:=length(s); if Len < SizeOf(TDnsRequestHeader) then Exit; Move(s[1],Ans^,SizeOf(FResponseBuf)); { Check for minimum response length } Flags := WSocket_htons(Ans^.Flags); { Check if we got a response } if (Flags and $8000) = 0 then Exit; FResponseLen := Len; { Decode response header } FResponseID := WSocket_htons(Ans^.ID); FResponseCode := Flags and $000F; FResponseOpCode := (Flags shr 11) and $000F; FResponseAuthoritative := (Flags and $0400) = $0400; FResponseTruncation := (Flags and $0200) = $0200; FResponseRecursionAvailable := (Flags and $0080) = $0080; FResponseQDCount := WSocket_ntohs(Ans^.QDCount); FResponseANCount := WSocket_ntohs(Ans^.ANCount); FResponseNSCount := WSocket_ntohs(Ans^.NSCount); FResponseARCount := WSocket_ntohs(Ans^.ARCount); P := @ResponseBuf[SizeOf(TDnsRequestHeader)]; if FResponseQDCount = 0 then begin { I don't think we could receive 0 questions } FQuestionName := ''; FQuestionType := 0; FQuestionClass := 0; end else begin { Should never be greater than 1 because we sent only one question } P := DecodeQuestion(@FResponseBuf, P, FQuestionName, FQuestionType, FQuestionClass); end; if FResponseANCount = 0 then begin // FAnswerName := ''; // FAnswerType := 0; // FAnswerClass := 0; // FAnswerTTL := 0; RDataPtr := nil; RDataLen := 0; FMXRecordCount := 0; end else begin FMXRecordCount := 0; for I := 0 to FResponseANCount - 1 do begin P := DecodeAnswer(@FResponseBuf, P, FAnswerNameArray[I], FAnswerTypeArray[I], FAnswerClassArray[I], FAnswerTTLArray[I], RDataPtr, RDataLen); FAnswerTagArray[I] := -1; case FAnswerTypeArray[I] of DnsQueryMX: begin if FMXRecordCount <= High(FMXPreferenceArray) then begin FAnswerTagArray[I] := FMXRecordCount; DecodeMXData(@FResponseBuf, RDataPtr, FMXPreferenceArray[FMXRecordCount], FMXExchangeArray[FMXRecordCount]); Inc(FMXRecordCount); end; end; DnsQueryA: begin if FARecordCount <= High(FAddressArray) then begin FAnswerTagArray[I] := FARecordCount; DecodeAData(@FResponseBuf, RDataPtr, FAddressArray[FARecordCount]); Inc(FARecordCount); end; end; end; end; end; TriggerRequestDone(0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.ExtractName( Base : PChar; From : PChar; var Name : String) : PChar; var N : Integer; I : Integer; P : PChar; NameEnd : String; begin P := From; if P^ = #0 then begin Name := ''; Inc(P); end else begin Name := ''; while TRUE do begin { Get name part length } N := Ord(P^); if (N and $C0) = $C0 then begin { Message compression } N := ((N and $3F) shl 8) + Ord(P[1]); if Length(Name) = 0 then ExtractName(Base, Base + N, Name) else begin ExtractName(Base, Base + N, NameEnd); Name := Name + NameEnd; end; Inc(P, 2); break; end; Inc(P); if N = 0 then break; { Copy name part } for I := 1 to N do begin Name := Name + P^; Inc(P); end; if P^ <> #0 then Name := Name + '.'; end; end; Result := P; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.DecodeQuestion( Base : PChar; From : PChar; var Name : String; var QType : Integer; var QClass : Integer) : PChar; var P : PChar; begin P := ExtractName(Base, From, Name); QType := WSocket_ntohs(PWORD(P)^); Inc(P, 2); QClass := WSocket_ntohs(PWORD(P)^); Inc(P, 2); Result := P; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.DecodeAnswer( Base : PChar; From : PChar; var Name : String; var QType : Integer; var QClass : Integer; var TTL : LongInt; var RDataPtr : Pointer; var RDataLen : Integer) : PChar; var P : PChar; begin P := ExtractName(Base, From, Name); QType := WSocket_ntohs(PWORD(P)^); Inc(P, 2); QClass := WSocket_ntohs(PWORD(P)^); Inc(P, 2); TTL := WSocket_ntohl(PDWORD(P)^); Inc(P, 4); RDataLen := WSocket_ntohs(PWORD(P)^); Inc(P, 2); RDataPtr := P; Result := P + RDataLen; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.DecodeMXData( Base : PChar; From : PChar; var Preference : Integer; var Exchange : String) : PChar; begin Result := From; Preference := WSocket_ntohs(PWORD(Result)^); Inc(Result, 2); Result := ExtractName(Base, Result, Exchange); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TRtcDnsQuery.DecodeAData( Base : PChar; From : PChar; var Address : TInAddr) : PChar; begin Result := From; Address.S_addr := PDWORD(Result)^; Inc(Result, 4); end; end.
unit UTimerSpy; {-$define _log_} {-$define _debug_} interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, Math {$ifdef _log_}, ULog {$endif}; const PH_PREF = 'ph_c832_cod_'; type TSpyType = (stSingle,stMulti); TResumeTimerType = (rttAsIs,rttResume,rttRestart); TTimerSpy = class(TObject) public DelaySec: Double; Enable: Boolean; Name: string; SpyType: TSpyType; TimeStartSec: Double; constructor Create; end; TProcHang = class(TObject) public CallingClassName: string; CallingProcName: string; DelaySec: Double; Handle: Integer; HangClassName: string; HangProcName: string; TimeStartSec: Double; constructor Create; end; TimerSpy = class(TObject) private class function Get(aName: string): TTimerSpy; static; class function GetCheck(aName:string): Boolean; static; class function GetDelaySec(aName:string): Double; static; class function GetEnable(aName:string): Boolean; static; class procedure SetDelaySec(aName:string; const Value: Double); static; class procedure SetEnable(aName:string; const Value: Boolean); static; public class procedure ALL_PAUSE(aSoftly:boolean = false); class procedure ALL_RESUME(aRestart:TResumeTimerType = rttRestart); class function DateTimeToSec(aDate:TDateTime): Double; class function GetTime: TDateTime; static; class function GetTimeFromStart: TDateTime; static; class function GetTimeFromStartSec: Double; static; class function GetTimeSec: Double; static; class function GetTimeStart: TDateTime; static; class function Init(aName: string; aDelaySec: double = 60; aSpyType: TSpyType = stMulti; aEnable: Boolean = false): TTimerSpy; static; class function _Check(aName: string): Boolean; static; class property Check[aName:string]: Boolean read GetCheck; default; class property DelaySec[aName:string]: Double read GetDelaySec write SetDelaySec; class property Enable[aName:string]: Boolean read GetEnable write SetEnable; end; ProcHang = class(TObject) protected class function _Assigned(aIndex: Integer = -1): Boolean; static; class function _Count: Integer; static; class function _Del(aRef: TProcHang): Boolean; static; class function _Item(aIndex: Integer): TProcHang; static; class function _ItemByHandle(aHandle: Integer): TProcHang; static; public class procedure Clear; static; class function GetHangProc: TProcHang; static; class function HaveHang: Boolean; static; class function start(aHangTimeSec: Double; aHangClassName, aHangProcName, aCallingClassName, aCallingProcName: string): Integer; static; class procedure stop(aHandle: Integer); static; class procedure TerminateThisApplication; static; class procedure MeasureProcessTimeStart(aProcessName:string);static; class function MeasureProcessTimeStopSec(aProcessName:string):double;static; class function MeasureProcessTimeStop(aProcessName:string):string;static; end; implementation var _Timers:array of TTimerSpy; _TimeStart:TDateTime; _Hangs:TList = nil; _MeasureProcess:TStringList = nil; _PauseTimers:TList; _PauseStartTimeSec:double; { ********************************** TTimerSpy *********************************** } constructor TTimerSpy.Create; begin inherited Create; Name:=''; DelaySec := 60; Enable := false; SpyType := stMulti; TimeStartSec := TimerSpy.GetTimeSec(); end; { ********************************** TProcHang *********************************** } constructor TProcHang.Create; begin inherited Create; Handle:=-1; DelaySec := 0; TimeStartSec := TimerSpy.GetTimeSec(); CallingProcName:=''; CallingClassName:=''; end; { *********************************** TimerSpy *********************************** } class procedure TimerSpy.ALL_PAUSE(aSoftly:boolean = false); var i: Integer; begin // приостанавливает работу всех таймеров, которые были активны if (_PauseTimers.Count>0) then begin if (not aSoftly) then begin ShowMessage('TimerSpy.ALL_PAUSE calling reusable. Call ALL_RESUME first'); exit; end; end; if (not aSoftly) or (_PauseTimers.Count = 0) then begin _PauseStartTimeSec:=GetTimeSec(); for i:=0 to Length(_Timers)-1 do begin if _Timers[i].Enable then begin _Timers[i].Enable:=false; _PauseTimers.Add(_Timers[i]); end; end; end; end; class procedure TimerSpy.ALL_RESUME(aRestart:TResumeTimerType = rttRestart); var i :integer; cTimer :TTimerSpy; cCurrentTime: Double; begin // возобновляет работу всех таймеров cCurrentTime:=GetTimeSec(); for i:=0 to _PauseTimers.Count-1 do begin cTimer:=TTimerSpy(_PauseTimers.Items[i]); case aRestart of rttResume: cTimer.TimeStartSec:=cTimer.TimeStartSec+(cCurrentTime-_PauseStartTimeSec); rttRestart: cTimer.TimeStartSec:=cCurrentTime; end;//case cTimer.Enable:=true; end; _PauseTimers.Clear; end; class function TimerSpy.DateTimeToSec(aDate:TDateTime): Double; begin result:=aDate*100000; end; class function TimerSpy.Get(aName: string): TTimerSpy; var i: Integer; cCount: Integer; begin cCount:=Length(_Timers); for i:=0 to cCount - 1 do begin result:=_Timers[i]; if UpperCase(Trim(result.Name)) = UpperCase(Trim(aName)) then exit; end; result:=nil; end; class function TimerSpy.GetCheck(aName:string): Boolean; begin result:=_Check(aName); end; class function TimerSpy.GetDelaySec(aName:string): Double; var cTimer: TTimerSpy; begin cTimer:=Get(aName); if cTimer<>nil then result:=cTimer.DelaySec else result:=-1; end; class function TimerSpy.GetEnable(aName:string): Boolean; var cTimer: TTimerSpy; begin cTimer:=Get(aName); if cTimer<>nil then result:=cTimer.Enable else result:=false; end; class function TimerSpy.GetTime: TDateTime; begin result:=Now(); end; class function TimerSpy.GetTimeFromStart: TDateTime; begin result:=TimerSpy.GetTime - _TimeStart; end; class function TimerSpy.GetTimeFromStartSec: Double; begin result:=TimerSpy.DateTimeToSec(TimerSpy.GetTimeFromStart()); end; class function TimerSpy.GetTimeSec: Double; begin result:=TimerSpy.DateTimeToSec(TimerSpy.GetTime()); end; class function TimerSpy.GetTimeStart: TDateTime; begin result:=_TimeStart; end; class function TimerSpy.Init(aName: string; aDelaySec: double = 60; aSpyType: TSpyType = stMulti; aEnable: Boolean = false): TTimerSpy; var cCount: Integer; begin result:=Get(aName); if result = nil then begin result:=TTimerSpy.Create; result.name:=aName; result.DelaySec:=aDelaySec; result.SpyType:=aSpyType; result.Enable:=aEnable; cCount:=Length(_Timers); Setlength(_Timers,cCount+1); _Timers[cCount]:=result; end; end; class procedure TimerSpy.SetDelaySec(aName:string; const Value: Double); var cTimer: TTimerSpy; begin cTimer:=Get(aName); if cTimer<>nil then cTimer.DelaySec:=Value; end; class procedure TimerSpy.SetEnable(aName:string; const Value: Boolean); var cTimer: TTimerSpy; begin cTimer:=Get(aName); if cTimer<>nil then begin if cTimer.Enable<>Value then begin cTimer.Enable:=Value; if cTimer.Enable then cTimer.TimeStartSec:=GetTimeSec(); end; end; end; class function TimerSpy._Check(aName: string): Boolean; var cTimer: TTimerSpy; cCurrentTime: Double; begin result:=false; cTimer:=Get(aName); if (cTimer = nil) or ( not cTimer.Enable) then exit; cCurrentTime:=GetTimeSec(); if (cTimer.TimeStartSec+cTimer.DelaySec)<=cCurrentTime then begin result:=true; if cTimer.SpyType = stSingle then begin cTimer.Enable:=false; end else begin cTimer.TimeStartSec:=cCurrentTime; end; end; end; { *********************************** ProcHang *********************************** } class procedure ProcHang.Clear; begin _Del(nil); end; class function ProcHang.GetHangProc: TProcHang; var cCurrentTime: Double; i: Integer; begin cCurrentTime:=TimerSpy.GetTimeSec; for i:=0 to _Count - 1 do begin result:=_Item(i); if (cCurrentTime - result.TimeStartSec>result.DelaySec) then exit; end; result:=nil; end; class function ProcHang.HaveHang: Boolean; begin result:=(GetHangProc<>nil); end; class procedure ProcHang.MeasureProcessTimeStart(aProcessName: string); begin // засекаем, сколько времени работает процесс if _MeasureProcess = nil then _MeasureProcess:=TStringList.Create; _MeasureProcess.Values[aProcessName]:=FloatToStr(TimerSpy.GetTimeSec()); end; class function ProcHang.MeasureProcessTimeStopSec(aProcessName: string): double; var aIndex: Integer; begin aIndex:=_MeasureProcess.IndexOfName(aProcessName); if aIndex>=0 then begin result:=TimerSpy.GetTimeSec - StrToFloat(_MeasureProcess.ValueFromIndex[aIndex]); _MeasureProcess.Delete(aIndex); end else result:=-1; end; class function ProcHang.MeasureProcessTimeStop(aProcessName: string): string; begin result:=Format('Time of [%s] = %2.3f sec.',[aProcessName,ProcHang.MeasureProcessTimeStopSec(aProcessName)]); end; class function ProcHang.start(aHangTimeSec: Double; aHangClassName, aHangProcName, aCallingClassName, aCallingProcName: string): Integer; const cFuncName = 'start'; var cMax: Integer; i: Integer; cRef: TProcHang; begin cMax:=-1; for i:=0 to _Count-1 do begin cRef:=_Item(i); if i = 0 then cMax:=cRef.Handle else cMax:=Max(cref.Handle,cMax); end; cMax:=cMax+1; cRef:=TProcHang.Create; cRef.Handle :=cMax; cRef.DelaySec :=aHangTimeSec; cRef.HangProcName :=aHangProcName; cRef.HangClassName :=aHangClassName; cRef.CallingProcName :=aCallingProcName; cRef.CallingClassName :=aCallingClassName; _Hangs.Add(cRef); result:=cRef.Handle; {$ifdef _debug_}ULog.Log('Handle='+IntToStr(cRef.Handle)+' '+aHangClassName+'.'+aHangProcName+' from '+aCallingClassName+'.'+aCallingProcName,ClassName,cFuncName);{$endif} end; class procedure ProcHang.stop(aHandle: Integer); const cFuncName = 'stop'; var cRef: TProcHang; begin cRef:=_ItemByHandle(aHandle); {$ifdef _debug_}ULog.Log('Handle='+IntToStr(cRef.Handle)+' '+cRef.HangClassName+'.'+cRef.HangProcName+' from '+cRef.CallingClassName+'.'+cref.CallingProcName,ClassName,cFuncName);{$endif} _Del(cRef); end; class procedure ProcHang.TerminateThisApplication; const PROCESS_TERMINATE=$0001; begin TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0), GetCurrentProcessId), 0); end; class function ProcHang._Assigned(aIndex: Integer = -1): Boolean; begin result:=(_Hangs<>nil); if (result) and (aIndex>=0) then result:=(aIndex>=0) and (aIndex<_Hangs.Count); end; class function ProcHang._Count: Integer; begin result:=0; if _Assigned() then result:=_Hangs.Count; end; class function ProcHang._Del(aRef: TProcHang): Boolean; var cIndex: Integer; begin result:=true; if aRef = nil then begin while _Hangs.Count >0 do _Del(_Hangs.Items[_Hangs.Count-1]); end else begin cIndex:=_Hangs.IndexOf(aRef); _Hangs.Delete(cIndex); aRef.Free; end; end; class function ProcHang._Item(aIndex: Integer): TProcHang; begin result:=nil; if _Assigned(aIndex) then result:=TProcHang(_Hangs.Items[aIndex]); end; class function ProcHang._ItemByHandle(aHandle: Integer): TProcHang; var i: Integer; begin for i:=0 to _Count-1 do begin result:=_Item(i); if result.Handle = aHandle then exit; end; result:=nil; end; initialization _PauseTimers:=TList.Create; _TimeStart:=TimerSpy.GetTime; _Hangs:=TList.Create; finalization ProcHang.Clear; _Hangs.Free; _Hangs:=nil; if _MeasureProcess <> nil then _MeasureProcess.Free; _PauseTimers.Free; end.
unit GC.LaserCutBoxes.Box.Sides; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TLaserCutBoxSideType } TLaserCutBoxSideType = (bstTop, bstBottom, bstLeft, bstRight, bstBack, bstFront); { TLaserCutBoxSide } TLaserCutBoxSide = class(TObject) private FSideType: TLaserCutBoxSideType; FWidth: Double; FHeight: Double; FTabsWidth: Double; FLegend: String; procedure SetHeight(Value: Double); procedure SetLegend(Value: String); procedure SetWidth(Value: Double); procedure SetTabsWidth(Value: Double); procedure ReCalculate; protected public constructor Create(aSideType: TLaserCutBoxSideType); destructor Destroy; override; property SideType: TLaserCutBoxSideType read FSideType; property Width: Double read FWidth write SetWidth; property Height: Double read FHeight write SetHeight; property TabsWidth: Double read FTabsWidth write SetTabsWidth; property Legend: String read FLegend write SetLegend; end; implementation { TLaserCutBoxSide } constructor TLaserCutBoxSide.Create(aSideType: TLaserCutBoxSideType); begin FSideType := aSideType; FWidth := 0.0; FHeight := 0.0; FTabsWidth := 0.0; case FSideType of bstTop: FLegend := 'Top'; bstBottom: FLegend := 'Bottom'; bstLeft: FLegend := 'Left'; bstRight: FLegend := 'Right'; bstBack: FLegend := 'Back'; bstFront: FLegend := 'Front'; end; end; destructor TLaserCutBoxSide.Destroy; begin inherited Destroy; end; procedure TLaserCutBoxSide.ReCalculate; begin // end; procedure TLaserCutBoxSide.SetHeight(Value: Double); begin if FHeight = Value then Exit; FHeight := Value; ReCalculate; end; procedure TLaserCutBoxSide.SetLegend(Value: String); begin if FLegend = Value then Exit; FLegend := Value; ReCalculate; end; procedure TLaserCutBoxSide.SetWidth(Value: Double); begin if FWidth = Value then Exit; FWidth := Value; ReCalculate; end; procedure TLaserCutBoxSide.SetTabsWidth(Value: Double); begin if FTabsWidth = Value then Exit; FTabsWidth := Value; ReCalculate; end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.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. } {$I DDuce.inc} unit DDuce.Components.ValueList; interface uses System.Classes, System.Types, Vcl.Graphics, VirtualTrees, Spring, Spring.Collections, DDuce.Components.VirtualTrees.Node, DDuce.Factories.VirtualTrees, DDuce.DynamicRecord; type TValueListNode = TVTNode<IDynamicField>; type TValueList = class(TCustomVirtualStringTree) private FData : IDynamicRecord; procedure SetFocusedField(const Value: IDynamicField); protected {$REGION 'property access methods'} procedure SetNameColumn(const Value: TVirtualTreeColumn); procedure SetValueColumn(const Value: TVirtualTreeColumn); function GetEditable: Boolean; procedure SetEditable(const Value: Boolean); function GetNameColumn: TVirtualTreeColumn; function GetValueColumn: TVirtualTreeColumn; function GetShowHeader: Boolean; procedure SetShowHeader(const Value: Boolean); function GetData: IDynamicRecord; procedure SetData(const Value: IDynamicRecord); function GetMultiSelect: Boolean; procedure SetMultiSelect(const Value: Boolean); function GetShowGutter: Boolean; procedure SetShowGutter(const Value: Boolean); function GetFocusedField: IDynamicField; {$ENDREGION} procedure Initialize; procedure BuildTree; procedure DoGetText(var pEventArgs: TVSTGetCellTextEventArgs); override; procedure DoBeforeCellPaint( Canvas : TCanvas; Node : PVirtualNode; Column : TColumnIndex; CellPaintMode : TVTCellPaintMode; CellRect : TRect; var ContentRect : TRect ); override; procedure DoNewText( Node : PVirtualNode; Column : TColumnIndex; const Text : string ); override; procedure DoTextDrawing( var PaintInfo : TVTPaintInfo; const Text : string; CellRect : TRect; DrawFormat : Cardinal ); override; procedure DoFreeNode(Node: PVirtualNode); override; public procedure AfterConstruction; override; destructor Destroy; override; procedure Repaint; override; procedure Refresh; virtual; property Data: IDynamicRecord read GetData write SetData; published property Align; property Alignment; property Anchors; property Background; property BackgroundOffsetX; property BackgroundOffsetY; property BiDiMode; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind; property BevelWidth; property BorderStyle; property BottomSpace; property ButtonFillMode; property ButtonStyle; property BorderWidth; property ChangeDelay; property ClipboardFormats; property Color; property Colors; property Constraints; property Ctl3D; property CustomCheckImages; property DefaultNodeHeight; property DefaultPasteMode; property DragCursor; property DragHeight; property DragKind; property DragImageKind; property DragMode; property DragOperations; property DragType; property DragWidth; property DrawSelectionMode; property EditDelay; property Enabled; property Font; property HintMode; property HotCursor; property Images; property IncrementalSearch; property IncrementalSearchDirection; property IncrementalSearchStart; property IncrementalSearchTimeout; property Indent; property LineMode; property LineStyle; property Margin; property OnEnter; property OnExit; property ParentBiDiMode; property ParentColor default False; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ScrollBarOptions; property SelectionBlendFactor; property SelectionCurveRadius; property ShowHint; property TreeOptions; property Touch; property StateImages; property StyleElements; property TabOrder; property TabStop default True; property TextMargin; property Visible; property WantTabs; property ShowHeader: Boolean read GetShowHeader write SetShowHeader; property ShowGutter: Boolean read GetShowGutter write SetShowGutter; property Editable: Boolean read GetEditable write SetEditable; property FocusedField: IDynamicField read GetFocusedField write SetFocusedField; property MultiSelect: Boolean read GetMultiSelect write SetMultiSelect; property NameColumn: TVirtualTreeColumn read GetNameColumn write SetNameColumn; property ValueColumn: TVirtualTreeColumn read GetValueColumn write SetValueColumn; end; implementation uses System.SysUtils, Vcl.Forms, Vcl.Controls; const GUTTER_COLUMN = 0; NAME_COLUMN = 1; VALUE_COLUMN = 2; {$REGION 'construction and destruction'} procedure TValueList.AfterConstruction; begin inherited AfterConstruction; Initialize; end; destructor TValueList.Destroy; begin FData := nil; inherited Destroy; end; {$ENDREGION} {$REGION 'property access methods'} function TValueList.GetData: IDynamicRecord; begin Result := FData; end; procedure TValueList.SetData(const Value: IDynamicRecord); begin if Value <> Data then begin FData := Value; if Assigned(FData) then begin NodeDataSize := SizeOf(TValueListNode); BuildTree; Header.AutoFitColumns; end; end; end; function TValueList.GetEditable: Boolean; begin Result := toEditable in TreeOptions.MiscOptions; end; procedure TValueList.SetEditable(const Value: Boolean); begin if Value <> Editable then begin if Value then TreeOptions.MiscOptions := TreeOptions.MiscOptions + [toEditable] else TreeOptions.MiscOptions := TreeOptions.MiscOptions - [toEditable]; end; end; function TValueList.GetMultiSelect: Boolean; begin Result := toMultiSelect in TreeOptions.SelectionOptions; end; procedure TValueList.SetMultiSelect(const Value: Boolean); begin if Value <> MultiSelect then begin if Value then TreeOptions.SelectionOptions := TreeOptions.SelectionOptions + [toMultiSelect] else TreeOptions.SelectionOptions := TreeOptions.SelectionOptions - [toMultiSelect]; end; end; function TValueList.GetNameColumn: TVirtualTreeColumn; begin Result := Header.Columns.Items[NAME_COLUMN]; end; procedure TValueList.SetNameColumn(const Value: TVirtualTreeColumn); begin Header.Columns.Items[NAME_COLUMN].Assign(Value); end; function TValueList.GetValueColumn: TVirtualTreeColumn; begin Result := Header.Columns.Items[VALUE_COLUMN]; end; procedure TValueList.SetValueColumn(const Value: TVirtualTreeColumn); begin Header.Columns.Items[VALUE_COLUMN].Assign(Value); end; function TValueList.GetFocusedField: IDynamicField; var N : TValueListNode; begin N := GetNodeData<TValueListNode>(FocusedNode); if Assigned(N) then Result := N.Data else Result := nil; end; procedure TValueList.SetFocusedField(const Value: IDynamicField); var VN : PVirtualNode; N : TValueListNode; begin BeginUpdate; for VN in Nodes do begin N := GetNodeData<TValueListNode>(VN); if Assigned(N) and (N.Data = Value) then begin ClearSelection; FocusedNode := VN; Selected[VN] := True; Break; end; end; EndUpdate; end; function TValueList.GetShowGutter: Boolean; begin Result := coVisible in Header.Columns.Items[GUTTER_COLUMN].Options; end; procedure TValueList.SetShowGutter(const Value: Boolean); begin if Value <> ShowGutter then begin if Value then Header.Columns.Items[GUTTER_COLUMN].Options := Header.Columns.Items[GUTTER_COLUMN].Options + [coVisible] else Header.Columns.Items[GUTTER_COLUMN].Options := Header.Columns.Items[GUTTER_COLUMN].Options - [coVisible]; end; end; function TValueList.GetShowHeader: Boolean; begin Result := hoVisible in Header.Options; end; procedure TValueList.SetShowHeader(const Value: Boolean); begin if Value <> ShowHeader then begin if Value then Header.Options := Header.Options + [hoVisible] else Header.Options := Header.Options - [hoVisible]; end; end; {$ENDREGION} {$REGION 'event dispatch methods'} procedure TValueList.DoBeforeCellPaint(Canvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); //var // L : Integer; begin // L := GetNodeLevel(Node); // ContentRect.Offset(2, 0); // if (Column = NAME_COLUMN) and (CellPaintMode = cpmPaint) then // begin // Canvas.Brush.Color := clCream; // if L = 0 then // begin // Canvas.Pen.Color := clGray; // Canvas.MoveTo(CellRect.Left + 12, CellRect.Top); // Canvas.LineTo(CellRect.Left + 12, CellRect.Top + CellRect.Height); // Canvas.FillRect(Rect(0, 0, 12, CellRect.Height)); // end // else // begin // Canvas.FillRect(Rect(0, 0, 20, CellRect.Height)); // Canvas.Pen.Color := clGray; // Canvas.MoveTo(CellRect.Left + 12, CellRect.Top); // Canvas.LineTo(CellRect.Left + 20, CellRect.Top); // Canvas.LineTo(CellRect.Left + 20, CellRect.Top + CellRect.Height - 1); // Canvas.LineTo(CellRect.Left + 12, CellRect.Top + CellRect.Height - 1); // end; // end; inherited DoBeforeCellPaint( Canvas, Node, Column, CellPaintMode, CellRect, ContentRect ); end; procedure TValueList.DoFreeNode(Node: PVirtualNode); var N : TValueListNode; begin N := GetNodeData<TValueListNode>(Node); N.Free; inherited DoFreeNode(Node); end; procedure TValueList.DoGetText(var pEventArgs: TVSTGetCellTextEventArgs); var N : TValueListNode; begin inherited DoGetText(pEventArgs); N := GetNodeData<TValueListNode>(pEventArgs.Node); if Assigned(N) then begin if pEventArgs.Column = NAME_COLUMN then begin pEventArgs.CellText := N.Data.Name end else if pEventArgs.Column = VALUE_COLUMN then begin pEventArgs.CellText := N.Data.Value.ToString; end; end; end; { Gets called after text has been edited. } procedure TValueList.DoNewText(Node: PVirtualNode; Column: TColumnIndex; const Text: string); var N : TValueListNode; begin N := GetNodeData<TValueListNode>(Node); if Column = NAME_COLUMN then N.Data.Name := Text else if Column = VALUE_COLUMN then N.Data.Value := Text; inherited DoNewText(Node, Column, Text); end; procedure TValueList.DoTextDrawing(var PaintInfo: TVTPaintInfo; const Text: string; CellRect: TRect; DrawFormat: Cardinal); begin (* { DrawText() Format Flags } DT_TOP = 0; DT_LEFT = 0; DT_CENTER = 1; DT_RIGHT = 2; DT_VCENTER = 4; DT_BOTTOM = 8; DT_WORDBREAK = $10; DT_SINGLELINE = $20; DT_EXPANDTABS = $40; DT_TABSTOP = $80; DT_NOCLIP = $100; DT_EXTERNALLEADING = $200; DT_CALCRECT = $400; DT_NOPREFIX = $800; DT_INTERNAL = $1000; DT_EDITCONTROL = $2000; DT_PATH_ELLIPSIS = $4000; DT_END_ELLIPSIS = $8000; DT_MODIFYSTRING = $10000; DT_RTLREADING = $20000; DT_WORD_ELLIPSIS = $40000; DT_NOFULLWIDTHCHARBREAK = $0080000; DT_HIDEPREFIX = $00100000; DT_PREFIXONLY = $00200000; *) inherited DoTextDrawing(PaintInfo, Text, CellRect, DrawFormat); end; {$ENDREGION} {$REGION 'protected methods'} procedure TValueList.BuildTree; var LField : IDynamicField; begin BeginUpdate; Clear; for LField in FData do begin TValueListNode.Create(Self, LField); end; FullExpand; EndUpdate; end; procedure TValueList.Initialize; begin Header.Options := [ hoAutoResize, hoColumnResize, hoDblClickResize, hoRestrictDrag, hoShowHint, hoShowImages, hoShowSortGlyphs, hoAutoSpring, hoVisible, hoDisableAnimatedResize ]; TreeOptions.PaintOptions := [ toHideFocusRect, toHotTrack, toPopupMode, toShowBackground, toShowButtons, toShowDropmark, toStaticBackground, toShowRoot, toShowVertGridLines, toThemeAware, toUseBlendedImages, toUseBlendedSelection, toStaticBackground, toUseExplorerTheme ]; TreeOptions.AnimationOptions := []; TreeOptions.AutoOptions := [ toAutoDropExpand, toAutoScroll, toAutoScrollOnExpand, toAutoSort, toAutoTristateTracking, toAutoDeleteMovedNodes, toAutoChangeScale, toDisableAutoscrollOnEdit, toAutoBidiColumnOrdering ]; TreeOptions.SelectionOptions := [toExtendedFocus, toFullRowSelect, toAlwaysSelectNode]; // toGridExtensions causes the inline editor to have the full size of the cell TreeOptions.MiscOptions := [ toCheckSupport, toInitOnSave, toWheelPanning, toVariableNodeHeight, toEditable, toEditOnDblClick, toGridExtensions ]; TreeOptions.EditOptions := toVerticalEdit; with Header.Columns.Add do begin Color := clCream; MaxWidth := 12; MinWidth := 12; Options := [coFixed, coAllowClick, coEnabled, coParentBidiMode, coVisible]; Position := GUTTER_COLUMN; Width := 12; Text := ''; end; with Header.Columns.Add do begin Color := clWhite; MaxWidth := 400; MinWidth := 80; // needs to be coFixed to allow column resizing when no header is shown. Options := [coFixed, coAllowClick, coEnabled, coParentBidiMode, coResizable, coVisible, coAutoSpring, coSmartResize, coAllowFocus, coEditable]; Position := NAME_COLUMN; Width := 100; Text := 'Name'; end; with Header.Columns.Add do begin MaxWidth := 800; MinWidth := 50; Options := [coAllowClick, coEnabled, coParentBidiMode, coResizable, coVisible, coAutoSpring, coAllowFocus, coEditable]; Position := VALUE_COLUMN; Width := 100; Text := 'Value'; EditOptions := toVerticalEdit; end; Header.MainColumn := GUTTER_COLUMN; Header.AutoSizeIndex := VALUE_COLUMN; Indent := 0; // pixels between node levels Margin := 0; LineMode := lmBands; LineStyle := lsSolid; DrawSelectionMode := smBlendedRectangle; HintMode := hmTooltip; Colors.SelectionRectangleBlendColor := clGray; Colors.SelectionTextColor := clBlack; end; procedure TValueList.Refresh; var F : IDynamicField; begin F := FocusedField; Repaint; FocusedField := F; end; procedure TValueList.Repaint; begin BuildTree; inherited Repaint; end; {$ENDREGION} end.
unit Node; {$mode objfpc}{$H+}{$J-} {$modeswitch nestedprocvars} interface uses LGHashMap; type { INode } INode = interface ['{A8ECD00D-5DEB-44EE-990A-DD3036081382}'] function NextGeneration: INode; function CenteredSubnode: INode; function CenteredSubSubNode: INode; function GetNW: INode; function GetNE: INode; function GetSW: INode; function GetSE: INode; function GetLevel: Cardinal; function GetPopulation: Cardinal; function GetAlive: Boolean; function GetBit(const X, Y: Integer): Integer; function SetBit(const X, Y: Integer): INode; function EmptyTree(const Level: Cardinal): INode; function ExpandUniverse: INode; function GetLastUsed: TDateTime; procedure SetLastUsed(const Value: TDateTime); property NW: INode read GetNW; property NE: INode read GetNE; property SW: INode read GetSW; property SE: INode read GetSE; property Level: Cardinal read GetLevel; property Population: Cardinal read GetPopulation; property Alive: Boolean read GetAlive; property LastUsed: TDateTime read GetLastUsed write SetLastUsed; end; { TNode } TNode = class(TInterfacedObject, INode) private type TNodeHashMap = specialize TGBaseHashMapQP<INode, INode, TNode>; class var FNodeHashMap: TNodeHashMap; class constructor Create; class destructor Destroy; var FNW, FNE: INode; FSW, FSE: INode; FLevel: Cardinal; FPopulation: Cardinal; FAlive: Boolean; FResult: INode; FLastUsed: TDateTime; {%H-}constructor Init(const Alive: Boolean); {%H-}constructor Init(const NW, NE, SW, SE: INode); function GetNW: INode; function GetNE: INode; function GetSW: INode; function GetSE: INode; function GetLevel: Cardinal; function GetPopulation: Cardinal; function GetAlive: Boolean; class function OneGen(Bitmask: UInt16): INode; function SlowSimulation: INode; function EmptyTree(const Level: Cardinal): INode; function ExpandUniverse: INode; function GetLastUsed: TDateTime; procedure SetLastUsed(const Value: TDateTime); class function HashCode(constref Node: INode): SizeInt; class function Equal(constref L, R: INode): Boolean; public class function Create: INode; class function Create(const Alive: Boolean): INode; class function Create(const NW, NE, SW, SE: INode): INode; function NextGeneration: INode; function CenteredSubnode: INode; function CenteredSubSubNode: INode; class function CenteredHorizontalSubnode(const W, E: INode): INode; class function CenteredVerticalSubnode(const N, S: INode): INode; function GetBit(const X, Y: Integer): Integer; function SetBit(const X, Y: Integer): INode; class procedure GarbageCollector; end; implementation uses Math, SysUtils, DateUtils, LGHash; class constructor TNode.Create; begin FNodeHashMap := TNodeHashMap.Create; end; class destructor TNode.Destroy; begin FNodeHashMap.Free; end; function TNode.GetNW: INode; begin Result := FNW; end; function TNode.GetNE: INode; begin Result := FNE; end; function TNode.GetSW: INode; begin Result := FSW; end; function TNode.GetSE: INode; begin Result := FSE; end; function TNode.GetLevel: Cardinal; begin Result := FLevel; end; function TNode.GetPopulation: Cardinal; begin Result := FPopulation; end; function TNode.GetAlive: Boolean; begin Result := FAlive; end; class function TNode.OneGen(Bitmask: UInt16): INode; var Alive: Integer; NeighborCount: Integer; begin if Bitmask = 0 then Exit(TNode.Create(False)); Alive := (Bitmask shr 5) and 1; Bitmask := Bitmask and $757; NeighborCount := 0; while Bitmask <> 0 do begin Inc(NeighborCount); Bitmask := Bitmask and (Bitmask - 1); end; Result := TNode.Create((NeighborCount = 3) or ((Alive = 1) and (NeighborCount = 2))); end; function TNode.SlowSimulation: INode; var x, y: Integer; AllBits: UInt16; begin AllBits := 0; for y := -2 to 1 do begin for x := -2 to 1 do begin AllBits := (AllBits shl 1) or GetBit(x, y); end; end; Result := Tnode.Create( TNode.OneGen(AllBits shr 5), TNode.OneGen(AllBits shr 4), TNode.OneGen(AllBits shr 1), TNode.OneGen(AllBits) ); end; function TNode.EmptyTree(const Level: Cardinal): INode; var Node: INode; begin if Level = 0 then Exit(TNode.Create(False)); Node := EmptyTree(Level - 1); Result := TNode.Create( Node, Node, Node, Node ); end; function TNode.ExpandUniverse: INode; var Border: INode; begin Border := EmptyTree(FLevel - 1); Result := TNode.Create( Tnode.Create( Border, Border, Border, FNW ), Tnode.Create( Border, Border, FNE, Border ), Tnode.Create( Border, FSW, Border, Border ), Tnode.Create( FSE, Border, Border, Border ) ); end; function TNode.GetLastUsed: TDateTime; begin Result := FLastUsed; end; procedure TNode.SetLastUsed(const Value: TDateTime); begin FLastUsed := Value; end; function TNode.GetBit(const X, Y: Integer): Integer; var Offset: Integer; begin if FLevel = 0 then Exit(IfThen(FAlive, 1)); Offset := (1 shl FLevel) shr 2; if X < 0 then begin if Y < 0 then Result := FNW.GetBit(X + Offset, Y + Offset) else Result := FSW.GetBit(X + Offset, Y - Offset); end else begin if Y < 0 then Result := FNE.GetBit(X - Offset, Y + Offset) else Result := FSE.GetBit(X - Offset, Y - Offset); end; end; function TNode.SetBit(const X, Y: Integer): INode; var Offset: Integer; begin if FLevel = 0 then Exit(TNode.Create(True)); Offset := (1 shl FLevel) shr 2; if X < 0 then begin if Y < 0 then Result := TNode.Create( FNW.SetBit(X + Offset, Y + Offset), FNE, FSW, FSE ) else Result := TNode.Create( FNW, FNE, FSW.SetBit(X + Offset, Y - Offset), FSE ); end else begin if Y < 0 then Result := TNode.Create( FNW, FNE.SetBit(X - Offset, Y + Offset), FSW, FSE ) else Result := TNode.Create( FNW, FNE, FSW, FSE.SetBit(X - Offset, Y - Offset) ); end; end; class procedure TNode.GarbageCollector; function TestNode(const Node: INode): Boolean; begin Result := ((Node as TNode).RefCount < 3) and (SecondsBetween(Now, Node.LastUsed) > 30); end; begin FNodeHashMap.RemoveIf(@TestNode); end; constructor TNode.Init(const Alive: Boolean); begin inherited Create; FAlive := Alive; FPopulation := IfThen(FAlive, 1); FLastUsed := Now; end; constructor TNode.Init(const NW, NE, SW, SE: INode); begin inherited Create; FNW := NW; FNE := NE; FSW := SW; FSE := SE; FLevel := FNW.Level + 1; FPopulation := FNW.Population + FNE.Population + FSW.Population + FSE.Population; FLastUsed := Now; end; class function TNode.Create: INode; begin Result := TNode.Create(False).EmptyTree(3); FNodeHashMap.Clear; end; class function TNode.Create(const Alive: Boolean): INode; begin Result := Init(Alive); if not FNodeHashMap.Add(Result, Result) then begin Result := FNodeHashMap[Result]; Result.LastUsed := Now; end; end; class function TNode.Create(const NW, NE, SW, SE: INode): INode; begin Result := Init(NW, NE, SW, SE); if not FNodeHashMap.Add(Result, Result) then begin Result := FNodeHashMap[Result]; Result.LastUsed := Now; end; end; function TNode.NextGeneration: INode; var N00, N01, N02: INode; N10, N11, N12: INode; N20, N21, N22: INode; begin if Assigned(FResult) then Exit(FResult); if FPopulation = 0 then Result := FNW else if FLevel = 2 then Result := SlowSimulation else begin N00 := FNW.CenteredSubnode; N01 := CenteredHorizontalSubnode(FNW, FNE); N02 := FNE.CenteredSubnode; N10 := CenteredVerticalSubnode(FNW, FSW); N11 := CenteredSubSubNode; N12 := CenteredVerticalSubnode(FNE, FSE); N20 := FSW.CenteredSubnode; N21 := CenteredHorizontalSubnode(FSW, FSE); N22 := FSE.CenteredSubnode; Result := TNode.Create( TNode.Create( N00, N01, N10, N11 ).NextGeneration, TNode.Create( N01, N02, N11, N12 ).NextGeneration, TNode.Create( N10, N11, N20, N21 ).NextGeneration, TNode.Create( N11, N12, N21, N22 ).NextGeneration ); end; FResult := Result; end; function TNode.CenteredSubnode: INode; begin Result := TNode.Create( FNW.SE, FNE.SW, FSW.NE, FSE.NW ); end; function TNode.CenteredSubSubNode: INode; begin Result := TNode.Create( FNW.SE.SE, FNE.SW.SW, FSW.NE.NE, FSE.NW.NW ); end; class function TNode.CenteredHorizontalSubnode(const W, E: INode): INode; begin Result := TNode.Create( W.NE.SE, E.NW.SW, W.SE.NE, E.SW.NW ); end; class function TNode.CenteredVerticalSubnode(const N, S: INode): INode; begin Result := TNode.Create( N.SW.SE, N.SE.SW, S.NW.NE, S.NE.NW ); end; class function TNode.HashCode(constref Node: INode): SizeInt; begin if Node.Level = 0 then Exit(Node.Population); {$ifdef CPU64} Result := TxxHash32LE.HashQWord(QWord(Node.NW)); Result := TxxHash32LE.HashQWord(QWord(Node.NE), Result); Result := TxxHash32LE.HashQWord(QWord(Node.SW), Result); Result := TxxHash32LE.HashQWord(QWord(Node.SE), Result); {$else} Result := TxxHash32LE.HashDWord(DWord(Node.NW)); Result := TxxHash32LE.HashDWord(DWord(Node.NE), Result); Result := TxxHash32LE.HashDWord(DWord(Node.SW), Result); Result := TxxHash32LE.HashDWord(DWord(Node.SE), Result); {$endif} end; class function TNode.Equal(constref L, R: INode): Boolean; begin if L.Level <> R.Level then Exit(False); if L.Level = 0 then Result := (L.Alive = R.Alive) else Result := (L.NW = R.NW) and (L.NE = R.NE) and (L.SW = R.SW) and (L.SE = R.SE); end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, winsock, TCPClientCollection, ExtCtrls; type TForm1 = class(TForm) bStartServer: TButton; Memo1: TMemo; SocketCheckTimer: TTimer; procedure SocketCheckTimerTimer(Sender: TObject); procedure bStartServerClick(Sender: TObject); private { Private declarations } public SocketCoord: TSocketCoordinator; ServerActive: Boolean; { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses MessageCollection; {procedure TestWinSockError(S:String); function TestFuncError(iErr:Integer; FuncName:String):Boolean; begin Result:=false; if iErr = SOCKET_ERROR then begin TestWinSockError(FuncName); Result:=true; end; end; } procedure TForm1.bStartServerClick(Sender: TObject); begin SocketCoord:=TSocketCoordinator.Create(5050); SocketCoord.Resume; ServerActive:=True; end; procedure TForm1.SocketCheckTimerTimer(Sender: TObject); var MsgCollection: TMessageCollection; begin if ServerActive then begin MsgCollection := TMessageCollection.Create(); SocketCoord.CheckClients(MsgCollection); end; end; end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit Tests_OriStrings; {$mode objfpc}{$H+} interface uses FpcUnit, TestRegistry; type TTest_OriStrings = class(TTestCase) published procedure SplitStr; end; implementation uses OriStrings; procedure TTest_OriStrings.SplitStr; var S: String; R: TStringArray; begin S := 'C1 λ_min,рус; ЉϢȠЂӔӜ ڝڶڥڰڇکگ'; R := OriStrings.SplitStr(S, ';, '); AssertEquals(5, Length(R)); AssertEquals('C1', R[0]); AssertEquals('λ_min', R[1]); AssertEquals('рус', R[2]); AssertEquals('ЉϢȠЂӔӜ', R[3]); AssertEquals('ڝڶڥڰڇکگ', R[4]); end; initialization RegisterTest(TTest_OriStrings); end.
unit U_RVG; interface function calcRVG(streitwert: integer):integer; implementation // Funktion um die Einfachgebühr zu berechnen function calcRVG(streitwert: integer):integer; var currentSW, ergebnis: integer; begin currentSW:= 501; // Zwischenstand: Streitwert ergebnis:= 45; // Basisgebühr while currentSW <= streitwert do // bis der angegebene Streitwert erreicht ist begin case currentSW of 501..2000: begin currentSW:= currentSW + 500; ergebnis:= ergebnis + 35; end; 2001..10000: begin currentSW:= currentSW + 1000; ergebnis:= ergebnis + 51; end; 10001..25000: begin currentSW:= currentSW + 3000; ergebnis:= ergebnis + 46; end; 25001..50000: begin currentSW:= currentSW + 5000; ergebnis:= ergebnis + 75; end; 50001..200000: begin currentSW:= currentSW + 15000; ergebnis:= ergebnis + 85; end; 200001..500000: begin currentSW:= currentSW + 30000; ergebnis:= ergebnis + 120; end; 500001..High(Integer): begin currentSW:= currentSW + 50000; ergebnis:= ergebnis + 150; end; end; end; result:= ergebnis; end; end.
unit UnitTSemanticFormulizer; interface uses SysUtils,UnitTSintaxFormulizer; type TSemanticFormulizer=class private sFormula:string; bError:boolean; sDescError:string; //metodos para propiedades Procedure setsFormula(sEntrada:string); //metodos de operacion Function esToken(sEntrada:string):boolean;//quitar Function esOperador(sEntrada:string):boolean; Function esCondicional(sEntrada:string):boolean; Function esNumero(sEntrada:string):boolean; Function valor(sEntrada:string):real; Function buscarValor(sEntrada:string):real; Function suma(oper1,oper2:real):real; Function resta(oper1,oper2:real):real; Function producto(oper1,oper2:real):real; Function division(oper1,oper2:real):real; Function calcular(rAcumulado:real;sToken,sOperador:string):real; Function parsearCondicional(sEntrada:string):real; Function parsearCadena(sCadena:string):real; public //propiedades property error:boolean read bError; property descError:string read sDescError; property formula:string read sFormula write setsFormula; //metodos publicos constructor Create(sEntrada:string); Function generarResult:real; Function verificarSintaxis:boolean; end; implementation constructor TSemanticFormulizer.Create(sEntrada:string); BEGIN sFormula:=sEntrada; bError:=false; sDescError:=''; END; Function TSemanticFormulizer.generarResult:real; BEGIN result:=parsearCadena(sFormula); END; Procedure TSemanticFormulizer.setsFormula(sEntrada:string); BEGIN //Aqui validar si la entrada es correcta sFormula:=sEntrada; END; Function TSemanticFormulizer.buscarValor(sEntrada:string):real; const variables : array[0..9] of string =('a', 'b', 'c', 'd', 'e', 'f', 'ab', 'abc', 'ba', 'cde') ; valores : array[0..9] of real =( 1, 2, 3, -4, 5, 5.5, -1.32, 0, -0.79, 2.6) ; var ii,jj:integer; BEGIN jj:=-1; ii:=0; while (ii<length(variables))and(jj<0) do begin if variables[ii]=sEntrada then jj:=ii else inc(ii); end; result:=0; if jj<0 then begin//la variable no existe sDescError:='La variable '+sEntrada+' no existe.'; bError:=true; //break; end else result:=valores[jj]; END; Function TSemanticFormulizer.valor(sEntrada:string):real; BEGIN if esNumero(sEntrada) then result:=strtofloat(sEntrada) else result:=buscarValor(sEntrada); END; Function TSemanticFormulizer.verificarSintaxis:boolean; var sintax:TSintaxFormulizer; BEGIN result:=true; sintax:=TSintaxFormulizer.Create(sFormula); if not sintax.verificarSintaxis then begin result:=false; bError:=true; sDescError:=sintax.descError; end; END; Function TSemanticFormulizer.esToken(sEntrada:string):boolean; BEGIN result:=true; END; Function TSemanticFormulizer.esOperador(sEntrada:string):boolean; BEGIN result:=false; if (sEntrada='+') or (sEntrada='-') or (sEntrada='*') or (sEntrada='/') then result:=true END; Function TSemanticFormulizer.esCondicional(sEntrada:string):boolean; BEGIN result:=false; if sEntrada='?' then result:=true; END; Function TSemanticFormulizer.esNumero(sEntrada:string):boolean; const numeros : array[0..9] of string =('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') ; BEGIN result:=false; if (sEntrada[1]='0') or (sEntrada[1]='1') or (sEntrada[1]='2') or (sEntrada[1]='3') or (sEntrada[1]='4') or (sEntrada[1]='5') or (sEntrada[1]='6') or (sEntrada[1]='7') or (sEntrada[1]='8') or (sEntrada[1]='9') then result:=true; END; Function TSemanticFormulizer.suma(oper1,oper2:real):real; BEGIN result:=oper1+oper2; END; Function TSemanticFormulizer.resta(oper1,oper2:real):real; BEGIN result:=oper1-oper2 END; Function TSemanticFormulizer.producto(oper1,oper2:real):real; BEGIN result:=oper1*oper2; END; Function TSemanticFormulizer.division(oper1,oper2:real):real; BEGIN result:=0; if oper2=0 then begin bError:=true; sDescError:='division entre cero no permitida'; end else result:=oper1/oper2; END; FUNCTION TSemanticFormulizer.calcular(rAcumulado:real;sToken,sOperador:string):real; var rOperando:real; BEGIN result:=0; if sToken[1]='(' then begin sToken:=copy(sToken,2,length(sToken)-2); rOperando:=parsearCadena(sToken); end else if sToken[1]='?' then begin sToken:=copy(sToken,3,length(sToken)-3); rOperando:=parsearCondicional(sToken); end else begin rOperando:=valor(sToken); end; if sOperador='+' then result:=suma(rAcumulado,rOperando) else if sOperador='-' then result:=resta(rAcumulado,rOperando) else if sOperador='*' then result:=producto(rAcumulado,rOperando) else if sOperador='/' then result:=division(rAcumulado,rOperando) END; Function TSemanticFormulizer.parsearCondicional(sEntrada:string):real; function esOperadorCond(sEntrada:char):boolean; begin result:=false; if (sEntrada='=') or (sEntrada='<') or (sEntrada='>') then result:=true; end; function resolverCond(operando1,operando2,operador:string):boolean; var rOp1,rOp2:real; begin result:=false; rOp1:=parsearCadena(operando1); rOp2:=parsearCadena(operando2); if operador='=' then begin if rOp1=rOp2 then result:=true; end else if operador='<' then begin if rOp1<rOp2 then result:=true; end else if operador='>' then begin if rOp1>rOp2 then result:=true; end else if operador='<=' then begin if rOp1<=rOp2 then result:=true; end else if operador='>=' then begin if rOp1>=rOp2 then result:=true; end else begin //<> if rOp1<>rOp2 then result:=true; end; end; var operando1,operando2,respuesta1,respuesta2,operador:string; ii,jj,iParentesis:integer; BEGIN result:=0; operando1:=''; operando2:=''; respuesta1:=''; respuesta2:=''; operador:=''; ii:=1; iParentesis:=0; //while ii<=length(sEntrada) do begin //operando1 if sEntrada[ii]='(' then begin //operando es una operacion con varios valores operando1:=operando1+sEntrada[ii]; inc(iParentesis); jj:=ii+1; while iParentesis<>0 do begin operando1:=operando1+sEntrada[jj]; if sEntrada[jj]='(' then inc(iParentesis) else if sEntrada[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; end else begin //operando es un valor while not esOperadorCond(sEntrada[ii]) do begin operando1:=operando1+sEntrada[ii]; inc(ii); end; end; //operador while esOperadorCond(sEntrada[ii]) do begin operador:=operador+sEntrada[ii]; inc(ii); end; //operando2 if sEntrada[ii]='(' then begin //operando es una operacion con varios valores operando2:=operando2+sEntrada[ii]; inc(iParentesis); jj:=ii+1; while iParentesis<>0 do begin operando2:=operando2+sEntrada[jj]; if sEntrada[jj]='(' then inc(iParentesis) else if sEntrada[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; end else begin //operando es un valor while sEntrada[ii]<>',' do begin operando2:=operando2+sEntrada[ii]; inc(ii); end; end; inc(ii); //respuesta1 if sEntrada[ii]='(' then begin //respuesta es una operacion con varios valores respuesta1:=respuesta1+sEntrada[ii]; inc(iParentesis); jj:=ii+1; while iParentesis<>0 do begin respuesta1:=respuesta1+sEntrada[jj]; if sEntrada[jj]='(' then inc(iParentesis) else if sEntrada[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; end else begin //respuesta es un valor while sEntrada[ii]<>',' do begin respuesta1:=respuesta1+sEntrada[ii]; inc(ii); end; end; inc(ii); //respuesta2 if sEntrada[ii]='(' then begin //respuesta es una operacion con varios valores respuesta2:=respuesta2+sEntrada[ii]; inc(iParentesis); jj:=ii+1; while iParentesis<>0 do begin respuesta2:=respuesta2+sEntrada[jj]; if sEntrada[jj]='(' then inc(iParentesis) else if sEntrada[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; end else begin //respuesta es un valor while ii<=length(sEntrada) do begin respuesta2:=respuesta2+sEntrada[ii]; inc(ii); end; end; //resultado if resolverCond(operando1,operando2,operador) then result:=parsearCadena(respuesta1) else result:=parsearCadena(respuesta2); //inc(ii); //end; END; Function TSemanticFormulizer.parsearCadena(sCadena:string):real; var ii,jj:integer; sToken:string; sOperador:string; rAcumulado:real; iParentesis:integer; BEGIN sToken:=''; sOperador:='+'; ii:=1; iParentesis:=0; rAcumulado:=0; if length(sCadena)>0 then begin while ii<=length(sCadena) do begin if bError then//si hay error, cerrar el ciclo break; if esOperador(sCadena[ii]) then begin rAcumulado:=calcular(rAcumulado,sToken,sOperador); sOperador:=sCadena[ii]; sToken:=''; end else if esCondicional(sCadena[ii]) then begin sToken:=sToken+sCadena[ii]+sCadena[ii+1]; inc(iParentesis); jj:=ii+2; while iParentesis<>0 do begin sToken:=sToken+sCadena[jj]; if sCadena[jj]='(' then inc(iParentesis) else if sCadena[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; end else if sCadena[ii]='(' then begin sToken:=sToken+sCadena[ii]; inc(iParentesis); jj:=ii+1; while iParentesis<>0 do begin sToken:=sToken+sCadena[jj]; if sCadena[jj]='(' then inc(iParentesis) else if sCadena[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; end else begin//es un caracter del token sToken:=sToken+sCadena[ii]; end; inc(ii); end; if bError then rAcumulado:=0 else rAcumulado:=calcular(rAcumulado,sToken,sOperador); end; result:=rAcumulado; END; end.
unit JD.Weather.Services.OpenWeatherMap; interface {$R 'OpenWeatherMapsRes.res' 'OpenWeatherMapsRes.rc'} uses System.SysUtils, System.Classes, JD.Weather.Intf, JD.Weather.SuperObject, System.Generics.Collections; const SVC_CAPTION = 'Open Weather Map'; SVC_NAME = 'OpenWeatherMap'; SVC_UID = '{12ECA995-0C16-49EB-AF76-83690B426A9D}'; URL_MAIN = 'https://openweathermap.org/'; URL_API = 'https://openweathermap.org/api'; URL_REGISTER = 'https://home.openweathermap.org/users/sign_up'; URL_LOGIN = 'https://home.openweathermap.org/users/sign_in'; URL_LEGAL = 'http://openweathermap.org/terms'; //Supported Pieces of Information SUP_INFO = [wiConditions, wiForecastSummary, wiForecastDaily, wiMaps]; SUP_LOC = [wlZip, wlCityState, wlCoords, wlCityCode]; SUP_LOGO = [ltColor, ltColorInvert, ltColorWide, ltColorInvertWide]; SUP_COND_PROP = [wpIcon, wpCaption, wpDescription, wpTemp, wpTempMin, wpTempMax, wpWindDir, wpWindSpeed, wpPressure, wpHumidity, wpCloudCover, wpRainAmt, wpSnowAmt, wpSunrise, wpSunset]; SUP_ALERT_TYPE = []; SUP_ALERT_PROP = []; SUP_FOR = [ftSummary, ftDaily]; SUP_FOR_SUM = [wpIcon, wpCaption, wpDescription, wpTemp, wpTempMin, wpTempMax, wpWindDir, wpWindSpeed, wpPressure, wpPressureGround, wpPressureSea, wpHumidity, wpCloudCover, wpRainAmt, wpSnowAmt, wpPrecipPred]; SUP_FOR_HOUR = []; SUP_FOR_DAY = [wpIcon, wpCaption, wpDescription, wpTemp, wpTempMin, wpTempMax, wpWindDir, wpWindSpeed, wpPressure, wpPressureGround, wpPressureSea, wpHumidity, wpCloudCover, wpRainAmt, wpSnowAmt]; SUP_UNITS = [wuKelvin, wuImperial, wuMetric]; SUP_MAP = [mpClouds, mpPrecip, mpPressureSea, mpWind, mpTemp, mpSnowCover]; SUP_MAP_FOR = [wfPng, wfGif]; type TWeatherSupport = class(TInterfacedObject, IWeatherSupport) public function GetSupportedLogos: TWeatherLogoTypes; function GetSupportedUnits: TWeatherUnitsSet; function GetSupportedInfo: TWeatherInfoTypes; function GetSupportedLocations: TWeatherLocationTypes; function GetSupportedAlerts: TWeatherAlertTypes; function GetSupportedAlertProps: TWeatherAlertProps; function GetSupportedConditionProps: TWeatherPropTypes; function GetSupportedForecasts: TWeatherForecastTypes; function GetSupportedForecastSummaryProps: TWeatherPropTypes; function GetSupportedForecastHourlyProps: TWeatherPropTypes; function GetSupportedForecastDailyProps: TWeatherPropTypes; function GetSupportedMaps: TWeatherMapTypes; function GetSupportedMapFormats: TWeatherMapFormats; property SupportedLogos: TWeatherLogoTypes read GetSupportedLogos; property SupportedUnits: TWeatherUnitsSet read GetSupportedUnits; property SupportedInfo: TWeatherInfoTypes read GetSupportedInfo; property SupportedLocations: TWeatherLocationTypes read GetSupportedLocations; property SupportedAlerts: TWeatherAlertTypes read GetSupportedAlerts; property SupportedAlertProps: TWeatherAlertProps read GetSupportedAlertProps; property SupportedConditionProps: TWeatherPropTypes read GetSupportedConditionProps; property SupportedForecasts: TWeatherForecastTypes read GetSupportedForecasts; property SupportedForecastSummaryProps: TWeatherPropTypes read GetSupportedForecastSummaryProps; property SupportedForecastHourlyProps: TWeatherPropTypes read GetSupportedForecastHourlyProps; property SupportedForecastDailyProps: TWeatherPropTypes read GetSupportedForecastDailyProps; property SupportedMaps: TWeatherMapTypes read GetSupportedMaps; property SupportedMapFormats: TWeatherMapFormats read GetSupportedMapFormats; end; TWeatherURLs = class(TInterfacedObject, IWeatherURLs) public function GetMainURL: WideString; function GetApiURL: WideString; function GetLoginURL: WideString; function GetRegisterURL: WideString; function GetLegalURL: WideString; property MainURL: WideString read GetMainURL; property ApiURL: WideString read GetApiURL; property LoginURL: WideString read GetLoginURL; property RegisterURL: WideString read GetRegisterURL; property LegalURL: WideString read GetLegalURL; end; TWeatherServiceInfo = class(TInterfacedObject, IWeatherServiceInfo) private FSupport: TWeatherSupport; FURLs: TWeatherURLs; FLogos: TLogoArray; procedure SetLogo(const LT: TWeatherLogoType; const Value: IWeatherGraphic); procedure LoadLogos; public constructor Create; destructor Destroy; override; public function GetCaption: WideString; function GetName: WideString; function GetUID: WideString; function GetURLs: IWeatherURLs; function GetSupport: IWeatherSupport; function GetLogo(const LT: TWeatherLogoType): IWeatherGraphic; property Logos[const LT: TWeatherLogoType]: IWeatherGraphic read GetLogo write SetLogo; property Caption: WideString read GetCaption; property Name: WideString read GetName; property UID: WideString read GetUID; property Support: IWeatherSupport read GetSupport; property URLs: IWeatherURLs read GetURLs; end; TWeatherService = class(TWeatherServiceBase, IWeatherService) private FInfo: TWeatherServiceInfo; public constructor Create; override; destructor Destroy; override; public function GetInfo: IWeatherServiceInfo; function GetMultiple(const Info: TWeatherInfoTypes): IWeatherMultiInfo; function GetLocation: IWeatherLocation; function GetConditions: IWeatherProps; function GetAlerts: IWeatherAlerts; function GetForecastSummary: IWeatherForecast; function GetForecastHourly: IWeatherForecast; function GetForecastDaily: IWeatherForecast; function GetMaps: IWeatherMaps; property Info: IWeatherServiceInfo read GetInfo; end; implementation { TWeatherSupport } function TWeatherSupport.GetSupportedUnits: TWeatherUnitsSet; begin Result:= SUP_UNITS; end; function TWeatherSupport.GetSupportedLocations: TWeatherLocationTypes; begin Result:= SUP_LOC; end; function TWeatherSupport.GetSupportedLogos: TWeatherLogoTypes; begin Result:= SUP_LOGO; end; function TWeatherSupport.GetSupportedAlertProps: TWeatherAlertProps; begin Result:= SUP_ALERT_PROP; end; function TWeatherSupport.GetSupportedAlerts: TWeatherAlertTypes; begin Result:= SUP_ALERT_TYPE; end; function TWeatherSupport.GetSupportedConditionProps: TWeatherPropTypes; begin Result:= SUP_COND_PROP; end; function TWeatherSupport.GetSupportedForecasts: TWeatherForecastTypes; begin Result:= SUP_FOR; end; function TWeatherSupport.GetSupportedForecastDailyProps: TWeatherPropTypes; begin Result:= SUP_FOR_DAY; end; function TWeatherSupport.GetSupportedForecastHourlyProps: TWeatherPropTypes; begin Result:= SUP_FOR_HOUR; end; function TWeatherSupport.GetSupportedForecastSummaryProps: TWeatherPropTypes; begin Result:= SUP_FOR_SUM; end; function TWeatherSupport.GetSupportedInfo: TWeatherInfoTypes; begin Result:= SUP_INFO; end; function TWeatherSupport.GetSupportedMapFormats: TWeatherMapFormats; begin Result:= SUP_MAP_FOR; end; function TWeatherSupport.GetSupportedMaps: TWeatherMapTypes; begin Result:= SUP_MAP; end; { TWeatherURLs } function TWeatherURLs.GetApiURL: WideString; begin Result:= URL_API; end; function TWeatherURLs.GetLegalURL: WideString; begin Result:= URL_LEGAL; end; function TWeatherURLs.GetLoginURL: WideString; begin Result:= URL_LOGIN; end; function TWeatherURLs.GetMainURL: WideString; begin Result:= URL_MAIN; end; function TWeatherURLs.GetRegisterURL: WideString; begin Result:= URL_REGISTER; end; { TWeatherServiceInfo } constructor TWeatherServiceInfo.Create; var LT: TWeatherLogoType; begin FSupport:= TWeatherSupport.Create; FSupport._AddRef; FURLs:= TWeatherURLs.Create; FURLs._AddRef; for LT:= Low(TWeatherLogoType) to High(TWeatherLogoType) do begin FLogos[LT]:= TWeatherGraphic.Create; FLogos[LT]._AddRef; end; LoadLogos; end; destructor TWeatherServiceInfo.Destroy; var LT: TWeatherLogoType; begin for LT:= Low(TWeatherLogoType) to High(TWeatherLogoType) do begin FLogos[LT]._Release; end; FURLs._Release; FURLs:= nil; FSupport._Release; FSupport:= nil; inherited; end; function TWeatherServiceInfo.GetCaption: WideString; begin Result:= SVC_CAPTION; end; function TWeatherServiceInfo.GetName: WideString; begin Result:= SVC_NAME; end; function TWeatherServiceInfo.GetSupport: IWeatherSupport; begin Result:= FSupport; end; function TWeatherServiceInfo.GetUID: WideString; begin Result:= SVC_UID; end; function TWeatherServiceInfo.GetURLs: IWeatherURLs; begin Result:= FURLs; end; function TWeatherServiceInfo.GetLogo(const LT: TWeatherLogoType): IWeatherGraphic; begin Result:= FLogos[LT]; end; procedure TWeatherServiceInfo.SetLogo(const LT: TWeatherLogoType; const Value: IWeatherGraphic); begin FLogos[LT].Base64:= Value.Base64; end; procedure TWeatherServiceInfo.LoadLogos; function Get(const N, T: String): IWeatherGraphic; var S: TResourceStream; R: TStringStream; begin Result:= TWeatherGraphic.Create; if ResourceExists(N, T) then begin S:= TResourceStream.Create(HInstance, N, PChar(T)); try R:= TStringStream.Create; try S.Position:= 0; R.LoadFromStream(S); R.Position:= 0; Result.Base64:= R.DataString; finally FreeAndNil(R); end; finally FreeAndNil(S); end; end; end; begin SetLogo(ltColor, Get('LOGO_COLOR', 'PNG')); SetLogo(ltColorInvert, Get('LOGO_COLOR_INVERT', 'PNG')); SetLogo(ltColorWide, Get('LOGO_COLOR_WIDE', 'PNG')); SetLogo(ltColorInvertWide, Get('LOGO_COLOR_INVERT_WIDE', 'PNG')); SetLogo(ltColorLeft, Get('LOGO_COLOR_LEFT', 'PNG')); SetLogo(ltColorRight, Get('LOGO_COLOR_RIGHT', 'PNG')); end; { TWeatherService } constructor TWeatherService.Create; begin inherited; FInfo:= TWeatherServiceInfo.Create; FInfo._AddRef; end; destructor TWeatherService.Destroy; begin FInfo._Release; FInfo:= nil; inherited; end; function TWeatherService.GetInfo: IWeatherServiceInfo; begin Result:= FInfo; end; function TWeatherService.GetLocation: IWeatherLocation; begin //TODO end; function TWeatherService.GetMultiple( const Info: TWeatherInfoTypes): IWeatherMultiInfo; begin //TODO end; function TWeatherService.GetConditions: IWeatherProps; begin //TODO end; function TWeatherService.GetAlerts: IWeatherAlerts; begin //TODO end; function TWeatherService.GetForecastDaily: IWeatherForecast; begin //TODO end; function TWeatherService.GetForecastHourly: IWeatherForecast; begin //TODO end; function TWeatherService.GetForecastSummary: IWeatherForecast; begin //TODO end; function TWeatherService.GetMaps: IWeatherMaps; begin //TODO end; end.
(* Wordcount: Max Mitter, 2020-03-13 *) (* ------ *) (* A Program that counts how often a word is contained in a certain text using Binary Trees *) (* ========================================================================= *) PROGRAM Wordcount; USES WinCrt, Timer, WordReader, TreeUnit; var w: Word; n: longint; t: Tree; c: NodePtr; BEGIN (* Wordcount *) WriteLn('Starting Wordcounter with Binary Tree...'); OpenFile('Kafka.txt', toLower); StartTimer; n := 0; ReadWord(w); while w <> '' do begin n := n + 1; (* INSERT *) Insert(t, w); ReadWord(w); end; StopTimer; CloseFile; WriteLn('Ending Wordcounter with Binary Tree.'); WriteLn('Number of words read: ', n); WriteLn('Elapsed Time: ', ElapsedTime); c := GetHighestCount(t); WriteLn('Most Common Word: ', c^.val, ', ', c^.count, ' times.'); DisposeTree(t); END. (* Wordcount *)
unit fPtSelMsg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, fBase508Form, VA508AccessibilityManager; type TfrmPtSelMsg = class(TfrmBase508Form) cmdClose: TButton; timClose: TTimer; memMessages: TRichEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cmdCloseClick(Sender: TObject); procedure timCloseTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FSeconds: Integer; FChanging: boolean; FEventsActive: boolean; FOldActiveFormChanged: TNotifyEvent; FOldTabChanged: TNotifyEvent; procedure ClearEvents; procedure TabChanged(Sender: TObject); procedure ActiveFormChanged(Sender: TObject); public { Public declarations } end; procedure ShowPatientSelectMessages(const AMsg: string); procedure HidePatientSelectMessages; implementation {$R *.DFM} uses ORFn, uCore, fFrame, VAUtils; var frmPtSelMsg: TfrmPtSelMsg = nil; procedure ShowPatientSelectMessages(const AMsg: string); begin if assigned(frmPtSelMsg) then begin frmPtSelMsg.Free; frmPtSelMsg := nil; end; if Length(AMsg) = 0 then Exit; frmPtSelMsg := TfrmPtSelMsg.Create(Application); ResizeAnchoredFormToFont(frmPtSelMsg); frmPtSelMsg.memMessages.Lines.SetText(PChar(AMsg)); // Text := AMsg doesn't seem to work frmPtSelMsg.memMessages.SelStart := 0; if User.PtMsgHang = 0 then frmPtSelMsg.timClose.Enabled := False else begin //frmPtSelMsg.timClose.Interval := User.PtMsgHang * 1000; frmPtSelMsg.FSeconds := User.PtMsgHang; frmPtSelMsg.timClose.Enabled := True; end; frmPtSelMsg.Show; end; procedure HidePatientSelectMessages; begin if assigned(frmPtSelMsg) then begin frmPtSelMsg.Free; frmPtSelMsg := nil; end; end; procedure TfrmPtSelMsg.timCloseTimer(Sender: TObject); begin Dec(FSeconds); if FSeconds > 0 then Caption := 'Patient Lookup Messages (Auto-Close in ' + IntToStr(FSeconds) + ' seconds)' else Close; end; procedure TfrmPtSelMsg.cmdCloseClick(Sender: TObject); begin Close; end; procedure TfrmPtSelMsg.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmPtSelMsg.FormCreate(Sender: TObject); begin FOldActiveFormChanged := Screen.OnActiveFormChange; Screen.OnActiveFormChange := ActiveFormChanged; FOldTabChanged := frmFrame.OnTabChanged; frmFrame.OnTabChanged := TabChanged; FEventsActive := TRUE; end; procedure TfrmPtSelMsg.FormDestroy(Sender: TObject); begin ClearEvents; frmPtSelMsg := nil; end; procedure TfrmPtSelMsg.ActiveFormChanged(Sender: TObject); begin if assigned(FOldActiveFormChanged) then FOldActiveFormChanged(Sender); if (not FChanging) and (Screen.ActiveForm <> Self) and (not (csDestroying in Self.ComponentState)) then begin FChanging := TRUE; try SetFocus; finally FChanging := FALSE; end; end; end; procedure TfrmPtSelMsg.ClearEvents; begin if FEventsActive then begin Screen.OnActiveFormChange := FOldActiveFormChanged; frmFrame.OnTabChanged := FOldTabChanged; FEventsActive := FALSE; end; end; procedure TfrmPtSelMsg.TabChanged(Sender: TObject); begin if assigned(FOldTabChanged) then FOldTabChanged(Sender); ClearEvents; end; end.
unit Money; interface uses SysUtils, Spring.Collections; type ECurrencyCodeMismatch = Exception; IMoney = interface function GetAmount: Integer; procedure SetAmount(const Value: Integer); function GetFormatSettings: TFormatSettings; function GetDecimalAmount: Currency; function ToString: string; function Add(Amount : IMoney): IMoney; function Subtract(Amount : IMoney): IMoney; function Multiply(Amount : Currency): IMoney; function Allocate(Ratios : array of integer): IList<IMoney>; function Equals(Amount : IMoney): boolean; property Amount : Integer read GetAmount write SetAmount; property DecimalAmount : Currency read GetDecimalAmount; property FormatSettings : TFormatSettings read GetFormatSettings; end; TMoney = class(TInterfacedObject, IMoney) strict private FCents : array[0..3] of integer; FAmount : integer; FFormatSettings : TFormatSettings; procedure FillCentsArray; function CentFactor: integer; function NewMoney(Amount : integer): IMoney; function GetAmount: Integer; procedure SetAmount(const Value: Integer); function GetDecimalAmount: Currency; function GetFormatSettings: TFormatSettings; public constructor Create(Amount : Currency); overload; constructor Create(Amount : integer); overload; constructor Create(Amount : Currency; FormatSettings : TFormatSettings); overload; constructor Create(Amount : integer; FormatSettings : TFormatSettings); overload; constructor Create(Other : IMoney); overload; constructor ChangeCurrency(const FromMoney : IMoney; const ToFormatSettings : TFormatSettings; const ExchangeRate : Double); function ToString: string; override; function Add(Amount : IMoney): IMoney; function Subtract(Amount : IMoney): IMoney; function Multiply(Amount : Currency): IMoney; function Allocate(Ratios : array of integer): IList<IMoney>; function Equals(Amount : IMoney): boolean; reintroduce; overload; property Amount : Integer read GetAmount write SetAmount; property DecimalAmount : Currency read GetDecimalAmount; property FormatSettings : TFormatSettings read GetFormatSettings; end; implementation { TMoney } function TMoney.Add(Amount: IMoney): IMoney; begin if Amount.FormatSettings.CurrencyFormat = FFormatSettings.CurrencyFormat then result := NewMoney(FAmount + Amount.Amount) else raise ECurrencyCodeMismatch.Create('Currency Codes don''t match.'); end; function TMoney.Allocate(Ratios: array of integer): IList<IMoney>; var Total : integer; Remainder : integer; i: Integer; begin Total := 0; Remainder := FAmount; for i := Low(Ratios) to High(Ratios) do Total := Total + Ratios[i]; result := TCollections.CreateList<IMoney>; for i := Low(Ratios) to High(Ratios) do begin result.Add(TMoney.Create(FAmount * Ratios[i] div Total, FFormatSettings)); Remainder := Remainder - result.Last.Amount; end; for i := 0 to Remainder - 1 do result.Items[i].Amount := result.Items[i].Amount + 1; end; function TMoney.CentFactor: integer; begin result := FCents[FFormatSettings.CurrencyDecimals]; end; constructor TMoney.ChangeCurrency(const FromMoney: IMoney; const ToFormatSettings: TFormatSettings; const ExchangeRate: Double); begin FillCentsArray; FFormatSettings := ToFormatSettings; FAmount := FromMoney.Multiply(ExchangeRate).Amount; end; constructor TMoney.Create(Amount: Currency); begin FillCentsArray; FFormatSettings := TFormatSettings.Create; FAmount := Trunc(Amount * CentFactor); end; constructor TMoney.Create(Amount: integer); begin FillCentsArray; FAmount := Amount; FFormatSettings := TFormatSettings.Create; end; constructor TMoney.Create(Other: IMoney); begin FillCentsArray; FAmount := Other.Amount; FFormatSettings := Other.FormatSettings; end; function TMoney.Equals(Amount: IMoney): boolean; begin if Amount.FormatSettings.CurrencyFormat = FFormatSettings.CurrencyFormat then result := FAmount = Amount.Amount else raise ECurrencyCodeMismatch.Create('Currency Codes don''t match.'); end; constructor TMoney.Create(Amount: integer; FormatSettings : TFormatSettings); begin FillCentsArray; FAmount := Amount; FFormatSettings := FormatSettings; end; procedure TMoney.FillCentsArray; begin FCents[0] := 1; FCents[1] := 10; FCents[2] := 100; FCents[3] := 1000; end; function TMoney.GetAmount: Integer; begin result := FAmount; end; function TMoney.GetDecimalAmount: Currency; begin result := FAmount / CentFactor; end; function TMoney.GetFormatSettings: TFormatSettings; begin result := FFormatSettings; end; function TMoney.Multiply(Amount: Currency): IMoney; begin result := NewMoney(Round(FAmount * Amount)); end; constructor TMoney.Create(Amount: Currency; FormatSettings : TFormatSettings); begin FillCentsArray; FFormatSettings := FormatSettings; FAmount := Trunc(Amount * CentFactor); end; function TMoney.NewMoney(Amount: integer): IMoney; begin result := TMoney.Create(Amount, FFormatSettings); end; procedure TMoney.SetAmount(const Value: Integer); begin FAmount := Value; end; function TMoney.Subtract(Amount: IMoney): IMoney; begin if Amount.FormatSettings.CurrencyFormat = FFormatSettings.CurrencyFormat then result := NewMoney(FAmount - Amount.Amount) else raise ECurrencyCodeMismatch.Create('Currency Codes don''t match.'); end; function TMoney.ToString: string; begin result := Format('%m', [DecimalAmount], FFormatSettings); end; end.
unit Unit1; interface uses Winapi.Windows, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.Jpeg, //GLS GLNGDManager, GLMaterial, GLCadencer, GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLScene, GLGeomObjects, GLBitmapFont, GLWindowsFont, GLObjects, GLCoordinates, GLFile3DS, GLFileJPEG, GLNavigator, GLKeyboard, GLVectorGeometry, GLVectorTypes, GLVectorFileObjects, GLColor, GLHUDObjects, GLTexture, GLUtils; type TMap = record mdl: TGLFreeForm; dyn: boolean; end; TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLNGDManager1: TGLNGDManager; GLCadencer1: TGLCadencer; GLMaterialLibrary1: TGLMaterialLibrary; Player_Cam: TGLCamera; Cam_Cube: TGLDummyCube; Player_Cube: TGLDummyCube; Scene_Objects: TGLDummyCube; Game_Menu: TGLDummyCube; OpenDialog1: TOpenDialog; GLWindowsBitmapFont1: TGLWindowsBitmapFont; Player_Capsule: TGLCapsule; GLLightSource1: TGLLightSource; GLCube2: TGLCube; GLNavigator1: TGLNavigator; GLUserInterface1: TGLUserInterface; GLNavigator2: TGLNavigator; TIPickTimer: TTimer; GLHUDSprite1: TGLHUDSprite; GLSphere1: TGLSphere; Memo1: TMemo; GLCube3: TGLCube; Jump_Timer: TTimer; GLHUDText1: TGLHUDText; Timer_OnVelocity: TTimer; On_Drop: TTimer; GLLines1: TGLLines; procedure FormCreate(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure TIPickTimerTimer(Sender: TObject); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Jump_TimerTimer(Sender: TObject); procedure Timer_OnVelocityTimer(Sender: TObject); procedure On_DropTimer(Sender: TObject); private { Private declarations } public { Public declarations } procedure Menu_Load; procedure Game_Load; end; var Form1: TForm1; maps: array of TMap; currentPick: TGLCustomSceneObject; FPickedSceneObject: TGLBaseSceneObject; NGDDynamicBehav: TGLNGDDynamic; point3d, FPaneNormal: TVector; M_X, M_Y: Integer; Maps_Count: Integer; OnAir, OnGround: boolean; OnMouse_Click, OnDrop, OnPick: boolean; pickjoint: TNGDJoint; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin // Switch to English keyboard leyout LoadKeyboardLayout('00000409', KLF_ACTIVATE); Menu_Load; GLHUDText1.Text := 'Walk - WASD'+#13+ 'Jump - Space'+#13+ 'Pick/Drop - Left mouse'+#13+ 'Push - Right mouse'; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); var I, D: TVector4f; F: TVector4f; peak_Up, peak_Down: boolean; ray, GP3D, result_GP3D: TVector4f; j: Integer; point2d, GotoPoint3d: TVector; key_space: boolean; cp: TPoint; visible_cursor: boolean; ScObj, FScObj: TGLBaseSceneObject; targetColor: TColorVector; picked: TGLCustomSceneObject; mm: TMatrix4f; begin GetCursorPos(cp); cp := GLSceneViewer1.ScreenToClient(cp); for j := 0 to Scene_Objects.Count - 1 do begin with Scene_Objects[j] as TGLCustomSceneObject do begin if Tag = 1 then Material.FrontProperties.Emission.Color := clrBlack; end; end; if Assigned(currentPick) then if currentPick.Tag = 1 then begin with currentPick do begin if currentPick.DistanceTo(Player_Capsule) <= 3.5 then begin targetColor := clrRed; end; // Set new color at 66% between current and target color with Material.FrontProperties.Emission do Color := targetColor; // VectorLerp(targetColor, Color, 0.66) end; end; GLUserInterface1.MouseLook; GLUserInterface1.MouseUpdate; TIPickTimer.Enabled := True; Player_Cube.Position := Player_Capsule.Position; if Assigned(FPickedSceneObject) and Assigned(GetNGDDynamic(FPickedSceneObject)) and OnMouse_Click then begin GP3D.V[0] := Player_Cube.AbsolutePosition.V[0] + Player_Cube.AbsoluteDirection.V[0] * -2; GP3D.V[1] := Player_Capsule.AbsolutePosition.V[1] + 1.6 + Player_Cam.AbsoluteDirection.V[1]; GP3D.V[2] := Player_Cube.AbsolutePosition.V[2] + Player_Cube.AbsoluteDirection.V[2] * -2; if (roundto((point3d.V[0]), -3) <> roundto((GP3D.V[0]), -3)) or (roundto((point3d.V[1]), -3) <> roundto((GP3D.V[1]), -3)) or (roundto((point3d.V[2]), -3) <> roundto(GP3D.V[2], -3)) then begin GP3D.V[0] := point3d.V[0] - GP3D.V[0]; GP3D.V[1] := point3d.V[1] - GP3D.V[1]; GP3D.V[2] := point3d.V[2] - GP3D.V[2]; NormalizeVector(GP3D); GotoPoint3d.V[0] := point3d.V[0] + GP3D.V[0] * -6 * deltaTime; GotoPoint3d.V[1] := point3d.V[1] + GP3D.V[1] * -6 * deltaTime; GotoPoint3d.V[2] := point3d.V[2] + GP3D.V[2] * -6 * deltaTime; point3d := GotoPoint3d; end else begin GotoPoint3d.V[0] := Player_Cube.AbsolutePosition.V[0] + Player_Cube.AbsoluteDirection.V[0] * -2; GotoPoint3d.V[1] := Player_Capsule.AbsolutePosition.V[1] + 1.6 + Player_Cam.AbsoluteDirection.V[1]; GotoPoint3d.V[2] := Player_Cube.AbsolutePosition.V[2] + Player_Cube.AbsoluteDirection.V[2] * -2; end; pickjoint.KinematicControllerPick(point3d, paMove); end; if IsKeyDown(VK_LBUTTON) then begin point3d := VectorMake(GLSceneViewer1.Buffer.PixelRayToWorld(cp.X, cp.Y)); if not(OnMouse_Click) and OnPick then begin FPickedSceneObject := GLSceneViewer1.Buffer.GetPickedObject(cp.X, cp.Y); if Assigned(FPickedSceneObject) then if FPickedSceneObject.DistanceTo(Player_Capsule) <= 3.5 then begin if Assigned(FPickedSceneObject) and Assigned(GetNGDDynamic(FPickedSceneObject)) and (FPickedSceneObject.Tag=1) then // If the user click on a glSceneObject begin // point3d is the global space point of the body to attach pickjoint.ParentObject := FPickedSceneObject; pickjoint.KinematicControllerPick(point3d, paAttach); OnMouse_Click := True; GotoPoint3d := point3d; On_Drop.Tag := 1; On_Drop.Enabled := True; end else FPickedSceneObject := nil; // We save the normal to create a plane parallel to camera in mouseMove Event. FPaneNormal := Player_Cam.AbsoluteDirection; end; end else begin if Assigned(FPickedSceneObject) and Assigned(GetNGDDynamic(FPickedSceneObject)) and OnDrop then begin pickjoint.KinematicControllerPick(point3d, paDetach); NGDDynamicBehav := nil; FPickedSceneObject := nil; OnMouse_Click := False; On_Drop.Tag := 0; On_Drop.Enabled := True; end; end; end; if Assigned(FPickedSceneObject) then begin ScObj := FPickedSceneObject; end; if not(OnMouse_Click) then begin // Detach the body if Assigned(NGDDynamicBehav) then begin Timer_OnVelocity.Enabled := True; end; end; if Assigned(FPickedSceneObject) and Assigned(GetNGDDynamic(FPickedSceneObject)) and IsKeyDown(VK_RBUTTON) then begin I:=Player_Cam.AbsoluteDirection; i.V[0]:=I.V[0]*20; i.V[1]:=I.V[1]*20; i.V[2]:=I.V[2]*20; with TGLNGDDynamic(FPickedSceneObject.Behaviours.GetByClass(TGLNGDDynamic)) do SetVelocity(I); pickjoint.KinematicControllerPick(point3d, paDetach); NGDDynamicBehav := nil; FPickedSceneObject := nil; OnMouse_Click:=false; On_Drop.Tag:=0; On_Drop.Enabled:=true; end; for j := 0 to Maps_Count - 1 do begin OnGround := maps[j].mdl.OctreeAABBIntersect (GLCube3.AxisAlignedBoundingBox(), GLCube3.AbsoluteMatrix, GLCube3.InvAbsoluteMatrix); if OnGround then break; end; if IsKeyDown(VK_SPACE) and OnGround and not(OnAir) then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := Player_Cube.AbsoluteDirection; if IsKeyDown('w') then begin i.V[0]:=-i.V[0]*6; i.V[0]:=10; i.V[0]:=-i.V[2]*6; SetVelocity(i); end else SetVelocity(VectorMake(0,10,0)); OnGround := False; end; OnAir := True; Jump_Timer.Enabled := True; end; if Assigned(currentPick) then if currentPick.Material.FrontProperties.Emission.Color.V[0] = 1 then begin GLHUDSprite1.Visible := True; end else begin GLHUDSprite1.Visible := False; end; if IsKeyDown('w') and OnGround and not(IsKeyDown(VK_SPACE)) then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := Player_Cube.AbsoluteDirection; i.V[0]:=-I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=-I.V[2]*4; SetVelocity(i); end; end; if IsKeyDown('s') and OnGround then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := Player_Cube.AbsoluteDirection; i.V[0]:=I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=I.V[2]*4; SetVelocity(i); end; end; if IsKeyDown('a') and OnGround then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := Player_Cam.AbsoluteRight; i.V[0]:=I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=I.V[2]*4; SetVelocity(i); end; end; if IsKeyDown('d') and OnGround then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := Player_Cam.AbsoluteLeft; i.V[0]:=I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=I.V[2]*4; SetVelocity(i); end; end; if IsKeyDown('d') and IsKeyDown('w') and OnGround then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := VectorAdd(Player_Cube.AbsoluteLeft, Player_Cube.AbsoluteDirection); i.V[0]:=-I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=-I.V[2]*4; SetVelocity(i); end; end; if IsKeyDown('a') and IsKeyDown('w') and OnGround then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := VectorAdd(Player_Cube.AbsoluteRight, Player_Cube.AbsoluteDirection); i.V[0]:=-I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=-I.V[2]*4; SetVelocity(i); end; end; if IsKeyDown('a') and IsKeyDown('s') and OnGround then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := VectorAdd(Player_Cube.AbsoluteLeft, Player_Cube.AbsoluteDirection); i.V[0]:=I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=I.V[2]*4; SetVelocity(i); end; end; if IsKeyDown('d') and IsKeyDown('s') and OnGround then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin I := VectorAdd(Player_Cube.AbsoluteRight, Player_Cube.AbsoluteDirection); i.V[0]:=I.V[0]*4; i.V[1]:=AppliedVelocity.y; i.V[2]:=I.V[2]*4; SetVelocity(i); end; end; GLSceneViewer1.Invalidate; GLNGDManager1.Step(deltaTime); if Player_Capsule.Position.Y < -10 then begin with TGLNGDDynamic(Player_Capsule.Behaviours.GetByClass(TGLNGDDynamic)) do begin mm := NewtonBodyMatrix; mm.V[3] := VectorMake(0, 0, 0, 1); NewtonBodyMatrix := mm; end; end; if IsKeyDown(VK_ESCAPE) then close; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin M_X := X; M_Y := Y; end; procedure TForm1.Menu_Load; begin Form1.Width := 1280; Form1.Height := 1024; GLHUDSprite1.Position.X := 640; GLHUDSprite1.Position.Y := 512; GLSceneViewer1.Height := 1024; GLSceneViewer1.Width := 1280; (* GLMaterialLibrary1.AddTextureMaterial('brick_b','brick_b.jpg'); with GLMaterialLibrary1.Materials.GetLibMaterialByName('brick_b') do begin Material.Texture.Disabled:=false; end; GLMaterialLibrary1.AddTextureMaterial('mat1','Finishes.jpg'); with GLMaterialLibrary1.Materials.GetLibMaterialByName('mat1') do begin Material.Texture.Disabled:=false; end; *) pickjoint := TNGDJoint(GLNGDManager1.NewtonJoint.Items[1]); OnPick := True; GLUserInterface1.MouseLookActivate; Game_Load; end; procedure TForm1.Game_Load; var X, j, dyns: Integer; Models: string; PX, PY, PZ: Integer; RX, RY, RZ: Integer; DX, DY, DZ: Integer; Nam, end1, end2: Integer; b_ti1, b_ti2, b_ti3, ML_col: Integer; begin SetGLSceneMediaDir(); // Memo1.Lines.Clear; // memo1.Lines.LoadFromFile('level.txt'); SetLength(maps, Memo1.Lines.Count); For X := 0 to Memo1.Lines.Count - 1 do begin if copy(Memo1.Lines.Strings[X], 0, 8) = '[Model]=' then begin Models := Memo1.Lines.Strings[X]; for j := 0 to Length(Models) do begin if copy(Models, j, 3) = 'PX_' then PX := j + 3; if copy(Models, j, 3) = 'PY_' then PY := j + 3; if copy(Models, j, 3) = 'PZ_' then PZ := j + 3; if copy(Models, j, 3) = 'RX_' then RX := j + 3; if copy(Models, j, 3) = 'RY_' then RY := j + 3; if copy(Models, j, 3) = 'RZ_' then RZ := j + 3; if copy(Models, j, 3) = 'DX_' then DX := j + 3; if copy(Models, j, 3) = 'DY_' then DY := j + 3; if copy(Models, j, 3) = 'DZ_' then DZ := j + 3; if copy(Models, j, 7) = '[Name]=' then Nam := j + 7; if copy(Models, j, 10) = '[Dynamic]=' then dyns := j + 10; if copy(Models, j, 1) = ':' then end1 := j - 1; if copy(Models, j, 3) = 'DM=' then b_ti1 := j + 3; if copy(Models, j, 3) = 'NM=' then b_ti2 := j + 3; if copy(Models, j, 3) = 'LM=' then b_ti3 := j + 3; if copy(Models, j, 1) = ';' then end2 := j - 1; end; if StrToBool(copy(Models, dyns, b_ti1 - dyns - 4 { end1-dyns+1 } )) = False then begin with maps[X] do begin mdl := TGLFreeForm.CreateAsChild(Scene_Objects); mdl.MaterialLibrary := GLMaterialLibrary1; mdl.LoadFromFile(copy(Models, Nam, dyns - Nam - 10)); mdl.Position.X := StrToFloat(copy(Models, PX, PY - PX - 3)); mdl.Position.Y := StrToFloat(copy(Models, PY, PZ - PY - 3)); mdl.Position.Z := StrToFloat(copy(Models, PZ, RX - PZ - 3)); mdl.RollAngle := StrToFloat(copy(Models, RX, RY - RX - 3)); mdl.TurnAngle := StrToFloat(copy(Models, RY, RZ - RY - 3)); mdl.PitchAngle := StrToFloat(copy(Models, RZ, DX - RZ - 3)); mdl.Direction.X := StrToFloat(copy(Models, DX, DY - DX - 3)); mdl.Direction.Y := StrToFloat(copy(Models, DY, DZ - DY - 3)); mdl.Direction.Z := StrToFloat(copy(Models, DZ, Nam - DZ - 7)); mdl.BuildOctree(); mdl.Behaviours.GetOrCreate(TGLNGDStatic); Maps_Count := Maps_Count + 1; with TGLNGDStatic(mdl.Behaviours.GetByClass(TGLNGDStatic)) do begin Manager:=GLNGDManager1; NGDNewtonCollisions:=nc_Tree; end; end; end else begin with maps[X] do begin mdl := TGLFreeForm.CreateAsChild(Scene_Objects); mdl.LoadFromFile(copy(Models, Nam, dyns - Nam - 10)); mdl.Position.X := StrToFloat(copy(Models, PX, PY - PX - 3)); mdl.Position.Y := StrToFloat(copy(Models, PY, PZ - PY - 3)); mdl.Position.Z := StrToFloat(copy(Models, PZ, RX - PZ - 3)); mdl.RollAngle := StrToFloat(copy(Models, RX, RY - RX - 3)); mdl.TurnAngle := StrToFloat(copy(Models, RY, RZ - RY - 3)); mdl.PitchAngle := StrToFloat(copy(Models, RZ, DX - RZ - 3)); mdl.Direction.X := StrToFloat(copy(Models, DX, DY - DX - 3)); mdl.Direction.Y := StrToFloat(copy(Models, DY, DZ - DY - 3)); mdl.Direction.Z := StrToFloat(copy(Models, DZ, Nam - DZ - 7)); Maps_Count := Maps_Count + 1; mdl.Behaviours.GetOrCreate(TGLNGDDynamic); with TGLNGDDynamic(mdl.Behaviours.GetByClass(TGLNGDDynamic)) do begin Manager:=GLNGDManager1; NGDNewtonCollisions:=nc_Mesh; Density:=1; //NGDSurfaceItem:=GLNGDManager1.NewtonSurfaceItem.Items[3] as TNGDSurfaceItem; end; mdl.Tag := 1; mdl.OnProgress := GLCube2.OnProgress; mdl.BuildOctree(); end; end; end; end; end; procedure TForm1.Jump_TimerTimer(Sender: TObject); begin OnAir := False; Jump_Timer.Enabled := False; end; procedure TForm1.On_DropTimer(Sender: TObject); begin if On_Drop.Tag = 1 then begin OnDrop := True; OnPick := False; On_Drop.Enabled := False; end else begin OnDrop := False; OnPick := True; On_Drop.Enabled := False; end; end; procedure TForm1.Timer_OnVelocityTimer(Sender: TObject); begin pickjoint.KinematicControllerPick(point3d,paDetach); NGDDynamicBehav := nil; FPickedSceneObject := nil; Timer_OnVelocity.Enabled := False; On_Drop.Tag := 0; On_Drop.Enabled := True; end; procedure TForm1.TIPickTimerTimer(Sender: TObject); var cp: TPoint; begin GetCursorPos(cp); cp := GLSceneViewer1.ScreenToClient(cp); currentPick := (GLSceneViewer1.Buffer.GetPickedObject(cp.X, cp.Y) as TGLCustomSceneObject); TIPickTimer.Enabled := False; end; end.
unit ncaFrmNovaEtiqueta; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, StdCtrls, cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, cxTextEdit, cxMaskEdit, cxLabel, cxGroupBox, cxSpinEdit, cxCurrencyEdit, cxDropDownEdit, frxClass, cxMemo, cxPCdxBarPopupMenu, cxPC; type TDadosEtiqueta = record deNome : String; deAltura : Double; deLargura : Double; deMTop, deMBottom, deMLeft, deMRight : Double; deQtdPorLinha : Byte; deAlturaEtq : Double; deLarguraEtq : Double; deGapH, deGapV : Double; end; TFrmNovaEtiqueta = class(TForm) LMDSimplePanel1: TLMDSimplePanel; btnVoltar: TcxButton; btnCancelar: TcxButton; Paginas: TcxPageControl; tsNome: TcxTabSheet; tsFolha: TcxTabSheet; tsEtiqueta: TcxTabSheet; cbFolha: TcxGroupBox; lbLargura: TcxLabel; lbAltura: TcxLabel; cxLabel3: TcxLabel; cxLabel4: TcxLabel; cxLabel5: TcxLabel; cxLabel6: TcxLabel; edLargura: TcxCurrencyEdit; edAltura: TcxCurrencyEdit; edMTopo: TcxCurrencyEdit; edMRodape: TcxCurrencyEdit; edMEsquerda: TcxCurrencyEdit; edMDireita: TcxCurrencyEdit; cxLabel7: TcxLabel; edFolha: TcxComboBox; cbEtiqueta: TcxGroupBox; cxLabel8: TcxLabel; cxLabel9: TcxLabel; edLarguraEtq: TcxCurrencyEdit; edAlturaEtq: TcxCurrencyEdit; cxLabel11: TcxLabel; edQtdPorLinha: TcxSpinEdit; edGapH: TcxCurrencyEdit; cxLabel12: TcxLabel; edGapV: TcxCurrencyEdit; cxLabel14: TcxLabel; panNome: TLMDSimplePanel; lbNome: TcxLabel; edNome: TcxTextEdit; panObs: TLMDSimplePanel; lbObs: TcxLabel; edObs: TcxMemo; btnAvancar: TcxButton; procedure edFolhaPropertiesChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCancelarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaginasChange(Sender: TObject); procedure btnVoltarClick(Sender: TObject); procedure btnAvancarClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure CriarEtq; function Criar(var aNome, aObs: String): Boolean; end; var FrmNovaEtiqueta: TFrmNovaEtiqueta; implementation uses ncaFrmPri, ncafbProdutos; {$R *.dfm} resourcestring rsNomeEmBranco = 'É necessário informar um nome'; rsAlturaEmBranco = 'É necessário informar a altura da folha'; rsLarguraEmBranco = 'É necessário informar a largura da folha'; rsEtqPorLinhaZero = 'É necessário informar a quantidade de etiquetas por linha'; rsAlturaEtqEmBranco = 'É necessário informar a altura da etiqueta'; rsLarguraEtqEmBranco = 'É necessário informar a largura da etiqueta'; rsCriar = 'Criar!'; rsAvancar = 'Avançar'; procedure TFrmNovaEtiqueta.btnAvancarClick(Sender: TObject); begin case Paginas.ActivePageIndex of 0 : begin if Trim(edNome.Text)='' then begin edNome.SetFocus; raise exception.Create(rsNomeEmBranco); end; Paginas.ActivePageIndex := 1; end; 1 : begin if edAltura.Value<1 then begin edAltura.SetFocus; raise exception.Create(rsAlturaEmBranco); end; if edLargura.Value<1 then begin edLargura.SetFocus; raise exception.Create(rsLarguraEmBranco); end; Paginas.ActivePageIndex := 2; end; 2 : CriarEtq; end; end; procedure TFrmNovaEtiqueta.btnCancelarClick(Sender: TObject); begin Close; end; procedure TFrmNovaEtiqueta.btnVoltarClick(Sender: TObject); begin Paginas.ActivePageIndex := Paginas.ActivePageIndex - 1; end; function TFrmNovaEtiqueta.Criar(var aNome, aObs: String): Boolean; begin ShowModal; Result := (ModalResult=mrOk); aNome := Trim(edNome.Text); aObs := edObs.Text; end; procedure TFrmNovaEtiqueta.CriarEtq; var M : TfrxMasterData; S : TfrxShapeView; P : TfrxReportPage; begin if edAlturaEtq.Value<1 then begin edAlturaEtq.SetFocus; raise exception.Create(rsAlturaEtqEmBranco); end; if edLarguraEtq.Value<1 then begin edLarguraEtq.SetFocus; raise exception.Create(rsLarguraEtqEmBranco); end; if edQtdPorLinha.Value<1 then begin edQtdPorLinha.SetFocus; raise exception.Create(rsLarguraEmBranco); end; with TfbProdutos(FrmPri.FM.FormByClass(TfbProdutos)^.fiInstance) do begin repEtqCriar.ReportOptions.Description.Text := edObs.Text; M := repEtqCriar.FindObject('Etiquetas') as TfrxMasterData; S := repEtqCriar.FindObject('shapeEtiqueta') as TfrxShapeView; P := repEtqCriar.FindObject('Page1') as TFrxReportPage; P.PaperWidth := edLargura.Value * 10; P.PaperHeight := edAltura.Value * 10; P.TopMargin := edMTopo.Value * 10; P.BottomMargin := edMRodape.Value * 10; P.LeftMargin := edMEsquerda.Value * 10; P.RightMargin := edMDireita.Value * 10; M.Columns := edQtdPorLinha.Value; M.ColumnWidth := edLarguraEtq.Value * fr1cm; M.ColumnGap := edGapH.Value * fr1cm; M.Height := (edGapV.Value + edAlturaEtq.Value) * fr1cm; S.Width := edLarguraEtq.Value * fr1cm; S.Height := edAlturaEtq.Value * fr1cm; S.Left := 0; S.Top := 0; repEtqCriar.SaveToFile(ExtractFilePath(ParamStr(0))+'temp.frx'); end; ModalResult := mrOk; end; procedure TFrmNovaEtiqueta.edFolhaPropertiesChange(Sender: TObject); begin lbAltura.Enabled := (edFolha.ItemIndex=(edFolha.Properties.Items.Count-1)); lbLargura.Enabled := lbAltura.Enabled; edAltura.Enabled := lbAltura.Enabled; edLargura.Enabled := lbAltura.Enabled; case edFolha.ItemIndex of 0 : begin edAltura.Value := 29.7; edlargura.Value := 21; end; 1 : begin edAltura.Value := 27.9; edLargura.Value := 21.6; end; 2 : begin edAltura.Value := 35.6; edLargura.Value := 21.6; end; end; end; procedure TFrmNovaEtiqueta.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmNovaEtiqueta.FormCreate(Sender: TObject); begin Paginas.ActivePageIndex := 0; Paginas.HideTabs := True; end; procedure TFrmNovaEtiqueta.FormShow(Sender: TObject); begin if lbNome.Width > lbObs.Width then begin lbObs.AutoSize := False; lbObs.Width := lbNome.Width; end else begin lbNome.AutoSize := False; lbNome.Width := lbObs.Width; end; end; procedure TFrmNovaEtiqueta.PaginasChange(Sender: TObject); begin case Paginas.ActivePageIndex of 0 : begin btnAvancar.Caption := rsAvancar; btnVoltar.Visible := False; end; 1 : begin btnAvancar.Caption := rsAvancar; btnVoltar.Visible := True; end; 2 : begin btnAvancar.Caption := rsCriar; btnVoltar.Visible := True; end; end; end; end.
unit LabelOptionsDialogUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, DBTables; type TLabelOptionsDialog = class(TForm) OKButton: TBitBtn; CancelButton: TBitBtn; LabelTypeRadioGroup: TRadioGroup; FirstLineRadioGroup: TRadioGroup; OptionsGroupBox: TGroupBox; Label10: TLabel; LaserTopMarginEdit: TEdit; PrintLabelsBoldCheckBox: TCheckBox; OldAndNewLabelCheckBox: TCheckBox; PrintSwisCodeOnParcelIDCheckBox: TCheckBox; GroupBox1: TGroupBox; FontSizeLabel: TLabel; PrintParcelIDOnlyCheckBox: TCheckBox; FontSizeEdit: TEdit; ResidentLabelsCheckBox: TCheckBox; LegalAddressLabelsCheckBox: TCheckBox; ExtractToExcelCheckBox: TCheckBox; FontSizeAdditionalLinesLabel: TLabel; FontSizeAdditionalLinesEdit: TEdit; CommaDelimitedExtractCheckBox: TCheckBox; EliminateDuplicatesCheckBox: TCheckBox; SaveDialog: TSaveDialog; procedure OKButtonClick(Sender: TObject); procedure PrintParcelIDOnlyCheckBoxClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } _PrintLabelsBold, _PrintOldAndNewParcelIDs, _PrintSwisCodeOnParcelIDs, _PrintParcelIDOnly : Boolean; _LabelType, _NumLinesPerLabel, _NumLabelsPerPage, _NumColumnsPerPage, _SingleParcelFontSize, _FontSizeAdditionalLines : Integer; _ResidentLabels, _LegalAddressLabels, _PrintParcelIDOnlyOnFirstLine : Boolean; _LaserTopMargin : Real; _PrintParcelID_PropertyClass, _ExtractToExcel, _CommaDelimitedExtract, _PrintAccountNumber_OldID, _EliminateDuplicateOwners : Boolean; _ExtractFileName : String; end; var LabelOptionsDialog: TLabelOptionsDialog; implementation {$R *.DFM} uses GlblCnst, DataModule, PASUtils, GlblVars; {===========================================================} Procedure TLabelOptionsDialog.FormCreate(Sender: TObject); var SwisCodeTable : TTable; begin SwisCodeTable := FindTableInDataModuleForProcessingType(DataModuleSwisCodeTableName, NextYear); {CHG11182003-5(2.07k): If there is only one swis code, default print swis on parcel IDs to false.} PrintSwisCodeOnParcelIDCheckBox.Checked := (SwisCodeTable.RecordCount > 1); end; {FormCreate} {===========================================================} Procedure TLabelOptionsDialog.PrintParcelIDOnlyCheckBoxClick(Sender: TObject); begin FontSizeEdit.Enabled := PrintParcelIDOnlyCheckBox.Checked; FontSizeLabel.Enabled := PrintParcelIDOnlyCheckBox.Checked; FontSizeAdditionalLinesLabel.Enabled := PrintParcelIDOnlyCheckBox.Checked; FontSizeAdditionalLinesEdit.Enabled := PrintParcelIDOnlyCheckBox.Checked; end; {PrintParcelIDOnlyCheckBoxClick} {===========================================================} Procedure TLabelOptionsDialog.OKButtonClick(Sender: TObject); begin If (LabelTypeRadioGroup.ItemIndex = -1) then begin MessageDlg('Please select a label type.', mtError, [mbOK], 0); LabelTypeRadioGroup.SetFocus; end else begin _PrintLabelsBold := PrintLabelsBoldCheckBox.Checked; _LabelType := LabelTypeRadioGroup.ItemIndex; _PrintParcelID_PropertyClass := (FirstLineRadioGroup.ItemIndex = flPropertyClass); _PrintParcelIDOnlyOnFirstLine := (FirstLineRadioGroup.ItemIndex = flParcelIDOnly); _PrintAccountNumber_OldID := (FirstLineRadioGroup.ItemIndex = 3); _PrintSwisCodeOnParcelIDs := PrintSwisCodeOnParcelIDCheckBox.Checked; _PrintOldAndNewParcelIDs := OldAndNewLabelCheckBox.Checked; _PrintParcelIDOnly := PrintParcelIDOnlyCheckBox.Checked; _ResidentLabels := ResidentLabelsCheckBox.Checked; _LegalAddressLabels := LegalAddressLabelsCheckBox.Checked; {CHG05222004-1(2.08): Add option to extract labels to Excel.} _ExtractToExcel := ExtractToExcelCheckBox.Checked; _CommaDelimitedExtract := CommaDelimitedExtractCheckBox.Checked; {CHG06262005-1(2.8.5.2)[2152]: Option to eliminate duplicate owners from label print.} _EliminateDuplicateOwners := EliminateDuplicatesCheckBox.Checked; try _SingleParcelFontSize := StrToInt(FontSizeEdit.Text); except _SingleParcelFontSize := 16; end; If _PrintParcelIDOnly then try _FontSizeAdditionalLines := StrToInt(FontSizeAdditionalLinesEdit.Text); except _FontSizeAdditionalLines := 14; end else _FontSizeAdditionalLines := 0; try _LaserTopMargin := StrToFloat(LaserTopMarginEdit.Text); except _LaserTopMargin := 0.66; end; case _LabelType of lbDotMatrix : begin _NumLinesPerLabel := 12; _NumLabelsPerPage := 6; _NumColumnsPerPage := 1; end; lbLaser5161 : begin _NumLinesPerLabel := 6; _NumLabelsPerPage := 20; _NumColumnsPerPage := 2; end; lbLaser5160 : begin _NumLinesPerLabel := 6; _NumLabelsPerPage := 30; _NumColumnsPerPage := 3; end; lbLaser1Liner : begin _NumLinesPerLabel := 1; _NumLabelsPerPage := 8; _NumColumnsPerPage := 1; end; {CHG12021999-1: Allow print to envelopes.} lbEnvelope : begin _NumLinesPerLabel := 6; _NumLabelsPerPage := 1; _NumColumnsPerPage := 1; end; end; {case LabelType of} {CHG11122005-1(2.9.4.1): Actually do the comma delimited and Excel extract.} If _CommaDelimitedExtract then begin SaveDialog.InitialDir := GlblExportDir; If SaveDialog.Execute then begin _ExtractFileName := SaveDialog.FileName; ModalResult := mrOK; end else ModalResult := mrCancel; end else ModalResult := mrOK; end; {else of If (LabelTypeRadioGroup.ItemIndex = -1)} end; {OKButtonClick} end.
unit uCidade; interface uses uEstado; // criacao classe Modelo TCidade type TCidade = class private codigo: Integer; descricao: String; cep: String; estado: TEstado; public // construtor da classe constructor TCidadeCreate; // destrutor da classe destructor TCidadeDestroy; // metodos "procedimento set do objeto" procedure setCodigo(param: Integer); procedure setDescricao(param: String); procedure setCep(param: String); procedure setEstado(param: TEstado); // metodo "function" get do Objeto function getCodigo: Integer; function getDescricao: String; function getCep: String; function getEstado: TEstado; end; var Cidade : TCidade; implementation { TCidade implementacao dos metodos utilizados } function TCidade.getCep: String; begin result := cep; end; function TCidade.getCodigo: Integer; begin result := codigo; end; function TCidade.getDescricao: String; begin result := descricao; end; function TCidade.getEstado: TEstado; begin result := estado; end; procedure TCidade.setCodigo(param: Integer); begin codigo := param; end; procedure TCidade.setDescricao(param: String); begin descricao := param; end; procedure TCidade.setEstado(param: TEstado); begin estado := param; end; procedure TCidade.setCep(param: String); begin cep := param; end; constructor TCidade.TCidadeCreate; begin codigo := 0; descricao := ''; cep := ''; estado := TEstado.TEstadoCreate; end; destructor TCidade.TCidadeDestroy; begin estado.TEstadoDestroy; FreeInstance; end; end.
(************************************************************************ History: 28Feb1999 - added startsWith function - added endsWith function 4Aug1999 - fixed a wrong-result case bug in 'endsWith' function 6Aug1999 - added RightPos function 26Sep1999 - added toEnd function ************************************************************************) Unit ac_STRINGS; (* (C)opyright 1995-1999 George Birbilis / Agrinio Club *) interface type charSet=set of char; function StringChar(s:string; pos:integer):char; function extractnum(s:string;var start:integer{start=0};default:word):word; function CharPos(s:string;c:char;start:integer;RightDir:boolean):integer; function RightPos(c:char;s:string):integer; function Long2CommaStr(x:longint):string; function Int2Str(x:integer):string; function Long2Str(x:real):string; function Real2Str(x:real):string; function Str2Int(s:string):integer; function Str2Long(s:string):longint; function Str2Real(s:string):real; function part(s:string;first,last:integer):string; function upStr(s:string):string; procedure upString(var s:string); procedure lTrim(var s:string;c:char); procedure rTrim(var s:string;c:char); procedure convertChars(var s:string;FromChars,ToChars:string); function _convertChars(s:string;FromChars,ToChars:string):string; procedure InsertNChars(c:char;n:integer;var S:String;Index:integer); function integer2BinStr(b:integer):string; function NCharStr(c:char;count:integer):string; function containsOnly(chrset:charSet;s:string):boolean; function compareStr(s,match:string):boolean; function FindChars(s,matchChars:string;start:integer):integer; //find the first char from the left that is one of... function FindNonChars(s,notWantedChars:string;start:integer):integer; //find the first char from the left that isn't one of... function ReverseStr(s:string):string; function startsWith(const substr:string;const s:string):boolean; function endsWith(const substr:string;const s:string):boolean; function copyTillBeforeLastChar(c:char;s:string):string; function toEnd(s:string;start:integer):string; implementation {$B-} function startsWith; begin result:=(pos(substr,s)=1); end; function endsWith; //4Aug1999: fixed to handle a case where pos returned -1 (not found) and endsWith returned "true" var position:integer; begin position:=pos(substr,s); result:=(position>0) and (position=(length(s)-length(substr)+1)); end; function extractnum; var s1:string; code:integer; const numdigits=['0'..'9']; begin {ignore a sequence of spaces and/or tabs at s[start]} while (start<length(s)) and (s[start] in [' ',#9]) do inc(start); {go on} s1:=''; inc(start); while (start<=length(s)) and (s[start] in numdigits+['$']) do begin s1:=s1+s[start]; inc(start); end; if s1<>'' then val(s1,default,code); extractnum:=default; end; function CharPos(s:string;c:char;start:integer;RightDir:boolean):integer; var i:integer; begin result:=0; if (start=0) or (start>length(s)) then exit; if rightDir then begin for i:=start to length(s) do if s[i]=c then begin result:=i; exit; end; end else for i:=start downto 1 do if s[i]=c then begin result:=i; exit; end; end; (* function CharPos;assembler; //Turbo Pascal code, doesn't work in Delphi asm push ds {keep ds} lds si,s {ds:si points to s[0]} xor al,al {initially set return code to 0} mov bh,start {bh=start} or bh,bh jz @exit {if start=0 then goto @exit (with al=0)} xor ch,ch mov cl,bh {cx=start} mov bl,[si] {bl=length(s)} mov dl,bl {dl=>>} sub bl,bh {bl=length(s)-start} jc @exit {if bl<0 [start>length(s)] then goto @exit (with al=0)} add si,cx {ds:si points at s[start]} mov ah,RightDir or ah,ah std {si-- ;LeftDir} jz @check {if not rightDir then goto @check (with Flag(d)=1)} mov cl,bl {cl=bl=length(s)-start} inc cl cld {si++ ;RightDir} @check: lodsb cmp al,c je @out loop @check @out: mov al,cl or cl,cl jz @exit {if cl=0 then goto @exit} or ah,ah jz @exit sub dl,al mov al,dl inc al @exit: pop ds {restore ds} end; *) function Long2CommaStr; var s:string; counter,len,i:integer; begin str(x,s); len:=length(s); counter:=Trunc(len/3); if Frac(len/3)=0 then counter:=counter-1; for i:=1 to counter do insert(',',s,len-3*i+1); Long2CommaStr:=s; end; function int2str; var s:string; begin str(x,s); int2str:=s; end; function long2str; var s:string; begin str(x,s); long2str:=s; end; function real2str; var s:string; begin str(x,s); real2str:=s; end; function str2int; var i,err:integer; begin val(s,i,err); str2int:=i; end; function str2long; var err:integer; i:longint; begin val(s,i,err); str2long:=i; end; function str2real; var err:integer; i:real; begin val(s,i,err); str2real:=i; end; procedure InsertNChars; var i:integer; begin for i:=1 to n do insert(c,s,index); end; procedure upString; var i:integer; begin for i:=1 to length(s) do s[i]:=upcase(s[i]); end; function upStr; begin upString(s); upStr:=s; end; function integer2BinStr; var i:integer; s:string; begin s:=''; for i:=1 to 8 do begin if odd(b) then s:='1'+s else s:='0'+s; b:=b shr 1; end; integer2BinStr:=s; end; function NCharStr; var s:string; begin setLength(s,count); fillchar(s[1],count,c); NCharStr:=s; end; procedure lTrim; var i:integer; begin i:=1; while (i<=length(s)) and (s[i]=c) do inc(i); //i<=length must precede the s[i]=c check, in case i=0 at first loop s:=copy(s,i,length(s)-i+1); end; procedure rTrim; var i:integer; begin i:=length(s); while (i>0) and (s[i]=c) do dec(i); //i>0 check must precede the s[i]=c check, in case i=0 at first loop s:=copy(s,1,i); end; function rightPos(c:char;s:string):integer; var i:integer; begin for i:=length(s) downto 1 do if s[i]=c then begin result:=i; exit; end; result:=0; end; function containsOnly; var i:integer; begin containsonly:=FALSE; for i:=1 to length(s) do if not (s[i] in chrset) then exit; containsonly:=TRUE; end; function compareStr; const wildcards:set of char=['*','?']; var i:integer; {$B-} begin if (s=match) then compareStr:=TRUE else begin compareStr:=FALSE; {!} for i:=1 to length(match) do if s[i]='*' then begin compareStr:=TRUE; exit; end else if (i>length(s)) then break else if (s[i]<>match[i]) and (s[i]<>'?') then exit; {FALSE} {length(s)>length(match)} if containsOnly(wildcards,copy(s,length(match)+1,length(s)-length(match))) then compareStr:=TRUE; {! else compareStr:=FALSE !} end; end; procedure convertChars; var i,p,ToCharsLen:integer; result:string; begin result:=''; ToCharsLen:=Length(ToChars); for i:=1 to length(s) do begin p:=pos(s[i],FromChars); if p=0 then result:=result+s[i] else if ToCharsLen=0 then continue {if ToChars='' the FromChars are striped} else begin if p>ToCharsLen then p:=length(ToChars); {else are changed by same pos} result:=result+ToChars[p]; {char at ToChars or the last char of ToChars} end; end; s:=result; end; function _convertChars; begin convertChars(s,FromChars,ToChars); _convertChars:=s; end; function FindChars; var i:integer; begin if start>0 then for i:=start to length(s) do if pos(s[i],matchChars)<>0 then begin FindChars:=i; exit; end; FindChars:=0; end; function FindNonChars; var i:integer; begin if start>0 then for i:=start to length(s) do if pos(s[i],notWantedChars)=0 then begin FindNonChars:=i; exit; end; FindNonChars:=0; end; function part; begin part:=copy(s,first,last-first+1); end; function StringChar; begin StringChar:=s[pos]; end; function ReverseStr; var i:integer; begin result:=''; for i:=length(s) downto 1 do result:=result+s[i]; end; function copyTillBeforeLastChar; var i:integer; begin i:=rightPos(c,s); if (i>0) then result:=copy(s,1,i-1) else result:=s; end; function toEnd; begin result:=part(s,start,length(s)); end; end.
// GLMeshOptimizer {: Mesh optimization for GLScene.<p> <b>History : </b><font size=-1><ul> <li>27/11/07 - mrqzzz - added FacesSmooth InvertNormals parameter. Now smoothes correctly. <li>21/08/03 - EG - Added basic mooStandardize support <li>03/06/03 - EG - Creation </ul></font> } unit GLMeshOptimizer; interface uses Classes, Sysutils, GLVectorGeometry, GLVectorFileObjects; type // TMeshOptimizerOptions // TMeshOptimizerOption = (mooStandardize, mooVertexCache, mooSortByMaterials, mooMergeObjects); TMeshOptimizerOptions = set of TMeshOptimizerOption; var vDefaultMeshOptimizerOptions : TMeshOptimizerOptions = [mooStandardize, mooVertexCache, mooSortByMaterials, mooMergeObjects]; procedure OptimizeMesh(aList : TMeshObjectList; options : TMeshOptimizerOptions); overload; procedure OptimizeMesh(aList : TMeshObjectList); overload; procedure OptimizeMesh(aMeshObject : TMeshObject; options : TMeshOptimizerOptions); overload; procedure OptimizeMesh(aMeshObject : TMeshObject); overload; procedure FacesSmooth(aMeshObj: TMeshObject; aWeldDistance: Single=0.0000001; aThreshold: Single=35.0; InvertNormals:boolean=false); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses GLPersistentClasses, GLVectorLists, GLMeshUtils; // OptimizeMesh (list, default options) // procedure OptimizeMesh(aList : TMeshObjectList); begin OptimizeMesh(aList, vDefaultMeshOptimizerOptions); end; // OptimizeMesh (list, with options) // procedure OptimizeMesh(aList : TMeshObjectList; options : TMeshOptimizerOptions); var i, k : Integer; mob, mo : TMeshObject; fg : TFaceGroup; fgvi : TFGVertexIndexList; begin // optimize all mesh objects for i:=0 to aList.Count-1 do begin OptimizeMesh(aList[i], options); end; if (mooStandardize in options) then begin // drop mesh objects that have become empty for i:=aList.Count-1 downto 0 do begin if (aList[i].Mode=momFaceGroups) and (aList[i].FaceGroups.Count=0) then aList[i].Free; end; end; if (aList.Count>0) and (mooMergeObjects in options) then begin mob:=aList[0]; Assert(mob.Mode=momFaceGroups); for i:=1 to aList.Count-1 do begin mo:=aList[i]; Assert(mo.Mode=momFaceGroups); k:=mob.Vertices.Count; mob.Vertices.Add(mo.Vertices); mob.Normals.Add(mo.Normals); mob.TexCoords.Add(mo.TexCoords); while mo.FaceGroups.Count>0 do begin fg:=mo.FaceGroups[0]; fgvi:=(fg as TFGVertexIndexList); fgvi.Owner:=mob.FaceGroups; mob.FaceGroups.Add(fgvi); mo.FaceGroups.Delete(0); fgvi.VertexIndices.Offset(k); end; end; for i:=aList.Count-1 downto 1 do aList[i].Free; end; end; // OptimizeMesh (object, default options) // procedure OptimizeMesh(aMeshObject : TMeshObject); begin OptimizeMesh(aMeshObject, vDefaultMeshOptimizerOptions); end; // OptimizeMesh (object, with options) // procedure OptimizeMesh(aMeshObject : TMeshObject; options : TMeshOptimizerOptions); var i : Integer; fg : TFaceGroup; coords, texCoords, normals : TAffineVectorList; il : TIntegerList; materialName : String; begin if (mooMergeObjects in options) then begin if aMeshObject.Mode=momFaceGroups then begin // remove empty facegroups for i:=aMeshObject.FaceGroups.Count-1 downto 0 do begin fg:=aMeshObject.FaceGroups[i]; if fg.TriangleCount=0 then fg.Free; end; end; end; if (mooStandardize in options) then begin if (aMeshObject.Mode<>momFaceGroups) or (aMeshObject.FaceGroups.Count<=1) then begin if aMeshObject.FaceGroups.Count=1 then materialName:=aMeshObject.FaceGroups[0].MaterialName; texCoords:=TAffineVectorList.Create; normals:=TAffineVectorList.Create; coords:=aMeshObject.ExtractTriangles(texCoords, normals); try il:=BuildVectorCountOptimizedIndices(coords, normals, texCoords); try aMeshObject.Clear; if il.Count>0 then begin RemapReferences(normals, il); RemapReferences(texCoords, il); RemapAndCleanupReferences(coords, il); aMeshObject.Vertices:=coords; aMeshObject.Normals:=normals; aMeshObject.TexCoords:=texCoords; fg:=TFGVertexIndexList.CreateOwned(aMeshObject.FaceGroups); fg.MaterialName:=materialName; TFGVertexIndexList(fg).VertexIndices:=il; end; finally il.Free; end; finally coords.Free; normals.Free; texCoords.Free; end; end else Assert(False, 'Standardization with multiple facegroups not supported... yet.'); end; if (mooVertexCache in options) and (aMeshObject.Mode=momFaceGroups) then begin for i:=0 to aMeshObject.FaceGroups.Count-1 do begin fg:=aMeshObject.FaceGroups[i]; if fg.ClassType=TFGVertexIndexList then with TFGVertexIndexList(fg) do begin if Mode in [fgmmTriangles, fgmmFlatTriangles] then IncreaseCoherency(VertexIndices, 12); end; end; end; if mooSortByMaterials in options then aMeshObject.FaceGroups.SortByMaterial; end; procedure FacesSmooth(aMeshObj: TMeshObject; aWeldDistance: Single=0.0000001; aThreshold: Single=35.0; InvertNormals:boolean=false); Var I, J, K, L: integer; WeldedVertex: TAffineVectorList; TmpIntegerList: TIntegerList; IndexMap: TStringList; n: TAffineVector; indicesMap : TIntegerList; Index: Integer; FaceList: TIntegerList; NormalList: TAffineVectorList; FaceNormalList: TAffineVectorList; FaceGroup: TFaceGroup; FG, FG1: TFGVertexIndexList; Threshold: Single; Angle: Single; ReferenceMap: TIntegerList; ID1, ID2: Integer; Index1, Index2, Index3: Integer; function FindReferenceIndex(aID: Integer): Integer; begin Result := ReferenceMap[aID]; end; function iMin(a, b: Integer): Integer; begin if a<b then Result := a else Result := b; end; function iMax(a, b: Integer): Integer; begin if a>b then Result := a else Result := b; end; begin Threshold := aThreshold * Pi/180.0; //build the vectices reference map ReferenceMap := TIntegerList.Create; WeldedVertex := TAffineVectorList.Create; WeldedVertex.Assign(aMeshObj.Vertices); indicesMap := TIntegerList.Create; //first of all, weld the very closed vertices WeldVertices(WeldedVertex, indicesMap, aWeldDistance); //then, rebuild the map list IndexMap := TStringList.Create; for I:=0 to WeldedVertex.Count-1 do begin ReferenceMap.Assign(indicesMap); TmpIntegerList := TIntegerList.Create; Index := ReferenceMap.IndexOf(I); while Index>=0 do begin TmpIntegerList.Add(Index); ReferenceMap[Index] := -99999; Index := ReferenceMap.IndexOf(I); end; IndexMap.AddObject(IntToStr(I), TmpIntegerList); end; ReferenceMap.Assign(indicesMap); //never used these, free them all WeldedVertex.free; indicesMap.free; //create a TexPoint list for save face infomation, where s=facegroup index, t=face index FaceList := TIntegerList.Create; NormalList := TAffineVectorList.Create; FaceNormalList := TAffineVectorList.Create; //NormalIndex := TIntegerList.Create; for I:=0 to aMeshObj.FaceGroups.Count-1 do begin FaceGroup := aMeshObj.FaceGroups[I]; TmpIntegerList := TFGVertexIndexList(FaceGroup).VertexIndices; for J:=0 to (TmpIntegerList.Count div 3)-1 do begin FaceList.Add(I); FaceList.Add(J); CalcPlaneNormal(aMeshObj.Vertices[TmpIntegerList[J * 3 + 0]], aMeshObj.Vertices[TmpIntegerList[J * 3 + 1]], aMeshObj.Vertices[TmpIntegerList[J * 3 + 2]], n); //add three normals for one trangle FaceNormalList.Add(n); NormalList.Add(n); NormalList.Add(n); NormalList.Add(n); end; end; //do smooth for I:=0 to (FaceList.Count div 2)-1 do begin Index := FaceList[I*2+0]; Index1 := FaceList[I*2+1]; FG := TFGVertexIndexList(aMeshObj.FaceGroups[Index]); for J:=0 to 2 do begin for K:=0 to (FaceList.Count div 2)-1 do begin Index2 := FaceList[K*2+0]; Index3 := FaceList[K*2+1]; FG1 := TFGVertexIndexList(aMeshObj.FaceGroups[Index2]); if I<>K then begin for L:=0 to 2 do begin //two face contain the same vertex ID1 := FindReferenceIndex(FG.VertexIndices[Index1*3+J]); ID2 := FindReferenceIndex(FG1.VertexIndices[Index3*3+L]); if ID1=ID2 then begin Angle := VectorDotProduct(FaceNormalList[I],FaceNormalList[K]); if angle>Threshold then NormalList[I*3+J] := VectorAdd(NormalList[I*3+J],FaceNormalList[K]); end; end; end; end; n := NormalList[I*3+J]; NormalizeVector(n); NormalList[I*3+J] := n; end; end; for I:=0 to (FaceList.Count div 2)-1 do begin Index := FaceList[I*2+0]; FG := TFGVertexIndexList(aMeshObj.FaceGroups[Index]); Index := FaceList[I*2+1]; aMeshObj.Normals[FG.VertexIndices[(Index*3+0)]] := NormalList[(I*3+0)]; aMeshObj.Normals[FG.VertexIndices[(Index*3+1)]] := NormalList[(I*3+1)]; aMeshObj.Normals[FG.VertexIndices[(Index*3+2)]] := NormalList[(I*3+2)]; if InvertNormals then begin aMeshObj.Normals[FG.VertexIndices[(Index*3+0)]] := VectorNegate(aMeshObj.Normals[FG.VertexIndices[(Index*3+0)]]); aMeshObj.Normals[FG.VertexIndices[(Index*3+1)]] := VectorNegate(aMeshObj.Normals[FG.VertexIndices[(Index*3+1)]]); aMeshObj.Normals[FG.VertexIndices[(Index*3+2)]] := VectorNegate(aMeshObj.Normals[FG.VertexIndices[(Index*3+2)]]); end; end; FaceList.free; NormalList.free; FaceNormalList.free; ReferenceMap.free; for I:=0 to IndexMap.Count-1 do IndexMap.Objects[I].free; IndexMap.free; end; end.
unit xElecTV; interface uses xElecLine, xElecPoint, System.Classes, System.SysUtils; type /// <summary> /// 电压互感器 /// </summary> TElecTV = class private FOnValueChnage: TNotifyEvent; FTVFirstValue: Double; FTVSecondValue: Double; FTVName: string; FFirstVolL: TElecLine; FFirstVolH: TElecLine; FSecondVolH: TElecLine; FSecondVolL: TElecLine; procedure ValueChangeVol(Sender : TObject); procedure ValueChange(Sender : TObject); public constructor Create; destructor Destroy; override; /// <summary> /// 电压互感器名称 /// </summary> property TVName : string read FTVName write FTVName; /// <summary> /// 一次电压高端 /// </summary> property FirstVolH : TElecLine read FFirstVolH write FFirstVolH; /// <summary> /// 一次电压低端 /// </summary> property FirstVolL : TElecLine read FFirstVolL write FFirstVolL; /// <summary> /// 二次电压高端 /// </summary> property SecondVolH : TElecLine read FSecondVolH write FSecondVolH; /// <summary> /// 二次电压低端 /// </summary> property SecondVolL : TElecLine read FSecondVolL write FSecondVolL; /// <summary> /// TV变比一次侧值 /// </summary> property TVFirstValue : Double read FTVFirstValue write FTVFirstValue; /// <summary> /// TV变比二次侧值 /// </summary> property TVSecondValue : Double read FTVSecondValue write FTVSecondValue; /// <summary> /// 值改变事件 /// </summary> property OnValueChnage : TNotifyEvent read FOnValueChnage write FOnValueChnage; public /// <summary> /// 清空电压值 /// </summary> procedure ClearVolVlaue; /// <summary> /// 清除权值 /// </summary> procedure ClearWValue; /// <summary> /// 清空电流列表 /// </summary> procedure ClearCurrentList; end; implementation { TElecTV } procedure TElecTV.ClearCurrentList; begin FFirstVolL.ClearCurrentList; FFirstVolH.ClearCurrentList; FSecondVolH.ClearCurrentList; FSecondVolL.ClearCurrentList; end; procedure TElecTV.ClearVolVlaue; begin end; procedure TElecTV.ClearWValue; begin FFirstVolL.ClearWValue; FFirstVolH.ClearWValue; FSecondVolH.ClearWValue; FSecondVolL.ClearWValue; end; constructor TElecTV.Create; begin FFirstVolL:= TElecLine.Create; FFirstVolH:= TElecLine.Create; FSecondVolH:= TElecLine.Create; FSecondVolL:= TElecLine.Create; FFirstVolH.OnChangeVol := ValueChangeVol; FSecondVolH.OnChange := ValueChange; FFirstVolL.LineName:= 'TV一次低端'; FFirstVolH.LineName:= 'TV一次高端'; FSecondVolH.LineName:= 'TV二次高端'; FSecondVolL.LineName:= 'TV二次低端'; FTVFirstValue:= 1; FTVSecondValue:= 1; FTVName := '电压电压互感器'; end; destructor TElecTV.Destroy; begin FFirstVolL.Free; FFirstVolH.Free; FSecondVolH.Free; FSecondVolL.Free; inherited; end; procedure TElecTV.ValueChange(Sender: TObject); begin if Assigned(FOnValueChnage) then begin FOnValueChnage(Self); end; end; procedure TElecTV.ValueChangeVol(Sender: TObject); begin if Assigned(FFirstVolH) then begin FSecondVolH.Voltage.Value := FFirstVolH.Voltage.Value/FTVFirstValue*FTVSecondValue; FSecondVolH.Voltage.Angle := FFirstVolH.Voltage.Angle; FSecondVolH.WID := FFirstVolH.WID; FSecondVolH.SendVolValue; end; end; end.
unit Dialogs4D.Modal.Error; interface uses Dialogs4D.Modal.Intf; type TDialogModalError = class(TInterfacedObject, IDialogModal) private /// <summary> /// Displays a dialog box for the user with a error message. /// </summary> /// <param name="Content"> /// Error message to be displayed to the user. /// </param> procedure Show(const Content: string); end; implementation uses {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} UniGuiDialogs, UniGuiTypes, {$ELSEIF DEFINED(MSWINDOWS)} Vcl.Forms, Winapi.Windows, Vcl.BlockUI.Intf, Vcl.BlockUI, {$ENDIF} System.SysUtils, Dialogs4D.Constants; {$IF (DEFINED(UNIGUI_VCL) or DEFINED(UNIGUI_ISAPI) or DEFINED(UNIGUI_SERVICE))} procedure TDialogModalError.Show(const Content: string); begin MessageDlg(Content, mtError, [mbOK]); end; {$ELSEIF DEFINED(MSWINDOWS)} procedure TDialogModalError.Show(const Content: string); var BlockUI: IBlockUI; begin BlockUI := TBlockUI.Create(); Application.MessageBox(PWideChar(Content), PWideChar(Application.Title), MB_ICONHAND); end; {$ELSE} procedure TDialogModalError.Show(const Content: string); begin raise Exception.Create(DIRECTIVE_NOT_DEFINED); end; {$ENDIF} end.
unit uLogger; interface uses Classes, SysUtils, StrUtils, SyncObjs, Forms; type TLogger = class class var FLogger: TLogger; private FCS: TCriticalSection; FActive: boolean; FStream: array of string; MaxStreamCount: integer; FMaxFileLength: integer; FLogFileNamePrefix, FLogFilePath, FLogFileName: string; function GetNewLogFileName: string; class constructor Create; protected procedure PutLogMessageToFile(ALine: string); procedure PutLogMessageToStream(ALine: string); public class function GetInstance: TLogger; constructor Create(ALogFileNamePrefix, ALogFilePath: string); destructor Destroy; override; property Active: boolean read FActive write FActive; end; procedure SetLogLevel(LogLevel: integer); procedure AddLog(data: string; level: integer = 0); procedure GetSLLog(sl: TStringList); implementation const FMaxSLCount = 23; var FSLLog: TStringList; FLogLevel: integer; procedure AddLog(data: string; level: integer = 0); var msg: string; begin if level > FLogLevel then exit; msg := IntToStr(level) + '|' + DateTimeToStr(Now) + ' ' + data; FSLLog.Add(msg); if FSLLog.Count > FMaxSLCount then FSLLog.Delete(0); TLogger.GetInstance.PutLogMessageToFile(msg); end; procedure SetLogLevel(LogLevel: integer); begin FLogLevel := LogLevel; end; procedure GetSLLog(sl: TStringList); begin sl.Assign(FSLLog); end; // ------------------ TLogger ------------------ class function TLogger.GetInstance: TLogger; begin if not assigned(FLogger) then FLogger := TLogger.Create( '', ExtractFilePath(Application.ExeName) + 'logs\'); Result := FLogger; end; function TLogger.GetNewLogFileName: string; begin Result := FLogFilePath + FLogFileNamePrefix + FormatDateTime('DDMMYY-HHNNSS', Now) + '.log'; end; procedure TLogger.PutLogMessageToFile(ALine: string); var f : TextFile; isEx : boolean; FileLen : integer; sr : TSearchRec; begin if not FActive then exit; FCS.Enter; try isEx := FileExists(FLogFileName); FileLen := 0; if isEx then begin FindFirst(FLogFileName, faAnyFile, sr); FileLen := sr.Size; FindClose(sr); end; AssignFile(f, FLogFileName); if isEx then Append(f) else Rewrite(f); Writeln(f, ALine); flush(f); CloseFile(f); if (FileLen <> 0) and (FileLen > FMaxFileLength) then FLogFileName := GetNewLogFileName; except end; FCS.Leave; end; procedure TLogger.PutLogMessageToStream(ALine: string); var i: integer; begin FCS.Enter; try if length(FStream) >= MaxStreamCount then begin for i := 0 to MaxStreamCount - 2 do FStream[i] := FStream[i + 1]; end else SetLength(FStream, length(FStream) + 1); FStream[length(FStream) - 1] := ALine; except end; FCS.Leave; end; constructor TLogger.Create(ALogFileNamePrefix, ALogFilePath: string); begin FCS := TCriticalSection.Create; SetLength(FStream, 0); MaxStreamCount := 40; FMaxFileLength := 100000; // bytes FActive := false; FLogFileNamePrefix := ALogFileNamePrefix; FLogFilePath := ALogFilePath; if not DirectoryExists(ALogFilePath) then CreateDir(ALogFilePath); FLogFileName := GetNewLogFileName; end; class constructor TLogger.Create; begin FLogger := nil; end; destructor TLogger.Destroy; begin SetLength(FStream, 0); FCS.Destroy; end; initialization FLogLevel := 100; FSLLog := TStringList.Create; TLogger.GetInstance.Active := true; end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIDlg.pas // Creator : Shen Min // Date : 2003-03-31 V1-V3 // 2003-07-14 V4 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIDlg; interface {$I SUIPack.inc} uses Controls, Classes, Math, Forms, Dialogs, Graphics, SysUtils, SUIThemes, SUIMgr; type TsuiDialogButtonsCount = 1..3; TsuiIconType = (suiNone, suiWarning, suiStop, suiInformation, suiHelp); type TsuiDialog = class(TComponent) private m_Position : TPosition; m_Caption : TCaption; m_ButtonCursor : TCursor; m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; m_Font : TFont; m_CaptionFont : TFont; procedure SetFileTheme(const Value: TsuiFileTheme); procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetFont(const Value: TFont); procedure SetCaptionFont(const Value: TFont); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; property ButtonCursor : TCursor read m_ButtonCursor write m_ButtonCursor; public constructor Create(AOwner : TComponent); override; destructor Destroy(); override; function ShowModal : TModalResult; virtual; abstract; published property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property Position : TPosition read m_Position write m_Position; property Caption : TCaption read m_Caption write m_Caption; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property Font : TFont read m_Font write SetFont; property CaptionFont : TFont read m_CaptionFont write SetCaptionFont; end; TsuiMessageDialog = class(TsuiDialog) private m_ButtonCount : TsuiDialogButtonsCount; m_Button1Caption : TCaption; m_Button2Caption : TCaption; m_Button3Caption : TCaption; m_Button1ModalResult : TModalResult; m_Button2ModalResult : TModalResult; m_Button3ModalResult : TModalResult; m_IconType : TsuiIconType; m_Text : String; public constructor Create(AOwner : TComponent); override; function ShowModal : TModalResult; override; published property ButtonCursor; property ButtonCount : TsuiDialogButtonsCount read m_ButtonCount write m_ButtonCount; property Button1Caption : TCaption read m_Button1Caption write m_Button1Caption; property Button2Caption : TCaption read m_Button2Caption write m_Button2Caption; property Button3Caption : TCaption read m_Button3Caption write m_Button3Caption; property Button1ModalResult : TModalResult read m_Button1ModalResult write m_Button1ModalResult; property Button2ModalResult : TModalResult read m_Button2ModalResult write m_Button2ModalResult; property Button3ModalResult : TModalResult read m_Button3ModalResult write m_Button3ModalResult; property IconType : TsuiIconType read m_IconType write m_IconType; property Text : String read m_Text write m_Text; end; TsuiPasswordDialog = class(TsuiDialog) private m_ButtonCancelCaption: TCaption; m_ButtonOKCaption: TCaption; m_Item1Caption: TCaption; m_Item1PasswordChar: Char; m_Item2Caption: TCaption; m_Item2PasswordChar: Char; m_Item1Text : String; m_Item2Text : String; public constructor Create(AOwner : TComponent); override; function ShowModal : TModalResult; override; published property Item1Caption : TCaption read m_Item1Caption write m_Item1Caption; property Item2Caption : TCaption read m_Item2Caption write m_Item2Caption; property Item1PasswordChar : Char read m_Item1PasswordChar write m_Item1PasswordChar; property Item2PasswordChar : Char read m_Item2PasswordChar write m_Item2PasswordChar; property Item1Text : String read m_Item1Text write m_Item1Text; property Item2Text : String read m_Item2Text write m_Item2Text; property ButtonOKCaption : TCaption read m_ButtonOKCaption write m_ButtonOKCaption; property ButtonCancelCaption : TCaption read m_ButtonCancelCaption write m_ButtonCancelCaption; property ButtonCursor; end; TsuiInputDialog = class(TsuiDialog) private m_ButtonCancelCaption: TCaption; m_ButtonOKCaption: TCaption; m_PromptText : String; m_ValueText : String; m_PasswordChar : Char; public constructor Create(AOwner : TComponent); override; function ShowModal : TModalResult; override; published property PasswordChar : Char read m_PasswordChar write m_PasswordChar; property PromptText : String read m_PromptText write m_PromptText; property ValueText : String read m_ValueText write m_ValueText; property ButtonOKCaption : TCaption read m_ButtonOKCaption write m_ButtonOKCaption; property ButtonCancelCaption : TCaption read m_ButtonCancelCaption write m_ButtonCancelCaption; property ButtonCursor; end; function SUIMsgDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; UIStyle : TsuiUIStyle = SUI_THEME_DEFAULT): TModalResult; overload; function SUIMsgDlg(const Msg, Caption : String; DlgType : TMsgDlgType; Buttons: TMsgDlgButtons; UIStyle : TsuiUIStyle = SUI_THEME_DEFAULT) : TModalResult; overload; implementation uses frmPassword, frmMessage, frmInput, SUIButton, SUIResDef, SUIPublic; //function SUIMsgDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; UIStyle : TsuiUIStyle = SUI_THEME_DEFAULT): TModalResult; //var // MsgDlg : TsuiMessageDialog; //begin // MsgDlg := TsuiMessageDialog.Create(nil); // MsgDlg.UIStyle := UIStyle; // MsgDlg.Text := Msg; // // case DlgType of // mtWarning : MsgDlg.IconType := suiWarning; // mtError : MsgDlg.IconType := suiStop; // mtInformation : MsgDlg.IconType := suiInformation; // mtConfirmation : MsgDlg.IconType := suiHelp; // mtCustom : MsgDlg.IconType := suiNone; // end; // case // // //mbYes, mbNo, mbOK, mbCancel, mbAbort, mbRetry, mbIgnore, mbAll, mbNoToAll, mbYesToAll, mbHelp // // Result := MsgDlg.ShowModal(); // MsgDlg.Free(); //end; function SUIMsgDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; UIStyle : TsuiUIStyle = SUI_THEME_DEFAULT): TModalResult; begin if Assigned(Application) then Result := SUIMsgDlg(Msg, Application.Title, DlgType, Buttons, UIStyle) else Result := SUIMsgDlg(Msg, 'Default', DlgType, Buttons, UIStyle) end; function SUIMsgDlg(const Msg, Caption : String; DlgType : TMsgDlgType; Buttons: TMsgDlgButtons; UIStyle : TsuiUIStyle = SUI_THEME_DEFAULT) : TModalResult; var MsgDlg : TsuiMessageDialog; B: TMsgDlgBtn; bc: String; bmr: TModalResult; btnCnt: Integer; begin MsgDlg := TsuiMessageDialog.Create(nil); MsgDlg.Text := Msg; btnCnt := 0; bmr := mrOK; for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do begin if B in Buttons then begin inc(btnCnt); case B of //ESTABLISH BUTTON CAPTION mbOk: begin bc := 'Ok'; bmr := mrOK end; mbYes: begin bc := 'Yes'; bmr := mrYes end; mbNo: begin bc := 'No'; bmr := mrNo end; mbYesToAll: begin bc := 'Yes to All'; bmr := mrYesToAll end; mbNoToAll: begin bc := 'No to All'; bmr := mrNoToAll end; mbAbort: begin bc := 'Abort'; bmr := mrAbort end; mbCancel: begin bc := 'Cancel'; bmr := mrCancel end; mbRetry: begin bc := 'Retry'; bmr := mrRetry end; mbIgnore: begin bc := 'Ignore'; bmr := mrIgnore end; mbAll: begin bc := 'All'; bmr := mrAll; end; //mbHelp: begin bc := 'Help'; bmr := mrHelp end; end; Case btnCnt of //ESTABLISH BUTTON RESULT 1: begin MsgDlg.Button1Caption := bc; MsgDlg.Button1ModalResult := bmr; end; 2: begin MsgDlg.Button2Caption := bc; MsgDlg.Button2ModalResult := bmr; end; 3: begin MsgDlg.Button3Caption := bc; MsgDlg.Button3ModalResult := bmr; end; end; end; end; MsgDlg.ButtonCount := btnCnt; case DlgType of mtWarning : MsgDlg.IconType := suiWarning; mtError : MsgDlg.IconType := suiStop; mtInformation : MsgDlg.IconType := suiInformation; mtConfirmation : MsgDlg.IconType := suiHelp; mtCustom : MsgDlg.IconType := suiNone; end; // case //mbYes, mbNo, mbOK, mbCancel, mbAbort, mbRetry, mbIgnore, mbAll, mbNoToAll, mbYesToAll, mbHelp MsgDlg.UIStyle := UIStyle; MsgDlg.Caption := Caption; Result := MsgDlg.ShowModal(); MsgDlg.Free(); end; { TsuiDialog } constructor TsuiDialog.Create(AOwner: TComponent); begin inherited; m_Caption := 'suiDialog'; m_Position := poScreenCenter; m_ButtonCursor := crHandPoint; m_UIStyle := SUI_THEME_DEFAULT; m_Font := TFont.Create(); m_CaptionFont := TFont.Create(); m_CaptionFont.Color := clWhite; m_CaptionFont.Name := 'Tahoma'; m_CaptionFont.Style := [fsBold]; UIStyle := GetSUIFormStyle(AOwner); end; destructor TsuiDialog.Destroy; begin m_CaptionFont.Free(); m_CaptionFont := nil; m_Font.Free(); m_Font := nil; inherited; end; procedure TsuiDialog.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiDialog.SetCaptionFont(const Value: TFont); begin m_CaptionFont.Assign(Value); end; procedure TsuiDialog.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiDialog.SetFont(const Value: TFont); begin m_Font.Assign(Value); end; procedure TsuiDialog.SetUIStyle(const Value: TsuiUIStyle); var OutUIStyle : TsuiUIStyle; Tmp : Integer; begin m_UIStyle := Value; if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then begin Tmp := m_FileTheme.GetColor(SUI_THEME_TITLEBAR_FONT_COLOR); if Tmp = -1 then begin Tmp := m_FileTheme.GetColor(SUI_THEME_CONTROL_FONT_COLOR); if (Tmp = 65536) or (Tmp = 262144) or (Tmp = 196608) or (Tmp = 327680) then m_CaptionFont.Color := clBlack else m_CaptionFont.Color := clWhite; end else m_CaptionFont.Color := Tmp; end else begin {$IFDEF RES_MACOS} if m_UIStyle = MacOS then m_CaptionFont.Color := clBlack else {$ENDIF} m_CaptionFont.Color := clWhite; end; end; { TsuiMessageDialog } constructor TsuiMessageDialog.Create(AOwner: TComponent); begin inherited; ButtonCount := 1; Button1Caption := 'OK'; Button2Caption := 'Cancel'; Button3Caption := 'Cancel'; Button1ModalResult := mrOK; Button2ModalResult := mrCancel; Button3ModalResult := mrCancel; m_Text := 'Hello world!'; end; function TsuiMessageDialog.ShowModal: TModalResult; var Dlg : TfrmMsg; i : Integer; Btn : TsuiButton; lblHeight : Integer; btnleft : Integer; TmpBmp : TBitmap; begin Dlg := TfrmMsg.Create(Application); Dlg.Font.Assign(m_Font); Dlg.lbl.Caption := m_Text; lblheight := Max(Dlg.Image1.BoundsRect.Bottom, Dlg.lbl.BoundsRect.Bottom); if m_IconType <> suiNone then begin Dlg.lbl.Left := 88; TmpBmp := TBitmap.Create(); TmpBmp.LoadFromResourceName(hInstance, 'MSGDLG'); SpitBitmap(TmpBmp, Dlg.Image1.Picture.Bitmap, 4, Ord(m_IconType)); TmpBmp.Free() end else begin Dlg.lbl.Left := 24; Dlg.Image1.Visible := false; if m_ButtonCount < 3 then Dlg.Width := Dlg.Width - 64; end; btnleft := Dlg.Width - 73 - 24; for i := m_ButtonCount downto 1 do begin Btn := TsuiButton.Create(Dlg); Btn.Parent := Dlg.suiForm1; Btn.Top := lblheight + 20; Btn.Height := 25; Btn.Width := 73; Btn.Cursor := m_ButtonCursor; Btn.Left := btnLeft; Btn.TabStop := true; Btn.TabOrder := 1; Dec(btnLeft, 73 + 20); case i of 1 : begin Btn.Caption := Button1Caption; Btn.ModalResult := Button1ModalResult; Dlg.ActiveControl := Btn; end; 2 : begin Btn.Caption := Button2Caption; Btn.ModalResult := Button2ModalResult; Dlg.ActiveControl := Btn; end; 3: begin Btn.Caption := Button3Caption; Btn.ModalResult := Button3ModalResult; Dlg.ActiveControl := Btn; end; end; if Btn.ModalResult = mrCancel then begin Btn.Cancel := true; Btn.Default := false; end else if Btn.ModalResult = mrOk then begin Btn.Cancel := false; Btn.Default := true; end else begin Btn.Cancel := false; Btn.Default := false; end; end; Dlg.Height := lblheight + 20 + 25 + 20; Dlg.Position := m_Position; Dlg.suiForm1.ReAssign(); Dlg.suiForm1.Caption := m_Caption; Dlg.suiForm1.UIStyle := m_UIStyle; Dlg.suiForm1.FileTheme := m_FileTheme; Dlg.suiForm1.Font.Assign(m_CaptionFont); Result := Dlg.ShowModal(); Dlg.Free(); end; { TsuiPasswordDialog } constructor TsuiPasswordDialog.Create(AOwner: TComponent); begin inherited; Item1Caption := 'User name:'; Item2Caption := 'Password:'; Item1PasswordChar := #0; Item2PasswordChar := '*'; Item1Text := ''; Item2Text := ''; ButtonOKCaption := 'OK'; ButtonCancelCaption := 'Cancel'; end; function TsuiPasswordDialog.ShowModal: TModalResult; var Dlg : TfrmPass; lblLength : Integer; begin Dlg := TfrmPass.Create(Application); Dlg.Font.Assign(m_Font); Dlg.lbl1.Caption := m_Item1Caption; Dlg.lbl2.Caption := m_Item2Caption; Dlg.edt1.Text := m_Item1Text; Dlg.edt2.Text := m_Item2Text; lblLength := Max(Dlg.lbl1.Width, Dlg.lbl2.Width); Dlg.edt1.Left := Dlg.lbl1.Left + lblLength + 5; Dlg.edt2.Left := Dlg.edt1.Left; Dlg.edt1.PasswordChar := m_Item1PasswordChar; Dlg.edt2.PasswordChar := m_Item2PasswordChar; Dlg.btn1.Caption := m_ButtonOKCaption; Dlg.btn1.Default := true; Dlg.btn2.Caption := m_ButtonCancelCaption; Dlg.btn2.Cancel := true; Dlg.Width := Dlg.edt1.Left + Dlg.edt1.Width + 24; Dlg.Position := m_Position; Dlg.suiForm1.ReAssign(); Dlg.btn1.Left := Dlg.Width div 2 - 8 - Dlg.btn1.Width; Dlg.btn2.Left := Dlg.Width div 2 + 8; Dlg.btn1.Cursor := ButtonCursor; Dlg.btn2.Cursor := ButtonCursor; Dlg.suiForm1.Caption := m_Caption; Dlg.suiForm1.UIStyle := m_UIStyle; Dlg.suiForm1.FileTheme := m_FileTheme; Dlg.suiForm1.Font.Assign(m_CaptionFont); Result := Dlg.ShowModal(); if Result = mrOK then begin m_Item1Text := Dlg.edt1.Text; m_Item2Text := Dlg.edt2.Text; end; Dlg.Free(); end; { TsuiInputDialog } constructor TsuiInputDialog.Create(AOwner: TComponent); begin inherited; PromptText := 'Prompt text:'; ValueText := ''; ButtonOKCaption := 'OK'; ButtonCancelCaption := 'Cancel'; end; function TsuiInputDialog.ShowModal: TModalResult; var Dlg : TfrmInput; begin Dlg := TfrmInput.Create(Application); Dlg.Font.Assign(m_Font); Dlg.lbl_prompt.Caption := m_PromptText; Dlg.edt_value.Text := m_ValueText; Dlg.edt_value.PasswordChar := m_PasswordChar; Dlg.btn1.Caption := m_ButtonOKCaption; Dlg.btn1.Default := true; Dlg.btn2.Caption := m_ButtonCancelCaption; Dlg.btn2.Cancel := true; Dlg.Position := m_Position; Dlg.suiForm1.ReAssign(); Dlg.btn1.Left := Dlg.Width div 2 - 8 - Dlg.btn1.Width; Dlg.btn2.Left := Dlg.Width div 2 + 8; Dlg.btn1.Cursor := ButtonCursor; Dlg.btn2.Cursor := ButtonCursor; Dlg.suiForm1.Caption := m_Caption; Dlg.suiForm1.UIStyle := m_UIStyle; Dlg.suiForm1.FileTheme := m_FileTheme; Dlg.suiForm1.Font.Assign(m_CaptionFont); Result := Dlg.ShowModal(); if Result = mrOK then m_ValueText := Dlg.edt_value.Text; Dlg.Free(); end; end.
unit ORM.Model.COUNTRY; interface uses Spring.Persistence.Mapping.Attributes; {$M+} type [Entity] [Table('COUNTRY')] TCountry = class private FCountry: string; FCurrency: string; public [UniqueConstraint] [Column('COUNTRY', [cpRequired, cpPrimaryKey, cpNotNull], 15)] property Country: string read FCountry write FCountry; [Column('CURRENCY', [], 10)] property Currency: string read FCurrency write FCurrency; end; {$M-} implementation end.
unit fHistoryDbg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, ActnList, Buttons, ImgList, ToolWin, FlexBase, FlexControls, FlexUtils, FlexProps, FlexPath, FlexHistory, FlexActions; type TfmHistoryDebug = class(TForm) tvHistory: TTreeView; sbrMain: TStatusBar; mmUndo: TMemo; Splitter3: TSplitter; mmRedo: TMemo; Splitter1: TSplitter; procedure tvHistoryCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); procedure acHistoryUndoExecute(Sender: TObject); procedure acHistoryRedoExecute(Sender: TObject); procedure tvHistoryChange(Sender: TObject; Node: TTreeNode); procedure fpMainNotify(Sender: TObject; Control: TFlexControl; Notify: TFlexNotify); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FInUpdate: boolean; FPanel: TFlexPanel; procedure CheckTools; procedure SetPanel(const Value: TFlexPanel); public { Public declarations } property Flex: TFlexPanel read FPanel write SetPanel; procedure HistoryChange(Sender: TObject); end; var fmHistoryDebug: TfmHistoryDebug; implementation {$R *.DFM} procedure TfmHistoryDebug.FormCreate(Sender: TObject); begin HistoryChange(Nil); tvHistoryChange(tvHistory, tvHistory.Selected); CheckTools; end; procedure TfmHistoryDebug.FormDestroy(Sender: TObject); begin fmHistoryDebug := Nil; end; procedure TfmHistoryDebug.SetPanel(const Value: TFlexPanel); begin if Value = FPanel then exit; FPanel := Value; if (csDestroying in ComponentState) then exit; HistoryChange(FPanel); tvHistoryChange(tvHistory, tvHistory.Selected); end; procedure TfmHistoryDebug.HistoryChange(Sender: TObject); procedure AddAction(Action: THistoryAction; AParent: TTreeNode); var Node: TTreeNode; i: integer; begin if Assigned(AParent) then Node := tvHistory.Items.AddChildObject(AParent, Action.Caption, Action) else Node := tvHistory.Items.AddObject(AParent, Action.Caption, Action); if Action is THistoryGroup then begin with THistoryGroup(Action) do for i:=0 to ActionCount-1 do AddAction(Actions[i], Node); Node.Expand(true); end; end; var i: integer; begin tvHistory.Items.BeginUpdate; try FInUpdate := true; tvHistory.Items.Clear; if not Assigned(FPanel) then exit; for i:=0 to FPanel.History.ActionCount-1 do AddAction(FPanel.History[i], Nil); finally tvHistory.Items.EndUpdate; FInUpdate := false; end; CheckTools; tvHistoryChange(tvHistory, tvHistory.Selected); end; procedure TfmHistoryDebug.tvHistoryCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); var Index: integer; begin if not Assigned(FPanel) then exit; Index := FPanel.History.IndexOf(THistoryAction(Node.Data)); if (Index >= 0) and (FPanel.History.ActionIndex = Index) then tvHistory.Canvas.Font.Style := [fsBold]; DefaultDraw := true; end; procedure TfmHistoryDebug.acHistoryUndoExecute(Sender: TObject); begin if not Assigned(FPanel) then exit; FPanel.History.Undo; tvHistory.Invalidate; tvHistoryChange(tvHistory, tvHistory.Selected); CheckTools; end; procedure TfmHistoryDebug.acHistoryRedoExecute(Sender: TObject); begin FPanel.History.Redo; tvHistory.Invalidate; tvHistoryChange(tvHistory, tvHistory.Selected); CheckTools; end; procedure TfmHistoryDebug.CheckTools; begin { acHistoryUndo.Enabled := fpMain.History.ActionIndex >= 0; acHistoryRedo.Enabled := fpMain.History.ActionIndex < fpMain.History.ActionCount - 1;} end; procedure TfmHistoryDebug.tvHistoryChange(Sender: TObject; Node: TTreeNode); var Action: THistoryAction; Memo: TMemo; procedure AddOrderInfo(const Info: TOrderHistoryActionInfo; Memo: TMemo); begin Memo.Clear; if not Info.Exist then exit; with Info do begin Memo.Lines.Add(Format('Index = %d', [Index])); Memo.Lines.Add(Format('ParentId = %d', [ParentId])); Memo.Lines.Add(Format('LayerId = %d', [LayerId])); end; end; procedure LoadStream(Stream: TStream; Memo: TMemo); var List: TStringList; i: integer; begin List := TStringList.Create; try Stream.Position := 0; List.LoadFromStream(Stream); for i:=0 to List.Count-1 do Memo.Lines.Add(List[i]); finally List.Free; end; end; procedure LoadPoints(const Info: TPointsHistoryActionInfo; Memo: TMemo); var i: integer; PtType: string; begin with Info do begin if not Exist then exit; Memo.Lines.Add(Format('DocRect: (%d, %d, %d, %d)', [DocRect.Left, DocRect.Top, DocRect.Right, DocRect.Bottom])); for i:=0 to Length(Info.Points)-1 do begin case Info.Types[i] of ptNode : PtType := 'ptNode'; ptEndNode : PtType := 'ptEndNode'; ptEndNodeClose : PtType := 'ptEndNodeClose'; ptControl : PtType := 'ptControl'; else PtType := '?'; end; Memo.Lines.Add(Format('(%d, %d) - %s', [Info.Points[i].X, Info.Points[i].Y, PtType])); end; end; end; begin mmUndo.Clear; mmRedo.Clear; if FInUpdate then exit; if not Assigned(Node) then exit; Action := TObject(Node.Data) as THistoryAction; if Action is TIdHistoryAction then with TIdHistoryAction(Action) do begin mmUndo.Lines.Add(Format('SourceId = %d', [SourceId])); mmRedo.Lines.Add(Format('SourceId = %d', [SourceId])); end; if Action is TOrderHistoryAction then with TOrderHistoryAction(Action) do begin AddOrderInfo(UndoInfo, mmUndo); AddOrderInfo(RedoInfo, mmRedo); end; if Action is THistoryStreamAction then with TCustomControlHistoryAction(Action) do begin if Assigned(UndoStream) then LoadStream(UndoStream, mmUndo); if Assigned(RedoStream) then LoadStream(RedoStream, mmRedo); end; if Action is TCreateDestroyHistoryGroup then with TCreateDestroyHistoryGroup(Action) do begin if Action is TControlCreateHistoryGroup then Memo := mmRedo else Memo := mmUndo; Memo.Lines.Text := Format( 'SourceId = %d'#13#10 + 'ParentId = %d'#13#10 + 'ParentIndex = %d', [SourceId, ParentId, ParentIndex]); if Assigned(Stream) then LoadStream(Stream, Memo); end; if Action is TDocRectHistoryAction then with TDocRectHistoryAction(Action) do begin if UndoExist then with UndoDocRect do mmUndo.Lines.Add(Format('DocRect: (%d, %d, %d, %d)', [Left, Top, Right, Bottom])); if RedoExist then with RedoDocRect do mmRedo.Lines.Add(Format('DocRect: (%d, %d, %d, %d)', [Left, Top, Right, Bottom])); end; if Action is TPointsHistoryAction then with TPointsHistoryAction(Action) do begin LoadPoints(UndoInfo, mmUndo); LoadPoints(RedoInfo, mmRedo); end; end; procedure TfmHistoryDebug.fpMainNotify(Sender: TObject; Control: TFlexControl; Notify: TFlexNotify); begin { if csDestroying in ComponentState then exit; if Notify = fnSelect then if fpMain.SelectedCount = 1 then sbrMain.SimpleText := Format('ID: %d', [fpMain.Selected[0].ID]) else sbrMain.SimpleText := ''; } end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC TFDQuery editor form } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.VCLUI.QEdit; interface uses {$IFDEF MSWINDOWS} Winapi.Messages, Winapi.Windows, {$ENDIF} System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Data.DB, Vcl.Buttons, Vcl.CheckLst, Vcl.ActnList, Vcl.ImgList, System.IniFiles, FireDAC.VCLUI.OptsBase, FireDAC.VCLUI.Controls, FireDAC.VCLUI.ResourceOptions, FireDAC.VCLUI.UpdateOptions, FireDAC.VCLUI.FormatOptions, FireDAC.VCLUI.FetchOptions, FireDAC.VCLUI.Memo, FireDAC.UI.Intf, FireDAC.DatS, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.Stan.Param, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.Async, FireDAC.DApt, System.Actions; type TfrmFDGUIxFormsQEdit = class(TfrmFDGUIxFormsOptsBase) pcMain: TPageControl; pcResult: TPageControl; tsSQL: TTabSheet; tsAdvOptions: TTabSheet; ptAdvOptions: TFDGUIxFormsPanelTree; frmFetchOptions: TfrmFDGUIxFormsFetchOptions; frmFormatOptions: TfrmFDGUIxFormsFormatOptions; frmUpdateOptions: TfrmFDGUIxFormsUpdateOptions; frmResourceOptions: TfrmFDGUIxFormsResourceOptions; DataSource1: TDataSource; tsRecordSet: TTabSheet; tsStructure: TTabSheet; DBGrid1: TDBGrid; Splitter1: TSplitter; tsMessages: TTabSheet; lvStructure: TListView; mmMessages: TMemo; tsParameters: TTabSheet; lbParams: TListBox; Panel19: TPanel; tsMacros: TTabSheet; FQuery: TFDQuery; alActions: TActionList; ilImages: TImageList; lbMacros: TListBox; pnlRight: TPanel; Panel16: TPanel; btnExecute: TButton; btnNextRecordSet: TButton; btnQBuilder: TButton; acNextRS: TAction; acQueryBuilder: TAction; acExecute: TAction; BitBtn1: TButton; acUpdateSQLEditor: TAction; acCodeEditor: TAction; Bevel5: TBevel; Bevel7: TBevel; pnlResult: TPanel; cbRollback: TCheckBox; Label1: TLabel; cbParamType: TComboBox; Label2: TLabel; edtValue: TEdit; Label3: TLabel; cbDataType: TComboBox; Label4: TLabel; edtDataSize: TEdit; Bevel1: TBevel; Label5: TLabel; cbArrayType: TComboBox; Label6: TLabel; edtArraySize: TEdit; Label7: TLabel; edtPosition: TEdit; Bevel4: TBevel; Panel1: TPanel; Bevel9: TBevel; Label10: TLabel; Label11: TLabel; cbMacroType: TComboBox; edtMacroValue: TEdit; procedure FormShow(Sender: TObject); procedure mmSQLKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lbParamsClick(Sender: TObject); procedure lbMacrosClick(Sender: TObject); procedure mmSQLChange(Sender: TObject); procedure acExecuteExec(Sender: TObject); procedure acNextRSExecute(Sender: TObject); procedure acNextRSUpdate(Sender: TObject); procedure acQueryBuilderExecute(Sender: TObject); procedure acExecuteUpdate(Sender: TObject); procedure frmOptionsModified(Sender: TObject); procedure acUpdateSQLEditorUpdate(Sender: TObject); procedure acUpdateSQLEditorExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure pcMainChanging(Sender: TObject; var AllowChange: Boolean); procedure edtParametersExit(Sender: TObject); procedure edtMacrosExit(Sender: TObject); private FDefinitionChanged: Boolean; mmSQL: TFDGUIxFormsMemo; procedure LoadParameters(AIndex: Integer); procedure LoadParameter(AIndex: Integer); procedure SaveParameter(AIndex: Integer); procedure LoadMacros(AIndex: Integer); procedure LoadMacro(AIndex: Integer); procedure SaveMacros(AIndex: Integer); procedure ExecQuery; procedure NextRecordSet; procedure FillMessages(AMessages: EFDDBEngineException); procedure FillStructure(ATable: TFDDatSTable); procedure FillInfos; procedure UpdateQuery; function ExecuteBase(AQuery: TFDCustomQuery; const ACaption: String): Boolean; protected procedure LoadFormState(AIni: TCustomIniFile); override; procedure SaveFormState(AIni: TCustomIniFile); override; public class function Execute(AQuery: TFDCustomQuery; const ACaption: String): Boolean; end; implementation uses System.Variants, Data.DBCommon, System.Math, FireDAC.Stan.Consts, FireDAC.Stan.ResStrs, FireDAC.Stan.Util, FireDAC.VCLUI.USEdit; {$R *.dfm} { --------------------------------------------------------------------------- } function GetStringValue(AValue: Variant): string; var iVarType: Integer; begin iVarType := VarType(AValue); if iVarType = varEmpty then Result := '<unassigned>' else if iVarType = varNull then Result := '<null>' else Result := VarToStr(AValue); end; { --------------------------------------------------------------------------- } function GetVariantValue(AVarType: Integer; const AValue: string): Variant; begin if CompareText(AValue, '<unassigned>') = 0 then Result := Unassigned else if (CompareText(AValue, '<null>') = 0) or (AValue = '') and not ((AVarType = varString) or (AVarType = varOleStr) or (AVarType = varUString)) then Result := Null else if AVarType = varError then Result := AValue else VarCast(Result, AValue, AVarType); end; { --------------------------------------------------------------------------- } { TfrmFDGUIxFormsQEdit } { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsQEdit.FormCreate(Sender: TObject); var ePT: TParamType; eFT: TFieldType; eAT: TFDParamArrayType; eMT: TFDMacroDataType; begin mmSQL := TFDGUIxFormsMemo.Create(Self); mmSQL.Parent := tsSQL; mmSQL.Left := 5; mmSQL.Top := 5; mmSQL.Width := tsSQL.ClientWidth - 11; mmSQL.Height := tsSQL.ClientHeight - 11; mmSQL.Align := alNone; mmSQL.Anchors := [akLeft, akTop, akRight, akBottom]; mmSQL.ScrollBars := ssBoth; mmSQL.TabOrder := 0; mmSQL.OnChange := mmSQLChange; mmSQL.OnKeyDown := mmSQLKeyDown; cbParamType.Items.Clear; for ePT := Low(TParamType) to High(TParamType) do cbParamType.Items.Add(C_ParamTypeNames[ePT]); cbDataType.Items.Clear; for eFT := Low(TFieldType) to High(TFieldType) do cbDataType.Items.Add('ft' + FieldTypeNames[eFT]); cbArrayType.Items.Clear; for eAT := Low(TFDParamArrayType) to High(TFDParamArrayType) do cbArrayType.Items.Add(C_FDParamArrayTypeNames[eAT]); cbMacroType.Items.Clear; for eMT := Low(TFDMacroDataType) to High(TFDMacroDataType) do cbMacroType.Items.Add(C_MacroTypeNames[eMT]); acQueryBuilder.Visible := False; acQueryBuilder.Enabled := False; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsQEdit.FormShow(Sender: TObject); begin end; { --------------------------------------------------------------------------- } function TfrmFDGUIxFormsQEdit.ExecuteBase(AQuery: TFDCustomQuery; const ACaption: String): Boolean; var oConn: TFDCustomConnection; begin LoadState; Caption := Format(S_FD_QEditCaption, [ACaption]); // Referenced objects FQuery.OptionsIntf := AQuery.OptionsIntf; FQuery.ConnectionName := AQuery.ConnectionName; FQuery.Connection := AQuery.Connection; FQuery.UpdateObject := TFDQuery(AQuery).UpdateObject; // SQL if (AQuery is TFDTable) and (TFDTable(AQuery).SQL.Count = 0) and (TFDTable(AQuery).TableName <> '') then TFDTable(AQuery).GenerateSQL; FQuery.SQL.SetStrings(AQuery.SQL); mmSQL.Lines.SetStrings(AQuery.SQL); oConn := AQuery.PointedConnection; if oConn <> nil then mmSQL.RDBMSKind := oConn.RDBMSKind; FDefinitionChanged := False; // Parameters FQuery.Params.Assign(TFDQuery(AQuery).Params); LoadParameters(0); // Macroses FQuery.Macros.Assign(TFDQuery(AQuery).Macros); LoadMacros(0); // Load options frmFetchOptions.LoadFrom(TFDQuery(AQuery).FetchOptions); frmUpdateOptions.LoadFrom(TFDQuery(AQuery).UpdateOptions); frmFormatOptions.LoadFrom(TFDQuery(AQuery).FormatOptions); frmResourceOptions.LoadFrom(TFDQuery(AQuery).ResourceOptions); try pcMain.ActivePageIndex := 0; Result := ShowModal = mrOK; finally TFDQuery(AQuery).UpdateObject := FQuery.UpdateObject; end; if Result then begin UpdateQuery; if AQuery is TFDTable then TFDTable(AQuery).TableName := GetTableNameFromSQLEx(FQuery.SQL.Text, idKeepQuotes) else begin AQuery.SQL.SetStrings(FQuery.SQL); TFDQuery(AQuery).Params.Assign(FQuery.Params); TFDQuery(AQuery).Macros.Assign(FQuery.Macros); end; frmFetchOptions.SaveTo(TFDQuery(AQuery).FetchOptions); frmUpdateOptions.SaveTo(TFDQuery(AQuery).UpdateOptions); frmFormatOptions.SaveTo(TFDQuery(AQuery).FormatOptions); frmResourceOptions.SaveTo(TFDQuery(AQuery).ResourceOptions); end; SaveState; end; { --------------------------------------------------------------------------- } class function TfrmFDGUIxFormsQEdit.Execute(AQuery: TFDCustomQuery; const ACaption: String): Boolean; var oFrm: TfrmFDGUIxFormsQEdit; begin oFrm := TfrmFDGUIxFormsQEdit.Create(nil); try Result := oFrm.ExecuteBase(AQuery, ACaption); finally FDFree(oFrm); end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.LoadFormState(AIni: TCustomIniFile); begin inherited LoadFormState(AIni); // If to uncomment, then form will have pnlButtons in the middle and // splitter stops to work. // pnlResult.Height := AIni.ReadInteger(Name, 'Spliter', pnlResult.Height); ptAdvOptions.LoadState(Name, AIni); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.SaveFormState(AIni: TCustomIniFile); begin inherited SaveFormState(AIni); // AIni.WriteInteger(Name, 'Spliter', pnlResult.Height); ptAdvOptions.SaveState(Name, AIni); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.LoadParameters(AIndex: Integer); var i: Integer; begin lbParams.Items.BeginUpdate; try lbParams.Items.Clear; for i := 0 to FQuery.Params.Count - 1 do lbParams.Items.Add(FQuery.Params[i].Name); if AIndex > -1 then begin if AIndex < lbParams.Items.Count then lbParams.ItemIndex := AIndex else lbParams.ItemIndex := lbParams.Items.Count - 1; end else if lbParams.Items.Count > 0 then lbParams.ItemIndex := 0 else lbParams.ItemIndex := -1; lbParamsClick(nil); finally lbParams.Items.EndUpdate; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.LoadParameter(AIndex: Integer); var oParam: TFDParam; begin // Following properties are editable, but in most cases, this is not required // - IsCaseSensitive // - FDDataType // - Precision // - NumericScale if AIndex >= 0 then begin oParam := FQuery.Params[AIndex]; cbParamType.ItemIndex := Integer(oParam.ParamType); cbDataType.ItemIndex := Integer(oParam.DataType); edtDataSize.Text := IntToStr(oParam.Size); edtValue.Text := GetStringValue(oParam.Value); cbArrayType.ItemIndex := Integer(oParam.ArrayType); edtArraySize.Text := IntToStr(oParam.ArraySize); edtPosition.Text := IntToStr(oParam.Position); end else begin cbParamType.ItemIndex := -1; cbDataType.ItemIndex := -1; edtDataSize.Text := ''; edtValue.Text := ''; cbArrayType.ItemIndex := -1; edtArraySize.Text := ''; edtPosition.Text := ''; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.SaveParameter(AIndex: Integer); var oParam: TFDParam; begin if AIndex >= 0 then begin oParam := FQuery.Params[AIndex]; if cbParamType.ItemIndex <> -1 then oParam.ParamType := TParamType(cbParamType.ItemIndex); if cbDataType.ItemIndex <> -1 then oParam.DataType := TFieldType(cbDataType.ItemIndex); if edtDataSize.Text <> '' then oParam.Size := StrToInt(edtDataSize.Text); oParam.Value := GetVariantValue(C_FieldType2VarType[oParam.DataType], edtValue.Text); if cbArrayType.ItemIndex <> -1 then oParam.ArrayType := TFDParamArrayType(cbArrayType.ItemIndex); if edtArraySize.Text <> '' then oParam.ArraySize := StrToInt(edtArraySize.Text); if edtPosition.Text <> '' then oParam.Position := StrToInt(edtPosition.Text); end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.LoadMacros(AIndex: Integer); var i: Integer; begin lbMacros.Items.BeginUpdate; try lbMacros.Items.Clear; for i := 0 to FQuery.Macros.Count - 1 do lbMacros.Items.Add(FQuery.Macros[i].Name); if AIndex > -1 then begin if AIndex < lbMacros.Items.Count then lbMacros.ItemIndex := AIndex else lbMacros.ItemIndex := lbMacros.Items.Count - 1; end else if lbMacros.Items.Count > 0 then lbMacros.ItemIndex := 0 else lbMacros.ItemIndex := -1; lbMacrosClick(nil); finally lbMacros.Items.EndUpdate; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.LoadMacro(AIndex: Integer); var oMacro: TFDMacro; begin if AIndex >= 0 then begin oMacro := FQuery.Macros[AIndex]; cbMacroType.ItemIndex := Integer(oMacro.DataType); edtMacroValue.Text := GetStringValue(oMacro.Value); end else begin cbMacroType.ItemIndex := -1; edtMacroValue.Text := ''; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.SaveMacros(AIndex: Integer); var oMacro: TFDMacro; begin if AIndex >= 0 then begin oMacro := FQuery.Macros[AIndex]; if cbMacroType.ItemIndex <> -1 then oMacro.DataType := TFDMacroDataType(cbMacroType.ItemIndex); oMacro.Value := GetVariantValue(C_MacroDataType2VarType[oMacro.DataType], edtMacroValue.Text); end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.UpdateQuery; begin if FDefinitionChanged then begin FDefinitionChanged := False; FQuery.SQL.SetStrings(mmSQL.Lines); LoadParameters(lbParams.ItemIndex); LoadMacros(lbMacros.ItemIndex); frmFetchOptions.SaveTo(FQuery.FetchOptions); frmUpdateOptions.SaveTo(FQuery.UpdateOptions); frmFormatOptions.SaveTo(FQuery.FormatOptions); frmResourceOptions.SaveTo(FQuery.ResourceOptions); end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.ExecQuery; var oConn: TFDCustomConnection; oConnMeta: IFDPhysConnectionMetadata; begin FQuery.DisableControls; try FQuery.Disconnect; UpdateQuery; SaveParameter(lbParams.ItemIndex); SaveMacros(lbMacros.ItemIndex); oConn := nil; if cbRollback.Checked then begin oConn := FQuery.Command.AcquireConnection; oConn.Open; oConn.ConnectionIntf.CreateMetadata(oConnMeta); if oConnMeta.TxSupported then oConn.StartTransaction; end; try FQuery.Prepare; FQuery.OpenOrExecute; finally FillInfos; if cbRollback.Checked then begin if oConnMeta.TxSupported then oConn.Rollback; FQuery.Command.ReleaseConnection(oConn); end; end; finally FQuery.EnableControls; if not FQuery.Active and (FQuery.PointedConnection <> nil) and (FQuery.PointedConnection.Messages <> nil) then pcResult.ActivePage := tsMessages; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.NextRecordSet; begin FQuery.DisableControls; try UpdateQuery; FQuery.NextRecordSet; finally FillInfos; FQuery.EnableControls; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.FillMessages(AMessages: EFDDBEngineException); var i: Integer; begin mmMessages.Lines.BeginUpdate; try mmMessages.Lines.Clear; if AMessages <> nil then begin for i := 0 to AMessages.ErrorCount - 1 do mmMessages.Lines.Add(AMessages.Errors[i].Message); end; finally mmMessages.Lines.EndUpdate; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.FillStructure(ATable: TFDDatSTable); var i: Integer; sTmp: string; eAttribute: TFDDataAttribute; oColumn: TFDDatSColumn; oItem: TListItem; function FormatDataType(ADataType: TFDDataType; ASize, APrecision, AScale: Integer): String; begin Result := C_FD_DataTypeNames[ADataType]; case ADataType of dtAnsiString, dtWideString, dtByteString: Result := Result + Format('(%d)', [ASize]); dtSByte, dtInt16, dtInt32, dtInt64, dtByte, dtUInt16, dtUInt32, dtUInt64: if APrecision > 0 then Result := Result + Format('(%d)', [APrecision]); dtSingle, dtDouble, dtExtended, dtCurrency, dtBCD, dtFmtBCD: if APrecision = 0 then Result := Result + Format('(*, %d)', [AScale]) else Result := Result + Format('(%d, %d)', [APrecision, AScale]); dtDateTime, dtDateTimeStamp, dtTime: if AScale > 0 then Result := Result + Format('(*, %d msec)', [AScale]); dtTimeIntervalFull, dtTimeIntervalYM, dtTimeIntervalDS: if (APrecision <> 0) or (AScale <> 0) then if APrecision = 0 then Result := Result + Format('(*, %d)', [AScale]) else Result := Result + Format('(%d, %d)', [APrecision, AScale]); end; end; begin lvStructure.Items.BeginUpdate; try lvStructure.Items.Clear; if ATable <> nil then begin for i := 0 to ATable.Columns.Count - 1 do begin oColumn := ATable.Columns.ItemsI[i]; oItem := lvStructure.Items.Add; oItem.Caption := oColumn.Name; oItem.SubItems.Add(FormatDataType(oColumn.DataType, oColumn.Size, oColumn.Precision, oColumn.Scale)); sTmp := ''; for eAttribute := Low(TFDDataAttribute) to High(TFDDataAttribute) do if eAttribute in oColumn.Attributes then sTmp := sTmp + C_FDDataAttributeNames[eAttribute] + '; '; if sTmp <> '' then SetLength(sTmp, Length(sTmp) - 2); oItem.SubItems.Add(sTmp); sTmp := oColumn.OriginTabName; if oColumn.OriginColName <> '' then begin if sTmp <> '' then sTmp := sTmp + '.'; sTmp := sTmp + oColumn.OriginColName; end; oItem.SubItems.Add(sTmp); oItem.SubItems.Add(FormatDataType(oColumn.SourceDataType, oColumn.SourceSize, oColumn.SourcePrecision, oColumn.SourceScale)); oItem.SubItems.Add(oColumn.SourceDataTypeName); end; end; finally lvStructure.Items.EndUpdate; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.FillInfos; begin if FQuery.Table <> nil then FillStructure(FQuery.Table); if (FQuery.PointedConnection <> nil) and (FQuery.PointedConnection.ConnectionIntf <> nil) and (FQuery.PointedConnection.ConnectionIntf.Messages <> nil) then FillMessages(FQuery.Connection.ConnectionIntf.Messages); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.lbParamsClick(Sender: TObject); begin LoadParameter(lbParams.ItemIndex); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.edtParametersExit(Sender: TObject); begin SaveParameter(lbParams.ItemIndex); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.lbMacrosClick(Sender: TObject); begin LoadMacro(lbMacros.ItemIndex); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.edtMacrosExit(Sender: TObject); begin SaveMacros(lbMacros.ItemIndex); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.mmSQLChange(Sender: TObject); begin FDefinitionChanged := True; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.frmOptionsModified(Sender: TObject); begin FDefinitionChanged := True; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.mmSQLKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and ((Key = Ord('A')) or (Key = Ord('a'))) then begin mmSQL.SelectAll; Key := 0; end else if Key = VK_ESCAPE then begin ModalResult := mrCancel; Key := 0; end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.pcMainChanging(Sender: TObject; var AllowChange: Boolean); begin UpdateQuery; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.acExecuteUpdate(Sender: TObject); begin acExecute.Enabled := mmSQL.Lines.Count > 0; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.acExecuteExec(Sender: TObject); begin ExecQuery; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.acNextRSUpdate(Sender: TObject); begin acNextRS.Enabled := FQuery.Active; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.acNextRSExecute(Sender: TObject); begin NextRecordSet; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.acQueryBuilderExecute(Sender: TObject); begin // UpdateQuery; // if ShowQueryBuilder then begin // FQuery.Close; // pcMain.ActivePage := tsSQL; // end; end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.acUpdateSQLEditorUpdate(Sender: TObject); begin acUpdateSQLEditor.Enabled := (FQuery.UpdateObject <> nil) and (FQuery.UpdateObject is TFDUpdateSQL); end; {------------------------------------------------------------------------------} procedure TfrmFDGUIxFormsQEdit.acUpdateSQLEditorExecute(Sender: TObject); begin UpdateQuery; TfrmFDGUIxFormsUSEdit.Execute(TFDUpdateSQL(FQuery.UpdateObject), FQuery.UpdateObject.Name); end; end.
unit rhlWhirlpool; interface uses rhlCore; type { TrhlWhirlpool } TrhlWhirlpool = class(TrhlHash) private const ROUNDS = 10; const REDUCTION_POLYNOMIAL = $11d; const s_SBOX: array[0..255] of Byte = ( $18,$23,$c6,$e8,$87,$b8,$01,$4f,$36,$a6,$d2,$f5,$79,$6f,$91,$52, $60,$bc,$9b,$8e,$a3,$0c,$7b,$35,$1d,$e0,$d7,$c2,$2e,$4b,$fe,$57, $15,$77,$37,$e5,$9f,$f0,$4a,$da,$58,$c9,$29,$0a,$b1,$a0,$6b,$85, $bd,$5d,$10,$f4,$cb,$3e,$05,$67,$e4,$27,$41,$8b,$a7,$7d,$95,$d8, $fb,$ee,$7c,$66,$dd,$17,$47,$9e,$ca,$2d,$bf,$07,$ad,$5a,$83,$33, $63,$02,$aa,$71,$c8,$19,$49,$d9,$f2,$e3,$5b,$88,$9a,$26,$32,$b0, $e9,$0f,$d5,$80,$be,$cd,$34,$48,$ff,$7a,$90,$5f,$20,$68,$1a,$ae, $b4,$54,$93,$22,$64,$f1,$73,$12,$40,$08,$c3,$ec,$db,$a1,$8d,$3d, $97,$00,$cf,$2b,$76,$82,$d6,$1b,$b5,$af,$6a,$50,$45,$f3,$30,$ef, $3f,$55,$a2,$ea,$65,$ba,$2f,$c0,$de,$1c,$fd,$4d,$92,$75,$06,$8a, $b2,$e6,$0e,$1f,$62,$d4,$a8,$96,$f9,$c5,$25,$59,$84,$72,$39,$4c, $5e,$78,$38,$8c,$d1,$a5,$e2,$61,$b3,$21,$9c,$1e,$43,$c7,$fc,$04, $51,$99,$6d,$0d,$fa,$df,$7e,$24,$3b,$ab,$ce,$11,$8f,$4e,$b7,$eb, $3c,$81,$94,$f7,$b9,$13,$2c,$d3,$e7,$6e,$c4,$03,$56,$44,$7f,$a9, $2a,$bb,$c1,$53,$dc,$0b,$9d,$6c,$31,$74,$f6,$46,$ac,$89,$14,$e1, $16,$3a,$69,$09,$70,$b6,$d0,$ed,$cc,$42,$98,$a4,$28,$5c,$f8,$86 ); var s_C0,s_C1,s_C2,s_C3,s_C4,s_C5,s_C6,s_C7: array[0..255] of QWord; var s_rc: array[0..ROUNDS] of QWord; var m_hash: array[0..7] of QWord; function maskWithReductionPolynomial(const input: DWord): DWord; function packIntoULong(b7, b6, b5, b4, b3, b2, b1, b0: QWord): QWord; protected procedure UpdateBlock(const AData); override; public constructor Create; override; procedure Init; override; procedure Final(var ADigest); override; end; implementation { TrhlWhirlpool } function TrhlWhirlpool.maskWithReductionPolynomial(const input: DWord): DWord; begin if (input >= $100) then Result := input xor REDUCTION_POLYNOMIAL else Result := input; end; function TrhlWhirlpool.packIntoULong(b7, b6, b5, b4, b3, b2, b1, b0: QWord ): QWord; begin Result := (b7 shl 56) xor (b6 shl 48) xor (b5 shl 40) xor (b4 shl 32) xor (b3 shl 24) xor (b2 shl 16) xor (b1 shl 8) xor b0; end; procedure TrhlWhirlpool.UpdateBlock(const AData); var data, temp, k, m: array[0..7] of QWord; round, i: Integer; begin ConvertBytesToQWordsSwapOrder(AData, BlockSize, data); //ulong[] k = new ulong[8]; //ulong[] m = new ulong[8]; // //ulong[] temp = new ulong[8]; //ulong[] data = Converters.ConvertBytesToULongsSwapOrder(a_data, a_index, BlockSize); for i := 0 to 7 do begin k[i] := m_hash[i]; temp[i] := data[i] xor k[i]; end; for round := 1 to ROUNDS do begin for i := 0 to 7 do begin m[i] := 0; m[i] := m[i] xor s_C0[byte(k[(i - 0) and 7] shr 56)]; m[i] := m[i] xor s_C1[byte(k[(i - 1) and 7] shr 48)]; m[i] := m[i] xor s_C2[byte(k[(i - 2) and 7] shr 40)]; m[i] := m[i] xor s_C3[byte(k[(i - 3) and 7] shr 32)]; m[i] := m[i] xor s_C4[byte(k[(i - 4) and 7] shr 24)]; m[i] := m[i] xor s_C5[byte(k[(i - 5) and 7] shr 16)]; m[i] := m[i] xor s_C6[byte(k[(i - 6) and 7] shr 8)]; m[i] := m[i] xor s_C7[byte(k[(i - 7) and 7])]; end; Move(m, k, SizeOf(k)); k[0] := k[0] xor s_rc[round]; for i := 0 to 7 do begin m[i] := k[i]; m[i] := m[i] xor s_C0[byte(temp[(i - 0) and 7] shr 56)]; m[i] := m[i] xor s_C1[byte(temp[(i - 1) and 7] shr 48)]; m[i] := m[i] xor s_C2[byte(temp[(i - 2) and 7] shr 40)]; m[i] := m[i] xor s_C3[byte(temp[(i - 3) and 7] shr 32)]; m[i] := m[i] xor s_C4[byte(temp[(i - 4) and 7] shr 24)]; m[i] := m[i] xor s_C5[byte(temp[(i - 5) and 7] shr 16)]; m[i] := m[i] xor s_C6[byte(temp[(i - 6) and 7] shr 8)]; m[i] := m[i] xor s_C7[byte(temp[(i - 7) and 7])]; end; Move(m, temp, SizeOf(temp)); end; for i := 0 to 7 do m_hash[i] := m_hash[i] xor temp[i] xor data[i]; end; constructor TrhlWhirlpool.Create; var v1, v2, v4, v5, v8, v9: DWord; i, r: Integer; begin HashSize := 64; BlockSize := 64; for i := 0 to 255 do begin v1 := s_SBOX[i]; v2 := maskWithReductionPolynomial(v1 shl 1); v4 := maskWithReductionPolynomial(v2 shl 1); v5 := v4 xor v1; v8 := maskWithReductionPolynomial(v4 shl 1); v9 := v8 xor v1; s_C0[i] := packIntoULong(v1, v1, v4, v1, v8, v5, v2, v9); s_C1[i] := packIntoULong(v9, v1, v1, v4, v1, v8, v5, v2); s_C2[i] := packIntoULong(v2, v9, v1, v1, v4, v1, v8, v5); s_C3[i] := packIntoULong(v5, v2, v9, v1, v1, v4, v1, v8); s_C4[i] := packIntoULong(v8, v5, v2, v9, v1, v1, v4, v1); s_C5[i] := packIntoULong(v1, v8, v5, v2, v9, v1, v1, v4); s_C6[i] := packIntoULong(v4, v1, v8, v5, v2, v9, v1, v1); s_C7[i] := packIntoULong(v1, v4, v1, v8, v5, v2, v9, v1); end; s_rc[0] := 0; for r := 1 to ROUNDS do begin i := 8 * (r - 1); s_rc[r] := (s_C0[i + 0] and $ff00000000000000) xor (s_C1[i + 1] and $00ff000000000000) xor (s_C2[i + 2] and $0000ff0000000000) xor (s_C3[i + 3] and $000000ff00000000) xor (s_C4[i + 4] and $00000000ff000000) xor (s_C5[i + 5] and $0000000000ff0000) xor (s_C6[i + 6] and $000000000000ff00) xor (s_C7[i + 7] and $00000000000000ff); end; end; procedure TrhlWhirlpool.Init; begin inherited Init; FillChar(m_hash, SizeOf(m_hash), 0); end; procedure TrhlWhirlpool.Final(var ADigest); var bits: QWord; padIndex: Integer; pad: TBytes; begin bits := QWord(FProcessedBytes) * 8; if FBuffer.Pos > 31 then padIndex := 120 - FBuffer.Pos else padIndex := 56 - FBuffer.Pos; SetLength(pad, padIndex + 8); pad[0] := $80; bits := SwapEndian(bits); Move(bits, pad[padIndex], SizeOf(bits)); Inc(padIndex, 8); UpdateBytes(pad[0], padIndex); ConvertQWordsToBytesSwapOrder(m_hash, Length(m_hash), ADigest); end; end.
// 8-Tem-se um conjunto de dados contendo a altura e o sexo (masculino, // feminino) de 50 pessoas. Fazer um algoritmo que calcule e escreva: // • - a maior e a menor altura do grupo; // • - a média de altura das mulheres; // • - o número de homens; // • - A porcentagem de homens e de mulheres. Program Votacao; const MAX = 50; type Pessoa = array [1..MAX] of record altura : integer; sexo : integer; end; var maior, menor, soma_f, qtd_f, qtd_m, i : integer; media, porc_f, porc_m : real; p : Pessoa; Begin maior := -9999; menor := 9999; soma_f := 0; qtd_f := 0; qtd_m := 0; media := 0; porc_f := 0; porc_m := 0; FOR i := 1 to MAX do begin writeln('Digite a altura da pessoa ', i, ' em cm:'); readln(p[i].altura); writeln('Digite o sexo da pessoa ', i, ' (1 - M / 2 - F):'); readln(p[i].sexo); end; FOR i := 1 to MAX do begin if p[i].altura > maior then maior := p[i].altura; if p[i].altura < menor then menor := p[i].altura; end; writeln('Maior altura: ', maior, ' cm'); writeln('Menor altura: ', menor, ' cm'); FOR i := 1 to MAX do begin if p[i].sexo = 2 then begin soma_f := p[i].altura + soma_f; qtd_f := qtd_f + 1; end else qtd_m := qtd_m + 1; end; media := soma_f / qtd_f; writeln('Media das alturas femininas: ', media:6:2, ' cm'); writeln('Numero de homens: ', qtd_m); porc_f := (qtd_f/MAX)*100; porc_m := (qtd_m/MAX)*100; writeln('Porcentagem feminina: ', porc_f:6:2, '%'); writeln('Porcentagem masculina: ', porc_m:6:2, '%'); End.
unit Androidapi.JNI.SunmiPrinter; interface uses Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes; type JSunmiPrinter = Interface; JSunmiPrinterClass = interface(JObjectClass) ['{D10A3CF9-9D61-446E-BD75-F56B5100625F}'] { class } function init(aContext: JContext): JSunmiPrinter; cdecl; end; [JavaSignature('com/acbr/sunmi_printer/Printer')] JSunmiPrinter = interface(JObject) ['{ECC4767A-37E2-4549-AC7A-018E9A8851FE}'] Procedure PrintTeste; cdecl; Function getServiceVersion: JString; cdecl; Function getPrinterSerialNo: JString; cdecl; Function getPrinterVersion: JString; cdecl; Function getPrinterModal: JString; cdecl; Procedure printerInit; cdecl; Procedure printerSelfChecking; cdecl; Procedure lineWrap(n: Integer); cdecl; Procedure sendRAWData(data: TJavaArray<Byte>); cdecl; Procedure setAlignment(alignment: Integer); cdecl; Procedure setFontName(typeface: JString); cdecl; Procedure setFontSize(fontsize: Single); cdecl; Procedure printText(text: JString); cdecl; Procedure printTextLF(text: JString); cdecl; Procedure printTextWithFont(text: JString; typeface: JString; fontsize: Single); cdecl; Procedure printColumnsText(colsTextArr: Array of JString; colsWidthArr: Array Of Integer; colsAlign: Array Of Integer); cdecl; Procedure printBitmap(bitmap: JBitmap); cdecl; Procedure printBarCode(data: JString; symbology, height, width, textposition: Integer); cdecl; Procedure printQRCode(data: JString; modulesize: Integer; errorlevel: Integer); cdecl; Procedure printOriginalText(text: JString); cdecl; Procedure commitPrinterBuffer; cdecl; Procedure enterPrinterBuffer(clean: Boolean); cdecl; Procedure exitPrinterBuffer(commit: Boolean); cdecl; Procedure cutPaper; cdecl; Procedure openDrawer; cdecl; Function getCutPaperTimes: Integer; cdecl; Function getOpenDrawerTimes: Integer; cdecl; Function getPrinterMode: Integer; cdecl; Function getPrinterBBMDistance: Integer; cdecl; Function updatePrinterState: Integer; cdecl; Function getDrawerStatus: Boolean; cdecl; end; TJSunmiPrinter = class(TJavaGenericImport<JSunmiPrinterClass, JSunmiPrinter>) end; implementation end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit Test_Methods; {$mode objfpc}{$H+} interface uses FpcUnit, TestRegistry; type TTest_Methods = class(TTestCase) private procedure TextRectPaint(Sender: TObject); published procedure TextRect; end; implementation uses Classes, Controls, ExtCtrls, Forms, Graphics; procedure TTest_Methods.TextRect; var W: TForm; pb: TPaintBox; begin W := TForm.CreateNew(Application.MainForm); W.Width := 400; W.Height := 400; pb := TPaintBox.Create(W); pb.Parent := W; pb.SetBounds(100, 100, 200, 200); pb.Anchors := [akTop, akLeft, akRight, akBottom]; pb.OnPaint := @TextRectPaint; W.Show; end; procedure TTest_Methods.TextRectPaint(Sender: TObject); var pb: TPaintBox; Style: TTextStyle; TxtRect: TRect; begin pb := TPaintBox(Sender); TxtRect.Left := pb.Width div 4; TxtRect.Top := pb.Height div 4; TxtRect.Right := TxtRect.Left * 3; TxtRect.Bottom := TxtRect.Top * 3; pb.Canvas.Pen.Style := psSolid; pb.Canvas.Pen.Color := clRed; pb.Canvas.Rectangle(0, 0, pb.Width, pb.Height); pb.Canvas.Pen.Color := clBlue; pb.Canvas.Rectangle(TxtRect); Style.Opaque := True; // warning suppress FillChar(Style, SizeOf(TTextStyle), 0); Style.SingleLine := True; {%region 'Horizontal'} Style.Alignment := taCenter; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlack; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlCenter', Style); Style.Alignment := taLeftJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clRed; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlCenter', Style); Style.Alignment := taRightJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlue; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlCenter', Style); Style.Alignment := taCenter; Style.Layout := tlTop; pb.Canvas.Font.Color := clFuchsia; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taCenter,tlTop', Style); Style.Alignment := taLeftJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clMaroon; pb.Canvas.TextRect(TxtRect, TxtRect.Left, TxtRect.Top, 'taLeft,tlTop', Style); Style.Alignment := taRightJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clTeal; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taRight,tlTop', Style); Style.Alignment := taCenter; Style.Layout := tlBottom; pb.Canvas.Font.Color := clGreen; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlBottom', Style); Style.Alignment := taLeftJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clNavy; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlBottom', Style); Style.Alignment := taRightJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clOlive; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlBottom', Style); {%endregion} {%region 'Bottom to top'} // TODO: сделать процедуру для вывода вертикального текста // или найти готовую. Поведение Canvas.TextRect неожиданное // при повернутом шрифте и отличается от то того что делает // виндовая процедура с аналогичными настройками (проверить) pb.Canvas.Font.Orientation := 900; Style.Alignment := taCenter; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlack; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlCenter', Style); Style.Alignment := taLeftJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clRed; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlCenter', Style); Style.Alignment := taRightJustify; Style.Layout := tlCenter; pb.Canvas.Font.Color := clBlue; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlCenter', Style); Style.Alignment := taCenter; Style.Layout := tlTop; pb.Canvas.Font.Color := clFuchsia; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taCenter,tlTop', Style); Style.Alignment := taLeftJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clMaroon; pb.Canvas.TextRect(TxtRect, TxtRect.Left, TxtRect.Top, 'taLeft,tlTop', Style); Style.Alignment := taRightJustify; Style.Layout := tlTop; pb.Canvas.Font.Color := clTeal; pb.Canvas.TextRect(TxtRect, 0, TxtRect.Top, 'taRight,tlTop', Style); Style.Alignment := taCenter; Style.Layout := tlBottom; pb.Canvas.Font.Color := clGreen; pb.Canvas.TextRect(TxtRect, 0, 0, 'taCenter,tlBottom', Style); Style.Alignment := taLeftJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clNavy; pb.Canvas.TextRect(TxtRect, TxtRect.Left, 0, 'taLeft,tlBottom', Style); Style.Alignment := taRightJustify; Style.Layout := tlBottom; pb.Canvas.Font.Color := clOlive; pb.Canvas.TextRect(TxtRect, 0, 0, 'taRight,tlBottom', Style); {%endregion} end; initialization RegisterTest(TTest_Methods); end.
unit fOptionsTeams; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ORCtrls, OrFn, Menus, fBase508Form, VA508AccessibilityManager; type TfrmOptionsTeams = class(TfrmBase508Form) pnlBottom: TPanel; btnClose: TButton; lstPatients: TORListBox; lstTeams: TORListBox; lblTeams: TLabel; lblPatients: TLabel; lstUsers: TORListBox; lblTeamMembers: TLabel; btnRemove: TButton; chkPersonal: TCheckBox; chkRestrict: TCheckBox; bvlBottom: TBevel; lblInfo: TMemo; lblSubscribe: TLabel; cboSubscribe: TORComboBox; mnuPopPatient: TPopupMenu; mnuPatientID: TMenuItem; chkPcmm: TCheckBox; procedure FormCreate(Sender: TObject); procedure chkPersonalClick(Sender: TObject); procedure chkPcmmClick(Sender: TObject); procedure lstTeamsClick(Sender: TObject); procedure chkRestrictClick(Sender: TObject); procedure cboSubscribeClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure mnuPatientIDClick(Sender: TObject); procedure lstPatientsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure cboSubscribeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cboSubscribeMouseClick(Sender: TObject); private FKeyBoarding: boolean; { Private declarations } procedure FillTeams; procedure FillATeams; procedure FillList(alist: TORListBox; members: TStrings); procedure AddPcmmTeams(alist: TStrings; pcmm: TStringList); procedure MergeList(alist: TORListBox; members: TStrings); function ItemNotAMember(alist: TStrings; listnum: string): boolean; function MemberNotOnList(alist: TStrings; listnum: string): boolean; public { Public declarations } end; var frmOptionsTeams: TfrmOptionsTeams; procedure DialogOptionsTeams(topvalue, leftvalue, fontsize: integer; var actiontype: Integer); implementation uses rOptions, uOptions, rCore, fOptions; {$R *.DFM} procedure DialogOptionsTeams(topvalue, leftvalue, fontsize: integer; var actiontype: Integer); // create the form and make it modal, return an action var frmOptionsTeams: TfrmOptionsTeams; begin frmOptionsTeams := TfrmOptionsTeams.Create(Application); actiontype := 0; try with frmOptionsTeams do begin if (topvalue < 0) or (leftvalue < 0) then Position := poScreenCenter else begin Position := poDesigned; Top := topvalue; Left := leftvalue; end; ResizeAnchoredFormToFont(frmOptionsTeams); ShowModal; end; finally frmOptionsTeams.Release; end; end; procedure TfrmOptionsTeams.FormCreate(Sender: TObject); begin rpcGetTeams(lstTeams.Items); lstTeams.ItemIndex := -1; FillATeams; end; procedure TfrmOptionsTeams.FillATeams; var i: integer; alist: TStringList; begin cboSubscribe.Items.Clear; alist := TStringList.Create; rpcGetAteams(alist); for i := 0 to alist.Count - 1 do if MemberNotOnList(lstTeams.Items, Piece(alist[i], '^', 1)) then cboSubscribe.Items.Add(alist[i]); cboSubscribe.Enabled := cboSubscribe.Items.Count > 0; lblSubscribe.Enabled := cboSubscribe.Items.Count > 0; alist.Free; end; procedure TfrmOptionsTeams.FillList(alist: TORListBox; members: TStrings); var i: integer; begin for i := 0 to members.Count - 1 do if MemberNotOnList(alist.Items, Piece(members[i], '^', 1)) then alist.Items.Add(members[i]); end; procedure TfrmOptionsTeams.FillTeams; { TDP - Added 5/23/2014 to work with PCMM team retrieval basic code taken from the chkPersonalClick, then modified to allow pcmm teams to be added as well } var lstPTeams: TStringList; begin lstTeams.Items.Clear; lstPTeams := TStringList.Create; if chkPersonal.Checked then rpcGetAllTeams(lstTeams.Items) else rpcGetTeams(lstTeams.Items); if chkPcmm.Checked then begin rpcGetPcmmTeams(lstPTeams); if Piece(lstPTeams[0], '^', 1) <> '' then AddPcmmTeams(lstTeams.Items, lstPTeams) end; lstTeams.ItemIndex := -1; lstTeamsClick(self); lstPTeams.Free end; procedure TfrmOptionsTeams.AddPcmmTeams(alist:TStrings; pcmm: TStringList); // TDP - Added 5/23/2014 to work with PCMM team retrieval // Adds the pcmm list to the passed in alist var i: integer; begin for i := 0 to pcmm.Count - 1 do alist.Add(pcmm[i]); end; procedure TfrmOptionsTeams.MergeList(alist: TORListBox; members: TStrings); var i: integer; begin for i := alist.Items.Count - 1 downto 0 do if ItemNotAMember(members, Piece(alist.Items[i], '^', 1)) then alist.Items.Delete(i); end; function TfrmOptionsTeams.ItemNotAMember(alist: TStrings; listnum: string): boolean; var i: integer; begin result := true; for i := 0 to alist.Count - 1 do if listnum = Piece(alist[i], '^', 1) then begin result := false; break; end; end; function TfrmOptionsTeams.MemberNotOnList(alist: TStrings; listnum: string): boolean; var i: integer; begin result := true; with alist do for i := 0 to Count - 1 do if listnum = Piece(alist[i], '^', 1) then begin result := false; break; end; end; procedure TfrmOptionsTeams.chkPersonalClick(Sender: TObject); // TDP - Modified 5/23/2014 to work with PCMM team retrieval begin FillTeams; {lstTeams.Items.Clear; if chkPersonal.Checked then rpcGetAllTeams(lstTeams.Items) else rpcGetTeams(lstTeams.Items); lstTeams.ItemIndex := -1; lstTeamsClick(self); } end; procedure TfrmOptionsTeams.chkPcmmClick(Sender: TObject); // TDP - Added 5/23/2014 begin FillTeams; end; procedure TfrmOptionsTeams.lstTeamsClick(Sender: TObject); var i, teamid, cnt: integer; astrings: TStringList; teamtype: string; begin lstPatients.Items.Clear; lstUsers.Items.Clear; chkRestrict.Enabled := lstTeams.SelCount > 1; astrings := TStringList.Create; cnt := 0; with lstTeams do begin for i := 0 to Items.Count - 1 do if Selected[i] then begin inc(cnt); teamid := strtointdef(Piece(Items[i], '^', 1), 0); teamtype := Piece(Items[i], '^', 3); if (cnt > 1) and chkRestrict.Checked then begin if teamtype <> 'E' then // TDP - 5/23/2014 If not PCMM team begin ListPtByTeam(astrings, teamid); MergeList(lstPatients, astrings); rpcListUsersByTeam(astrings, teamid); MergeList(lstPatients, astrings); end else begin // TDP - 5/23/2014 PCMM team ListPtByPcmmTeam(astrings, teamid); MergeList(lstUsers, astrings); rpcListUsersByPcmmTeam(astrings, teamid); MergeList(lstUsers, astrings); end; end else begin if teamtype <> 'E' then // TDP - 5/23/2014 If not PCMM team begin ListPtByTeam(astrings, teamid); if astrings.Count = 1 then // don't fill the '^No patients found.' msg begin if Piece(astrings[0], '^', 1) <> '' then FillList(lstPatients, astrings); end else FillList(lstPatients, astrings); rpcListUsersByTeam(astrings, teamid); FillList(lstUsers, astrings) end else begin // TDP - 5/23/2014 PCMM team ListPtByPcmmTeam(astrings, teamid); if astrings.Count = 1 then // don't fill the '^No patients found.' msg begin if Piece(astrings[0], '^', 1) <> '' then FillList(lstPatients, astrings) end else FillList(lstPatients, astrings); rpcListUsersByPcmmTeam(astrings, teamid); FillList(lstUsers, astrings); end; end; end; // TDP - 5/23/2014 Added code to prevent Remove Button enabling // when PCMM team. btnRemove.Enabled := (SelCount = 1) and (teamtype <> 'P') and (teamtype <> 'E') and (Piece(Items[ItemIndex], '^', 7) = 'Y'); if SelCount > 0 then begin if lstPatients.Items.Count = 0 then lstPatients.Items.Add('^No patients found.'); if lstUsers.Items.Count = 0 then lstUsers.Items.Add('^No team members found.'); end; end; astrings.Free; end; procedure TfrmOptionsTeams.chkRestrictClick(Sender: TObject); begin lstTeamsClick(self); end; procedure TfrmOptionsTeams.cboSubscribeClick(Sender: TObject); begin FKeyBoarding := False end; procedure TfrmOptionsTeams.btnRemoveClick(Sender: TObject); begin with lstTeams do if InfoBox('Do you want to remove yourself from ' + Piece(Items[ItemIndex], '^', 2) + '?', 'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then begin rpcRemoveList(ItemIEN); Items.Delete(ItemIndex); lstTeamsClick(self); FillATeams; end; end; procedure TfrmOptionsTeams.mnuPatientIDClick(Sender: TObject); begin DisplayPtInfo(lstPatients.ItemID); end; procedure TfrmOptionsTeams.lstPatientsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mnuPopPatient.AutoPopup := (lstPatients.Items.Count > 0) and (lstPatients.ItemIndex > -1) and (Button = mbRight); end; procedure TfrmOptionsTeams.cboSubscribeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: if (cboSubscribe.ItemIndex > -1) then begin FKeyBoarding := False; cboSubscribeMouseClick(self); // Provide onmouseclick behavior. end; else FKeyBoarding := True; // Suppress onmouseclick behavior. end; end; procedure TfrmOptionsTeams.cboSubscribeMouseClick(Sender: TObject); begin if FKeyBoarding then FKeyBoarding := False else begin with cboSubscribe do if ItemIndex < 0 then exit else if InfoBox('Do you want to join ' + Piece(Items[ItemIndex], '^', 2) + '?', 'Confirmation', MB_YESNO or MB_ICONQUESTION) = IDYES then begin rpcAddList(ItemIEN); lstTeams.Items.Add(Items[ItemIndex]); Items.Delete(ItemIndex); ItemIndex := -1; Text := ''; Enabled := Items.Count > 0; lblSubscribe.Enabled := Items.Count > 0; end else begin ItemIndex := -1; Text := ''; end; end; end; end.
unit DRTable; interface uses Windows, SysUtils, Classes, BDE, DB, DBTables; type { TDRList } TDRList = class(TBdeDataSet) protected function CreateHandle: HDBICur; override; end; { TDRDataSet } TDRDataSet = class(TBdeDataSet) private FDBIDR: HDBIDR; public property DRHandle: HDBIDR read FDBIDR write FDBIDR; end; { TDRObjectDescList } TDRObjectDescList = class(TDRDataSet) protected function CreateHandle: HDBICur; override; end; { TDRObjectItems } TDRObjectItems = class(TDRDataset) protected FObjectName: string; end; { TDRRelationshipDescList } TDRRelationshipDescList = class(TDRObjectItems) protected function CreateHandle: HDBICur; override; published property ObjectTypeName: string read FObjectName write FObjectName; end; { TDRAttrDescList } TDRAttrDescList = class(TDRObjectItems) protected function CreateHandle: HDBICur; override; published property TypeName: string read FObjectName write FObjectName; end; { TDRInstanceItems } TDRInstanceItems = class (TDRObjectItems) private FCond: string; published property Condition: string read FCond write FCond; end; { TDRObjectList } TDRObjectList = class(TDRInstanceItems) private FRelName: string; FSource: DRObject; protected function CreateHandle: HDBICur; override; public procedure NavigateFrom(const ASource: DRObject; const ARelationship: string); published property ObjectTypeName: string read FObjectName write FObjectName; end; { TDRRelationshipList } TDRRelationshipList = class(TDRInstanceItems) private FSource, FTarget: DRObject; protected function CreateHandle: HDBICur; override; public procedure NavigateFromTo(const ASource, ATarget: DRObject); published property RelationshipTypeName: string read FObjectName write FObjectName; end; { TQueryDescription } TQueryDescription = class(TBdeDataset) private FQuery: TQuery; FPrepared: Boolean; protected function CreateHandle: HDBICur; override; procedure DestroyHandle; override; procedure OpenCursor(InfoQuery: Boolean); override; public property Query: TQuery read FQuery write FQuery; end; const NullDRObject: DRObject = (ulObjId: 0; iVersion: 0); { **************************************************************************** } implementation { TDRList } function TDRList.CreateHandle: HDBICur; begin Check(DbiOpenRepositoryList(Result)); end; { TDRObjectDescList } function TDRObjectDescList.CreateHandle: HDBICur; begin Check(DbiDROpenObjectTypeList(DRHandle, Result)); end; { TDRRelationshipDescList } function TDRRelationshipDescList.CreateHandle: HDBICur; begin Check(DbiDROpenRelTypeList(DRHandle, PChar(ObjectTypeName), Result)); end; { TDRAttrDescList } function TDRAttrDescList.CreateHandle: HDBICur; begin Check(DbiDROpenAttrTypeList(DRHandle, PChar(TypeName), Result)); end; { TDRObjectList } function TDRObjectList.CreateHandle: HDBICur; begin Check(DbiDROpenObjSet(DRHandle, PChar(ObjectTypeName), @FSource, Pointer(FRelName), Pointer(Condition), Result)); end; procedure TDRObjectList.NavigateFrom(const ASource: DRObject; const ARelationship: string); begin FSource := ASource; FRelName := ARelationship; end; { TDRRelationshipList } function TDRRelationshipList.CreateHandle: HDBICur; var PS, PT: pDRObject; begin if FSource.ulObjId = 0 then PS := nil else PS := @FSource; if FTarget.ulObjId = 0 then PT := nil else PT := @FTarget; Check(DbiDROpenRelSet(DRHandle, PChar(RelationshipTypeName), PS, PT, Pointer(Condition), Result)); end; procedure TDRRelationshipList.NavigateFromTo(const ASource, ATarget: DRObject); begin FSource := ASource; FTarget := ATarget; end; { TQueryDescription } function TQueryDescription.CreateHandle: HDBICur; begin Result := nil; if Assigned(Query) then begin if Query.StmtHandle = nil then begin Query.Prepare; FPrepared := True; end; Check(DBIQGetBaseDescs(Query.StmtHandle, Result)); end; end; procedure TQueryDescription.DestroyHandle; begin inherited DestroyHandle; if FPrepared then Query.UnPrepare; end; procedure TQueryDescription.OpenCursor(InfoQuery: Boolean); begin inherited OpenCursor(InfoQuery); if Assigned(Query) then SetLocale(Query.Locale); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC InterBase driver } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$IF DEFINED(IOS) OR DEFINED(ANDROID)} {$HPPEMIT LINKUNIT} {$ELSE} {$IFDEF WIN32} {$HPPEMIT '#pragma link "FireDAC.Phys.IB.obj"'} {$ELSE} {$HPPEMIT '#pragma link "FireDAC.Phys.IB.o"'} {$ENDIF} {$ENDIF} unit FireDAC.Phys.IB; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.DatS, FireDAC.Phys, FireDAC.Phys.IBWrapper, FireDAC.Phys.IBBase; type TFDPhysIBDriverLink = class; TFDIBSDump = class; [ComponentPlatformsAttribute(pidAllPlatforms)] TFDPhysIBDriverLink = class(TFDPhysIBBaseDriverLink) private FLite: Boolean; protected function GetBaseDriverID: String; override; function IsConfigured: Boolean; override; procedure ApplyTo(const AParams: IFDStanDefinition); override; published property Lite: Boolean read FLite write FLite default False; end; [ComponentPlatformsAttribute(pidAllPlatforms)] TFDIBSDump = class (TFDIBService) private FDatabase: String; FBackupFiles: TStrings; FOverwrite: Boolean; FOptions: TIBSDumpOptions; procedure SetBackupFiles(const AValue: TStrings); protected function CreateService(AEnv: TIBEnv): TIBService; override; procedure SetupService(AService: TIBService); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Dump; published property Database: String read FDatabase write FDatabase; property BackupFiles: TStrings read FBackupFiles write SetBackupFiles; property Overwrite: Boolean read FOverwrite write FOverwrite default False; property Options: TIBSDumpOptions read FOptions write FOptions default []; end; {-------------------------------------------------------------------------------} implementation uses System.Variants, System.SysUtils, Data.DB, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.Stan.Option, FireDAC.Stan.Util, FireDAC.Stan.Consts, FireDAC.Stan.ResStrs, FireDAC.Phys.Intf, FireDAC.Phys.IBMeta, FireDAC.Phys.SQLGenerator, FireDAC.Phys.IBCli, FireDAC.Phys.IBDef, FireDAC.Phys.IBLiteDef; type TFDPhysIBDriver = class; TFDPhysIBLiteDriver = class; TFDPhysIBConnection = class; TFDPhysIBCommand = class; TFDPhysIBDriver = class(TFDPhysIBDriverBase) protected procedure InternalLoad; override; function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override; class function GetBaseDriverID: String; override; class function GetBaseDriverDesc: String; override; class function GetRDBMSKind: TFDRDBMSKind; override; class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override; function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override; function GetLite: Boolean; virtual; end; TFDPhysIBLiteDriver = class(TFDPhysIBDriver) protected class function GetBaseDriverID: String; override; class function GetBaseDriverDesc: String; override; class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override; function GetLite: Boolean; override; end; TFDPhysIBConnection = class(TFDPhysIBConnectionBase) protected function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override; function InternalCreateCommand: TFDPhysCommand; override; procedure BuildIBConnectParams(AParams: TStrings; const AConnectionDef: IFDStanConnectionDef); override; procedure InternalAnalyzeSession(AMessages: TStrings); override; end; TFDPhysIBEventAlerter = class(TFDPhysIBEventAlerterBase) private procedure DoRefreshHandler(const ASub: IFDPhysChangeHandler); protected procedure InternalRefresh(const ASubscription: IFDPhysChangeHandler); override; end; TFDPhysIBCommand = class(TFDPhysIBCommandBase) private procedure DoExecuteIB2007Batch(ATimes, AOffset: Integer; var ACount: TFDCounter); protected procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override; procedure ProcessMetaColumn(ATable: TFDDatSTable; AFmtOpts: TFDFormatOptions; AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDIBColInfoRec; ARowIndex: Integer); override; end; {-------------------------------------------------------------------------------} { TFDPhysIBDriverLink } {-------------------------------------------------------------------------------} function TFDPhysIBDriverLink.GetBaseDriverID: String; begin Result := S_FD_IBId; end; {-------------------------------------------------------------------------------} procedure TFDPhysIBDriverLink.ApplyTo(const AParams: IFDStanDefinition); begin inherited ApplyTo(AParams); if Lite then AParams.AsYesNo[S_FD_ConnParam_IB_Lite] := Lite; end; {-------------------------------------------------------------------------------} function TFDPhysIBDriverLink.IsConfigured: Boolean; begin Result := inherited IsConfigured or Lite; end; {-------------------------------------------------------------------------------} { TFDIBSDump } {-------------------------------------------------------------------------------} constructor TFDIBSDump.Create(AOwner: TComponent); begin inherited Create(AOwner); FBackupFiles := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor TFDIBSDump.Destroy; begin FDFreeAndNil(FBackupFiles); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDIBSDump.SetBackupFiles(const AValue: TStrings); begin FBackupFiles.SetStrings(AValue); end; {-------------------------------------------------------------------------------} function TFDIBSDump.CreateService(AEnv: TIBEnv): TIBService; begin Result := TIBSDump.Create(AEnv, Self); end; {-------------------------------------------------------------------------------} procedure TFDIBSDump.SetupService(AService: TIBService); begin inherited SetupService(AService); TIBSDump(AService).DatabaseName := FDExpandStr(Database); TIBSDump(AService).BackupFiles := BackupFiles; FDExpandStrs(TIBSDump(AService).BackupFiles); TIBSDump(AService).Overwrite := Overwrite; TIBSDump(AService).Options := Options; end; {-------------------------------------------------------------------------------} procedure TFDIBSDump.Dump; begin Execute; end; {-------------------------------------------------------------------------------} { TFDPhysIBDriver } {-------------------------------------------------------------------------------} procedure TFDPhysIBDriver.InternalLoad; var sHome, sLib: String; begin sHome := ''; sLib := ''; GetVendorParams(sHome, sLib); FLib.LoadIB(sHome, sLib, GetLite(), GetThreadSafe()); end; {-------------------------------------------------------------------------------} function TFDPhysIBDriver.InternalCreateConnection( AConnHost: TFDPhysConnectionHost): TFDPhysConnection; begin Result := TFDPhysIBConnection.Create(Self, AConnHost); end; {-------------------------------------------------------------------------------} class function TFDPhysIBDriver.GetBaseDriverID: String; begin Result := S_FD_IBId; end; {-------------------------------------------------------------------------------} class function TFDPhysIBDriver.GetBaseDriverDesc: String; begin Result := 'InterBase'; end; {-------------------------------------------------------------------------------} class function TFDPhysIBDriver.GetRDBMSKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.Interbase; end; {-------------------------------------------------------------------------------} class function TFDPhysIBDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass; begin Result := TFDPhysIBConnectionDefParams; end; {-------------------------------------------------------------------------------} function TFDPhysIBDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; var oView: TFDDatSView; i: Integer; sName: String; begin Result := inherited GetConnParams(AKeys, AParams); oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + ''''); if oView.Rows.Count = 1 then begin oView.Rows[0].BeginEdit; oView.Rows[0].SetValues('Type', '@F:InterBase Database|*.gdb;*.ib'); oView.Rows[0].EndEdit; end; if GetLite() then for i := Result.Rows.Count - 1 downto 0 do begin sName := Result.Rows[i].GetData('Name'); if (CompareText(sName, S_FD_ConnParam_Common_Pooled) = 0) or (CompareText(sName, S_FD_ConnParam_Common_OSAuthent) = 0) or (CompareText(sName, S_FD_ConnParam_IB_Protocol) = 0) or (CompareText(sName, S_FD_ConnParam_Common_Server) = 0) or (CompareText(sName, S_FD_ConnParam_Common_Port) = 0) or (CompareText(sName, S_FD_ConnParam_IB_SQLDialect) = 0) or (CompareText(sName, S_FD_ConnParam_IB_RoleName) = 0) then Result.Rows[i].Delete(); end else begin Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_InstanceName, '@S', '', S_FD_ConnParam_IB_InstanceName, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_IB_SEPassword, '@P', '', S_FD_ConnParam_IB_SEPassword, -1]); end; end; {-------------------------------------------------------------------------------} function TFDPhysIBDriver.GetLite: Boolean; begin Result := (Params <> nil) and Params.AsYesNo[S_FD_ConnParam_IB_Lite]; end; {-------------------------------------------------------------------------------} { TFDPhysIBLiteDriver } {-------------------------------------------------------------------------------} class function TFDPhysIBLiteDriver.GetBaseDriverID: String; begin Result := S_FD_IBLiteId; end; {-------------------------------------------------------------------------------} class function TFDPhysIBLiteDriver.GetBaseDriverDesc: String; begin Result := 'InterBase Lite'; end; {-------------------------------------------------------------------------------} class function TFDPhysIBLiteDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass; begin Result := TFDPhysIBLiteConnectionDefParams; end; {-------------------------------------------------------------------------------} function TFDPhysIBLiteDriver.GetLite: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} { TFDPhysIBConnection } {-------------------------------------------------------------------------------} function TFDPhysIBConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; begin if CompareText(AEventKind, S_FD_EventKind_IB_Events) = 0 then Result := TFDPhysIBEventAlerter.Create(Self, AEventKind) else Result := nil; end; {-------------------------------------------------------------------------------} function TFDPhysIBConnection.InternalCreateCommand: TFDPhysCommand; begin Result := TFDPhysIBCommand.Create(Self); end; {-------------------------------------------------------------------------------} procedure TFDPhysIBConnection.BuildIBConnectParams(AParams: TStrings; const AConnectionDef: IFDStanConnectionDef); var oParams: TFDPhysIBConnectionDefParams; begin inherited BuildIBConnectParams(AParams, AConnectionDef); if ConnectionDef.Params is TFDPhysIBConnectionDefParams then begin oParams := ConnectionDef.Params as TFDPhysIBConnectionDefParams; if ConnectionDef.HasValue(S_FD_ConnParam_IB_InstanceName) then AParams.Add('instance_name=' + oParams.InstanceName); if ConnectionDef.HasValue(S_FD_ConnParam_IB_SEPassword) then AParams.Add('sys_encrypt_password=' + oParams.SEPassword); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysIBConnection.InternalAnalyzeSession(AMessages: TStrings); begin inherited InternalAnalyzeSession(AMessages); // 3. Use IB driver to connect to InterBase server with gds32.dll if ServerBrand <> ibInterbase then AMessages.Add(S_FD_IBWarnNotIBSrv); if IBEnv.Lib.Brand <> ibInterbase then AMessages.Add(S_FD_IBWarnNotIBClnt); end; {-------------------------------------------------------------------------------} { TFDPhysIBEventAlerter } {-------------------------------------------------------------------------------} procedure TFDPhysIBEventAlerter.DoRefreshHandler(const ASub: IFDPhysChangeHandler); var oSrcMan: TFDDatSManager; oSrcTab: TFDDatSTable; i: Integer; begin if ASub.MergeManager <> nil then begin oSrcMan := TFDDatSManager.Create; oSrcTab := nil; end else begin oSrcMan := nil; oSrcTab := TFDDatSTable.Create; end; try if ASub.TrackCommand.State = csOpen then begin if ASub.TrackCommand.Options.FetchOptions.AutoFetchAll = afAll then if ASub.MergeManager <> nil then ASub.TrackCommand.Fetch(ASub.MergeManager, mmRely) else ASub.TrackCommand.Fetch(ASub.MergeTable, True, True); ASub.TrackCommand.CloseAll; end; ASub.TrackCommand.Prepare; ASub.TrackCommand.Open; if oSrcMan <> nil then begin oSrcMan.Assign(ASub.MergeManager); ASub.TrackCommand.Fetch(oSrcMan, mmRely); ASub.MergeManager.Merge(oSrcMan, GetOptions.MergeData, mmNone, []); for i := 0 to oSrcMan.Tables.Count - 1 do if oSrcMan.Tables[i].Rows.Count > 0 then begin ASub.ResyncContent; Break; end; end else begin oSrcTab.Assign(ASub.MergeTable); ASub.TrackCommand.Fetch(oSrcTab, True, True); ASub.MergeTable.Merge(oSrcTab, GetOptions.MergeData, mmNone, []); if oSrcTab.Rows.Count > 0 then ASub.ResyncContent; end; finally FDFree(oSrcMan); FDFree(oSrcTab); ASub.ContentModified := False; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysIBEventAlerter.InternalRefresh(const ASubscription: IFDPhysChangeHandler); var oConnMeta: IFDPhysConnectionMetadata; rName: TFDPhysParsedName; sSub, sDev: String; oHnlr: IFDPhysChangeHandler; oTx: IFDPhysTransaction; lStartTX: Boolean; ePrevIsol: TFDTxIsolation; oCmd: IFDPhysCommand; i: Integer; begin GetConnection.CreateMetadata(oConnMeta); if (GetSubscriptionName = '') or not (((oConnMeta as IFDPhysIBConnectionMetadata).Brand = ibInterbase) and (oConnMeta.ServerVersion >= ivIB120000) and (oConnMeta.ClientVersion >= ivIB120000)) then begin inherited InternalRefresh(ASubscription); Exit; end; sDev := ''; sSub := GetSubscriptionName; i := Pos(';', sSub); if i <> 0 then begin sDev := Copy(sSub, i + 1, Length(sSub)); sSub := Copy(sSub, 1, i - 1); if sDev <> '' then sDev := ' AT ' + QuotedStr(sDev); end; rName.FObject := sSub; sSub := oConnMeta.EncodeObjName(rName, nil, [eoNormalize]); if ASubscription <> nil then oHnlr := ASubscription else oHnlr := FChangeHandlers[0] as IFDPhysChangeHandler; oTx := oHnlr.TrackCommand.Transaction; if oTx = nil then oTx := GetConnection.Transaction; lStartTX := not oTx.Active; ePrevIsol := oTx.Options.Isolation; if lStartTX then begin oTx.Options.Isolation := xiSnapshot; oTx.StartTransaction; end; try GetConnection.CreateCommand(oCmd); SetupCommand(oCmd); oCmd.Prepare('SET SUBSCRIPTION ' + sSub + sDev + ' ACTIVE'); oCmd.Execute(); try if ASubscription <> nil then begin if IsRunning and ASubscription.ContentModified then DoRefreshHandler(ASubscription); end else for i := FChangeHandlers.Count - 1 to 0 do begin if not IsRunning then Break; oHnlr := FChangeHandlers[i] as IFDPhysChangeHandler; if oHnlr.ContentModified then DoRefreshHandler(oHnlr); end; finally oCmd.Prepare('SET SUBSCRIPTION ' + sSub + sDev + ' INACTIVE'); oCmd.Execute(); end; if lStartTX then begin oTx.Commit; oTx.Options.Isolation := ePrevIsol; end; except if lStartTX then begin oTx.Rollback; oTx.Options.Isolation := ePrevIsol; end; raise; end; end; {-------------------------------------------------------------------------------} { TFDPhysIBCommand } {-------------------------------------------------------------------------------} procedure TFDPhysIBCommand.DoExecuteIB2007Batch(ATimes, AOffset: Integer; var ACount: TFDCounter); var iBatchSize, iRows: LongWord; iCurTimes, iCurOffset, i: Integer; oResOpts: TFDResourceOptions; begin oResOpts := FOptions.ResourceOptions; // total size of XSQLVAR, which will be send to server in single packet iBatchSize := FStmt.MaximumBatchSize; if iBatchSize > LongWord(oResOpts.ArrayDMLSize) then iBatchSize := LongWord(oResOpts.ArrayDMLSize); // If block will have only single command or there are OUT params, then go // by standard route - execute command once for each param array item. if (iBatchSize <= 1) or (FStmt.OutVars.VarCount > 0) then begin DoExecute(ATimes, AOffset, ACount, False); Exit; end; iCurOffset := AOffset; iCurTimes := LongWord(AOffset) + iBatchSize; while iCurOffset < ATimes do begin if iCurTimes > ATimes then iCurTimes := ATimes; FStmt.InVars.RowCount := Word(iCurTimes - iCurOffset); SetParamValues(iCurTimes, iCurOffset); CheckArrayDMLWithIntStr(FHasIntStreams, iCurTimes, iCurOffset); try try if FStmt.InVars.RowCount = 1 then FStmt.Execute(False) else FStmt.ExecuteBatch; finally if FStmt <> nil then if FStmt.InVars.RowCount = 1 then Inc(ACount, FStmt.RowsAffected) else for i := 0 to FStmt.InVars.RowCount - 1 do begin iRows := FStmt.InVars.FRowsAffected[i]; if iRows = $FFFFFFFF then Break; if iRows > 0 then Inc(ACount); end; end; except on E: EIBNativeException do begin E.Errors[0].RowIndex := iCurOffset + ACount; raise; end; end; if FStmt.OutVars.VarCount > 0 then GetParamValues(iCurTimes, iCurOffset); FStmt.Close; Inc(iCurOffset, iBatchSize); Inc(iCurTimes, iBatchSize); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysIBCommand.InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); begin CheckSPPrepared(skStoredProcNoCrs); CheckParamInfos; ACount := 0; if (ATimes - AOffset > 1) and (FStmt.Lib.Brand = ibInterbase) and (FStmt.Lib.Version >= ivIB110000) and (GetCommandKind in [skDelete, skInsert, skUpdate, skMerge]) then DoExecuteIB2007Batch(ATimes, AOffset, ACount) else DoExecute(ATimes, AOffset, ACount, False); end; {-------------------------------------------------------------------------------} procedure TFDPhysIBCommand.ProcessMetaColumn(ATable: TFDDatSTable; AFmtOpts: TFDFormatOptions; AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDIBColInfoRec; ARowIndex: Integer); var iVal: Integer; iSize: Longword; eIndexType: TFDPhysIndexKind; eTableType: TFDPhysTableKind; eScope: TFDPhysObjectScope; pBlob: PISC_QUAD; eDataType: TFDDataType; eRule: TFDPhysCascadeRuleKind; s: String; lUseBase: Boolean; procedure SetScope; begin if not ApInfo^.FVar.GetData(iVal, iSize) or (iVal = 0) then eScope := osMy else eScope := osSystem; ARow.SetData(AColIndex, Integer(eScope)); end; procedure SetDataType; begin if not ApInfo^.FVar.GetData(iVal, iSize) or (iVal = 0) then eDataType := dtUnknown else case iVal of 7: eDataType := dtInt16; 8: eDataType := dtInt32; 9: eDataType := dtInt64; 10: eDataType := dtSingle; 11: eDataType := dtDouble; 12: eDataType := dtDate; 13: eDataType := dtTime; 14: eDataType := dtAnsiString; 16: eDataType := dtInt64; 17: eDataType := dtBoolean; 27: eDataType := dtDouble; 35: eDataType := dtDateTimeStamp; 37: eDataType := dtAnsiString; 40: eDataType := dtAnsiString; 45: eDataType := dtBlob; 261: eDataType := dtMemo; else eDataType := dtUnknown; end; ARow.SetData(AColIndex, Integer(eDataType)); end; begin lUseBase := True; if (IBConnection.ServerBrand = ibInterbase) and (IBConnection.ServerVersion < ivIB070500) then case GetMetaInfoKind of mkIndexes: if AColIndex = 6 then begin if not ApInfo^.FVar.GetData(iVal, iSize) or (iVal = 0) then eIndexType := ikNonUnique else if (iVal = 1) and not VarIsNull(ARow.GetData(5)) then eIndexType := ikPrimaryKey else eIndexType := ikUnique; ARow.SetData(AColIndex, Integer(eIndexType)); lUseBase := False; end; mkTables: if AColIndex = 4 then begin if not ApInfo^.FVar.GetData(pBlob, iSize) then eTableType := tkTable else eTableType := tkView; ARow.SetData(AColIndex, Integer(eTableType)); lUseBase := False; end else if AColIndex = 5 then begin SetScope; lUseBase := False; end; mkTableFields: if AColIndex = 6 then begin SetDataType; lUseBase := False; end; mkForeignKeys: if (AColIndex = 8) or (AColIndex = 9) then begin s := ApInfo^.FVar.AsString; if CompareText('RESTRICT', s) = 0 then eRule := ckRestrict else if CompareText('CASCADE', s) = 0 then eRule := ckCascade else if CompareText('SET NULL', s) = 0 then eRule := ckSetNull else if CompareText('SET DEFAULT', s) = 0 then eRule := ckSetDefault else eRule := ckNone; ARow.SetData(AColIndex, Integer(eRule)); lUseBase := False; end; mkProcs: if AColIndex = 7 then begin SetScope; lUseBase := False; end; mkProcArgs: if AColIndex = 9 then begin SetDataType; lUseBase := False; end; mkGenerators: if AColIndex = 4 then begin SetScope; lUseBase := False; end; mkResultSetFields: if (AColIndex = 7) or (AColIndex = 8) then begin if not ApInfo^.FVar.GetData(pBlob, iSize) then iVal := 0 else iVal := 1; ARow.SetData(AColIndex, iVal); lUseBase := False; end; end; if lUseBase then inherited ProcessMetaColumn(ATable, AFmtOpts, AColIndex, ARow, ApInfo, ARowIndex); end; {-------------------------------------------------------------------------------} initialization FDRegisterDriverClass(TFDPhysIBDriver); FDRegisterDriverClass(TFDPhysIBLiteDriver); finalization FDUnregisterDriverClass(TFDPhysIBDriver); FDUnregisterDriverClass(TFDPhysIBLiteDriver); end.
unit SubGroupsQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap, BaseEventsQuery; type TSubGroupW = class(TDSWrap) private FExternalID: TFieldWrap; FID: TFieldWrap; FIsMain: TFieldWrap; function GetIsRecordReadOnly: Boolean; public constructor Create(AOwner: TComponent); override; property ExternalID: TFieldWrap read FExternalID; property IsMain: TFieldWrap read FIsMain; property ID: TFieldWrap read FID; property IsRecordReadOnly: Boolean read GetIsRecordReadOnly; end; TfrmQuerySubGroups = class(TQueryBaseEvents) private FW: TSubGroupW; procedure DoAfterDBEvents(Sender: TObject); procedure UpdateReadOnly; { Private declarations } protected function CreateDSWrap: TDSWrap; override; public constructor Create(AOwner: TComponent); override; procedure Search(AFirstExternalID, AValue: string); overload; property W: TSubGroupW read FW; { Public declarations } end; implementation {$R *.dfm} uses NotifyEvents, StrHelper; constructor TfrmQuerySubGroups.Create(AOwner: TComponent); begin inherited; FW := FDSWrap as TSubGroupW; TNotifyEventWrap.Create(W.AfterOpen, DoAfterDBEvents, W.EventList); TNotifyEventWrap.Create(W.AfterInsert, DoAfterDBEvents, W.EventList); TNotifyEventWrap.Create(W.AfterScroll, DoAfterDBEvents, W.EventList); end; function TfrmQuerySubGroups.CreateDSWrap: TDSWrap; begin Result := TSubGroupW.Create(FDQuery); end; procedure TfrmQuerySubGroups.DoAfterDBEvents(Sender: TObject); begin UpdateReadOnly; end; procedure TfrmQuerySubGroups.Search(AFirstExternalID, AValue: string); var AMainExternalID: string; ASQL: string; AStipulation: string; begin AMainExternalID := 'MainExternalID'; AStipulation := Format('%s = :%s', [W.ExternalID.FullName, AMainExternalID]); // Меняем SQL запрос ASQL := ReplaceInSQL(SQL, AStipulation, 0); AStipulation := Format('instr('',''||:%s||'','', '',''||%s||'','') > 0', [W.ExternalID.FieldName, W.ExternalID.FullName]); // Меняем SQL запрос FDQuery.SQL.Text := ReplaceInSQL(ASQL, AStipulation, 1); SetParamType(W.ExternalID.FieldName, ptInput, ftWideString); SetParamType(AMainExternalID, ptInput, ftWideString); Search([AMainExternalID, W.ExternalID.FieldName], [AFirstExternalID, AValue]); end; procedure TfrmQuerySubGroups.UpdateReadOnly; begin FDQuery.UpdateOptions.EnableDelete := not W.IsRecordReadOnly; FDQuery.UpdateOptions.EnableUpdate := not W.IsRecordReadOnly; end; constructor TSubGroupW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'pc.ID', '', True); FIsMain := TFieldWrap.Create(Self, 'IsMain'); FExternalID := TFieldWrap.Create(Self, 'pc.ExternalID'); end; function TSubGroupW.GetIsRecordReadOnly: Boolean; begin Result := (DataSet.RecordCount > 0) and (not IsMain.F.IsNull) and (IsMain.F.AsInteger = 1); end; end.
unit UMainWindow; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, ExtCtrls, UTools, UShapesList, Buttons, StdCtrls, ComCtrls, Grids, UViewPort, UGeometry, types, math, UInspector, UPaletteEditor, UHistory, UExportWindow; type { TMainWindow } TMainWindow = class(TForm) ColorDialog: TColorDialog; ExportToRasterMI: TMenuItem; ClearMI: TMenuItem; PasteMI: TMenuItem; CopyMI: TMenuItem; RedoAllMI: TMenuItem; UndoAllMI: TMenuItem; RedoMI: TMenuItem; UndoMI: TMenuItem; SaveAsMI: TMenuItem; SaveMI: TMenuItem; OpenMI: TMenuItem; NewMI: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; ZOrderMI: TMenuItem; MoveUpMI: TMenuItem; MoveDownMI: TMenuItem; BottomMI: TMenuItem; TopMI: TMenuItem; PaletteDG: TDrawGrid; HorizontalSB: TScrollBar; PalettePanel: TPanel; MainColor: TShape; SecondaryColor: TShape; ShowAllMI: TMenuItem; ViewMI: TMenuItem; VerticalSB: TScrollBar; ZoomCB: TComboBox; ZoomLabel: TLabel; MainMenu: TMainMenu; EditMI, DeleteMI, FileMI, AboutMI, ExitMI: TMenuItem; EditorsPanel, ToolsPanel: TPanel; PaintBox: TPaintBox; StatusBar: TStatusBar; procedure AboutMIClick(Sender: TObject); procedure BottomMIClick(Sender: TObject); procedure ClearMIClick(Sender: TObject); procedure CopyMIClick(Sender: TObject); procedure DeleteMIClick(Sender: TObject); procedure ExportMIClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure HorizontalSBScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); procedure ColorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MoveDownMIClick(Sender: TObject); procedure MoveUpMIClick(Sender: TObject); procedure NewMIClick(Sender: TObject); procedure OpenMIClick(Sender: TObject); procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBoxMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure PaletteDGDblClick(Sender: TObject); procedure PaletteDGDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); procedure PaletteDGMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ExitMIClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure PaintBoxPaint(Sender: TObject); procedure PasteMIClick(Sender: TObject); procedure RedoAllMIClick(Sender: TObject); procedure RedoMIClick(Sender: TObject); procedure SaveAsMIClick(Sender: TObject); procedure SaveMIClick(Sender: TObject); procedure ShowAllMIClick(Sender: TObject); procedure ToolClick(Sender: TObject); procedure TopMIClick(Sender: TObject); procedure UndoAllMIClick(Sender: TObject); procedure UndoMIClick(Sender: TObject); procedure VerticalSBScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); procedure ZoomCBChange(Sender: TObject); procedure UpdateScroll(AVisible: Boolean; APageSize, APosition: Integer; AKind: TScrollBarType); procedure RecalculateScrollbars; procedure ZOrderSwitch(AEnabled: Boolean); procedure EditStatusUpdate; procedure UndoSwitch(AEnabled: Boolean); procedure RedoSwitch(AEnabled: Boolean); private FCurrentToolIndex: Integer; FCleared: boolean; FMousePressed: boolean; FPaletteColors: array of TColor; FNameSet: Boolean; FName: String; function ReadyToCloseFile: Boolean; procedure UndoRedo(AString: String); public { public declarations } end; var MainWindow: TMainWindow; implementation {$R *.lfm} { TMainWindow } procedure TMainWindow.AboutMIClick(Sender: TObject); begin ShowMessage('Vector Graphic Editor' + chr(10) + 'Поликутин Евгений, Б8103а, 2015'); end; procedure TMainWindow.BottomMIClick(Sender: TObject); begin Figures.ZBottom; PaintBox.Invalidate; end; procedure TMainWindow.ClearMIClick(Sender: TObject); begin ToolContainer.Tools[FCurrentToolIndex].Leave; Inspector.LoadNew(ToolContainer.Tools[FCurrentToolIndex].CreateShape); Figures.Clear; PaintBox.Invalidate; end; procedure TMainWindow.ExitMIClick(Sender: TObject); begin Close(); end; procedure TMainWindow.FormCreate(Sender: TObject); var i, r, g, b: integer; bt: TSpeedButton; begin FCurrentToolIndex := 0; FCleared := False; FMousePressed := False; PenColor := MainColor; BrushColor := SecondaryColor; Inspector := TInspector.Create(EditorsPanel); Inspector.OnParamsUpdate := @PaintBox.Invalidate; Figures := TShapesList.Create; Figures.OnZOrderSwitch := @ZOrderSwitch; FNameSet := False; FName := 'unnamed'; FormatSettings.DecimalSeparator := '.'; OnUpdateFileStatus := @EditStatusUpdate; THistory.OnUndoSwitch := @UndoSwitch; THistory.OnRedoSwitch := @RedoSwitch; OnUpdateFileStatus; for i := 0 to High(ToolContainer.Tools) do begin bt := TSpeedButton.Create(Self); bt.Parent := Self.ToolsPanel; bt.Width := 60; bt.Height := 60; bt.Top := 10; bt.Left := 10 + 70 * i; bt.Glyph := ToolContainer.Tools[i].Icon; bt.Tag := i; bt.OnClick := @ToolClick; bt.Flat := true; bt.ShowHint := true; bt.Hint := ToolContainer.Tools[i].Caption; if i = 0 then bt.Click; end; VP := TViewPort.Create; VP.ViewPosition := FloatPoint(PaintBox.Width / 2, PaintBox.Height / 2); VP.OnScrollUpdate := @UpdateScroll; {Generate palette} SetLength(FPaletteColors, PaletteDG.ColCount * PaletteDG.RowCount); for i := 64 to 79 do FPaletteColors[i] := RGBToColor(16 * i, 16 * i, 16 * i); for r := 0 to 3 do for g := 0 to 3 do for b := 0 to 3 do FPaletteColors[r * 4 + g * 16 + b] := RGBToColor(r * 85, g * 85, b * 85); PaletteDG.FocusRectVisible := False; end; procedure TMainWindow.PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbLeft) or (Button = mbRight) then begin FMousePressed := True; FCleared := False; ToolContainer.Tools[FCurrentToolIndex].MouseClick(Point(X, Y), Shift); PaintBox.Invalidate; end; if Button = mbRight then FMousePressed := False; end; procedure TMainWindow.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if FMousePressed then begin ToolContainer.Tools[FCurrentToolIndex].MouseMove(Point(X, Y), Shift); PaintBox.Invalidate; end; end; procedure TMainWindow.PaintBoxPaint(Sender: TObject); begin VP.PortSize := Point(PaintBox.Width, PaintBox.Height); RecalculateScrollbars; ZoomCB.Text := FloatToStr(VP.Scale * 100); {Make canvas white} PaintBox.Canvas.Brush.Color := clWhite; PaintBox.Canvas.FillRect(0, 0, PaintBox.Width, PaintBox.Height); {Draw all figures} Figures.Draw(PaintBox.Canvas); end; procedure TMainWindow.CopyMIClick(Sender: TObject); begin if FMousePressed then Exit; Figures.Copy; PaintBox.Invalidate; end; procedure TMainWindow.PasteMIClick(Sender: TObject); begin if FMousePressed then Exit; Figures.Paste; PaintBox.Invalidate; end; procedure TMainWindow.RedoAllMIClick(Sender: TObject); begin if FMousePressed then Exit; UndoRedo(History.RedoAll); end; procedure TMainWindow.RedoMIClick(Sender: TObject); begin if FMousePressed then Exit; UndoRedo(History.Redo); end; procedure TMainWindow.SaveAsMIClick(Sender: TObject); begin if SaveDialog.Execute then begin Figures.Save(SaveDialog.FileName); FName := SaveDialog.FileName; FNameSet := True; OnUpdateFileStatus; end; end; procedure TMainWindow.SaveMIClick(Sender: TObject); begin if FNameSet then Figures.Save(FName) else if SaveDialog.Execute then begin Figures.Save(SaveDialog.FileName); FNameSet := True; FName := SaveDialog.FileName; end else Exit; OnUpdateFileStatus; end; procedure TMainWindow.ToolClick(Sender: TObject); begin ToolContainer.Tools[FCurrentToolIndex].Leave; FCurrentToolIndex := TSpeedButton(Sender).Tag; StatusBar.Panels[0].Text := 'Current tool: ' + ToolContainer.Tools[FCurrentToolIndex].Caption; Inspector.LoadNew(ToolContainer.Tools[FCurrentToolIndex].CreateShape); end; procedure TMainWindow.TopMIClick(Sender: TObject); begin Figures.ZTop; PaintBox.Invalidate; end; procedure TMainWindow.UndoAllMIClick(Sender: TObject); begin if FMousePressed then Exit; UndoRedo(History.RedoAll); end; procedure TMainWindow.UndoMIClick(Sender: TObject); begin if FMousePressed then Exit; UndoRedo(History.Undo); end; procedure TMainWindow.DeleteMIClick(Sender: TObject); begin Figures.Delete; PaintBox.Invalidate; end; procedure TMainWindow.ExportMIClick(Sender: TObject); var img: TFloatRect; begin if (not Figures.IsEmpty) then begin img := Figures.ImageSize; ExportDialog.AspectRatio := (img.Right - img.Left) / (img.Bottom - img.Top); ExportDialog.ImgWidth := ceil(img.Right - img.Left); ExportDialog.ImgHeight := ceil(img.Bottom - img.Top); ExportDialog.WidthSE.Value := ceil(img.Right - img.Left); ExportDialog.HeightSE.Value := ceil(img.Bottom - img.Top); ExportDialog.Show; end; end; procedure TMainWindow.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin CanClose := ReadyToCloseFile; end; procedure TMainWindow.ShowAllMIClick(Sender: TObject); begin if not Figures.IsEmpty then Figures.ShowAll; PaintBox.Invalidate; end; procedure TMainWindow.HorizontalSBScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); begin ScrollPos := Min(ScrollPos, HorizontalSB.Max - HorizontalSB.PageSize); PaintBox.Invalidate; end; procedure TMainWindow.ColorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ColorDialog.Color := TShape(Sender).Brush.Color; if not ColorDialog.Execute then exit; TShape(Sender).Brush.Color := ColorDialog.Color; OnMainColorUpdate(nil); OnBrushColorUpdate(nil); PaintBox.Invalidate; end; procedure TMainWindow.MoveDownMIClick(Sender: TObject); begin Figures.ZDown; PaintBox.Invalidate; end; procedure TMainWindow.MoveUpMIClick(Sender: TObject); begin Figures.ZUp; PaintBox.Invalidate; end; procedure TMainWindow.NewMIClick(Sender: TObject); begin if FMousePressed or (not ReadyToCloseFile) then Exit; Figures.New; FNameSet := False; FName := 'unnamed'; OnUpdateFileStatus; PaintBox.Invalidate; end; procedure TMainWindow.OpenMIClick(Sender: TObject); begin if FMousePressed or (not ReadyToCloseFile) then Exit; if OpenDialog.Execute then if FileExists(OpenDialog.FileName) then begin FNameSet := Figures.Load(OpenDialog.FileName); if FNameSet then FName := OpenDialog.FileName else FName := 'unnamed'; OnUpdateFileStatus; end else MessageDlg('File not found', mtWarning, [mbOk], 0); PaintBox.Invalidate; end; procedure TMainWindow.PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin FMousePressed := False; ToolContainer.Tools[FCurrentToolIndex].MouseUp; PaintBox.Invalidate; end; end; procedure TMainWindow.PaintBoxMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin if not Figures.IsEmpty then VP.ScaleMouseWheel(MousePos, WheelDelta); PaintBox.Invalidate; end; procedure TMainWindow.PaletteDGDblClick(Sender: TObject); var t: integer; begin t := PaletteDG.ColCount * PaletteDG.Row + PaletteDG.Col; ColorDialog.Color := FPaletteColors[t]; if not ColorDialog.Execute then exit; FPaletteColors[t] := ColorDialog.Color; MainColor.Brush.Color := FPaletteColors[t]; PaletteDG.InvalidateCell(PaletteDG.Col, PaletteDG.Row); PaintBox.Invalidate; if OnMainColorUpdate <> nil then OnMainColorUpdate(nil); end; procedure TMainWindow.PaletteDGDrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); begin PaletteDG.Canvas.Brush.Color:= FPaletteColors[aRow*PaletteDG.ColCount+aCol]; PaletteDG.Canvas.FillRect(aRect); end; procedure TMainWindow.PaletteDGMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var t, c, r: Integer; begin PaletteDG.MouseToCell(X, Y, c, r); t := PaletteDG.ColCount * r + c; if Button = mbLeft then begin MainColor.Brush.Color:= FPaletteColors[t]; if OnMainColorUpdate <> nil then OnMainColorUpdate(nil); end; if Button = mbRight then begin SecondaryColor.Brush.Color:= FPaletteColors[t]; if OnBrushColorUpdate <> nil then OnBrushColorUpdate(nil); end; PaintBox.Invalidate; end; procedure TMainWindow.VerticalSBScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); begin ScrollPos := Min(ScrollPos, VerticalSB.Max - VerticalSB.PageSize); PaintBox.Invalidate; end; procedure TMainWindow.ZoomCBChange(Sender: TObject); begin if not Figures.IsEmpty then VP.Scale := StrToFloatDef(ZoomCB.Text, 100) / 100; PaintBox.Invalidate; end; procedure TMainWindow.UpdateScroll(AVisible: Boolean; APageSize, APosition: Integer; AKind: TScrollBarType); begin if AKind = sbHorizontal then begin HorizontalSB.Visible := AVisible; HorizontalSB.PageSize := APageSize; HorizontalSB.Position := APosition; end else begin VerticalSB.Visible := AVisible; VerticalSB.PageSize := APageSize; VerticalSB.Position := APosition; end; end; procedure TMainWindow.RecalculateScrollbars; var l, r, t, b: double; fp1, fp2, worldsize: TFloatPoint; imagesize: TFloatRect; begin imagesize := Figures.ImageSize; fp1 := VP.ScreenToWorld(Point(0, 0)); fp2 := VP.ScreenToWorld(VP.PortSize); l := Min(fp1.X, imagesize.Left); t := Min(fp1.Y, imagesize.Top); r := Max(fp2.X, imagesize.Right); b := Max(fp2.Y, imagesize.Bottom); worldsize := FloatPoint(r, b) - FloatPoint(l, t); if not ((worldsize.X = 0) or (worldsize.Y = 0)) then begin VP.SetScroll(HorizontalSB.Position, worldsize.X, l, sbHorizontal); VP.SetScroll(VerticalSB.Position, worldsize.Y, t, sbVertical); end; end; procedure TMainWindow.ZOrderSwitch(AEnabled: Boolean); begin ZOrderMI.Enabled := AEnabled; DeleteMI.Enabled := AEnabled; end; procedure TMainWindow.EditStatusUpdate; begin if History.IsChanged then Caption := 'Vector Graphic Editor - ' + FName + '*' else Caption := 'Vector Graphic Editor - ' + FName; end; procedure TMainWindow.UndoSwitch(AEnabled: Boolean); begin UndoMI.Enabled := AEnabled; UndoAllMI.Enabled := AEnabled; end; procedure TMainWindow.RedoSwitch(AEnabled: Boolean); begin RedoMI.Enabled := AEnabled; RedoAllMI.Enabled := AEnabled; end; function TMainWindow.ReadyToCloseFile: Boolean; begin Result := True; if History.IsChanged then case MessageDlg('File is not saved! Save the file?', mtWarning, mbYesNoCancel, 0) of mrYes: if FNameSet then Figures.Save(FName) else if SaveDialog.Execute then Figures.Save(SaveDialog.FileName) else Result := False; mrCancel: Result := False; end; end; procedure TMainWindow.UndoRedo(AString: String); begin ToolContainer.Tools[FCurrentToolIndex].Reset; Figures.LoadState(AString); OnUpdateFileStatus; PaintBox.Invalidate; end; end.
unit URepositorioLoteVacina; interface uses ULoteVacina , UEntidade , URepositorioDB , SqlExpr ; type TRepositorioLoteVacina = class(TRepositorioDB<TLOTEVACINA>) private public constructor Create; //destructor Destroy; override; procedure AtribuiDBParaEntidade(const coLOTEVACINA: TLOTEVACINA); override; procedure AtribuiEntidadeParaDB(const coLOTEVACINA: TLOTEVACINA; const coSQLQuery: TSQLQuery); override; end; implementation uses UDM , SysUtils , StrUtils ; { TRepositorioCoren } constructor TRepositorioLOTEVACINA.Create; begin inherited Create(TLOTEVACINA, TBL_LOTE_VACINA, FLD_ENTIDADE_ID, STR_LOTE_VACINA); end; procedure TRepositorioLoteVacina.AtribuiDBParaEntidade(const coLOTEVACINA: TLOTEVACINA); begin inherited; with FSQLSelect do begin //coLOTEVACINA.CODIGO := FieldByName(FLD_CODIGO).AsInteger ; coLOTEVACINA.VACINA_NOME := FieldByName(FLD_VACINA_NOME ).AsString ; coLOTEVACINA.LOTE := FieldByName(FLD_LOTE_VACINA).AsString; coLOTEVACINA.LABORATORIO := FieldByName(FLD_LABORATORIO ).AsString; coLOTEVACINA.VENCIMENTO_LOTE := FieldByName(FLD_VENCIMENTO_LOTE).AsDateTime; coLOTEVACINA.QUANTIDADE_ESTOQUE:= FieldByName(FLD_QUANTIDADE_ESTOQUE).AsString; end; end; procedure TRepositorioLoteVacina.AtribuiEntidadeParaDB(const coLOTEVACINA: TLOTEVACINA; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin //ParamByName(FLD_CODIGO).AsInteger := coLOTEVACINA.CODIGO; ParamByName(FLD_VACINA_NOME).AsString := coLOTEVACINA.VACINA_NOME; ParamByName(FLD_LOTE_VACINA).AsString := coLOTEVACINA.LOTE ; ParamByName(FLD_LABORATORIO).AsString := coLOTEVACINA.LABORATORIO ; ParamByName(FLD_VENCIMENTO_LOTE).AsDate := coLOTEVACINA.VENCIMENTO_LOTE; ParamByName(FLD_QUANTIDADE_ESTOQUE).AsString := coLOTEVACINA.QUANTIDADE_ESTOQUE; end; end; end.
unit frm_Agrega_Personal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type Tfrm_Agrega = class(TForm) lblNombre: TLabel; lblApPaterno: TLabel; lblApMaterno: TLabel; lblDomicilio: TLabel; lblCiudad: TLabel; lblTel: TLabel; lblEmail: TLabel; lblcurp: TLabel; lblIMSS: TLabel; lblNacionalidad: TLabel; lblEstadoCivil: TLabel; lblFNacimiento: TLabel; lblLNacimiento: TLabel; lblEdad: TLabel; edtNombres: TEdit; edtApPaterno: TEdit; edtApMaterno: TEdit; edtDomicilio: TEdit; edtCiudad: TEdit; edtTelefono: TEdit; edtEMail: TEdit; edtCURP: TEdit; edtIMSS: TEdit; edtNacionalidad: TEdit; edtEcivil: TEdit; edtFNacimiento: TEdit; edtLNacimiento: TEdit; edtEdad: TEdit; btnAceptar: TButton; btnCancelar: TButton; procedure btnCancelarClick(Sender: TObject); procedure btnAceptarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frm_Agrega: Tfrm_Agrega; implementation {$R *.dfm} procedure Tfrm_Agrega.btnAceptarClick(Sender: TObject); begin //zqryEmpleado.Activate := True; //zqryEmpleados.sql.Clear; //zqryEmpleados.Add( ); end; procedure Tfrm_Agrega.btnCancelarClick(Sender: TObject); begin frm_Agrega.Close; end; end.
unit fEncounterFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Tabs, ComCtrls, ExtCtrls, Menus, StdCtrls, Buttons, fPCEBase, fVisitType, fDiagnoses, fProcedure, fImmunization, fSkinTest, fPatientEd, fHealthFactor, fExam, uPCE, rPCE, rTIU, ORCtrls, ORFn, fEncVitals, rvitals, fBase508Form, VA508AccessibilityManager; const //tab names CT_VisitNm = 'Visit Type'; CT_DiagNm = 'Diagnoses'; CT_ProcNm = 'Procedures'; CT_ImmNm = 'Immunizations'; CT_SkinNm = 'Skin Tests'; CT_PedNm = 'Patient Ed'; CT_HlthNm = 'Health Factors'; CT_XamNm = 'Exams'; CT_VitNm = 'Vitals'; CT_GAFNm = 'GAF'; //numbers assigned to tabs to make changes easier //they must be sequential CT_NOPAGE = -1; CT_UNKNOWN = 0; CT_VISITTYPE = 1; CT_FIRST = 1; CT_DIAGNOSES = 2; CT_PROCEDURES = 3; CT_IMMUNIZATIONS = 4; CT_SKINTESTS = 5; CT_PATIENTED = 6; CT_HEALTHFACTORS = 7; CT_EXAMS = 8; CT_VITALS = 9; CT_GAF = 10; CT_LAST = 10; NUM_TABS = 3; TAG_VTYPE = 10; TAG_DIAG = 20; TAG_PROC = 30; TAG_IMMUNIZ = 40; TAG_SKIN = 50; TAG_PED = 60; TAG_HF = 70; TAG_XAM = 80; TAG_TRT = 90; TX_NOSECTION = '-1^No sections found'; TX_PROV_REQ = 'A primary encounter provider must be selected before encounter data can' + CRLF + 'be saved. Select the Primary Encounter Provider on the VISIT TYPE tab.' + CRLF + 'Otherwise, press <Cancel> to quit without saving data.'; TC_PROV_REQ = 'Missing Primary Provider for Encounter'; type TfrmEncounterFrame = class(TfrmBase508Form) StatusBar1: TStatusBar; pnlPage: TPanel; Bevel1: TBevel; TabControl: TTabControl; procedure tabPageChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure FormResize(Sender: TObject); procedure SectionClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure TabControlChange(Sender: TObject); procedure TabControlChanging(Sender: TObject; var AllowChange: Boolean); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); procedure FormShow(Sender: TObject); procedure TabControlEnter(Sender: TObject); private FAutoSave: boolean; FSaveNeeded: boolean; FChangeSource: Integer; FCancel: Boolean; //Indicates the cancel button has been pressed; FAbort: boolean; // indicates that neither OK or Cancel has been pressed FormList: TStringList; //Holds the types of any forms that will be used //in the frame. They must be available at compile time FLastPage: TfrmPCEBase; FGiveMultiTabMessage: boolean; procedure CreateChildForms(Sender: TObject; Location: integer); procedure SynchPCEData; procedure SwitchToPage(NewForm: TfrmPCEBase); //was tfrmPage function PageIDToForm(PageID: Integer): TfrmPCEBase; function PageIDToTab(PageID: Integer): string; procedure LoadFormList(Location: integer); procedure CreateForms; procedure AddTabs; function FormListContains(item: string): Boolean; procedure SendData; procedure UpdateEncounter(PCE: TPCEData); procedure SetFormFonts; public procedure SelectTab(NewTabName: string); property ChangeSource: Integer read FChangeSource; property Forms: tstringlist read FormList; property Cancel: Boolean read FCancel write FCancel; property Abort: Boolean read FAbort write FAbort; end; var frmEncounterFrame: TfrmEncounterFrame; uSCCond: TSCConditions; uVisitType: TPCEProc; // contains info for visit type page uEncPCEData: TPCEData; uProviders: TPCEProviderList; // Returns true if PCE data still needs to be saved - vitals/gaf are always saved function UpdatePCE(PCEData: TPCEData; SaveOnExit: boolean = TRUE): boolean; implementation uses uCore, fGAF, uConst, rCore, fPCEProvider, rMisc, VA508AccessibilityRouter, VAUtils; {$R *.DFM} {/////////////////////////////////////////////////////////////////////////////// //Name: function TfrmEncounterFrame.PageIDToTab(PageID: Integer): String; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: returns the tab index that corresponds to a given PageID . ///////////////////////////////////////////////////////////////////////////////} function TfrmEncounterFrame.PageIDToTab(PageID: Integer): String; begin result := ''; case PageID of CT_NOPAGE: Result := ''; CT_UNKNOWN: Result := ''; CT_VISITTYPE: Result := CT_VisitNm; CT_DIAGNOSES: Result := CT_DiagNm; CT_PROCEDURES: Result := CT_ProcNm; CT_IMMUNIZATIONS: Result := CT_ImmNm; CT_SKINTESTS: Result := CT_SkinNm; CT_PATIENTED: Result := CT_PedNm; CT_HEALTHFACTORS: Result := CT_HlthNm; CT_EXAMS: Result := CT_XamNm; CT_VITALS: Result := CT_VitNm; CT_GAF: Result := CT_GAFNm; end; end; {/////////////////////////////////////////////////////////////////////////////// //Name: function TfrmEncounterFrame.PageIDToForm(PageID: Integer): TfrmPCEBase; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: return the form name based on the PageID} ///////////////////////////////////////////////////////////////////////////////} function TfrmEncounterFrame.PageIDToForm(PageID: Integer): TfrmPCEBase; begin case PageID of CT_VISITTYPE: Result := frmVisitType; CT_DIAGNOSES: Result := frmDiagnoses; CT_PROCEDURES: Result := frmProcedures; CT_IMMUNIZATIONS: Result := frmImmunizations; CT_SKINTESTS: Result := frmSkinTests; CT_PATIENTED: Result := frmPatientEd; CT_HEALTHFACTORS: Result := frmHealthFactors; CT_EXAMS: Result := frmExams; CT_VITALS: Result := frmEncVitals; CT_GAF: Result := frmGAF; else //not a valid form result := frmPCEBase; end; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.CreatChildForms(Sender: TObject); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Finds out what pages to display, has the pages and tabs created. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.CreateChildForms(Sender: TObject; Location: integer); begin //load FormList with a list of all forms to display. inherited; LoadFormList(Location); AddTabs; CreateForms; end; {/////////////////////////////////////////////////////////////////////////////// //Name: TfrmEncounterFrame.LoadFormList; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Loads Formlist with the forms to create, will be replaced by RPC call. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.LoadFormList(Location: integer); begin //change this to an RPC in RPCE.pas FormList.clear; FormList.add(CT_VisitNm); FormList.add(CT_DiagNm); FormList.add(CT_ProcNm); formList.add(CT_VitNm); formList.add(CT_ImmNm); formList.add(CT_SkinNm); formList.add(CT_PedNm); formList.add(CT_HlthNm); formList.add(CT_XamNm); if MHClinic(Location) then formList.add(CT_GAFNm); end; {/////////////////////////////////////////////////////////////////////////////// //Name: function TfrmEncounterFrame.FormListContains(item: string): Boolean; //Created: 12/06/98 //By: Robert Bott //Location: ISL //Description: Returns a boolean value indicating if a given string exists in // the formlist. ///////////////////////////////////////////////////////////////////////////////} function TfrmEncounterFrame.FormListContains(item: string): Boolean; begin result := false; if (FormList.IndexOf(item) <> -1 ) then result := true; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.CreateForms; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Creates all of the forms in the list. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.CreateForms; var i: integer; begin //could this be placed in a loop using PagedIdToTab & PageIDToFOrm & ? if FormListContains(CT_VisitNm) then frmVisitType := TfrmVisitType.CreateLinked(pnlPage); if FormListContains(CT_DiagNm) then frmDiagnoses := TfrmDiagnoses.CreateLinked(pnlPage); if FormListContains(CT_ProcNm) then frmProcedures := TfrmProcedures.CreateLinked(pnlPage); if FormListContains(CT_VitNm) then frmEncVitals := TfrmEncVitals.CreateLinked(pnlPage); if FormListContains(CT_ImmNm) then frmImmunizations := TfrmImmunizations.CreateLinked(pnlPage); if FormListContains(CT_SkinNm) then frmSkinTests := TfrmSkinTests.CreateLinked(pnlPage); if FormListContains(CT_PedNm) then frmPatientEd := TfrmPatientEd.CreateLinked(pnlPage); if FormListContains(CT_HlthNm) then frmHealthFactors := TfrmHEalthFactors.CreateLinked(pnlPage); if FormListContains(CT_XamNm) then frmExams := TfrmExams.CreateLinked(pnlPage); if FormListContains(CT_GAFNm) then frmGAF := TfrmGAF.CreateLinked(pnlPage); //must switch based on caption, as all tabs may not be present. for i := CT_FIRST to CT_LAST do begin if Formlist.IndexOf(PageIdToTab(i)) <> -1 then PageIDToForm(i).Visible := (Formlist.IndexOf(PageIdToTab(i)) = 0); end; end; {/////////////////////////////////////////////////////////////////////////////// //Name: TfrmEncounterFrame.SwitchToPage(NewForm: tfrmPCEBase); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Brings the selected page to the front for display. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.SwitchToPage(NewForm: tfrmPCEBase);// was TfrmPage); { unmerge/merge menus, bring page to top of z-order, call form-specific OnDisplay code } begin if (NewForm = nil) or (FLastPage = NewForm) then Exit; if Assigned(FLastPage) then FLastPage.Hide; FLastPage := NewForm; // KeyPreview := (NewForm = frmEncVitals); NewForm.DisplayPage; // this calls BringToFront for the form end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.tabPageChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Finds the page, and calls SwithToPage to display it. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.tabPageChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); { switches to form linked to NewTab } var i: integer; begin //must switch based on caption, as all tabs may not be present. for i := CT_FIRST to CT_LAST do begin With Formlist do if NewTab = IndexOf(PageIdToTab(i)) then begin PageIDToForm(i).show; SwitchToPage(PageIDToForm(i)); end; end; end; { Resize and Font-Change procedures --------------------------------------------------------- } {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.FormResize(Sender: TObject); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Resizes all windows when parent changes. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.FormResize(Sender: TObject); var i: integer; begin for i := CT_FIRST to CT_LAST do if (FormList.IndexOf(PageIdToTab(i)) <> -1) then MoveWindow(PageIdToForm(i).Handle, 0, 0, pnlPage.ClientWidth, pnlpage.ClientHeight, true); self.repaint; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.AddTabs; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: adds a tab for each page that will be displayed ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.AddTabs; var i: integer; begin TabControl.Tabs.Clear; for I := 0 to (Formlist.count - 1) do TabControl.Tabs.Add(Formlist.Strings[i]); end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure UpdatePCE(PCEData: TPCEData); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: The main call to open the encounter frame and capture encounter // information. ///////////////////////////////////////////////////////////////////////////////} function UpdatePCE(PCEData: TPCEData; SaveOnExit: boolean = TRUE): boolean; var // FontHeight, // FontWidth: Integer; AUser: string; begin frmEncounterFrame := TfrmEncounterFrame.Create(Application); try frmEncounterFrame.FAutoSave := SaveOnExit; uEncPCEData := PCEData; if(uEncPCEData.Empty and ((uEncPCEData.Location = 0) or (uEncPCEData.VisitDateTime = 0)) and (not Encounter.NeedVisit)) then uEncPCEData.UseEncounter := TRUE; frmEncounterFrame.Caption := 'Encounter Form for ' + ExternalName(uEncPCEData.Location, 44) + ' (' + FormatFMDateTime('mmm dd,yyyy@hh:nn', uEncPCEData.VisitDateTime) + ')'; uProviders.Assign(uEncPCEData.Providers); SetDefaultProvider(uProviders, uEncPCEData); AUser := IntToStr(uProviders.PendingIEN(FALSE)); if(AUser <> '0') and (uProviders.IndexOfProvider(AUser) < 0) and AutoCheckout(uEncPCEData.Location) then uProviders.AddProvider(AUser, uProviders.PendingName(FALSE), FALSE); frmEncounterFrame.CreateChildForms(frmEncounterFrame, PCEData.Location); SetFormPosition(frmEncounterFrame); ResizeAnchoredFormToFont(frmEncounterFrame); //SetFormPosition(frmEncounterFrame); with frmEncounterFrame do begin SetRPCEncLocation(PCEData.Location); SynchPCEData; TabControl.Tabindex := 0; TabControlChange(TabControl); ShowModal; Result := FSaveNeeded; end; finally // frmEncounterFrame.Free; v22.11 (JD and SM) frmEncounterFrame.Release; //frmEncounterFrame := nil; access violation source? removed 7/28/03 RV end; end; {/////////////////////////////////////////////////////////////////////////////// //Name: TfrmEncounterFrame.SectionClick(Sender: TObject); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Call the procedure apropriate for the selected tab ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.SectionClick(Sender: TObject); begin with Sender as TListBox do case Tag of TAG_VTYPE: if FormListContains(CT_VisitNm) then begin with frmVisitType do lstVTypeSectionClick(Sender); end; end; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.SynchPCEData; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Synchronize any existing PCE data with what is displayed in the form. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.SynchPCEData; procedure InitList(AListBox: TORListBox); var DoClick: boolean; begin with AListBox do begin DoClick := TRUE; case Tag of TAG_VTYPE: begin if FormListContains(CT_VisitNm) then ListVisitTypeSections(Items); DoClick := AutoSelectVisit(PCERPCEncLocation); end; end; if Items.Count > 0 then begin if DoClick then begin ItemIndex := 0; SectionClick(AListBox); end; end else Items.Add(TX_NOSECTION); end; end; begin if FormListContains(CT_VisitNm) then with frmVisitType do begin InitList(frmVisitType.lstVTypeSection); // set up Visit Type page ListSCDisabilities(memSCDisplay.Lines); uSCCond := EligbleConditions; frmVisitType.fraVisitRelated.InitAllow(uSCCond); end; with uEncPCEData do // load any existing data from PCEData begin if FormListContains(CT_VisitNm) then frmVisitType.fraVisitRelated.InitRelated(uEncPCEData); if FormListContains(CT_DiagNm) then frmDiagnoses.InitTab(CopyDiagnoses, ListDiagnosisSections); if FormListContains(CT_ProcNm) then frmProcedures.InitTab(CopyProcedures, ListProcedureSections); if FormListContains(CT_ImmNm) then frmImmunizations.InitTab(CopyImmunizations,ListImmunizSections); if FormListContains(CT_SkinNm) then frmSkinTests.InitTab(CopySkinTests, ListSkinSections); if FormListContains(CT_PedNm) then frmPatientEd.InitTab(CopyPatientEds, ListPatientSections); if FormListContains(CT_HlthNm) then frmHealthFactors.InitTab(CopyHealthFactors, ListHealthSections); if FormListContains(CT_XamNm) then frmExams.InitTab(CopyExams, ListExamsSections); uVisitType.Assign(VisitType); if FormListContains(CT_VisitNm) then with frmVisitType do begin MatchVType; end; end; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.FormDestroy(Sender: TObject); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Free up objects in memory when destroying form. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.FormDestroy(Sender: TObject); var i: integer; begin inherited; for i := ComponentCount-1 downto 0 do if(Components[i] is TForm) then TForm(Components[i]).Free; formlist.clear; KillObj(@uProviders); uVisitType.Free; Formlist.free; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.FormCreate(Sender: TObject); //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Create instances of the objects needed. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.FormCreate(Sender: TObject); begin uProviders := TPCEProviderList.Create; uVisitType := TPCEProc.create; //uVitalOld := TStringList.create; //uVitalNew := TStringList.create; FormList := TStringList.create; fCancel := False; FAbort := TRUE; SetFormFonts; FGiveMultiTabMessage := ScreenReaderSystemActive; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.SendData; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Send Data back to the M side sor storing. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.SendData; //send PCE data to the RPC var StoreMessage: string; GAFScore: integer; GAFDate: TFMDateTime; GAFStaff: Int64; begin inherited; // do validation for vitals & anything else here //process vitals if FormListContains(CT_VitNm) then begin with frmEncVitals do if HasData then begin if AssignVitals then begin StoreMessage := ValAndStoreVitals(frmEncVitals.VitalNew); if (Storemessage <> 'True') then begin ShowMsg(storemessage); // exit; end; end; end; end; if(FormListContains(CT_GAFNm)) then begin frmGAF.GetGAFScore(GAFScore, GAFDate, GAFStaff); if(GAFScore > 0) then SaveGAFScore(GAFScore, GAFDate, GAFStaff); end; //PCE UpdateEncounter(uEncPCEData); with uEncPCEData do begin if FAutoSave then Save else FSaveNeeded := TRUE; end; Close; end; {/////////////////////////////////////////////////////////////////////////////// //Name: procedure TfrmEncounterFrame.FormCloseQuery(Sender: TObject; //Created: Jan 1999 //By: Robert Bott //Location: ISL //Description: Check to see if the Cancel button was pressed, if not, call // procedure to send the data to the server. ///////////////////////////////////////////////////////////////////////////////} procedure TfrmEncounterFrame.FormCloseQuery(Sender: TObject; var CanClose: Boolean); const TXT_SAVECHANGES = 'Save Changes?'; var TmpPCEData: TPCEData; ask, ChangeOK: boolean; begin CanClose := True; if(FAbort) then FCancel := (InfoBox(TXT_SAVECHANGES, TXT_SAVECHANGES, MB_YESNO) = ID_NO); if FCancel then Exit; //*KCM* if(uProviders.PrimaryIdx >= 0) then ask := TRUE else begin TmpPCEData := TPCEData.Create; try uEncPCEData.CopyPCEData(TmpPCEData); UpdateEncounter(TmpPCEData); ask := TmpPCEData.NeedProviderInfo; finally TmpPCEData.Free; end; end; if ask and (NoPrimaryPCEProvider(uProviders, uEncPCEData)) then begin InfoBox(TX_PROV_REQ, TC_PROV_REQ, MB_OK or MB_ICONWARNING); CanClose := False; Exit; end; uVisitType.Provider := uProviders.PrimaryIEN; {RV - v20.1} if FormListContains(CT_VitNm) then CanClose := frmEncVitals.OK2SaveVitals; if CanClose and FormListContains(CT_ProcNm) then begin CanClose := frmProcedures.OK2SaveProcedures; if not CanClose then begin tabPageChange(Self, FormList.IndexOf(CT_ProcNm), ChangeOK); SwitchToPage(PageIDToForm(CT_PROCEDURES)); TabControl.TabIndex := FormList.IndexOf(CT_ProcNm); end; end; if CanClose then SendData; //*KCM* end; procedure TfrmEncounterFrame.TabControlChange(Sender: TObject); var i: integer; begin //must switch based on caption, as all tabs may not be present. if (sender as tTabControl).tabindex = -1 then exit; if TabControl.CanFocus and Assigned(FLastPage) and not TabControl.Focused then TabControl.SetFocus; //CQ: 14845 for i := CT_FIRST to CT_LAST do begin with Formlist do with sender as tTabControl do if Tabindex = IndexOf(PageIdToTab(i)) then begin PageIDToForm(i).show; SwitchToPage(PageIDToForm(i)); Exit; end; end; end; procedure TfrmEncounterFrame.TabControlChanging(Sender: TObject; var AllowChange: Boolean); begin if(assigned(FLastPage)) then FLastPage.AllowTabChange(AllowChange); end; procedure TfrmEncounterFrame.UpdateEncounter(PCE: TPCEData); begin with PCE do begin if FormListContains(CT_VisitNm) then begin VisitType := uVisitType; frmVisitType.fraVisitRelated.GetRelated(uEncPCEData); Providers.Merge(uProviders); end; //ZZZZZZBELLC if FormListContains(CT_DiagNm) then SetDiagnoses(frmDiagnoses.lstCaptionList.ItemsStrings); if FormListContains(CT_ProcNm) then SetProcedures(frmProcedures.lstCaptionList.ItemsStrings); if FormListContains(CT_ImmNm) then SetImmunizations(frmImmunizations.lstCaptionList.ItemsStrings); if FormListContains(CT_SkinNm) then SetSkinTests(frmSkinTests.lstCaptionList.ItemsStrings); if FormListContains(CT_PedNm) then SetPatientEds(frmPatientEd.lstCaptionList.ItemsStrings); if FormListContains(CT_HlthNm) then SetHealthFactors(frmHealthFactors.lstCaptionList.ItemsStrings); if FormListContains(CT_XamNm) then SetExams(frmExams.lstCaptionList.ItemsStrings); end; end; procedure TfrmEncounterFrame.SelectTab(NewTabName: string); var AllowChange: boolean; begin AllowChange := True; tabControl.TabIndex := FormList.IndexOf(NewTabName); tabPageChange(Self, tabControl.TabIndex, AllowChange); end; procedure TfrmEncounterFrame.TabControlEnter(Sender: TObject); begin if FGiveMultiTabMessage then // CQ#15483 begin FGiveMultiTabMessage := FALSE; GetScreenReader.Speak('Multi tab form'); end; end; procedure TfrmEncounterFrame.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var CanChange: boolean; begin inherited; if (Key = VK_ESCAPE) then begin Key := 0; FLastPage.btnCancel.Click; end else if Key = VK_TAB then begin if ssCtrl in Shift then begin CanChange := True; if Assigned(TabControl.OnChanging) then TabControl.OnChanging(TabControl, CanChange); if CanChange then begin if ssShift in Shift then begin if TabControl.TabIndex < 1 then TabControl.TabIndex := TabControl.Tabs.Count -1 else TabControl.TabIndex := TabControl.TabIndex - 1; end else TabControl.TabIndex := (TabControl.TabIndex + 1) mod TabControl.Tabs.Count; if Assigned(TabControl.OnChange) then TabControl.OnChange(TabControl); end; Key := 0; end; end; end; procedure TfrmEncounterFrame.SetFormFonts; var NewFontSize: integer; begin NewFontSize := MainFontsize; if FormListContains(CT_VisitNm) then frmVisitType.Font.Size := NewFontSize; if FormListContains(CT_DiagNm) then frmDiagnoses.Font.Size := NewFontSize; if FormListContains(CT_ProcNm) then frmProcedures.Font.Size := NewFontSize; if FormListContains(CT_ImmNm) then frmImmunizations.Font.Size := NewFontSize; if FormListContains(CT_SkinNm) then frmSkinTests.Font.Size := NewFontSize; if FormListContains(CT_PedNm) then frmPatientEd.Font.Size := NewFontSize; if FormListContains(CT_HlthNm) then frmHealthFactors.Font.Size := NewFontSize; if FormListContains(CT_XamNm) then frmExams.Font.Size := NewFontSize; if FormListContains(CT_VitNm) then frmEncVitals.Font.Size := NewFontSize; if FormListContains(CT_GAFNm) then frmGAF.SetFontSize(NewFontSize); end; procedure TfrmEncounterFrame.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveUserBounds(Self); end; procedure TfrmEncounterFrame.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); begin //CQ4740 if NewWidth < 200 then begin NewWidth := 200; Resize := false; end; end; procedure TfrmEncounterFrame.FormShow(Sender: TObject); begin inherited; if TabControl.CanFocus then TabControl.SetFocus; end; end.
unit BCEditor.Editor.RightMargin.Colors; interface uses Classes, Graphics; type TBCEditorRightMarginColors = class(TPersistent) strict private FEdge: TColor; FMovingEdge: TColor; FOnChange: TNotifyEvent; procedure SetEdge(Value: TColor); procedure SetMovingEdge(Value: TColor); procedure DoChange; public constructor Create; procedure Assign(Source: TPersistent); override; published property Edge: TColor read FEdge write SetEdge default clSilver; property MovingEdge: TColor read FMovingEdge write SetMovingEdge default clSilver; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation { TBCEditorSelectedColor } constructor TBCEditorRightMarginColors.Create; begin inherited; FEdge := clSilver; FMovingEdge := clSilver; end; procedure TBCEditorRightMarginColors.Assign(Source: TPersistent); begin if Assigned(Source) and (Source is TBCEditorRightMarginColors) then with Source as TBCEditorRightMarginColors do begin Self.FEdge := FEdge; Self.FMovingEdge := FMovingEdge; Self.DoChange; end else inherited Assign(Source); end; procedure TBCEditorRightMarginColors.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TBCEditorRightMarginColors.SetEdge(Value: TColor); begin if FEdge <> Value then begin FEdge := Value; DoChange; end; end; procedure TBCEditorRightMarginColors.SetMovingEdge(Value: TColor); begin if FMovingEdge <> Value then begin FMovingEdge := Value; DoChange; end; end; end.
unit SplashScreen; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TMultiP, ExtCtrls, Db, DBTables; type TSplashScreenForm = class(TForm) Panel1: TPanel; SplashImage: TPMultiImage; SystemTable: TTable; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var SplashScreenForm: TSplashScreenForm; implementation {$R *.DFM} uses Utilitys; {======================================================} Procedure TSplashScreenForm.FormCreate(Sender: TObject); var TempFile : TSearchRec; ReturnCode : Integer; begin try SystemTable.Open; {FXX01282004-1(2.08): Make sure that we include the drive letter for the displaying th splash screen.} ReturnCode := FindFirst(SystemTable.FieldByName('DriveLetter').Text + ':' + AddDirectorySlashes(SystemTable.FieldByName('SysProgramDir').Text) + 'SPLASH\*.*', faAnyFile, TempFile); If (ReturnCode = 0) then begin repeat ReturnCode := FindNext(TempFile); until ((ReturnCode <> 0) or ((TempFile.Name <> '.') and (TempFile.Name <> '..'))); {FXX02012005-2(2.8.3.3)-2: Make sure to include the drive and fully qualified directory when setting the image name.} SplashImage.ImageName := SystemTable.FieldByName('DriveLetter').Text + ':' + AddDirectorySlashes(SystemTable.FieldByName('SysProgramDir').Text) + 'SPLASH\' + TempFile.Name; end; {If (ReturnCode <> 0)} SystemTable.Close; except end; end; {FormCreate} end.