text
stringlengths
14
6.51M
unit Forms.Progress; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, AdvGlowButton, Vcl.ComCtrls; type TFrmProgress = class(TForm) Progress: TProgressBar; btnCancel: TAdvGlowButton; lblInfo: TLabel; private { Private declarations } procedure UpdateLabel; public { Public declarations } procedure Start( ACaption:String; AMax: Integer ); procedure UpdateProgress( AValue: Integer ); end; var FrmProgress: TFrmProgress; implementation {$R *.dfm} { TForm1 } procedure TFrmProgress.Start(ACaption:String; AMax: Integer); begin Progress.Max := AMax; Progress.Position := 0; Caption := ACaption; UpdateLabel; self.Show; end; procedure TFrmProgress.UpdateLabel; begin lblInfo.Caption := Format( '%d/%d', [Progress.Position, Progress.Max] ); end; procedure TFrmProgress.UpdateProgress(AValue: Integer); begin Progress.Position := Progress.Max - (AValue + 1); UpdateLabel; Application.ProcessMessages; end; end.
unit Class_WORK; interface uses Classes,SysUtils,Uni,UniEngine; type TWorkObjtType=(wotWork,wotDoct); TWORK=class(TUniEngine) private FUNITLINK: string; FWORKIDEX: Integer; FWORKNAME: string; FWORKCODE: string; FWORKMOBL: string; FWORKCALL: string; FWORKMEMO: string; FWORKAREA: string; public FListDoct: TStringList; protected procedure SetParameters;override; function GetStrInsert:string;override; function GetStrUpdate:string;override; function GetStrDelete:string;override; public function GetStrsIndex:string;override; public function GetNextIdex:Integer;overload; function GetNextIdex(AUniConnection:TUniConnection):Integer;overload; public function CheckExist(AUniConnection:TUniConnection):Boolean;override; public destructor Destroy; override; constructor Create; published property UNITLINK: string read FUNITLINK write FUNITLINK; property WORKIDEX: Integer read FWORKIDEX write FWORKIDEX; property WORKNAME: string read FWORKNAME write FWORKNAME; property WORKCODE: string read FWORKCODE write FWORKCODE; property WORKMOBL: string read FWORKMOBL write FWORKMOBL; property WORKCALL: string read FWORKCALL write FWORKCALL; property WORKMEMO: string read FWORKMEMO write FWORKMEMO; property WORKAREA: string read FWORKAREA write FWORKAREA; public class function ReadDS(AUniQuery:TUniQuery):TUniEngine;override; class procedure ReadDS(AUniQuery:TUniQuery;var Result:TUniEngine);override; class function CopyIt(AWORK:TWORK):TWORK;overload; class procedure CopyIt(AWORK:TWORK;var Result:TWORK);overload; end; implementation uses Class_KzUtils; { TWORK } procedure TWORK.SetParameters; begin inherited; with FUniSQL.Params do begin case FOptTyp of otAddx: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('WORK_IDEX').Value := WORKIDEX; ParamByName('WORK_NAME').Value := WORKNAME; ParamByName('WORK_CODE').Value := WORKCODE; ParamByName('WORK_MOBL').Value := WORKMOBL; ParamByName('WORK_CALL').Value := WORKCALL; ParamByName('WORK_MEMO').Value := WORKMEMO; ParamByName('WORK_AREA').Value := WORKAREA; end; otEdit: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('WORK_IDEX').Value := WORKIDEX; ParamByName('WORK_NAME').Value := WORKNAME; ParamByName('WORK_CODE').Value := WORKCODE; ParamByName('WORK_MOBL').Value := WORKMOBL; ParamByName('WORK_CALL').Value := WORKCALL; ParamByName('WORK_MEMO').Value := WORKMEMO; ParamByName('WORK_AREA').Value := WORKAREA; end; otDelt: begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('WORK_IDEX').Value := WORKIDEX; end; end; end; end; function TWORK.CheckExist(AUniConnection: TUniConnection): Boolean; begin Result:=CheckExist('TBL_WORK',['UNIT_LINK',UNITLINK,'WORK_IDEX',WORKIDEX],AUniConnection); end; function TWORK.GetNextIdex: Integer; begin end; function TWORK.GetNextIdex(AUniConnection: TUniConnection): Integer; begin Result:=CheckField('WORK_IDEX',TablNam,['UNIT_LINK',FUNITLINK],AUniConnection); end; function TWORK.GetStrDelete: string; begin Result:='DELETE FROM $TBL_WORK WHERE UNIT_LINK=:UNIT_LINK AND WORK_IDEX=:WORK_IDEX'; Result:=StringReplace(Result,'$TBL_WORK',TablNam,[rfReplaceAll]); end; function TWORK.GetStrInsert: string; begin Result:='INSERT INTO $TBL_WORK' +' ( UNIT_LINK, WORK_IDEX, WORK_NAME, WORK_CODE, WORK_MOBL' +' , WORK_CALL, WORK_MEMO, WORK_AREA)' +' VALUES' +' (:UNIT_LINK,:WORK_IDEX,:WORK_NAME,:WORK_CODE,:WORK_MOBL' +' ,:WORK_CALL,:WORK_MEMO,:WORK_AREA)'; Result:=StringReplace(Result,'$TBL_WORK',TablNam,[rfReplaceAll]); end; function TWORK.GetStrsIndex: string; begin Result:=Format('%S-%D',[UNITLINK,WORKIDEX]); end; function TWORK.GetStrUpdate: string; begin Result:='UPDATE $TBL_WORK SET' +' WORK_NAME=:WORK_NAME,' +' WORK_CODE=:WORK_CODE,' +' WORK_MOBL=:WORK_MOBL,' +' WORK_CALL=:WORK_CALL,' +' WORK_MEMO=:WORK_MEMO,' +' WORK_AREA=:WORK_AREA' +' WHERE UNIT_LINK=:UNIT_LINK' +' AND WORK_IDEX=:WORK_IDEX'; Result:=StringReplace(Result,'$TBL_WORK',TablNam,[rfReplaceAll]); end; constructor TWORK.Create; begin TablNam :='TBL_WORK'; UNITLINK :='-1'; FListDoct:=nil; end; destructor TWORK.Destroy; begin if FListDoct<>nil then TKzUtils.TryFreeAndNil(FListDoct); inherited; end; class function TWORK.ReadDS(AUniQuery: TUniQuery): TUniEngine; begin Result:=TWORK.Create; with TWORK(Result) do begin UNITLINK:=AUniQuery.FieldByName('UNIT_LINK').AsString; WORKIDEX:=AUniQuery.FieldByName('WORK_IDEX').AsInteger; WORKNAME:=AUniQuery.FieldByName('WORK_NAME').AsString; WORKCODE:=AUniQuery.FieldByName('WORK_CODE').AsString; WORKMOBL:=AUniQuery.FieldByName('WORK_MOBL').AsString; WORKCALL:=AUniQuery.FieldByName('WORK_CALL').AsString; WORKMEMO:=AUniQuery.FieldByName('WORK_MEMO').AsString; WORKAREA:=AUniQuery.FieldByName('WORK_AREA').AsString; end; end; class procedure TWORK.ReadDS(AUniQuery: TUniQuery; var Result: TUniEngine); begin if Result=nil then Exit; with TWORK(Result) do begin UNITLINK:=AUniQuery.FieldByName('UNIT_LINK').AsString; WORKIDEX:=AUniQuery.FieldByName('WORK_IDEX').AsInteger; WORKNAME:=AUniQuery.FieldByName('WORK_NAME').AsString; WORKCODE:=AUniQuery.FieldByName('WORK_CODE').AsString; WORKMOBL:=AUniQuery.FieldByName('WORK_MOBL').AsString; WORKCALL:=AUniQuery.FieldByName('WORK_CALL').AsString; WORKMEMO:=AUniQuery.FieldByName('WORK_MEMO').AsString; WORKAREA:=AUniQuery.FieldByName('WORK_AREA').AsString; end; end; class function TWORK.CopyIt(AWORK: TWORK): TWORK; begin Result:=TWORK.Create; TWORK.CopyIt(AWORK,Result) end; class procedure TWORK.CopyIt(AWORK:TWORK;var Result:TWORK); begin if Result=nil then Exit; Result.UNITLINK:=AWORK.UNITLINK; Result.WORKIDEX:=AWORK.WORKIDEX; Result.WORKNAME:=AWORK.WORKNAME; Result.WORKCODE:=AWORK.WORKCODE; Result.WORKMOBL:=AWORK.WORKMOBL; Result.WORKCALL:=AWORK.WORKCALL; Result.WORKMEMO:=AWORK.WORKMEMO; Result.WORKAREA:=AWORK.WORKAREA; end; end.
unit Objekt.Logger; interface uses SysUtils, Classes, Log4d; type TLoggerObj = class private fLogPath: string; fDebugLog: log4d.TLogLogger; fBackupLog: log4d.TLogLogger; fDienstLog: log4d.TLogLogger; protected public constructor Create; destructor Destroy; override; procedure Init; property LogPath: string read fLogPath; procedure DebugInfo(aMsg: string); procedure BackupInfo(aMsg: string); procedure DienstInfo(aMsg: string); function getLogger: log4d.TLogLogger; function getLoggerIni: log4d.TLogLogger; function getLoggerDienst: log4d.TLogLogger; end; implementation { TLoggerObj } uses Allgemein.System, Allgemein.Types, vcl.Forms, Winapi.ShlObj; constructor TLoggerObj.Create; begin fDebugLog := nil; fBackupLog := nil; fDienstLog := nil; if (not FileExists(ExtractFilePath(Application.ExeName) + 'log4dBackup.props')) then exit; TLogPropertyConfigurator.Configure(ExtractFilePath(Application.ExeName) + 'log4dBackup.props'); fLogPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'LogFiles\'; //fLogPath := GetShellFolder(CSIDL_APPDATA) + '\Optima\TapiLogFiles\'; if not DirectoryExists(fLogPath) then ForceDirectories(fLogPath); fDebugLog := TLogLogger.GetLogger('Debug'); fBackupLog := TLogLogger.GetLogger('Backup'); fDienstLog := TLogLogger.GetLogger('Dienst'); if fDebugLog.Appenders.Count = 1 then (fDebugLog.Appenders[0] as ILogRollingFileAppender).renameLogfile(fLogPath + 'Debug.log'); //<-- Pfad zuweisen if fBackupLog.Appenders.Count = 1 then (fBackupLog.Appenders[0] as ILogRollingFileAppender).renameLogfile(fLogPath + 'Backup.log'); //<-- Pfad zuweisen if fDienstLog.Appenders.Count = 1 then (fDienstLog.Appenders[0] as ILogRollingFileAppender).renameLogfile(fLogPath + 'Dienst.log'); //<-- Pfad zuweisen end; destructor TLoggerObj.Destroy; begin inherited; end; procedure TLoggerObj.DienstInfo(aMsg: string); begin if fDienstLog = nil then exit; fDienstLog.Info(aMsg); end; function TLoggerObj.getLogger: log4d.TLogLogger; begin Result := fDebugLog; end; function TLoggerObj.getLoggerDienst: log4d.TLogLogger; begin Result := fDienstLog; end; function TLoggerObj.getLoggerIni: log4d.TLogLogger; begin Result := fBackupLog; end; procedure TLoggerObj.DebugInfo(aMsg: string); begin if fDebugLog = nil then exit; fDebugLog.Info(aMsg); end; procedure TLoggerObj.BackupInfo(aMsg: string); begin if fBackupLog = nil then exit; fBackupLog.Info(aMsg); end; procedure TLoggerObj.Init; begin end; end.
unit uFuncionario; interface type TFuncionario = class private FNome: String; FCPF: String; FSalario: Double; procedure setNome(value: String); procedure setCPF(value: String); procedure setSalario(value: Double); function getNome: String; function getCPF: String; function getSalario: Double; public property Nome: String read getNome write setNome; property CPF: String read getCPF write setCPF; property Salario: Double read getSalario write setSalario; end; implementation { TFuncionario } function TFuncionario.getCPF: String; begin Result := FCPF; end; function TFuncionario.getNome: String; begin Result := FNome; end; function TFuncionario.getSalario: Double; begin Result := FSalario; end; procedure TFuncionario.setCPF(value: String); begin FCPF := value; end; procedure TFuncionario.setNome(value: String); begin FNome := value; end; procedure TFuncionario.setSalario(value: Double); begin FSalario := value; end; end.
Unit Square; { Отличается от Unit Square1 ошибками - нет Constructor } { и Virtual. Используется в программе Square15b. } Interface Uses Graph; Type TLocation = object X, Y: Integer; Procedure Init(InitX, InitY:Integer); Procedure PutX(AX: Integer); Procedure PutY(AY: Integer); Function GetX:Integer; Function GetY:Integer; End; TSquare = object(TLocation) Side: Word; Procedure Init(InitX, InitY:Integer; InitSide: Word); Procedure PutX(AX: Integer); Procedure PutY(AY: Integer); Function GetSide: Word; Procedure PutSide(ASide: Word); Procedure Show; Procedure Hide; Procedure MoveTo(NewX, NewY:Integer); End; Implementation {Реализация методов класса TLocation} Procedure TLocation.Init(InitX, InitY:Integer); Begin X:= InitX; Y:= InitY; End; Procedure TLocation.PutX(AX: Integer); Begin X:= AX; End; Procedure TLocation.PutY(AY: Integer); Begin Y:= AY; End; Function TLocation.GetX:Integer; Begin GetX:= X; End; Function TLocation.GetY:Integer; Begin GetY:= Y; End; {Реализация методов класса TSquare} Procedure TSquare.Init(InitX, InitY:Integer; InitSide: Word); Begin TLocation.Init(InitX, InitY); Side:=InitSide; End; Procedure TSquare.Show; Begin Rectangle(X,Y,X+Side,Y+Side); End; Procedure TSquare.Hide; Var color:Word; Begin color:=GetColor; SetColor(GetBkColor()); Rectangle(X,Y,X+Side,Y+Side); SetColor(color); End; Procedure TSquare.PutX(AX: Integer); Begin Hide; inherited; Show; End; Procedure TSquare.PutY(AY: Integer); Begin Hide; inherited; Show; End; Function TSquare.GetSide:Word; Begin GetSide:= Side; End; Procedure TSquare.PutSide(ASide:Word); Begin Hide; Side:= ASide; Show; End; Procedure TSquare.MoveTo(NewX, NewY:Integer); Begin Hide; X:= NewX; Y:= NewY; Show; End; End.
unit MeshSmoothFaceColours; interface uses MeshProcessingBase, Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector, MeshColourCalculator; {$INCLUDE source/Global_Conditionals.inc} type TMeshSmoothFaceColours = class (TMeshProcessingBase) protected procedure MeshSmoothOperation(var _Colours: TAVector4f; const _FaceColours: TAVector4f; const _Vertices: TAVector3f; _NumVertices: integer; const _Faces: auint32; _VerticesPerFace: integer; const _NeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32; var _Calculator: TMeshColourCalculator); procedure DoMeshProcessing(var _Mesh: TMesh); override; public DistanceFunction: TDistanceFunc; end; implementation uses MeshPluginBase, GLConstants, NeighborhoodDataPlugin, MeshBRepGeometry; procedure TMeshSmoothFaceColours.DoMeshProcessing(var _Mesh: TMesh); var Calculator : TMeshColourCalculator; NeighborhoodPlugin: PMeshPluginBase; NeighborDetector: TNeighborDetector; VertexEquivalences: auint32; NumVertices: integer; MyFaces: auint32; MyFaceColours: TAVector4f; begin Calculator := TMeshColourCalculator.Create; NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR); _Mesh.Geometry.GoToFirstElement; if NeighborhoodPlugin <> nil then begin if TNeighborhoodDataPlugin(NeighborhoodPlugin^).UseQuadFaces then begin NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceNeighbors; MyFaces := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaces; MyFaceColours := TNeighborhoodDataPlugin(NeighborhoodPlugin^).QuadFaceColours; end else begin NeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).FaceNeighbors; _Mesh.Geometry.GoToFirstElement; MyFaces := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Faces; MyFaceColours := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Colours; end; VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences; NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount; end else begin NeighborDetector := TNeighborDetector.Create(C_NEIGHBTYPE_VERTEX_FACE); NeighborDetector.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1); VertexEquivalences := nil; NumVertices := High(_Mesh.Vertices)+1; MyFaces := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Faces; MyFaceColours := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Colours; end; MeshSmoothOperation(_Mesh.Colours,MyFaceColours,_Mesh.Vertices,NumVertices,MyFaces,(_Mesh.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,NeighborDetector,VertexEquivalences,Calculator); if NeighborhoodPlugin = nil then begin NeighborDetector.Free; end; Calculator.Free; _Mesh.ForceRefresh; end; procedure TMeshSmoothFaceColours.MeshSmoothOperation(var _Colours: TAVector4f; const _FaceColours: TAVector4f; const _Vertices: TAVector3f; _NumVertices: integer; const _Faces: auint32; _VerticesPerFace: integer; const _NeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32; var _Calculator: TMeshColourCalculator); var OriginalColours,VertColours : TAVector4f; begin SetLength(OriginalColours,High(_Colours)+1); SetLength(VertColours,High(_Vertices)+1); BackupVector4f(_Colours,OriginalColours); _Calculator.GetVertexColoursFromFaces(VertColours,OriginalColours,_Vertices,_NumVertices,_Faces,_VerticesPerFace,_NeighborDetector,_VertexEquivalences,DistanceFunction); _Calculator.GetFaceColoursFromVertexes(VertColours,_Colours,_Faces,_VerticesPerFace); FilterAndFixColours(_Colours); // Free memory SetLength(VertColours,0); SetLength(OriginalColours,0); end; end.
unit Servers; interface uses Classes, LrProject; type TServerTarget = ( stDisk, stFTP ); // TServerItem = class(TLrProjectItem) private FRoot: string; FHost: string; FFTPHost: string; FFTPPassword: string; FFTPUser: string; FTarget: TServerTarget; protected procedure SetFTPHost(const Value: string); procedure SetFTPPassword(const Value: string); procedure SetFTPUser(const Value: string); procedure SetHost(const Value: string); procedure SetRoot(const Value: string); procedure SetTarget(const Value: TServerTarget); published property FTPHost: string read FFTPHost write SetFTPHost; property FTPUser: string read FFTPUser write SetFTPUser; property FTPPassword: string read FFTPPassword write SetFTPPassword; property Host: string read FHost write SetHost; property Root: string read FRoot write SetRoot; property Target: TServerTarget read FTarget write SetTarget; end; // TServersItem = class(TLrProjectItem) private FDefaultServer: TServerItem; FDefaultServerName: string; protected function GetDefaultServer: TServerItem; function GetServers(inIndex: Integer): TServerItem; procedure SetDefaultServer(const Value: TServerItem); procedure SetDefaultServerName(const Value: string); public constructor Create; override; property DefaultServer: TServerItem read GetDefaultServer write SetDefaultServer; property Servers[inIndex: Integer]: TServerItem read GetServers; default; published property DefaultServerName: string read FDefaultServerName write SetDefaultServerName; end; implementation { TServerItem } procedure TServerItem.SetFTPHost(const Value: string); begin FFTPHost := Value; end; procedure TServerItem.SetFTPPassword(const Value: string); begin FFTPPassword := Value; end; procedure TServerItem.SetFTPUser(const Value: string); begin FFTPUser := Value; end; procedure TServerItem.SetHost(const Value: string); begin FHost := Value; end; procedure TServerItem.SetRoot(const Value: string); begin FRoot := Value; Source := Root; end; procedure TServerItem.SetTarget(const Value: TServerTarget); begin FTarget := Value; end; { TServersItem } constructor TServersItem.Create; begin inherited; end; function TServersItem.GetDefaultServer: TServerItem; begin if (FDefaultServer = nil) and (Count > 0) then begin FDefaultServer := TServerItem(Find(FDefaultServerName)); if FDefaultServer = nil then DefaultServer := Servers[0]; end; Result := FDefaultServer end; function TServersItem.GetServers(inIndex: Integer): TServerItem; begin Result := TServerItem(Items[inIndex]); end; procedure TServersItem.SetDefaultServer(const Value: TServerItem); begin FDefaultServer := Value; FDefaultServerName := Value.Name; end; procedure TServersItem.SetDefaultServerName(const Value: string); begin FDefaultServer := nil; FDefaultServerName := Value; end; initialization RegisterClass(TServerItem); RegisterClass(TServersItem); end.
unit DSA.LeetCode._804; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DSA.Tree.BSTSet, DSA.Interfaces.Comparer; type TSolution = class public class function uniqueMorseRepresentations(words: array of string): integer; end; type TBSTSet_str = specialize TBSTSet<string, specialize TComparer<string>>; procedure main; implementation procedure main; var words: array of string; begin words := ['gin', 'zen', 'gig', 'msg']; Writeln(TSolution.uniqueMorseRepresentations(words)); end; { TSolution } class function TSolution.uniqueMorseRepresentations (words: array of string): integer; const codes: array of string = ('.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..'); var BSTSet: TBSTSet_str; i: integer; c: char; s: string; res: TStringBuilder; begin BSTSet := TBSTSet_str.Create; try for s in words do begin for c in s do begin res := TStringBuilder.Create; i := Ord(c) - Ord('a'); res.Append(codes[i]); end; BSTSet.Add(res.ToString); FreeAndNil(res); end; Result := BSTSet.GetSize; finally BSTSet.Free; end; end; end.
unit Class_Sell; //YXC_2010_04_21_20_56_43 //TBL_SELL //销售类 interface uses Classes,SysUtils,ADODB,Class_DBPool,Class_SellRecd; type TSell=class(TObject) public UnitLink:string; //*单位编码链 SellIdex:Integer;//*销售序列 SellCost:Double; //销售金额 UserCode:string; //销售人员 SellDate:TDateTime; //销售时间 SellMemo:string; //销售备注 public StrsRecd:TStringList; public procedure InsertDB;overload; procedure InsertDB(AADOCon:TADOConnection);overload; procedure DeleteDB;overload; procedure DeleteDB(AADOCon:TADOConnection);overload; function GetNextIdex:Integer; public procedure SaveToDB(AADOCon:TADOConnection); public constructor Create; public class function ReadDS(AADODS:TADODataSet):TSell;overload; class function StrsDB(ASQL:string):TStringList;overload; class function StrsDB(AADOCon:TADOConnection):TStringList;overload; class function StrsDB(AADOCon:TADOConnection;ASQL:string):TStringList;overload; end; implementation uses UtilLib; { TSell } constructor TSell.Create; begin UnitLink:='0001-0001'; end; procedure TSell.DeleteDB(AADOCon: TADOConnection); begin end; procedure TSell.DeleteDB; var ADOCon:TADOConnection; begin try ADOCon:=TDBPool.GetConnect(); DeleteDB(ADOCon); finally FreeAndNil(ADOCon); end; end; procedure TSell.InsertDB; var ADOCon:TADOConnection; begin try ADOCon:=TDBPool.GetConnect(); InsertDB(ADOCon); finally FreeAndNil(ADOCon); end; end; function TSell.GetNextIdex: Integer; var ADOCon:TADOConnection; begin try ADOCon:=TDBPool.GetConnect(); Result:=TryCheckField(ADOCon,'SELL_IDEX','TBL_SELL',['UNIT_LINK',UnitLink]); finally FreeAndNil(ADOCon); end; end; procedure TSell.InsertDB(AADOCon: TADOConnection); var ADOCmd : TADOCommand; begin try ADOCmd := TADOCommand.Create(nil); ADOCmd.Connection := AADOCon; ADOCmd.Prepared := True; with ADOCmd do begin CommandText :='INSERT INTO TBL_SELL ' + ' (UNIT_LINK, SELL_IDEX,SELL_COST,USER_CODE,SELL_DATE,SELL_MEMO)' + ' VALUES(:UNIT_LINK, :SELL_IDEX,:SELL_COST,:USER_CODE,:SELL_DATE,:SELL_MEMO)'; with Parameters do begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('SELL_IDEX').Value := SELLIDEX; ParamByName('SELL_COST').Value := SELLCOST; ParamByName('USER_CODE').Value := USERCODE; ParamByName('SELL_DATE').Value := SELLDATE; ParamByName('SELL_MEMO').Value := SELLMEMO; end; Execute; end; finally FreeAndNil(ADOCmd); end; end; class function TSell.ReadDS(AADODS: TADODataSet): TSell; begin Result:=TSell.Create; with Result do begin UNITLINK := Trim(AADODS.FieldByName('UNIT_LINK').AsString); SELLIDEX := AADODS.FieldByName('SELL_IDEX').AsInteger; SellCost := AADODS.FieldByName('SELL_COST').AsInteger; SellDate := AADODS.FieldByName('SELL_DATE').AsDateTime; UserCode := Trim(AADODS.FieldByName('USER_CODE').AsString); SELLMEMO := Trim(AADODS.FieldByName('SELL_MEMO').AsString); end; end; class function TSell.StrsDB(ASQL: string): TStringList; var ADOCon:TADOConnection; begin try ADOCon:=TDBPool.GetConnect(); Result:=StrsDB(ADOCon,ASQL); finally FreeAndNil(ADOCon); end; end; class function TSell.StrsDB(AADOCon: TADOConnection): TStringList; begin raise Exception.Create('函数维护:ERROR:;LINE:'); end; class function TSell.StrsDB(AADOCon: TADOConnection; ASQL: string): TStringList; var ADODS:TADODataSet; AObj :TSell; begin Result:=nil; try ADODS:=TADODataSet.Create(nil); ADODS.Connection:=AADOCon; ADODS.Prepared:=True; if ASQL='' then raise Exception.Create('ASQL=NIL'); ADODS.CommandText:=ASQL; ADODS.Open; ADODS.First; if ADODS.RecordCount=0 then Exit; Result:=TStringList.Create; while not ADODS.Eof do begin AObj:=ReadDS(ADODS); Result.AddObject('',AObj); ADODS.Next; end; finally FreeAndNil(ADODS); end; end; procedure TSell.SaveToDB(AADOCon: TADOConnection); var I:Integer; ARecd:TSellRecd; begin InsertDB(AADOCon); if (StrsRecd=nil) or (StrsRecd.Count=0) then Exit; for I:=0 to StrsRecd.Count-1 do begin ARecd:=TSellRecd(StrsRecd.Objects[I]); ARecd.InsertDB(AADOCon); end; end; end.
unit docs.community; interface uses Horse, Horse.GBSwagger; procedure registry(); implementation uses schemas.classes; procedure registry(); begin Swagger .Path('comunidade/{id_comunidade}') .Tag('Comunidades') .GET('listar uma comunidade', 'listar comunidade especifica') .AddParamPath('id_Comunidade', 'id_comunidade') .Schema(SWAG_INTEGER) .Required(true) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200) .Schema(TCommunity) .&End .AddResponse(404, 'comunidade não encontrada') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('comunidade') .Tag('Comunidades') .GET('listar regiões com paginação', 'listagem de comunidades com paginação e filtros') .Description('o query param find representa o nome de uma coluna do banco e value o valor que sera colocado no criterio de filtro exemplo: find=id&value=10') .AddParamQuery('page', 'page') .Schema(SWAG_INTEGER) .&End .AddParamQuery('limit', 'limit') .Schema(SWAG_INTEGER) .&End .AddParamQuery('find', 'find') .Schema(SWAG_STRING) .&End .AddParamQuery('value', 'value') .Schema(SWAG_STRING) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200) .Schema(TCommunityPagination) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('comunidade') .Tag('Comunidades') .Post('criar comunidade', 'criar uma nova comunidade') .AddParamBody .Schema(TRegion) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(201) .Schema(TCommunity) .&End .AddResponse(404, 'região não encontrada') .Schema(TMessage) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(SWAG_STRING) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('comunidade/{id_comunidade}') .Tag('Comunidades') .Put('alterar comunidade', 'alteração de uma comunidade') .AddParamPath('id_comunidade', 'id_comunidade') .Schema(SWAG_INTEGER) .&end .AddParamBody .Schema(TCommunity) .&End .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200) .Schema(TRegion) .&End .AddResponse(404, 'comunidade não encontrada') .Schema(TMessage) .&End .AddResponse(401, 'token não encontrado ou invalido') .Schema(SWAG_STRING) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('comunidade/{id_comunidade}') .Tag('Comunidades') .Delete('deletar comunidade', 'deletar uma comunidade') .AddParamPath('id_comunidade', 'id_comunidade') .Schema(SWAG_INTEGER) .&end .AddParamHeader('Authorization', 'bearer token jwt') .Schema(SWAG_STRING) .&End .AddResponse(200, 'comunidade deletada com sucesso') .Schema(TMessage) .&End .AddResponse(404, 'comunidade não encontrada') .Schema(TMessage) .&End .AddResponse(401, 'token não encontrado ou invalido, não foi possivel deletar a comunidade') .Schema(SWAG_STRING) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { SOAP Support } { } { Copyright (c) 2001 Borland Software Corporation } { } { Русификация: 2001-02 Polaris Software } { http://polesoft.da.ru } {*******************************************************} unit SOAPConst; interface uses TypInfo, XMLSchema; const {$IFNDEF VER140} SHTTPPrefix = 'http://'; { Do not localize } SContentId = 'Content-ID'; { Do not localize } SContentLocation = 'Content-Location'; { Do not localize } SContentLength = 'Content-Length'; { Do not localize } SContentType = 'Content-Type'; { Do not localize } SWSDLMIMENamespace = 'http://schemas.xmlsoap.org/wsdl/mime/';{ Do not location } SBorlandMimeBoundary = 'MIME_boundaryB0R9532143182121'; SSoapXMLHeader = '<?xml version="1.0" encoding=''UTF-8''?>'; { Do not localize } SUTF8 = 'UTF-8'; { Do not localize } ContentTypeTemplate = 'Content-Type: %s'; { Do not localize } ContentTypeApplicationBinary = 'application/binary'; { Do not localize } SBinaryEncoding = 'binary'; { Do not localize } S8BitEncoding = '8bit'; { Do not localize } ContentTypeTextPlain = 'text/plain'; { Do not localize } SCharacterEncodingFormat = 'Content-transfer-encoding: %s'; { Do not localize } SCharacterEncoding = 'Content-transfer-encoding'; { Do not localize } SBoundary = 'boundary='; { Do not localize } SMultiPartRelated = 'multipart/related'; { Do not localize } SMultiPartRelatedNoSlash = 'multipartRelated'; { Do not localize } ContentHeaderMime = SMultiPartRelated + '; boundary=%s'; { Do not localize } SStart = '; start="<%s>"'; { Do not localize} SBorlandSoapStart = 'http://www.borland.com/rootpart.xml'; { Do not localize} SAttachmentIdPrefix = 'cid:'; { Do not localize } MimeVersion = 'MIME-Version: 1.0'; {$ELSE} SSoapXMLHeader = '<?xml version="1.0" encoding=''UTF-8''?>'; { do not localize} SUTF8 = 'UTF-8'; { Do not localize} ContentHeaderUTF8 = 'Content-Type: text/xml; charset="utf-8"'; { Do not localize } ContentHeaderNoUTF8 = 'Content-Type: text/xml'; { Do not localize } {$ENDIF} sTextHtml = 'text/html'; { Do not localize } sTextXML = 'text/xml'; { Do not localize } ContentTypeUTF8 = 'text/xml; charset="utf-8"'; { Do not localize } ContentTypeNoUTF8 = 'text/xml'; { Do not localize } SSoapNameSpace = 'http://schemas.xmlsoap.org/soap/envelope/'; { do not localize} SXMLNS = 'xmlns'; { do not localize} SSoapEncodingAttr = 'encodingStyle'; { do not localize} SSoap11EncodingS5 = 'http://schemas.xmlsoap.org/soap/encoding/'; { do not localize} SSoapEncodingArray = 'Array'; { do not localize} SSoapEncodingArrayType = 'arrayType'; { do not localize} SSoapHTTPTransport = 'http://schemas.xmlsoap.org/soap/http'; { do not localize} SSoapBodyUseEncoded = 'encoded'; { do not localize} SSoapBodyUseLiteral = 'literal'; { do not localize} SSoapEnvelope = 'Envelope'; { do not localize} SSoapHeader = 'Header'; { do not localize} SSoapBody = 'Body'; { do not localize} SSoapResponseSuff = 'Response'; { do not localize} {$IFNDEF VER140} SRequired = 'required'; { do not localize } {$ELSE} SSoapMustUnderstand = 'mustUnderstand'; { do not localize} {$ENDIF} SSoapActor = 'actor'; { do not localize} {$IFNDEF VER140} STrue = 'true'; { do not localize} {$ENDIF} SSoapServerFaultCode = 'Server'; { do not localize} SSoapServerFaultString = 'Server Error'; { do not localize} SSoapFault = 'Fault'; { do not localize} SSoapFaultCode = 'faultcode'; { do not localize} SSoapFaultString = 'faultstring'; { do not localize} SSoapFaultActor = 'faultactor'; { do not localize} SSoapFaultDetails = 'detail'; { do not localize} {$IFNDEF VER140} SFaultCodeMustUnderstand = 'MustUnderstand'; { do not localize} {$ENDIF} SHTTPSoapAction = 'SOAPAction'; { do not localize} {$IFNDEF VER140} SHeaderMustUnderstand = 'mustUnderstand'; { do not localize} SHeaderActor = 'actor'; { do not localize} SActorNext= 'http://schemas.xmlsoap.org/soap/actor/next';{ do not localize} {$ENDIF} SSoapType = 'type'; { do not localize} SSoapResponse = 'Response'; { do not localize} SDefaultReturnName = 'return'; { do not localize} SDefaultResultName = 'result'; { do not localize} sNewPage = 'WebServices'; { do not localize} // absolete D6 Update Pack 2 SXMLID = 'id'; { do not localize} SXMLHREF = 'href'; { do not localize} SSoapNULL = 'NULL'; { do not localize} {$IFNDEF VER140} SSoapNIL = 'nil'; { do not localize} {$ENDIF} SHREFPre = '#'; { do not localize} SArrayIDPre = 'Array-'; { do not localize} SDefVariantElemName = 'V'; { do not localize} {$IFNDEF VER140} SDefaultBaseURI = 'thismessage:/'; { do not localize} {$ENDIF} SDelphiTypeNamespace = 'http://www.borland.com/namespaces/Delphi/Types'; { do not localize} SBorlandTypeNamespace= 'http://www.borland.com/namespaces/Types'; { do not localize} SOperationNameSpecifier = '%operationName%'; { Do not localize } SDefaultReturnParamNames= 'Result;Return'; { Do not localize } sReturnParamDelimiters = ';,/:'; { Do not localize } KindNameArray: array[tkUnknown..tkDynArray] of string = ('Unknown', 'Integer', 'Char', 'Enumeration', 'Float', { do not localize } 'String', 'Set', 'Class', 'Method', 'WChar', 'LString', 'WString', { do not localize } 'Variant', 'Array', 'Record', 'Interface', 'Int64', 'DynArray'); { do not localize } SSoapNameSpacePre = 'SOAP-ENV'; { do not localize } SXMLSchemaNameSpacePre = 'xsd'; { do not localize} SXMLSchemaInstNameSpace99Pre = 'xsi'; { do not localize} SSoapEncodingPre = 'SOAP-ENC'; { do not localize} {$IFNDEF VER140} {$IFDEF D6_STYLE_COLORS} sDefaultColor = '#006699'; sIntfColor = '#006699'; sTblHdrColor = '#CCCC99'; sTblColor1 = '#FFFFCC'; sTblColor0 = '#CCCC99'; sBkgndColor = '#CCCC99'; sTipColor = '#666666'; sWSDLColor = '#666699'; sOFFColor = '#A0A0A0'; sNavBarColor = '#006699'; sNavBkColor = '#cccccc'; {$ELSE} sDefaultColor = '#333333'; sIntfColor = '#660000'; sTblHdrColor = '#CCCC99'; sTblColor1 = '#f5f5dc'; sTblColor0 = '#d9d4aa'; sBkgndColor = '#d9d4aa'; sTipColor = '#666666'; sWSDLColor = '#990000'; sOFFColor = '#A0A0A0'; sNavBarColor = '#660000'; sNavBkColor = '#f5f5dc'; {$ENDIF} {$ENDIF} HTMLStylBeg = '<style type="text/css"><!--' + sLineBreak; HTMLStylEnd = '--></style>' + sLineBreak; BodyStyle1 = 'body {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; }' + sLineBreak; BodyStyle2 = 'body {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; margin-left: 0px; margin-top: 0px; margin-right: 0px; }' + sLineBreak; {$IFNDEF VER140} OtherStyles = 'h1 {color: '+sDefaultColor+'; font-size: 18pt; font-style: normal; font-weight: bold; }' + sLineBreak + 'h2 {color: '+sDefaultColor+'; font-size: 14pt; font-style: normal; font-weight: bold; }' + sLineBreak + 'h3 {color: '+sDefaultColor+'; font-size: 12pt; font-style: normal; font-weight: bold; }' + sLineBreak + '.h1Style {color: '+sDefaultColor+'; font-size: 18pt; font-style: normal; font-weight: bold; }' + sLineBreak + '.TblRow {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal; }' + sLineBreak + '.TblRow1 {color: '+sDefaultColor+'; background-color: '+sTblColor1+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-weight: normal; }' + sLineBreak + '.TblRow0 {color: '+sDefaultColor+'; background-color: '+sTblColor0+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-weight: normal; }' + sLineBreak + '.TblHdr {color: '+sTblHdrColor+ '; background-color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: bold; text-align: center;}' + sLineBreak + '.IntfName {color: '+sIntfColor + '; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: bold; }' + sLineBreak + '.MethName {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; text-decoration: none; }' + sLineBreak + '.ParmName {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; text-decoration: none; }' + sLineBreak + '.Namespace {color: '+sDefaultColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-style: italic; }' + sLineBreak + '.WSDL {color: '+sWSDLColor+ '; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; }' + sLineBreak + '.MainBkgnd {background-color : '+sBkgndColor+'; }' + sLineBreak + '.Info {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold; }' + sLineBreak + '.NavBar {color: '+sNavBarColor+'; background-color: '+sNavBkColor+'; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold;text-decoration: none; }'+ sLineBreak + '.Off {color: '+sOFFColor+'; }' + sLineBreak + '.Tip {color: '+sTipColor+'; font-family : Verdana, Arial, Helvetica, sans-serif; font-weight : normal; font-size : 9pt; }' + sLineBreak; {$ELSE} OtherStyles = 'h1 {color: #006699; font-size: 18pt; font-style: normal; font-weight: bold; }' + sLineBreak + 'h2 {color: #006699; font-size: 14pt; font-style: normal; font-weight: bold; }' + sLineBreak + 'h3 {color: #006699; font-size: 12pt; font-style: normal; font-weight: bold; }' + sLineBreak + '.h1Style {color: #006699; font-size: 18pt; font-style: normal; font-weight: bold; }' + sLineBreak + '.TblRow {color: #006699; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal; }' + sLineBreak + '.TblRow1 {color: #006699; background-color: #FFFFCC; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-weight: normal; }' + sLineBreak + '.TblRow0 {color: #006699; background-color: #CCCC99; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-weight: normal; }' + sLineBreak + '.TblHdr {color: #CCCC99; background-color: #006699; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: bold; text-align: center;}' + sLineBreak + '.IntfName {color: #006699; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: bold; }' + sLineBreak + '.MethName {color: #006699; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; text-decoration: none; }' + sLineBreak + '.ParmName {color: #006699; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; text-decoration: none; }' + sLineBreak + '.Namespace {color: #006699; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 9pt; font-style: italic; }' + sLineBreak + '.WSDL {color: #666699; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; }' + sLineBreak + '.MainBkgnd {background-color : #CCCC99; }' + sLineBreak + '.Info {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; font-weight: bold; }' + sLineBreak + '.NavBar {color: #006699; background-color: #CCCCCC; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold;text-decoration: none; }'+ sLineBreak + '.Off {color: #A0A0A0; }' + sLineBreak + '.Tip {color: #666666; font-family : Verdana, Arial, Helvetica, sans-serif; font-weight : normal; font-size : 9pt; }' + sLineBreak; {$ENDIF} HTMLStyles = HTMLStylBeg + BodyStyle1 + OtherStyles + HTMLStylEnd; HTMLNoMargin= HTMLStylBeg + BodyStyle2 + OtherStyles + HTMLStylEnd; TableStyle = 'border=1 cellspacing=1 cellpadding=2 '; {$IFNDEF VER140} resourcestring HTMLContentLanguage = ''; // '<meta http-equiv="Content-Language" content="ja"><meta http-equiv="Content-Type" content="text/html; charset=shift_jis">'; const HTMLHead = '<html><head>'; HTMLServiceInspection = '<META name="serviceInspection" content="inspection.wsil">'; {resourcestring - these are getting truncated as resources currently resulting in bad HTML pages!!} HTMLTopPlain = HTMLHead + '</head><body>'; HTMLTop = HTMLHead + '</head>'+HTMLStyles+'<body>'; HTMLTopNoMargin = HTMLHead + '</head>'+HTMLNoMargin+'<body>'; HTMLTopTitleNoMargin = HTMLHead + '<title>%s</title></head>'+HTMLNoMargin+'<body>'; HTMLTopNoStyles = HTMLHead + '</head><body>'; HTMLTopTitle = HTMLHead + '<title>%s</title></head>'+HTMLStyles+'<body>'; HTMLTopTitleNoMarginWSIL = HTMLHead + HTMLServiceInspection + '<title>%s</title></head>'+HTMLNoMargin+'<body>'; const {$ELSE} HTMLTopPlain= '<html><head></head><body>'; HTMLTop = '<html><head></head>'+HTMLStyles+'<body>'; HTMLTopNoM = '<html><head></head>'+HTMLNoMargin+'<body>'; HTMLTopTNoM = '<html><head><title>%s</title></head>'+HTMLNoMargin+'<body>'; HTMLTopNS = '<html><head></head><body>'; HTMLTopTitle= '<html><head><title>%s</title></head>'+HTMLStyles+'<body>'; {$ENDIF} HTMLEnd = '</body></html>'; InfoTitle1 = '<table class="MainBkgnd" border=0 cellpadding=0 cellspacing=0 width="100%">' + '<tr><td>&nbsp;</td></tr>'; InfoTitle2 = '<tr><td class="h1Style" align="center">%s - %s</td></tr>' + '</table>'; TblCls: array[Boolean] of string = ('TblRow0', 'TblRow1'); sTblRow = 'TblRow'; sTblHdrCls = 'TblHdr'; sQueryStringIntf = 'intf'; { Do not localize } sQueryStringTypes= 'types'; { Do not localize } sNBSP = '&nbsp;'; { Do not localize } var XMLSchemaNameSpace: string = SXMLSchemaURI_2001; { Default namespace we publish under } XMLSchemaInstNameSpace: string = SXMLSchemaInstURI; resourcestring SUnsupportedEncodingSyle = 'Неподдерживаемый SOAP encodingStyle %s'; SInvalidSoapRequest = 'Неверный SOAP запрос'; {$IFNDEF VER140} SInvalidSoapResponse = 'Неверный SOAP ответ'; {$ENDIF} SMultiBodyNotSupported = 'Не поддерживаются многочисленные элементы тела'; SUnsupportedCC = 'Неподдерживаемое соглашение о вызовах: %s'; SUnsupportedCCIntfMeth = 'Удаленный вызов метода: неподдерживаемое соглашение о вызовах %s для метода %s через интерфейс %s'; SInvClassNotRegistered = 'Нет зарегистрированного вызываемого класса для обеспечения интерфейса %s (soap action/path) %s'; SInvInterfaceNotReg = 'Нет зарегистрированного интерфейса для soap action ''%s'''; SInvInterfaceNotRegURL = 'Нет зарегистрированного интерфейса для URL ''%s'''; SRemTypeNotRegistered = 'Remotable Type %s не зарегистрирован'; STypeMismatchInParam = 'Несовпадение типов в параметре %s'; SNoSuchMethod = 'Нет метода c именем ''%s'', поддерживаемого интерфейсом ''%s'''; SInterfaceNotReg = 'Интерфейс не зарегистрирован, UUID = %s'; SInterfaceNoRTTI = 'Интерфейс не имеет RTTI, UUID = %s'; SNoWSDL = 'Нет WSDL документа, связанного с WSDLView'; SWSDLError = 'Неверный WSDL документ ''%s'' - Пожалуйста, проверьте размещение и содержание!'#13#10'Ошибка: %s'; SEmptyWSDL = 'Пустой документ'; sNoWSDLURL = 'Не установлены свойства WSDL или URL в компоненте THTTPRIO. Вы должны установить свойство WSDL или URL перед вызовом Web Service'; sCantGetURL= 'Не могу возвратить URL endpoint для Service/Port ''%s''/''%s'' из WSDL ''%s'''; SDataTypeNotSupported = 'Тип данных TypeKind: %s не поддерживается как аргумент для удаленного вызова'; {$IFDEF LINUX} SNoMatchingDelphiType = 'Cоответствующий Kylix тип не найден для типа: URI = %s, Name = %s on Node %s'; {$ENDIF} SUnknownSOAPAction = 'Неизвестное SOAPAction %s'; {$IFNDEF VER140} SScalarFromTRemotableS = 'Классы, которые представляют скалярные типы, должны порождаться из TRemotableXS, а %s - нет'; SNoSerializeGraphs = 'Must enable multiref output for objects when serializing a graph of objects - (%s)'; SUnsuportedClassType = 'Преобразование из класса %s в SOAP не поддерживается - классы SOAP должны порождаться из TRemotable'; {$ELSE} SScalarFromTRemotableS = 'Классы, которые представляют скалярные типы, должны порождаться из TRemotable, а %s - нет'; SNoSerializeGraphs = 'Must allow multiref output for objects when serializing a graph of objects'; SUnsuportedClassType = 'Преобразование из класса %s в SOAP не поддерживается'; {$ENDIF} SUnexpectedDataType = 'Внутренняя ошибка: тип данных вида %s не ожидается в этом контексте'; {$IFNDEF VER140} SInvalidContentType = 'Получено неверное значение настройки Content-Type: %s - SOAP ожидает "text/xml"'; {$ENDIF} SArrayTooManyElem = 'Узел массива: %s имеет слишком много элементов'; SWrongDocElem = 'DocumentElement %s:%s ожидается, %s:%s найден'; STooManyParameters = 'Слишком много параметров в методе %s'; SArrayExpected = 'Тип Массив ожидается. Узел %s'; {$IFDEF VER140} SNoMultiDimVar = 'Многоразмерные вариантные массивы не поддерживаются в данной версии'; SNoURL = 'Нет установленных URL'; {$ENDIF} SNoInterfaceGUID = 'Класс %s не обеспечивает интерфейс GUID %s'; SNoArrayElemRTTI = 'Элемент массива типа %s не имеет RTTI'; SInvalidResponse = 'Неверный ответ SOAP'; SInvalidArraySpec = 'Неверный спецификация массива SOAP'; SCannotFindNodeID = 'Не могу найти узел по ссылке ID %s'; SNoNativeNULL = 'Опция не установлена для разрешения типу Native быть установленным в NULL'; SFaultCodeOnlyAllowed = 'Допускается только один элемент FaultCode'; SFaultStringOnlyAllowed = 'Допускается только один элемент FaultString'; SMissingFaultValue = 'Отсутствует элемент FaultString или FaultCode'; SNoInterfacesInClass = 'Invokable класс %s не обеспечивает интерфейсов'; SVariantCastNotSupported = 'Тип не может быть приведен как Variant'; SVarDateNotSupported = 'Тип varDate не поддерживается'; SVarDispatchNotSupported = 'Тип varDispatch не поддерживается'; SVarErrorNotSupported = 'Тип varError не поддерживается'; SVarVariantNotSupported = 'Тип varVariant не поддерживается'; {$IFNDEF VER140} SHeaderError = 'Ошибка выполнения заголовка (%s)%s'; {$ELSE} SHeaderError = 'Ошибка выполнения заголовка %s'; {$ENDIF} SMissingSoapReturn = 'Ответный пакет SOAP: ожидается результирующий элемент, получено "%s"'; SInvalidPointer = 'Неверный указатель'; SNoMessageConverter = 'Не установлен конвертер из Native в Message'; SNoMsgProcessingNode = 'Не установлен Message processing node'; SHeaderAttributeError = 'Заголовок Soap %s с атрибутом ''mustUnderstand'' set to true was not handled'; {IntfInfo} SNoRTTI = 'Интерфейс %s не имеет RTTI'; SNoRTTIParam = 'Параметр %s метода %s интерфейса %s не имеет RTTI'; {XSBuiltIns} SInvalidDateString = 'Неверная строка даты: %s'; SInvalidTimeString = 'Неверная строка времени: %s'; SInvalidHour = 'Неверный час: %d'; SInvalidMinute = 'Неверная минута: %d'; SInvalidSecond = 'Неверная секунда: %d'; SInvalidFractionSecond = 'Неверная секунда: %f'; SInvalidMillisecond = 'Неверная миллисекунда: %d'; SInvalidFractionalSecond = 'Неверная дробная секунда: %f'; SInvalidHourOffset = 'Неверный сдвиг часа: %d'; SInvalidDay = 'Неверный день: %d'; SInvalidMonth = 'Неверный месяц: %d'; SInvalidDuration = 'Неверная строка длительности: %s'; SMilSecRangeViolation = 'Значения миллисекунд должны быть между 000 - 999'; SInvalidYearConversion = 'Год даты слишком большой для преобразования'; SInvalidTimeOffset = 'Сдвиг часа времени - неверный'; SInvalidDecimalString = 'Неверная decimal строка: ''''%s'''''; SEmptyDecimalString = 'Не могу преобразовать пустую строку в TBcd значение'; SNoSciNotation = 'Не могу преобразовать научную запись числа в TBcd значение'; SNoNAN = 'Не могу преобразовать NAN в TBcd значение'; SInvalidBcd = 'Неверная Bcd точность (%d) или Scale (%d)'; SBcdStringTooBig = 'Не могу преобразовать в TBcd: строка имеет больше чем 64 цифр: %s'; SInvalidHexValue = '%s - неверная шестнадцатиричная строка'; {$IFNDEF VER140} SInvalidHTTPRequest = 'Неверный HTTP запрос: длина равна 0'; SInvalidHTTPResponse = 'Неверный HTTP ответ: длина равна 0'; {$ENDIF} {WebServExp} SInvalidBooleanParameter = 'ByteBool, WordBool и LongBool не могут быть exposed by WebServices. Пожалуйста, используйте ''Boolean'''; {WSDLIntf} SWideStringOutOfBounds = 'Индекс WideString вышел за границы'; {WSDLPub} IWSDLPublishDoc = 'Lists all the PortTypes published by this Service'; SNoServiceForURL = 'Нет доступного сервиса для URL %s'; SNoInterfaceForURL = 'Нет зарегистрированного интерфейса для управления URL %s'; SNoClassRegisteredForURL = 'Нет зарегистрированного класса для обеспечения интерфейса %s'; SEmptyURL = 'Нет URL, определенного для ''GET'''; SInvalidURL = 'Неверный url ''%s'' - поддерживает только ''http'' и ''https'' схемы'; SNoClassRegistered = 'Нет зарегистрированного класса для вызываемого интерфейса %s'; SNoDispatcher = 'Нет установленного диспетчера'; SMethNoRTTI = 'Метод не имеет RTTI'; {$IFNDEF VER140} SUnsupportedVariant = 'Неподдерживаемый вариантный тип %d'; {$ELSE} SUnsupportedVariant = 'Неподдерживаемый вариантный тип'; {$ENDIF} SNoVarDispatch = 'Тип varDispatch не поддерживается'; SNoErrorDispatch = 'Тип varError не поддерживается'; SUnknownInterface = '(Unknown)'; SInvalidTimeZone = 'Неверный или неизвестный часовой пояс'; SLocationFilter = 'WSDL файлы (*.wsdl)|*.wsdl|XML файлы (*.xml)|*.xml'; sUnknownError = 'Неизвестная ошибка'; sErrorColon = 'Ошибка: '; {$IFNDEF VER140} sServiceInfo = '%s - PortTypes:'; sInterfaceInfo= '<a href="%s">%s</a>&nbsp;&gt;&nbsp;<span class="Off">%s</span>'; sWSILInfo = 'WSIL:'; sWSILLink = '&nbsp;&nbsp;<span class="Tip">Ссылка на WS-Inspection документ of Services <a href="%s">here</a></span>'; {$ELSE} sServiceInfo = '%s exposes следующие интерфейсы:'; sInterfaceInfo= '<a class="NavBar" href="%s">%s</a>&nbsp;&gt;&nbsp;<span class="Off">%s</span>'; {$ENDIF} sRegTypes = 'Зарегистрированные типы'; sWebServiceListing = 'WebService Listing'; sWebServiceListingAdmin = 'WebService Listing Administrator'; sPortType = 'Тип порта'; sNameSpaceURI = 'Namespace URI'; sDocumentation = 'Документация'; sWSDL = 'WSDL'; sPortName = 'PortName'; {$IFNDEF VER140} sInterfaceNotFound = HTMLHead + '</head><body>' + '<h1>Обнаружена ошибка</h1><P>Интерфейс %s не найден</P>' +HTMLEnd; sForbiddenAccess = HTMLHead + '</head><body>' + '<h1>Запрещено (403)</h1><P>Доступ запрещен</P>' +HTMLEnd; {$ELSE} sInterfaceNotFound = HTMLTopPlain + '<h1>Обнаружена ошибка</h1><P>Интерфейс %s не найден</P>' +HTMLEnd; sForbiddenAccess = HTMLTopNS + '<h1>Запрещено (403)</h1><P>Доступ запрещен</P>' +HTMLEnd; {$ENDIF} sWSDLPortsforPortType = 'WSDL порты для PortType'; sWSDLFor = ''; sServiceInfoPage = 'Service Info Page'; {$IFNDEF VER140} {SOAPAttach} SEmptyStream = 'Ошибка TAggregateStream: нет внутренних потоков'; SMethodNotSupported = 'метод не поддерживается'; SInvalidMethod = 'Метод неразрешен в TSoapDataList'; SNoContentLength = 'Заголовок Content-Length не найден'; SInvalidContentLength = 'Неполные данные для Content-Length'; SMimeReadError = 'Ошибка чтения из Mime Request Stream'; {$IFDEF MSWINDOWS} STempFileAccessError = 'Нет доступа к временному файлу'; {$ENDIF} {$IFDEF LINUX} STempFileAccessError = 'Нет доступа к временному файлу: проверьте настройку TMPDIR'; {$ENDIF} {SoapConn} SSOAPServerIIDFmt = '%s - %s'; SNoURL = 'Не установлено свойство URL - пожалуйста, укажите URL Сервиса, к которому Вы хотите подключиться'; SSOAPInterfaceNotRegistered = 'Интерфейс (%s) не зарегестрирован - пожалуйста, включите в Ваш проект модуль, который регистрирует этот интерфейс'; SSOAPInterfaceNotRemotable = 'Интерфейс (%s) не может быть удаленным - пожалуйста, проверьте объявление интерфейса - особенно соглашение о вызовах методов!'; SCantLoadLocation = 'Не могу загрузить WSDL Файл/Размещение: %s. Ошибка [%s]'; {$ENDIF} implementation end.
unit MainProgram; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, FunctionManager, RandomNumberGenerator; type TformMainProgram = class(TForm) btnDisplayCurrentDate: TButton; btnOpenWindowsNotepad: TButton; btnGenerateRandomNumbers: TButton; lblMainProgramFunctions: TLabel; procedure btnOpenWindowsNotepadClick(Sender: TObject); procedure btnDisplayCurrentDateClick(Sender: TObject); procedure btnGenerateRandomNumbersClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private fFunctionManager: TFunctionManager; { Private declarations } public { Public declarations } end; var formMainProgram: TformMainProgram; implementation {$R *.dfm} procedure TformMainProgram.btnDisplayCurrentDateClick(Sender: TObject); begin fFunctionManager.SpawnDateWindow; end; procedure TformMainProgram.btnOpenWindowsNotepadClick(Sender: TObject); begin fFunctionManager.OpenNotePad; end; procedure TformMainProgram.FormClose(Sender: TObject; var Action: TCloseAction); begin Application.Terminate() end; procedure TformMainProgram.btnGenerateRandomNumbersClick(Sender: TObject); begin formRandomNumberGenerator.Show; end; end.
unit TestUContadorController; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, DB, DBXJSON, UContadorVO, ConexaoBD, Generics.Collections, UController, Classes, SysUtils, DBClient, UPessoasVo, DBXCommon, UContadorController, SQLExpr, UPessoasController; type // Test methods for class TContadorController TestTContadorController = class(TTestCase) strict private FContadorController: TContadorController; public procedure SetUp; override; procedure TearDown; override; published procedure TestConsultarPorId; procedure TestConsultaPorIdNaoEncontrado; end; implementation procedure TestTContadorController.SetUp; begin FContadorController := TContadorController.Create; end; procedure TestTContadorController.TearDown; begin FContadorController.Free; FContadorController := nil; end; procedure TestTContadorController.TestConsultaPorIdNaoEncontrado; var ReturnValue: TContadorVO; begin ReturnValue := FContadorController.ConsultarPorId(400); if(returnvalue <> nil) then check(false,'Contador pesquisado com sucesso!') else check(true,'Contador nao encontrado!'); end; procedure TestTContadorController.TestConsultarPorId; var ReturnValue: TContadorVO; begin ReturnValue := FContadorController.ConsultarPorId(4); if(returnvalue <> nil) then check(true,'Contador pesquisado com sucesso!') else check(true,'Contador nao encontrado!'); end; initialization // Register any test cases with the test runner RegisterTest(TestTContadorController.Suite); end.
unit ibSHInputParametersFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Contnrs, SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf, TntStdCtrls,TntWideStrings,TntClasses; type TibBTInputParametersForm = class(TSHComponentForm) Panel1: TPanel; ScrollBox1: TScrollBox; procedure InputEditChange(Sender: TObject); private function GetParams: IibSHDRVParams; private { Private declarations } FPriorCursor: TCursor; FEdits: TObjectList; FCheckBoxes: TObjectList; vPreparedParams:TStrings; property Params: IibSHDRVParams read GetParams; protected { Protected declarations } procedure DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult; var Action: TCloseAction); procedure DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); function GetLastParamValue(const ParamName:string):variant; procedure SetLastParamValue(const ParamName:string;Value:variant); function GetHistoryParamValues(const ParamName:string):TStrings; procedure SaveHistoryParamValues; procedure LoadHistoryParamValues; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; end; var ibBTInputParametersForm: TibBTInputParametersForm; implementation {$R *.dfm} { TibBTInputParametersForm } var SessionParamValues:TStringList; procedure StringsToWideStrings(Source:TStrings;Dest:TWideStrings); var i:integer; begin Dest.Clear; Dest.Capacity:=Source.Count; for i:=0 to Pred(Source.Count)do begin Dest.Add(UTF8Decode(Source[I])); end end; constructor TibBTInputParametersForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); var I: Integer; // vEdit: TEdit; vEdit: TTntComboBox; vCheckBox: TCheckBox; vSQLHaveParamValue:boolean; begin inherited Create(AOwner, AParent, AComponent, ACallString); if SessionParamValues.Count=0 then LoadHistoryParamValues; FEdits := TObjectList.Create(False); FCheckBoxes := TObjectList.Create(False); vSQLHaveParamValue:=False; for I := 0 to Pred(Params.ParamCount) do begin vSQLHaveParamValue:=not Params.ParamIsNull[I]; if vSQLHaveParamValue then Break; end; vPreparedParams:=TStringList.Create; for I := 0 to Pred(Params.ParamCount) do if vPreparedParams.IndexOf(Params.ParamName(I))=-1 then begin vPreparedParams.Add(Params.ParamName(I)); with TBevel.Create(ScrollBox1) do begin Parent := ScrollBox1; Height := 2; Shape := bsBottomLine; Top := (I + 1)*41; Width := ScrollBox1.ClientWidth; end; // vEdit := TEdit.Create(ScrollBox1); vEdit:= TTntComboBox.Create(ScrollBox1); vEdit.Parent:=ScrollBox1; FEdits.Add(vEdit); with vEdit do begin Name := 'Edit' + IntToStr(I); if not Params.ParamIsNull[I] then begin if vSQLHaveParamValue then Text := Params.ParamByIndex[I] else Text:=VarToWideStr(GetLastParamValue(Params.ParamName(I))) end else begin if vSQLHaveParamValue then Text:='' else Text:=VarToWideStr(GetLastParamValue(Params.ParamName(I))) end; if GetHistoryParamValues(Params.ParamName(I))<>nil then StringsToWideStrings(GetHistoryParamValues(Params.ParamName(I)),vEdit.Items); // vEdit.Items.AddStrings(); Parent := ScrollBox1; Left := 220; Top := I * 41 + 8; Width := 290; OnChange := InputEditChange; end; // if I = 0 then ActiveControl := vEdit; vCheckBox := TCheckBox.Create(ScrollBox1); FCheckBoxes.Add(vCheckBox); with vCheckBox do begin Name := 'CheckBox' + IntToStr(I); Parent := ScrollBox1; Left := 170; Top := I*41 + 10; Width := 45; Caption := 'Null'; if vSQLHaveParamValue then Checked := Params.ParamIsNull[I] else Checked := VarIsNull(GetLastParamValue(Params.ParamName(I))) ; { if Params.ParamIsNull[I] then begin Checked := not VarIsNull(GetLastParamValue(Params.ParamName(I))) ; end else begin Checked := False; if (J>=0) and Boolean(SessionParamValues.Objects[J]) then Checked := True; end;} Font.Style := [fsBold]; TabStop := False; end; with TLabel.Create(ScrollBox1) do begin Parent := ScrollBox1; AutoSize := False; WordWrap := True; Left := 4; Top := I*41 + 4; Width := 165; Height := 26; Caption := Params.ParamName(I); end; end; if Assigned(ModalForm) then begin ModalForm.OnBeforeModalClose := DoOnBeforeModalClose; ModalForm.OnAfterModalClose := DoOnAfterModalClose; end; FPriorCursor := Screen.Cursor; Screen.Cursor := crDefault; end; destructor TibBTInputParametersForm.Destroy; begin FEdits.Free; FCheckBoxes.Free; vPreparedParams.Free; inherited; end; procedure TibBTInputParametersForm.DoOnBeforeModalClose(Sender: TObject; var ModalResult: TModalResult; var Action: TCloseAction); begin //inherited DoOnBeforeModalClose(Sender, ModalResult, Action); end; procedure TibBTInputParametersForm.SaveHistoryParamValues; var I: Integer; Path:string; begin Path:=ExtractFilePath(Application.ExeName)+'..\Data\Environment\'; ForceDirectories(Path); DeleteFile(Path+'\ParametersHistory.txt'); Designer.SaveStringsToIni(Path+'\ParametersHistory.txt', 'Parameters List',SessionParamValues,True); for I := 0 to SessionParamValues.Count - 1 do Designer.SaveStringsToIni(Path+'\ParametersHistory.txt', SessionParamValues[I],TStrings(SessionParamValues.Objects[I]),True); end; procedure TibBTInputParametersForm.LoadHistoryParamValues; var I: Integer; Path:string; begin for I:=Pred(SessionParamValues.count) downto 0 do SessionParamValues.Objects[i].Free; SessionParamValues.Clear; Path:=ExtractFilePath(Application.ExeName)+'..\Data\Environment\'; ForceDirectories(Path); Designer.ReadStringsFromIni(Path+'\ParametersHistory.txt', 'Parameters List',SessionParamValues); for I := 0 to SessionParamValues.Count - 1 do begin SessionParamValues.Objects[I]:=TStringList.Create; Designer.ReadStringsFromIni(Path+'\ParametersHistory.txt', SessionParamValues[I],TStrings(SessionParamValues.Objects[I])); end; end; procedure TibBTInputParametersForm.DoOnAfterModalClose(Sender: TObject; ModalResult: TModalResult); var I: Integer; // Path:string; begin Screen.Cursor := FPriorCursor; if ModalResult = mrOk then begin try for I := 0 to vPreparedParams.Count - 1 do begin if TCheckBox(FCheckBoxes[I]).Checked then Params.SetParamByName(vPreparedParams[I],Null) else Params.SetParamByName(vPreparedParams[I],TTntComboBox(FEdits[I]).Text); if TCheckBox(FCheckBoxes[I]).Checked then SetLastParamValue(vPreparedParams[I], null) else SetLastParamValue(vPreparedParams[I], TTntComboBox(FEdits[I]).Text) end; SaveHistoryParamValues; { for I := 0 to Params.ParamCount - 1 do begin if TCheckBox(FCheckBoxes[I]).Checked then Params.ParamIsNull[I] := True else Params.ParamByIndex[I] := TTntComboBox(FEdits[I]).Text; if TCheckBox(FCheckBoxes[I]).Checked then SetLastParamValue(Params.ParamName(I), null) else SetLastParamValue(Params.ParamName(I), TTntComboBox(FEdits[I]).Text) end;} except on E: Exception do begin Designer.ShowMsg(E.Message, mtError); end; end; end; end; procedure TibBTInputParametersForm.InputEditChange(Sender: TObject); var EditIndex: Integer; begin if Length((Sender as TTntComboBox).Text) > 0 then begin EditIndex := StrToInt(copy((Sender as TTntComboBox).Name, 5, MaxInt)); if TCheckBox(FCheckBoxes[EditIndex]).Checked then TCheckBox(FCheckBoxes[EditIndex]).Checked := False; end; end; function TibBTInputParametersForm.GetParams: IibSHDRVParams; begin if Assigned(Component) then Result := (Component as IibSHInputParameters).Params; end; function TibBTInputParametersForm.GetLastParamValue( const ParamName: string): variant; var J:integer; begin J:=SessionParamValues.IndexOf(ParamName); if (J<0) then Result:=null else if TStrings(SessionParamValues.Objects[J]).Count=0 then Result:=null else if Boolean(TStrings(SessionParamValues.Objects[J]).Objects[0]) then Result:=null else Result:=UTF8Decode(TStrings(SessionParamValues.Objects[J])[0]) end; procedure TibBTInputParametersForm.SetLastParamValue( const ParamName: string; Value: variant); var J:integer; History :TStrings; begin if SessionParamValues.Find(ParamName,J) then History:=TStrings(SessionParamValues.Objects[J]) else begin History:=TStringList.Create; SessionParamValues.AddObject(ParamName,History) end; J:=History.IndexOf(UTF8Encode(VarToWideStr(Value))); if J>=0 then History.Delete(J); History.InsertObject(0,UTF8Encode(VarToWideStr(Value)),TObject(VarIsNull(Value))); if History.Count>10 then History.Delete(History.Count-1) end; function TibBTInputParametersForm.GetHistoryParamValues( const ParamName: string): TStrings; var J:integer; begin J:=SessionParamValues.IndexOf(ParamName); if (J<0) then Result:=nil else Result:=TStrings(SessionParamValues.Objects[J]) end; procedure FreeParamsHistory; var j:integer; begin for j:=Pred(SessionParamValues.count) downto 0 do SessionParamValues.Objects[j].Free; SessionParamValues.Free; end; initialization SessionParamValues:=TStringList.Create; SessionParamValues.Sorted:=True; SessionParamValues.Duplicates:=dupIgnore finalization FreeParamsHistory end.
unit SampleFor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TSampleForm = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var SampleForm: TSampleForm; implementation {$R *.dfm} uses Consts, SampleConsts; procedure TSampleForm.FormCreate(Sender: TObject); resourcestring SMsg = 'Resource string'; begin // See comments in Unit1.pas Label2.Caption := SMsg; Label3.Caption := SampleConsts.SSampleString; Label4.Caption := Consts.SMsgDlgInformation; end; end.
program simdn; //Example of how to insert C code into FPC project // in this example, the C code uses SIMD intrinsics to generate SSE or Neon code //you must compile scale2uint8n.cpp first! // g++ -c -O3 scale2uint8n.cpp -o scale2uint8n.o // fpc -O3 simdn.pas; ./simdn {$mode objfpc}{$H+} uses Math, SysUtils,DateUtils; {$L scale2uint8n.o} function f32_i8neon(in32: pointer; out8: pointer; n: int64; slope, intercept: single): Integer; external name '__Z10f32_i8neonPfPhxff'; procedure testF32(reps: integer = 3); const //number of voxels for test, based on HCP resting state https://protocols.humanconnectome.org/HCP/3T/imaging-protocols.html n = 104*90*72*400; //= 104*90*72*400; slope = 1; intercept = 0.5; var i, r: Integer; f: single; in32: array of single; out8fpc, out8c: array of byte; startTime : TDateTime; ms, cSum, fpcSum, cMin, fpcMin: Int64; begin //initialize Writeln('values ', n, ' repetitions ', reps); setlength(in32, n); setlength(out8c, n); setlength(out8fpc, n); cSum := 0; fpcSum := 0; cMin := MaxInt; fpcMin := MaxInt; for i := 0 to (n-1) do in32[i] := (random(2048) - 100) * 0.1; for r := 1 to (reps) do begin //c Code startTime := Now; f32_i8neon(@in32[0], @out8c[0], n, slope, intercept); ms := MilliSecondsBetween(Now,startTime); cMin := min(cMin, ms); cSum += ms; //fpc code: startTime := Now; for i := 0 to (n-1) do begin f := max(min((in32[i] * slope) + intercept, 255), 0); out8fpc[i] := round(f); end; ms := MilliSecondsBetween(Now,startTime); fpcMin := min(fpcMin, ms); fpcSum += ms; end; //validate results: for i := 0 to (n-1) do begin if (out8c[i] <> out8fpc[i]) then Writeln(i, ' ', in32[i], ' c->', out8c[i], ' fpc-> ', out8fpc[i]); end; Writeln('f32 elapsed SIMD (msec) min ', cMin, ' total ', cSum); Writeln('f32 elapsed FPC (msec) min ', fpcMin, ' total ', fpcSum); end; //testF32() begin testF32(3); end.
unit Dfft; INTERFACE {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses util1; procedure libererFFT(NumPoints:integer); function allouerFFT(NumPoints:integer):boolean; procedure RealFFT(NumPoints : integer; Inverse : boolean; XReal : PtabFloat; XImag : PtabFloat; var Error : byte); {---------------------------------------------------------------------------} {- -} {- Input: NumPoints, Inverse, XReal, XImag, -} {- Output: XReal, XImag, Error -} {- -} {- Purpose: This procedure uses the complex Fourier transform -} {- routine (FFT) to transform real data. The real data -} {- is in the vector XReal. Appropriate shuffling of indices -} {- changes the real vector into two vectors (representing -} {- complex data) which are only half the size of the original -} {- vector. Appropriate unshuffling at the end produces the -} {- transform of the real data. -} {- -} {- User Defined Types: -} {- TNvector = array[0..TNArraySize] of real -} {- PtabFloat = ^TNvector -} {- -} {- Global Variables: NumPoints : integer Number of data -} {- points in X -} {- Inverse : boolean False => forward transform -} {- True ==> inverse transform -} {- XReal,XImag : PtabFloat Data points -} {- Error : byte Indicates an error -} {- -} {- Errors: 0: No Errors -} {- 1: NumPoints < 2 -} {- 2: NumPoints not a power of two -} {- (or 4 for radix-4 transforms) -} {- -} {---------------------------------------------------------------------------} procedure ComplexFFT(NumPoints : integer; Inverse : boolean; XReal : PtabFloat; XImag : PtabFloat; var Error : byte); IMPLEMENTATION const DummyReal: PtabFloat=nil; { doit contenir NumPoints } DummyImag: PtabFloat=nil; { " " } SinTable : PtabFloat=nil; { doit contenir NumPoints div 2 } CosTable : PtabFloat=nil; { " " } procedure libererFFT(NumPoints:integer); begin if DummyReal<>nil then freemem(DummyReal,NumPoints*10); if DummyImag<>nil then freemem(DummyImag,NumPoints*10); if SinTable<>nil then freemem(SinTable,NumPoints*5 ); if CosTable<>nil then freemem(CosTable,NumPoints*5); DummyReal:=nil; DummyImag:=nil; SinTable:=nil; CosTable:=nil; end; function allouerFFT(NumPoints:integer):boolean; var ok:boolean; begin if NumPoints=0 then begin allouerFFT:=true; exit; end; if maxavail>NumPoints*10 then getmem(DummyReal,NumPoints*10); if maxavail>NumPoints*10 then getmem(DummyImag,NumPoints*10); if maxavail>NumPoints*5 then getmem(SinTable,NumPoints*5); if maxavail>NumPoints*5 then getmem(CosTable,NumPoints*5); ok:=(DummyReal<>nil) and (DummyImag<>nil) and (CosTable<>nil) and (SinTable<>nil); if not ok then libererFFT(NumPoints); allouerFFT:=ok; end; procedure TestInput(NumPoints : integer; var NumberOfBits : byte; var Error : byte); type ShortArray = array[1..16] of integer; var Term : integer; const PowersOfTwo : ShortArray = (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192,16384,32768,65536); begin Error := 2; { Assume NumPoints not a power of two } if NumPoints < 2 then Error := 1; { NumPoints < 2 } Term := 1; while (Term <= 16) and (Error = 2) do begin if NumPoints = PowersOfTwo[Term] then begin NumberOfBits := Term; Error := 0; { NumPoints is a power of two } end; Term := Succ(Term); end; end; { procedure TestInput } procedure MakeSinCosTable(NumPoints : integer; var SinTable : PtabFloat; var CosTable : PtabFloat); var RealFactor, ImagFactor : Float; Term : integer; TermMinus1 : integer; UpperLimit : integer; begin RealFactor := Cos(2 * Pi / NumPoints); ImagFactor := -Sqrt(1 - Sqr(RealFactor)); CosTable^[0] := 1; SinTable^[0] := 0; CosTable^[1] := RealFactor; SinTable^[1] := ImagFactor; UpperLimit := NumPoints shr 1 - 1; for Term := 2 to UpperLimit do begin TermMinus1 := Term - 1; CosTable^[Term] := CosTable^[TermMinus1] * RealFactor - SinTable^[TermMinus1] * ImagFactor; SinTable^[Term] := CosTable^[TermMinus1] * ImagFactor + SinTable^[TermMinus1] * RealFactor; end; end; { procedure MakeSinCosTable } procedure FFT(NumberOfBits : byte; NumPoints : integer; Inverse : boolean; var XReal : PtabFloat; var XImag : PtabFloat; var SinTable : PtabFloat; var CosTable : PtabFloat); const RootTwoOverTwo = 0.707106781186548; var Term : byte; CellSeparation : integer; NumberOfCells : integer; NumElementsInCell : integer; NumElInCellLess1 : integer; NumElInCellSHR1 : integer; NumElInCellSHR2 : integer; RealRootOfUnity, ImagRootOfUnity : Float; Element : integer; CellElements : integer; ElementInNextCell : integer; Index : integer; RealDummy, ImagDummy : Float; procedure BitInvert(NumberOfBits : byte; NumPoints : integer; var XReal : PtabFloat; var XImag : PtabFloat); {-----------------------------------------------------------} {- Input: NumberOfBits, NumPoints -} {- Output: XReal, XImag -} {- -} {- This procedure bit inverts the order of data in the -} {- vector X. Bit inversion reverses the order of the -} {- binary representation of the indices; thus 2 indices -} {- will be switched. For example, if there are 16 points, -} {- Index 7 (binary 0111) would be switched with Index 14 -} {- (binary 1110). It is necessary to bit invert the order -} {- of the data so that the transformation comes out in the -} {- correct order. -} {-----------------------------------------------------------} var Term : integer; Invert : integer; Hold : Float; NumPointsDiv2, K : integer; begin NumPointsDiv2 := NumPoints shr 1; Invert := 0; for Term := 0 to NumPoints - 2 do begin if Term < Invert then { Switch these two indices } begin Hold := XReal^[Invert]; XReal^[Invert] := XReal^[Term]; XReal^[Term] := Hold; Hold := XImag^[Invert]; XImag^[Invert] := XImag^[Term]; XImag^[Term] := Hold; end; K := NumPointsDiv2; while K <= Invert do begin Invert := Invert - K; K := K shr 1; end; Invert := Invert + K; end; end; { procedure BitInvert } begin { procedure FFT } { The data must be entered in bit inverted order } { for the transform to come out in proper order } BitInvert(NumberOfBits, NumPoints, XReal, XImag); if Inverse then { Conjugate the input } for Element := 0 to NumPoints - 1 do XImag^[Element] := -XImag^[Element]; NumberOfCells := NumPoints; CellSeparation := 1; for Term := 1 to NumberOfBits do begin { NumberOfCells halves; equals 2^(NumberOfBits - Term) } NumberOfCells := NumberOfCells shr 1; { NumElementsInCell doubles; equals 2^(Term-1) } NumElementsInCell := CellSeparation; { CellSeparation doubles; equals 2^Term } CellSeparation := CellSeparation SHL 1; NumElInCellLess1 := NumElementsInCell - 1; NumElInCellSHR1 := NumElementsInCell shr 1; NumElInCellSHR2 := NumElInCellSHR1 shr 1; { Special case: RootOfUnity = EXP(-i 0) } Element := 0; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := XReal^[ElementInNextCell]; ImagDummy := XImag^[ElementInNextCell]; XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; for CellElements := 1 to NumElInCellSHR2 - 1 do begin Index := CellElements * NumberOfCells; RealRootOfUnity := CosTable^[Index]; ImagRootOfUnity := SinTable^[Index]; Element := CellElements; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := XReal^[ElementInNextCell] * RealRootOfUnity - XImag^[ElementInNextCell] * ImagRootOfUnity; ImagDummy := XReal^[ElementInNextCell] * ImagRootOfUnity + XImag^[ElementInNextCell] * RealRootOfUnity; XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; end; { Special case: RootOfUnity = EXP(-i PI/4) } if Term > 2 then begin Element := NumElInCellSHR2; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := RootTwoOverTwo * (XReal^[ElementInNextCell] + XImag^[ElementInNextCell]); ImagDummy := RootTwoOverTwo * (XImag^[ElementInNextCell] - XReal^[ElementInNextCell]); XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; end; for CellElements := NumElInCellSHR2 + 1 to NumElInCellSHR1 - 1 do begin Index := CellElements * NumberOfCells; RealRootOfUnity := CosTable^[Index]; ImagRootOfUnity := SinTable^[Index]; Element := CellElements; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := XReal^[ElementInNextCell] * RealRootOfUnity - XImag^[ElementInNextCell] * ImagRootOfUnity; ImagDummy := XReal^[ElementInNextCell] * ImagRootOfUnity + XImag^[ElementInNextCell] * RealRootOfUnity; XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; end; { Special case: RootOfUnity = EXP(-i PI/2) } if Term > 1 then begin Element := NumElInCellSHR1; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := XImag^[ElementInNextCell]; ImagDummy := -XReal^[ElementInNextCell]; XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; end; for CellElements := NumElInCellSHR1 + 1 to NumElementsInCell - NumElInCellSHR2 - 1 do begin Index := CellElements * NumberOfCells; RealRootOfUnity := CosTable^[Index]; ImagRootOfUnity := SinTable^[Index]; Element := CellElements; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := XReal^[ElementInNextCell] * RealRootOfUnity - XImag^[ElementInNextCell] * ImagRootOfUnity; ImagDummy := XReal^[ElementInNextCell] * ImagRootOfUnity + XImag^[ElementInNextCell] * RealRootOfUnity; XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; end; { Special case: RootOfUnity = EXP(-i 3PI/4) } if Term > 2 then begin Element := NumElementsInCell - NumElInCellSHR2; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := -RootTwoOverTwo * (XReal^[ElementInNextCell] - XImag^[ElementInNextCell]); ImagDummy := -RootTwoOverTwo * (XReal^[ElementInNextCell] + XImag^[ElementInNextCell]); XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; end; for CellElements := NumElementsInCell - NumElInCellSHR2 + 1 to NumElInCellLess1 do begin Index := CellElements * NumberOfCells; RealRootOfUnity := CosTable^[Index]; ImagRootOfUnity := SinTable^[Index]; Element := CellElements; while Element < NumPoints do begin { Combine the X[Element] with the element in } { the identical location in the next cell } ElementInNextCell := Element + NumElementsInCell; RealDummy := XReal^[ElementInNextCell] * RealRootOfUnity - XImag^[ElementInNextCell] * ImagRootOfUnity; ImagDummy := XReal^[ElementInNextCell] * ImagRootOfUnity + XImag^[ElementInNextCell] * RealRootOfUnity; XReal^[ElementInNextCell] := XReal^[Element] - RealDummy; XImag^[ElementInNextCell] := XImag^[Element] - ImagDummy; XReal^[Element] := XReal^[Element] + RealDummy; XImag^[Element] := XImag^[Element] + ImagDummy; Element := Element + CellSeparation; end; end; end; {----------------------------------------------------} {- Divide all the values of the transformation -} {- by the square root of NumPoints. If taking the -} {- inverse, conjugate the output. -} {----------------------------------------------------} { if Inverse then ImagDummy := -1/Sqrt(NumPoints) else ImagDummy := 1/Sqrt(NumPoints); RealDummy := ABS(ImagDummy); } if Inverse then ImagDummy := -1/NumPoints else ImagDummy := 1; RealDummy := ABS(ImagDummy); for Element := 0 to NumPoints - 1 do begin XReal^[Element] := XReal^[Element] * RealDummy; XImag^[Element] := XImag^[Element] * ImagDummy; end; end; { procedure FFT } procedure RealFFT(NumPoints : integer; Inverse : boolean; XReal : PtabFloat; XImag : PtabFloat; var Error : byte); var NumberOfBits : byte; { Number of bits necessary to } { represent the number of points } procedure MakeRealDataComplex(NumPoints : integer; var XReal : PtabFloat; var XImag : PtabFloat); var Index, NewIndex : integer; begin for Index := 0 to NumPoints - 1 do begin NewIndex := Index shl 1; DummyReal^[Index] := XReal^[NewIndex]; DummyImag^[Index] := XReal^[NewIndex + 1]; end; move(dummyReal^,Xreal^,numPoints*sizeof(float)); move(dummyImag^,Ximag^,numPoints*sizeof(float)); end; procedure UnscrambleComplexOutput(NumPoints : integer; var SinTable : PtabFloat; var CosTable : PtabFloat; var XReal : PtabFloat; var XImag : PtabFloat); var PiOverNumPoints : Float; Index : integer; indexSHR1 : integer; NumPointsMinusIndex : integer; SymmetricIndex : integer; Multiplier : Float; Factor : Float; CosFactor, SinFactor : Float; RealSum, ImagSum, RealDif, ImagDif : Float; NumPointsSHL1 : integer; begin move(Xreal^,DummyReal^,2*numPoints*sizeof(float)); move(XImag^,DummyImag^,2*numPoints*sizeof(float)); PiOverNumPoints := Pi / NumPoints; NumPointsSHL1 := NumPoints shl 1; DummyReal^[0] := (XReal^[0] + XImag^[0]) / Sqrt(2); DummyImag^[0] := 0; DummyReal^[NumPoints] := (XReal^[0] - XImag^[0]) / Sqrt(2); DummyImag^[NumPoints] := 0; for Index := 1 to NumPoints - 1 do begin Multiplier := 0.5 / Sqrt(2); Factor := PiOverNumPoints * Index; NumPointsMinusIndex := NumPoints - Index; SymmetricIndex := NumPointsSHL1 - Index; if Odd(Index) then begin CosFactor := Cos(Factor); SinFactor := -Sin(Factor); end else begin indexSHR1 := Index shr 1; CosFactor := CosTable^[indexSHR1]; SinFactor := SinTable^[indexSHR1]; end; RealSum := XReal^[Index] + XReal^[NumPointsMinusIndex]; ImagSum := XImag^[Index] + XImag^[NumPointsMinusIndex]; RealDif := XReal^[Index] - XReal^[NumPointsMinusIndex]; ImagDif := XImag^[Index] - XImag^[NumPointsMinusIndex]; DummyReal^[Index] := Multiplier * (RealSum + CosFactor * ImagSum + SinFactor * RealDif); DummyImag^[Index] := Multiplier * (ImagDif + SinFactor * ImagSum - CosFactor * RealDif); DummyReal^[SymmetricIndex] := DummyReal^[Index]; DummyImag^[SymmetricIndex] := -DummyImag^[Index]; end; { for } move(DummyReal^,XReal^,2*numPoints*sizeof(float)); move(DummyImag^,XImag^,2*numPoints*sizeof(float)); end; begin { procedure RealFFT } NumPoints := NumPoints shr 1; TestInput(NumPoints, NumberOfBits, Error); if Error = 0 then begin MakeRealDataComplex(NumPoints, XReal, XImag); MakeSinCosTable(NumPoints, SinTable, CosTable); FFT(NumberOfBits, NumPoints, Inverse, XReal, XImag, SinTable, CosTable); UnscrambleComplexOutput(NumPoints, SinTable, CosTable, XReal, XImag); end; end; { procedure RealFFT } procedure ComplexFFT(NumPoints : integer; Inverse : boolean; XReal : PtabFloat; XImag : PtabFloat; var Error : byte); var NumberOfBits : byte; { Number of bits to represent the } { number of data points. } begin { procedure ComplexFFT } TestInput(NumPoints, NumberOfBits, Error); if Error = 0 then begin MakeSinCosTable(NumPoints, SinTable, CosTable); FFT(NumberOfBits, NumPoints, Inverse, XReal, XImag, SinTable, CosTable); end; end; { procedure ComplexFFT } end.
(*----------------------------------------------------------------------------* * Direct3D sample from DirectX 9.0 SDK December 2006 * * Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) * * * * Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 * * * * Latest version can be downloaded from: * * http://www.clootie.ru * * http://sourceforge.net/projects/delphi-dx9sdk * *----------------------------------------------------------------------------* * $Id: ShadowMapUnit.pas,v 1.19 2007/02/05 22:21:11 clootie Exp $ *----------------------------------------------------------------------------*) //-------------------------------------------------------------------------------------- // File: ShadowMap.cpp // // Starting point for new Direct3D applications // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- {$I DirectX.inc} unit ShadowMapUnit; interface uses Windows, Messages, SysUtils, DXTypes, Direct3D9, D3DX9, DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTmesh, DXUTSettingsDlg; {.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders {.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders const SHADOWMAP_SIZE = 512; const HELPTEXTCOLOR: TD3DXColor = (r: 0.0; g:1.0; b:0.3; a:1.0); const //todo: Probably convert this back to PAnsiChar when FPC with mine bug-fixes will be out g_aszMeshFile: array[0..13] of PWideChar = ( 'room.x', 'airplane\airplane 2.x', 'misc\car.x', 'misc\sphere.x', 'UI\arrow.x', 'UI\arrow.x', 'UI\arrow.x', 'UI\arrow.x', 'UI\arrow.x', 'UI\arrow.x', 'UI\arrow.x', 'UI\arrow.x', 'ring.x', 'ring.x' ); NUM_OBJ = High(g_aszMeshFile) + 1; g_amInitObjWorld: array[0..NUM_OBJ-1] of TD3DXMATRIXA16 = ( (m: ((3.5, 0.0, 0.0, 0.0), (0.0, 3.0, 0.0, 0.0), (0.0, 0.0, 3.5, 0.0), (0.0, 0.0, 0.0, 1.0)) ), (m: ((0.43301, 0.25, 0.0, 0.0), (-0.25, 0.43301, 0.0, 0.0), (0.0, 0.0, 0.5, 0.0), (5.0, 1.33975, 0.0, 1.0)) ), (m: ((0.8, 0.0, 0.0, 0.0), (0.0, 0.8, 0.0, 0.0), (0.0, 0.0, 0.8, 0.0), (-14.5, -7.1, 0.0, 1.0)) ), (m: ((2.0, 0.0, 0.0, 0.0), (0.0, 2.0, 0.0, 0.0), (0.0, 0.0, 2.0, 0.0), (0.0, -7.0, 0.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (5.0, 0.2, 5.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (5.0, 0.2, -5.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (-5.0, 0.2, 5.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (-5.0, 0.2, -5.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (14.0, 0.2, 14.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (14.0, 0.2, -14.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (-14.0, 0.2, 14.0, 1.0)) ), (m: ((5.5, 0.0, 0.0, 0.0), (0.0, 0.0, 5.5, 0.0), (0.0, -9.0, 0.0, 0.0), (-14.0, 0.2, -14.0, 1.0)) ), (m: ((0.9, 0.0, 0.0, 0.0), (0.0, 0.9, 0.0, 0.0), (0.0, 0.0, 0.9, 0.0), (-14.5, -9.0, 0.0, 1.0)) ), (m: ((0.9, 0.0, 0.0, 0.0), (0.0, 0.9, 0.0, 0.0), (0.0, 0.0, 0.9, 0.0), (14.5, -9.0, 0.0, 1.0)) ) ); g_aVertDecl: array[0..3] of TD3DVertexElement9 = ( (Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0), (Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0), (Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0), {D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0) ); type //----------------------------------------------------------------------------- // Name: class TObj // Desc: Encapsulates a mesh object in the scene by grouping its world matrix // with the mesh. //----------------------------------------------------------------------------- CObj = class m_Mesh: CDXUTMesh; m_mWorld: TD3DXMatrixA16; constructor Create; destructor Destroy; override; end; //----------------------------------------------------------------------------- // Name: class CViewCamera // Desc: A camera class derived from CFirstPersonCamera. The arrow keys and // numpad keys are disabled for this type of camera. //----------------------------------------------------------------------------- CViewCamera = class(CFirstPersonCamera) protected function MapKey(nKey: LongWord): TD3DUtil_CameraKeys; override; end; //----------------------------------------------------------------------------- // Name: class CLightCamera // Desc: A camera class derived from CFirstPersonCamera. The letter keys // are disabled for this type of camera. This class is intended for use // by the spot light. //----------------------------------------------------------------------------- CLightCamera = class(CFirstPersonCamera) protected function MapKey(nKey: LongWord): TD3DUtil_CameraKeys; override; end; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- var g_pFont: ID3DXFont; // Font for drawing text g_pFontSmall: ID3DXFont; // Font for drawing text g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls g_pEffect: ID3DXEffect; // D3DX effect interface g_bShowHelp: Boolean = True; // If true, it renders the UI control text g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog g_HUD: CDXUTDialog; // dialog for standard controls //todo: Fill Bug report - g_VCamera and g_LCamera should be custom cameras? g_VCamera: CFirstPersonCamera; // View camera g_LCamera: CFirstPersonCamera; // Camera obj to help adjust light g_Obj: array[0..NUM_OBJ-1] of CObj; // Scene object meshes g_pVertDecl: IDirect3DVertexDeclaration9; // Vertex decl for the sample g_pTexDef: IDirect3DTexture9; // Default texture for objects g_Light: TD3DLight9; // The spot light in the scene g_LightMesh: CDXUTMesh; g_pShadowMap: IDirect3DTexture9; // Texture to which the shadow map is rendered g_pDSShadow: IDirect3DSurface9; // Depth-stencil buffer for rendering to shadow map g_fLightFov: Single; // FOV of the spot light (in radian) g_mShadowProj: TD3DXMatrixA16; // Projection matrix for shadow map g_bRightMouseDown: Boolean = False; // Indicates whether right mouse button is held g_bCameraPerspective: Boolean = True; // Indicates whether we should render view from // the camera's or the light's perspective g_bFreeLight: Boolean = True; // Whether the light is freely moveable. //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- const IDC_TOGGLEFULLSCREEN = 1; IDC_TOGGLEREF = 3; IDC_CHANGEDEVICE = 4; IDC_CHECKBOX = 5; IDC_LIGHTPERSPECTIVE = 6; IDC_ATTACHLIGHTTOCAR = 7; //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- procedure InitializeDialogs; function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; procedure RenderText; function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; procedure MouseProc(bLeftButtonDown, bRightButtonDown, bMiddleButtonDown, bSideButton1Down, bSideButton2Down: Boolean; nMouseWheelDelta, xPos, yPos: Integer; pUserContext: Pointer); stdcall; procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; procedure OnLostDevice(pUserContext: Pointer); stdcall; procedure OnDestroyDevice(pUserContext: Pointer); stdcall; procedure RenderScene(pd3dDevice: IDirect3DDevice9; bRenderShadow: Boolean; fElapsedTime: Single; const pmView: TD3DXMatrix; const pmProj: TD3DXMatrix); procedure CreateCustomDXUTobjects; procedure DestroyCustomDXUTobjects; implementation //-------------------------------------------------------------------------------------- // Sets up the dialogs //-------------------------------------------------------------------------------------- procedure InitializeDialogs; var iY: Integer; begin g_SettingsDlg.Init(g_DialogResourceManager); g_HUD.Init(g_DialogResourceManager); g_HUD.SetCallback(OnGUIEvent); iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); Inc(iY, 24); g_HUD.AddCheckBox(IDC_CHECKBOX, 'Display help text', 35, iY, 125, 22, True, VK_F1); Inc(iY, 24); g_HUD.AddCheckBox(IDC_LIGHTPERSPECTIVE, 'View from light''s perspective', 0, iY, 160, 22, False, Ord('V')); Inc(iY, 24); g_HUD.AddCheckBox(IDC_ATTACHLIGHTTOCAR, 'Attach light to car', 0, iY, 160, 22, False, Ord('F')); end; //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning false. //-------------------------------------------------------------------------------------- function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall; var pD3D: IDirect3D9; begin Result := False; // Skip backbuffer formats that don't support alpha blending pD3D := DXUTGetD3DObject; if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit; // Must support pixel shader 2.0 if (pCaps.PixelShaderVersion < D3DPS_VERSION(2, 0)) then Exit; // need to support D3DFMT_R32F render target if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_CUBETEXTURE, D3DFMT_R32F)) then Exit; // need to support D3DFMT_A8R8G8B8 render target if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_CUBETEXTURE, D3DFMT_A8R8G8B8)) then Exit; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- {static} var s_bFirstTime: Boolean = True; function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall; begin // Turn vsync off pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE; g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL).Enabled := False; // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or (pCaps.VertexShaderVersion < D3DVS_VERSION(1,1)) then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING else pDeviceSettings.BehaviorFlags := D3DCREATE_HARDWARE_VERTEXPROCESSING; // This application is designed to work on a pure device by not using // IDirect3D9::Get*() methods, so create a pure device if supported and using HWVP. if (pCaps.DevCaps and D3DDEVCAPS_PUREDEVICE <> 0) and (pDeviceSettings.BehaviorFlags and D3DCREATE_HARDWARE_VERTEXPROCESSING <> 0) then pDeviceSettings.BehaviorFlags := pDeviceSettings.BehaviorFlags or D3DCREATE_PUREDEVICE; // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. {$IFDEF DEBUG_VS} if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then with pDeviceSettings do begin BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING; BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE; BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING; end; {$ENDIF} {$IFDEF DEBUG_PS} pDeviceSettings.DeviceType := D3DDEVTYPE_REF; {$ENDIF} // For the first device created if its a REF device, optionally display a warning dialog box if s_bFirstTime then begin s_bFirstTime := False; if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning; end; Result:= True; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var dwShaderFlags: DWORD; str: array [0..MAX_PATH-1] of WideChar; i: Integer; mIdent: TD3DXMatrixA16; begin Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice); if V_Failed(Result) then Exit; // Initialize the font Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFont); if Failed(Result) then Exit; Result := D3DXCreateFont(pd3dDevice, 12, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, 'Arial', g_pFontSmall); if Failed(Result) then Exit; // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. dwShaderFlags := D3DXFX_NOT_CLONEABLE; {$IFDEF DEBUG} // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG; {$ENDIF} {$IFDEF DEBUG_VS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; {$ENDIF} {$IFDEF DEBUG_PS} dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; {$ENDIF} // Read the D3DX effect file Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('ShadowMap.fx')); if Failed(Result) then Exit; // If this fails, there should be debug output as to // they the .fx file failed to compile Result := D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil); if Failed(Result) then Exit; // Create vertex declaration Result := pd3dDevice.CreateVertexDeclaration(@g_aVertDecl, g_pVertDecl); if Failed(Result) then Exit; // Initialize the meshes for i := 0 to NUM_OBJ - 1 do begin Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, g_aszMeshFile[i]); if Failed(Result) then Exit; if FAILED(g_Obj[i].m_Mesh.CreateMesh(pd3dDevice, str)) then begin Result:= DXUTERR_MEDIANOTFOUND; Exit; end; Result:= g_Obj[i].m_Mesh.SetVertexDecl(pd3dDevice, @g_aVertDecl); if Failed(Result) then Exit; g_Obj[i].m_mWorld := g_amInitObjWorld[i]; end; // Initialize the light mesh Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('spotlight.x')); if Failed(Result) then Exit; if FAILED(g_LightMesh.CreateMesh(pd3dDevice, str)) then begin Result:= DXUTERR_MEDIANOTFOUND; Exit; end; Result:= g_LightMesh.SetVertexDecl(pd3dDevice, @g_aVertDecl); if Failed(Result) then Exit; // World transform to identity D3DXMatrixIdentity(mIdent); Result:= pd3dDevice.SetTransform(D3DTS_WORLD, mIdent); if Failed(Result) then Exit; Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall; var fAspectRatio: Single; lr: TD3DLockedRect; i: Integer; d3dSettings: TDXUTDeviceSettings; pControl: CDXUTControl; begin Result:= g_DialogResourceManager.OnResetDevice; if V_Failed(Result) then Exit; Result:= g_SettingsDlg.OnResetDevice; if V_Failed(Result) then Exit; if Assigned(g_pFont) then begin Result:= g_pFont.OnResetDevice; if Failed(Result) then Exit; end; if Assigned(g_pFontSmall) then begin Result:= g_pFontSmall.OnResetDevice; if Failed(Result) then Exit; end; if Assigned(g_pEffect) then begin Result:= g_pEffect.OnResetDevice; if Failed(Result) then Exit; end; // Create a sprite to help batch calls when drawing many lines of text Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite); if Failed(Result) then Exit; // Setup the camera's projection parameters fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height; g_VCamera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 100.0); g_LCamera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 100.0); // Create the default texture (used when a triangle does not use a texture) Result:= pd3dDevice.CreateTexture(1, 1, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, g_pTexDef, nil); if Failed(Result) then Exit; Result:= g_pTexDef.LockRect(0, lr, nil, 0); if Failed(Result) then Exit; PDWORD(lr.pBits)^ := D3DCOLOR_RGBA(255, 255, 255, 255); Result:= g_pTexDef.UnlockRect(0); if Failed(Result) then Exit; // Restore the scene objects for i := 0 to NUM_OBJ - 1 do begin Result:= g_Obj[i].m_Mesh.RestoreDeviceObjects(pd3dDevice); if Failed(Result) then Exit; end; Result:= g_LightMesh.RestoreDeviceObjects(pd3dDevice); if Failed(Result) then Exit; // Restore the effect variables Result:= g_pEffect.SetVector('g_vLightDiffuse', PD3DXVector4(@g_Light.Diffuse)^); if Failed(Result) then Exit; Result:= g_pEffect.SetFloat('g_fCosTheta', Cos(g_Light.Theta)); if Failed(Result) then Exit; // Create the shadow map texture Result:= pd3dDevice.CreateTexture(SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R32F, D3DPOOL_DEFAULT, g_pShadowMap, nil); if Failed(Result) then Exit; // Create the depth-stencil buffer to be used with the shadow map // We do this to ensure that the depth-stencil buffer is large // enough and has correct multisample type/quality when rendering // the shadow map. The default depth-stencil buffer created during // device creation will not be large enough if the user resizes the // window to a very small size. Furthermore, if the device is created // with multisampling, the default depth-stencil buffer will not // work with the shadow map texture because texture render targets // do not support multisample. d3dSettings := DXUTGetDeviceSettings; Result:= pd3dDevice.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, d3dSettings.pp.AutoDepthStencilFormat, D3DMULTISAMPLE_NONE, 0, True, g_pDSShadow, nil); if Failed(Result) then Exit; // Initialize the shadow projection matrix D3DXMatrixPerspectiveFovLH(g_mShadowProj, g_fLightFov, 1, 0.01, 100.0); g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0); g_HUD.SetSize(170, pBackBufferSurfaceDesc.Height); pControl := g_HUD.GetControl(IDC_LIGHTPERSPECTIVE); if Assigned(pControl) then pControl.SetLocation(0, pBackBufferSurfaceDesc.Height - 50); pControl := g_HUD.GetControl(IDC_ATTACHLIGHTTOCAR); if Assigned(pControl) then pControl.SetLocation(0, pBackBufferSurfaceDesc.Height - 25); Result:= S_OK; end; //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var m: TD3DXMatrixA16; vR: TD3DXVector3; begin // Update the camera's position based on user input g_VCamera.FrameMove(fElapsedTime); g_LCamera.FrameMove(fElapsedTime); // Animate the plane, car and sphere meshes D3DXMatrixRotationY(m, D3DX_PI * fElapsedTime / 4.0); D3DXMatrixMultiply(g_Obj[1].m_mWorld, g_Obj[1].m_mWorld, m); D3DXMatrixRotationY(m, -D3DX_PI * fElapsedTime / 4.0); D3DXMatrixMultiply(g_Obj[2].m_mWorld, g_Obj[2].m_mWorld, m); vR:= D3DXVector3(0.1, 1.0, -0.2); D3DXMatrixRotationAxis(m, vR, -D3DX_PI * fElapsedTime / 6.0); D3DXMatrixMultiply(g_Obj[3].m_mWorld, m, g_Obj[3].m_mWorld); end; //-------------------------------------------------------------------------------------- // Renders the scene onto the current render target using the current // technique in the effect. //-------------------------------------------------------------------------------------- procedure RenderScene(pd3dDevice: IDirect3DDevice9; bRenderShadow: Boolean; fElapsedTime: Single; const pmView: TD3DXMatrix; const pmProj: TD3DXMatrix); var v3: TD3DXVector3; v4: TD3DXVector4; m: TD3DXMatrixA16; v9: TD3DXVector4; vPos: TD3DXVector4; obj: Integer; mWorldView: TD3DXMatrixA16; pMesh: ID3DXMesh; cPass: LongWord; i, p: Integer; vDif: TD3DXVector4; begin // Set the projection matrix V(g_pEffect.SetMatrix('g_mProj', pmProj)); // Update the light parameters in the effect if g_bFreeLight then begin // Freely moveable light. Get light parameter // from the light camera. v3 := g_LCamera.GetEyePt^; D3DXVec3Transform(v4, v3, pmView); V(g_pEffect.SetVector('g_vLightPos', v4)); PD3DXVector3(@v4)^ := g_LCamera.GetWorldAhead^; v4.w := 0.0; // Set w 0 so that the translation part doesn't come to play D3DXVec4Transform(v4, v4, pmView); // Direction in view space D3DXVec3Normalize(PD3DXVector3(@v4)^, PD3DXVector3(@v4)^); V(g_pEffect.SetVector('g_vLightDir', v4)); end else begin // Light attached to car. Get the car's world position and direction. m := g_Obj[2].m_mWorld; v3 := D3DXVector3(m._41, m._42, m._43); D3DXVec3Transform(vPos, v3, pmView); v4 := D3DXVector4(0.0, 0.0, -1.0, 1.0 ); // In object space, car is facing -Z m._41 := 0.0; m._42 := 0.0; m._43 := 0.0; // Remove the translation D3DXVec4Transform(v4, v4, m); // Obtain direction in world space v4.w := 0.0; // Set w 0 so that the translation part doesn't come to play D3DXVec4Transform(v4, v4, pmView); // Direction in view space D3DXVec3Normalize(PD3DXVector3(@v4)^, PD3DXVector3(@v4)^); V(g_pEffect.SetVector('g_vLightDir', v4)); // vPos += v4 * 4.0f; // Offset the center by 3 so that it's closer to the headlight. D3DXVec4Scale(v9, v4, 4.0); D3DXVec4Add(vPos, vPos, v9); V(g_pEffect.SetVector('g_vLightPos', vPos)); end; // Clear the render buffers V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, $000000ff, 1.0, 0)); if bRenderShadow then V(g_pEffect.SetTechnique('RenderShadow')); // Begin the scene if SUCCEEDED(pd3dDevice.BeginScene) then begin if not bRenderShadow then V(g_pEffect.SetTechnique('RenderScene')); // Render the objects for obj := 0 to NUM_OBJ - 1 do begin mWorldView := g_Obj[obj].m_mWorld; D3DXMatrixMultiply(mWorldView, mWorldView, pmView); V(g_pEffect.SetMatrix('g_mWorldView', mWorldView )); pMesh := g_Obj[obj].m_Mesh.Mesh; V(g_pEffect._Begin(@cPass, 0)); for p := 0 to cPass - 1 do begin V(g_pEffect.BeginPass(p)); for i := 0 to g_Obj[obj].m_Mesh.m_dwNumMaterials - 1 do begin vDif := D3DXVector4(g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.r, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.g, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.b, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.a); V(g_pEffect.SetVector('g_vMaterial', vDif)); if (g_Obj[obj].m_Mesh.m_pTextures[i] <> nil) then V(g_pEffect.SetTexture('g_txScene', g_Obj[obj].m_Mesh.m_pTextures[i])) else V(g_pEffect.SetTexture('g_txScene', g_pTexDef)); V(g_pEffect.CommitChanges); V(pMesh.DrawSubset(i)); end; V(g_pEffect.EndPass); end; V(g_pEffect._End); end; // Render light if not bRenderShadow then V(g_pEffect.SetTechnique('RenderLight')); mWorldView := g_LCamera.GetWorldMatrix^; D3DXMatrixMultiply(mWorldView, mWorldView, pmView); V(g_pEffect.SetMatrix('g_mWorldView', mWorldView)); pMesh := g_LightMesh.Mesh; V(g_pEffect._Begin(@cPass, 0)); for p := 0 to cPass - 1 do begin V(g_pEffect.BeginPass(p)); for i := 0 to g_LightMesh.m_dwNumMaterials - 1 do begin vDif := D3DXVector4(g_LightMesh.m_pMaterials[i].Diffuse.r, g_LightMesh.m_pMaterials[i].Diffuse.g, g_LightMesh.m_pMaterials[i].Diffuse.b, g_LightMesh.m_pMaterials[i].Diffuse.a); V(g_pEffect.SetVector('g_vMaterial', vDif)); V(g_pEffect.SetTexture('g_txScene', g_LightMesh.m_pTextures[i])); V(g_pEffect.CommitChanges); V(pMesh.DrawSubset(i)); end; V(g_pEffect.EndPass); end; V(g_pEffect._End); if not bRenderShadow then RenderText; // Render stats and help text // Render the UI elements if not bRenderShadow then g_HUD.OnRender(fElapsedTime); V(pd3dDevice.EndScene); end; end; //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall; var mLightView: TD3DXMatrixA16; vPos, vUp: TD3DXVector3; vDir: TD3DXVector4; pOldRT: IDirect3DSurface9; pShadowSurf: IDirect3DSurface9; pOldDS: IDirect3DSurface9; pmView: PD3DXMatrix; mViewToLightProj: TD3DXMatrixA16; begin // If the settings dialog is being shown, then // render it instead of rendering the app's scene if g_SettingsDlg.Active then begin g_SettingsDlg.OnRender(fElapsedTime); Exit; end; // // Compute the view matrix for the light // This changes depending on the light mode // (free movement or attached) // if g_bFreeLight then mLightView := g_LCamera.GetViewMatrix^ else begin // Light attached to car. mLightView := g_Obj[2].m_mWorld; vPos := D3DXVector3(mLightView._41, mLightView._42, mLightView._43); // Offset z by -2 so that it's closer to headlight vDir := D3DXVector4(0.0, 0.0, -1.0, 1.0); // In object space, car is facing -Z mLightView._41 := 0.0; mLightView._42 := 0.0; mLightView._43 := 0.0; // Remove the translation D3DXVec4Transform(vDir, vDir, mLightView); // Obtain direction in world space vDir.w := 0.0; // Set w 0 so that the translation part below doesn't come to play D3DXVec4Normalize(vDir, vDir); vPos.x := vPos.x + vDir.x * 4.0; // Offset the center by 4 so that it's closer to the headlight vPos.y := vPos.y + vDir.y * 4.0; vPos.z := vPos.x + vDir.z * 4.0; vDir.x := vDir.x + vPos.x; // vDir denotes the look-at point vDir.y := vDir.y + vPos.y; vDir.z := vDir.z + vPos.z; vUp := D3DXVector3(0.0, 1.0, 0.0); D3DXMatrixLookAtLH(mLightView, vPos, PD3DXVector3(@vDir)^, vUp); end; // // Render the shadow map // V(pd3dDevice.GetRenderTarget(0, pOldRT)); if SUCCEEDED(g_pShadowMap.GetSurfaceLevel(0, pShadowSurf)) then begin pd3dDevice.SetRenderTarget(0, pShadowSurf); SAFE_RELEASE(pShadowSurf); end; if SUCCEEDED(pd3dDevice.GetDepthStencilSurface(pOldDS)) then pd3dDevice.SetDepthStencilSurface(g_pDSShadow); try DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Shadow Map'); // g:= CDXUTPerfEventGenerator.( DXUT_PERFEVENTCOLOR, L"Shadow Map"); RenderScene(pd3dDevice, True, fElapsedTime, mLightView, g_mShadowProj); finally DXUT_EndPerfEvent; end; if (pOldDS <> nil) then begin pd3dDevice.SetDepthStencilSurface(pOldDS); pOldDS := nil; end; pd3dDevice.SetRenderTarget(0, pOldRT); SAFE_RELEASE(pOldRT); // // Now that we have the shadow map, render the scene. // if g_bCameraPerspective then pmView := g_VCamera.GetViewMatrix else pmView := @mLightView; // Initialize required parameter V(g_pEffect.SetTexture('g_txShadow', g_pShadowMap)); // Compute the matrix to transform from view space to // light projection space. This consists of // the inverse of view matrix * view matrix of light * light projection matrix mViewToLightProj := pmView^; D3DXMatrixInverse(mViewToLightProj, nil, mViewToLightProj); D3DXMatrixMultiply(mViewToLightProj, mViewToLightProj, mLightView); D3DXMatrixMultiply(mViewToLightProj, mViewToLightProj, g_mShadowProj); V(g_pEffect.SetMatrix('g_mViewToLightProj', mViewToLightProj)); try DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'Scene'); // CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Scene" ); RenderScene(pd3dDevice, False, fElapsedTime, pmView^, g_VCamera.GetProjMatrix^); finally DXUT_EndPerfEvent; end; g_pEffect.SetTexture('g_txShadow', nil); end; //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- procedure RenderText; var txtHelper: CDXUTTextHelper; pd3dsdBackBuffer: PD3DSurfaceDesc; begin // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15); try // Output statistics txtHelper._Begin; txtHelper.SetInsertionPos(5, 5); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0)); txtHelper.DrawTextLine(DXUTGetFrameStats(True)); // Show FPS txtHelper.DrawTextLine(DXUTGetDeviceStats); txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); // Draw help if g_bShowHelp then begin pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc; txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*10); txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0)); txtHelper.DrawTextLine('Controls:'); txtHelper.SetInsertionPos(15, pd3dsdBackBuffer.Height-15*9); txtHelper.DrawFormattedTextLine( 'Rotate camera'#10'Move camera'#10+ 'Rotate light'#10'Move light'#10+ 'Change light mode (Current: %s)'#10'Change view reference (Current: %s)'#10+ 'Hide help'#10'Quit', [IfThen(g_bFreeLight, 'Free', 'Car-attached'), IfThen(g_bCameraPerspective, 'Camera', 'Light')]); txtHelper.SetInsertionPos(265, pd3dsdBackBuffer.Height-15*9); txtHelper.DrawTextLine( 'Left drag mouse'#10'W,S,A,D,Q,E'#10+ 'Right drag mouse'#10'W,S,A,D,Q,E while holding right mouse'#10+ 'F'#10'V'#10'F1'#10'ESC'); end else begin txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0)); txtHelper.DrawTextLine('Press F1 for help'); end; txtHelper._End; finally txtHelper.Free; end; end; //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall; begin Result:= 0; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; if g_SettingsDlg.IsActive then begin g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); Exit; end; pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if pbNoFurtherProcessing then Exit; // Pass all windows messages to camera and dialogs so they can respond to user input if (WM_KEYDOWN <> uMsg) or g_bRightMouseDown then g_LCamera.HandleMessages(hWnd, uMsg, wParam, lParam); if (WM_KEYDOWN <> uMsg) or not g_bRightMouseDown then begin if g_bCameraPerspective then g_VCamera.HandleMessages(hWnd, uMsg, wParam, lParam) else g_LCamera.HandleMessages(hWnd, uMsg, wParam, lParam); end; end; //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall; begin end; procedure MouseProc(bLeftButtonDown, bRightButtonDown, bMiddleButtonDown, bSideButton1Down, bSideButton2Down: Boolean; nMouseWheelDelta, xPos, yPos: Integer; pUserContext: Pointer); stdcall; begin g_bRightMouseDown := bRightButtonDown; end; //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall; var pCheck: CDXUTCheckBox; begin case nControlID of IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen; IDC_TOGGLEREF: DXUTToggleREF; IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active; IDC_CHECKBOX: begin pCheck := CDXUTCheckBox(pControl); g_bShowHelp := pCheck.Checked; end; IDC_LIGHTPERSPECTIVE: begin pCheck := CDXUTCheckBox(pControl); g_bCameraPerspective := not pCheck.Checked; if g_bCameraPerspective then begin g_VCamera.SetRotateButtons(True, False, False); g_LCamera.SetRotateButtons(False, False, True); end else begin g_VCamera.SetRotateButtons(False, False, False); g_LCamera.SetRotateButtons(True, False, True); end; end; IDC_ATTACHLIGHTTOCAR: begin pCheck := CDXUTCheckBox(pControl); g_bFreeLight := not pCheck.Checked; end; end; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- procedure OnLostDevice; stdcall; var i: Integer; begin g_DialogResourceManager.OnLostDevice; g_SettingsDlg.OnLostDevice; if Assigned(g_pFont) then g_pFont.OnLostDevice; if Assigned(g_pFontSmall) then g_pFontSmall.OnLostDevice; if Assigned(g_pEffect) then g_pEffect.OnLostDevice; SAFE_RELEASE(g_pTextSprite); SAFE_RELEASE(g_pDSShadow); SAFE_RELEASE(g_pShadowMap); SAFE_RELEASE(g_pTexDef); for i := 0 to NUM_OBJ - 1 do if Assigned(g_Obj[i]) then g_Obj[i].m_Mesh.InvalidateDeviceObjects; if Assigned(g_LightMesh) then g_LightMesh.InvalidateDeviceObjects; end; //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- procedure OnDestroyDevice; stdcall; var i: Integer; begin g_DialogResourceManager.OnDestroyDevice; g_SettingsDlg.OnDestroyDevice; SAFE_RELEASE(g_pEffect); SAFE_RELEASE(g_pFont); SAFE_RELEASE(g_pFontSmall); SAFE_RELEASE(g_pVertDecl); SAFE_RELEASE(g_pEffect); for i := 0 to NUM_OBJ - 1 do if Assigned(g_Obj[i]) then g_Obj[i].m_Mesh.DestroyMesh; if Assigned(g_LightMesh) then g_LightMesh.DestroyMesh; end; { CViewCamera } function CViewCamera.MapKey(nKey: LongWord): TD3DUtil_CameraKeys; begin // Provide custom mapping here. // Same as default mapping but disable arrow keys. case nKey of Ord('A'): Result:= CAM_STRAFE_LEFT; Ord('D'): Result:= CAM_STRAFE_RIGHT; Ord('W'): Result:= CAM_MOVE_FORWARD; Ord('S'): Result:= CAM_MOVE_BACKWARD; Ord('Q'): Result:= CAM_MOVE_DOWN; Ord('E'): Result:= CAM_MOVE_UP; VK_HOME: Result:= CAM_RESET; else Result:= CAM_UNKNOWN; end; end; { CLightCamera } function CLightCamera.MapKey(nKey: LongWord): TD3DUtil_CameraKeys; begin // Provide custom mapping here. // Same as default mapping but disable arrow keys. case nKey of VK_LEFT: Result:= CAM_STRAFE_LEFT; VK_RIGHT: Result:= CAM_STRAFE_RIGHT; VK_UP: Result:= CAM_MOVE_FORWARD; VK_DOWN: Result:= CAM_MOVE_BACKWARD; VK_PRIOR: Result:= CAM_MOVE_UP; // pgup VK_NEXT: Result:= CAM_MOVE_DOWN; // pgdn VK_NUMPAD4: Result:= CAM_STRAFE_LEFT; VK_NUMPAD6: Result:= CAM_STRAFE_RIGHT; VK_NUMPAD8: Result:= CAM_MOVE_FORWARD; VK_NUMPAD2: Result:= CAM_MOVE_BACKWARD; VK_NUMPAD9: Result:= CAM_MOVE_UP; VK_NUMPAD3: Result:= CAM_MOVE_DOWN; VK_HOME: Result:= CAM_RESET; else Result:= CAM_UNKNOWN; end; end; { CObj } constructor CObj.Create; begin m_Mesh:= CDXUTMesh.Create; end; destructor CObj.Destroy; begin FreeAndNil(m_Mesh); inherited; end; procedure CreateCustomDXUTobjects; var i: Integer; vFromPt, vLookatPt: TD3DXVector3; begin g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog g_HUD:= CDXUTDialog.Create; // dialog for standard controls g_VCamera:= CFirstPersonCamera.Create; // View camera g_LCamera:= CFirstPersonCamera.Create; // Camera obj to help adjust light for i:= 0 to NUM_OBJ-1 do g_Obj[i]:= CObj.Create; // Scene object meshes g_LightMesh:= CDXUTMesh.Create; // Initialize the camera g_VCamera.SetScalers(0.01, 15.0); g_LCamera.SetScalers(0.01, 8.0); g_VCamera.SetRotateButtons(True, False, False); g_LCamera.SetRotateButtons(False, False, True); // Set up the view parameters for the camera vFromPt := D3DXVector3(0.0, 5.0, -18.0); vLookatPt := D3DXVector3(0.0, -1.0, 0.0); g_VCamera.SetViewParams( vFromPt, vLookatPt); vFromPt := D3DXVector3(0.0, 0.0, -12.0); vLookatPt := D3DXVECTOR3(0.0, -2.0, 1.0); g_LCamera.SetViewParams(vFromPt, vLookatPt); // Initialize the spot light g_fLightFov := D3DX_PI / 2.0; g_Light.Diffuse.r := 1.0; g_Light.Diffuse.g := 1.0; g_Light.Diffuse.b := 1.0; g_Light.Diffuse.a := 1.0; g_Light.Position := D3DXVector3( -8.0, -8.0, 0.0); g_Light.Direction := D3DXVector3( 1.0, -1.0, 0.0); D3DXVec3Normalize(PD3DXVector3(@g_Light.Direction)^, PD3DXVector3(@g_Light.Direction)^); g_Light.Range := 10.0; g_Light.Theta := g_fLightFov / 2.0; g_Light.Phi := g_fLightFov / 2.0; end; procedure DestroyCustomDXUTobjects; var i: Integer; begin FreeAndNil(g_DialogResourceManager); FreeAndNil(g_SettingsDlg); FreeAndNil(g_HUD); FreeAndNil(g_VCamera); FreeAndNil(g_LCamera); for i:= 0 to NUM_OBJ-1 do FreeAndNil(g_Obj[i]); // Scene object meshes FreeAndNil(g_LightMesh); end; end.
unit ufrmProductTypeNBD; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMaster, ufraFooter5Button, StdCtrls, ExtCtrls, ActnList, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, System.Actions, ufrmMasterBrowse, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, ufraFooter4Button, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, dxBarBuiltInMenu, Vcl.Menus, cxButtons, cxPC; type TfrmProductTypeNBD = class(TfrmMasterBrowse) actlst1: TActionList; actAddProductTypeNBD: TAction; actEditProductTypeNBD: TAction; actDeleteProductTypeNBD: TAction; actRefreshProductTypeNBD: TAction; pnl1: TPanel; edtOwner: TEdit; lbl1: TLabel; lbl2: TLabel; edtCostCenterDesc: TEdit; edtAccNameDB: TEdit; lbl3: TLabel; edtAccNameCR: TEdit; lbl4: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure actAddProductTypeNBDExecute(Sender: TObject); procedure actEditProductTypeNBDExecute(Sender: TObject); procedure actDeleteProductTypeNBDExecute(Sender: TObject); procedure actRefreshProductTypeNBDExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure stringgridGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure FormActivate(Sender: TObject); procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); private IdProductTypeNBD: integer; strnama: string; procedure RefreshData(); public { Public declarations } end; var frmProductTypeNBD: TfrmProductTypeNBD; implementation uses ufrmDialogProductTypeNBD, uTSCommonDlg, Math, uConn, uConstanta; {$R *.dfm} procedure TfrmProductTypeNBD.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; //frmMain.DestroyMenu((sender as TForm)); Action := caFree; end; procedure TfrmProductTypeNBD.FormDestroy(Sender: TObject); begin inherited; frmProductTypeNBD := nil; end; procedure TfrmProductTypeNBD.actAddProductTypeNBDExecute(Sender: TObject); begin // if (MasterNewUnit.ID=0) or (Mastercompany.ID=0) then begin CommonDlg.ShowError(ER_UNIT_OR_COMPANY_NOT_SPECIFIC); //frmMain.cbbUnit.SetFocus; Exit; end; if not Assigned(frmDialogProductTypeNBD) then Application.CreateForm(TfrmDialogProductTypeNBD, frmDialogProductTypeNBD); frmDialogProductTypeNBD.Caption := 'Add NBD Product Type'; frmDialogProductTypeNBD.FormMode := fmAdd; //frmDialogProductTypeNBD.UntID := MasterNewUnit.ID; //frmDialogProductTypeNBD.CompID := Mastercompany.ID; SetFormPropertyAndShowDialog(frmDialogProductTypeNBD); if (frmDialogProductTypeNBD.IsProcessSuccessfull) then begin actRefreshProductTypeNBDExecute(Self); CommonDlg.ShowConfirm(atAdd); end; frmDialogProductTypeNBD.Free; end; procedure TfrmProductTypeNBD.actEditProductTypeNBDExecute(Sender: TObject); begin // if strgGrid.Cells[5,strgGrid.row]='0' then Exit; // if (MasterNewUnit.ID=0) or (Mastercompany.ID=0) then begin CommonDlg.ShowError(ER_UNIT_OR_COMPANY_NOT_SPECIFIC); //frmMain.cbbUnit.SetFocus; Exit; end; if not Assigned(frmDialogProductTypeNBD) then Application.CreateForm(TfrmDialogProductTypeNBD, frmDialogProductTypeNBD); frmDialogProductTypeNBD.Caption := 'Edit NBD Product Type'; frmDialogProductTypeNBD.FormMode := fmEdit; // frmDialogProductTypeNBD.UntID := MasterNewUnit.ID; // frmDialogProductTypeNBD.CompID := Mastercompany.ID; // frmDialogProductTypeNBD.ProductTypeNBDId := StrToInt(strgGrid.Cells[5,strgGrid.row]); SetFormPropertyAndShowDialog(frmDialogProductTypeNBD); if (frmDialogProductTypeNBD.IsProcessSuccessfull) then begin actRefreshProductTypeNBDExecute(Self); CommonDlg.ShowConfirm(atEdit); end; frmDialogProductTypeNBD.Free; end; procedure TfrmProductTypeNBD.actDeleteProductTypeNBDExecute(Sender: TObject); begin // if strgGrid.Cells[5,strgGrid.row]='0' then Exit; // if (CommonDlg.Confirm('Are you sure you wish to delete Product Type (Code : '+strgGrid.Cells[0,strgGrid.row]+')?') = mrYes) then begin { if not assigned(ProductTypeNBD) then ProductTypeNBD := TProductTypeNBD.Create; if ProductTypeNBD.DeleteProductTypeNBD(StrToInt(strgGrid.Cells[5,strgGrid.row])) then begin actRefreshProductTypeNBDExecute(Self); CommonDlg.ShowConfirm(atDelete); end else CommonDlg.ShowError('Sudah pernah ada Transaksi ' + #13 + ' Tidak dapat di hapus ' ); }end; end; procedure TfrmProductTypeNBD.RefreshData; var data: TDataSet; i: Integer; tempBool: Boolean; begin {if not assigned(ProductTypeNBD) then ProductTypeNBD := TProductTypeNBD.Create; data := ProductTypeNBD.GetDataProductTypeNBD(MasterNewUnit.ID); with strgGrid do begin Clear; RowCount := data.RecordCount+1; ColCount := 5; Cells[0, 0] := 'CODE'; Cells[1, 0] := 'NAME'; Cells[2, 0] := 'COST CENTER'; Cells[3, 0] := 'ACCOUNT DB'; Cells[4, 0] := 'ACCOUNT CR'; i:=1; if RowCount>1 then with data do while not Eof do begin Cells[0, i] := data.Fieldbyname('TPPRO_CODE').AsString; Cells[1, i] := data.Fieldbyname('TPPRO_NAME').AsString; Cells[2, i] := 'FAKE DATA COST CENTER '+ IntToStr(i); //data.Fieldbyname('TPPRO_NAME').AsString; Cells[3, i] := data.Fieldbyname('TPPRO_REK_DEBET').AsString; Cells[4, i] := data.Fieldbyname('TPPRO_REK_CREDIT').AsString; Cells[5, i] := IntToStr(data.Fieldbyname('TPPRO_ID').AsInteger); Cells[6, i] := data.Fieldbyname('TPPRO_OWNER').AsString; Cells[7, i] := 'FAKE DATA COST CENTER '+ IntToStr(i); Cells[8, i] := data.Fieldbyname('ACCOUNT_NAME_DB').AsString; Cells[9, i] := data.Fieldbyname('ACCOUNT_NAME_CR').AsString; i:=i+1; Next; end else begin RowCount:=2; Cells[0, 1] := ' '; Cells[1, 1] := ' '; Cells[2, 1] := ' '; Cells[3, 1] := ' '; Cells[4, 1] := ' '; Cells[5, 1] := '0'; //ID Cells[6, 1] := ' '; Cells[7, 1] := ' '; Cells[8, 1] := ' '; Cells[9, 1] := ' '; end; FixedRows := 1; AutoSize := true; end; strgGridRowChanging(Self,0,1,tempBool); strgGrid.SetFocus; } end; procedure TfrmProductTypeNBD.actRefreshProductTypeNBDExecute(Sender: TObject); begin RefreshData(); end; procedure TfrmProductTypeNBD.FormShow(Sender: TObject); begin inherited; lblHeader.Caption := 'NBD PRODUCT TYPE'; actRefreshProductTypeNBDExecute(Self); end; procedure TfrmProductTypeNBD.stringgridGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin inherited; // IdProductTypeNBD:= StrToInt(strgGrid.Cells[2,arow]); // strNama:= strgGrid.Cells[1,arow]; end; procedure TfrmProductTypeNBD.FormActivate(Sender: TObject); begin inherited; //frmMain.CreateMenu((sender as TForm)); end; procedure TfrmProductTypeNBD.strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin inherited; // edtOwner.Text := strgGrid.Cells[6,NewRow]; // edtCostCenterDesc.Text := strgGrid.Cells[7,NewRow]; // edtAccNameDB.Text := strgGrid.Cells[8,NewRow]; // edtAccNameCR.Text := strgGrid.Cells[9,NewRow]; end; end.
unit UniStrUtils; {$WEAKPACKAGEUNIT ON} interface uses SysUtils, Windows, StrUtils, WideStrUtils; (* В библиотеке введён дополнительный тип: UniString. На старых компиляторах UniString = WideString На новых UniString = UnicodeString (и == string, если включено UNICODE) Все функции существуют в следующих версиях: Function: агностическая функция (для типа string) AnsiFunction (FunctionA): версия для AnsiString WideFunction (FunctionW): версия для WideString UniFunction (FunctionU): версия для UniString (оптимальная) Библиотека старается наверстать все упущения Delphi, и добавляет недостающие функции: Агностические, если в Дельфи они забыты (объявлены, как AnsiFunction). Подлинные Ansi, если в Дельфи под этим именем агностическая. Подлинные Wide, если таких нет в стандартных библиотеках. И оптимальные Uni. В виде исключения, если подлинных Wide в дельфи нет, они иногда объявляются здесь сразу для UnicodeString. Таким образом, UniFunction/WideFunction даёт вам поддержку юникода в наилучшем возможном виде, а простая Function работает со строками, которые приняты по умолчанию на платформе компиляции. Следует помнить, что WideChar == UnicodeChar, и PWideChar в любом случае ничуть не отличается от PUnicodeChar. Поэтому функции, которые работают с PWideChar, не требуют изменений. Используются проверки: IFDEF UNICODE: для проверки типа string (Ansi или Unicode) IF CompilerVersion>=21: для проверки доступности новых типов и функций Например: IFDEF UNICODE => string == UnicodeString (по умолчанию включен юникод) IF CompilerVersion>=21 => UniString == UnicodeString (юникод ДОСТУПЕН В ПРИНЦИПЕ) *) (* О скорости разных методов работы со строками. I. Приведение к PWideChar ============================== @s[1] вызывает UniqueStringU PWideChar(s) вызывает WCharFromUStr Поэтому если нужно просто получить указатель, делайте: PWideChar(pointer(s))+offset*SizeOf(WideChar) Это самый быстрый способ (в несколько раз быстрее, никаких вызовов). II. Length ============= Зачем-то вызывает UniqueStringU. Если нужно просто проверить на непустоту, используйте: pointer(s) <> nil *) const BOM_UTF16BE: AnsiString = #254#255; //FE FF BOM_UTF16LE: AnsiString = #255#254; //FF FE //должны быть ansi, иначе получится два юникод-символа type //UniString - это наилучший доступный на платформе Unicode-тип. //На старых компиляторах UniString=WideString, на новых UniString=UnicodeString. {$IF CompilerVersion >= 21} UniString = UnicodeString; PUniString = PUnicodeString; {$ELSE} UniString = WideString; PUniString = PWideString; //Доопределяем новые символы на старых платформах для быстрой совместимости UnicodeString = UniString; PUnicodeString = PUniString; {$IFEND} UniChar = WideChar; PUniChar = PWideChar; TAnsiStringArray = array of AnsiString; TUniStringArray = array of UniString; TStringArrayA = TAnsiStringArray; TStringArrayU = TUniStringArray; {$IFDEF UNICODE} TUnicodeStringArray = TUniStringArray; TStringArray = TUniStringArray; {$ELSE} TStringArray = TAnsiStringArray; {$ENDIF} //С Wide мы не очень хорошо поступили: //возможно, кому-то хочется массив именно WideString. TWideStringArray = TUniStringArray; //Указатели PStringArray = ^TStringArray; PAnsiStringArray = ^TAnsiStringArray; PWideStringArray = ^TWideStringArray; PUniStringArray = ^TUniStringArray; //Обратная совместимость TStringArrayW = TWideStringArray; {$IF CompilerVersion < 21} //В старых версиях не объявлены, а ими удобно пользоваться UCS2Char = WideChar; PUCS2Char = PWideChar; UCS4Char = type LongWord; PUCS4Char = ^UCS4Char; TUCS4CharArray = array [0..$effffff] of UCS4Char; PUCS4CharArray = ^TUCS4CharArray; UCS4String = array of UCS4Char; //На старом компиляторе преобразований кодировки для AnsiString не выполняется, //и она безопасна для UTF8 и RawByte как есть (в новых нужно указать флаги) UTF8String = AnsiString; PUTF8String = ^UTF8String; RawByteString = AnsiString; PRawByteString = ^RawByteString; {$IFEND} {$IFDEF UNICODE} (* В юникод-версиях Дельфи некоторые Ansi-функции объявлены как UniString. Например, UpperCase - принимает string и работает только с ASCII AnsiUpperCase - принимает string и работает со всеми строками То есть, Ansi фактически Uni. Само по себе это не страшно (главное помнить не использовать UpperCase), но при компиляции Ansi-кода возникают дурацкие варнинги. Так что здесь представлены "честные" функции для Ansi-строк. *) function AnsiPos(const Substr, S: AnsiString): Integer; function AnsiStringReplace(const S, OldPattern, NewPattern: AnsiString; Flags: TReplaceFlags): AnsiString; function AnsiReplaceStr(const AText, AFromText, AToText: AnsiString): AnsiString; inline; function AnsiReplaceText(const AText, AFromText, AToText: AnsiString): AnsiString; inline; function AnsiUpperCase(const S: AnsiString): AnsiString; function AnsiLowerCase(const S: AnsiString): AnsiString; function AnsiCompareStr(const S1, S2: AnsiString): Integer; function AnsiSameStr(const S1, S2: AnsiString): Boolean; inline; function AnsiCompareText(const S1, S2: AnsiString): Integer; function AnsiSameText(const S1, S2: AnsiString): Boolean; inline; {$ENDIF} (* These are present in SysUtils/StrUtils/WideStrUtils function WideUpperCase(const S: WideString): WideString; function WideLowerCase(const S: WideString): WideString; ...etc But we have unicode versions (always optimal): *) function UStrPCopy(Dest: PUniChar; const Source: UniString): PUniChar; inline; function UStrPLCopy(Dest: PUniChar; const Source: UniString; MaxLen: Cardinal): PUniChar; inline; function UniLastChar(const S: UniString): PUniChar; inline; function UniQuotedStr(const S: UniString; Quote: UniChar): UniString; inline; function UniExtractQuotedStr(var Src: PUniChar; Quote: UniChar): UniString; inline; function UniDequotedStr(const S: UniString; AQuote: UniChar): UniString; inline; function UniAdjustLineBreaks(const S: UniString; Style: TTextLineBreakStyle = tlbsCRLF): UniString; inline; function UniStringReplace(const S, OldPattern, NewPattern: UniString; Flags: TReplaceFlags): UniString; inline; function UniReplaceStr(const AText, AFromText, AToText: UniString): UniString; inline; function UniReplaceText(const AText, AFromText, AToText: UniString): UniString; inline; function UniUpperCase(const S: UniString): UniString; inline; function UniLowerCase(const S: UniString): UniString; inline; function UniCompareStr(const S1, S2: UniString): Integer; inline; function UniSameStr(const S1, S2: UniString): Boolean; inline; function UniCompareText(const S1, S2: UniString): Integer; inline; function UniSameText(const S1, S2: UniString): Boolean; inline; (* Wide-версии стандартных функций. На новых компиляторах функции линкуются к системным. На старых реализованы с нуля. *) //remember, this returns the BYTE offset function WidePos(const Substr, S: UniString): Integer; function WideMidStr(const AText: UniString; const AStart: integer; const ACount: integer): UniString; //Логика функций сравнения та же, что у Ansi-версий: сравнение лингвистическое, //с учётом юникод-цепочек, а не бинарное, по байтам. function WideStrComp(S1, S2: PWideChar): Integer; function WideStrIComp(S1, S2: PWideChar): Integer; function WideStartsStr(const ASubText: UniString; const AText: UniString): boolean; function WideEndsStr(const ASubText: UniString; const AText: UniString): boolean; function WideContainsStr(const AText: UniString; const ASubText: UniString): boolean; function WideStartsText(const ASubText: UniString; const AText: UniString): boolean; function WideEndsText(const ASubText: UniString; const AText: UniString): boolean; function WideContainsText(const AText: UniString; const ASubText: UniString): boolean; (* Далее идут вспомогательные функции библиотеки, написанные во всех версиях с нуля. Юникод-версии представлены как FunctionW или WideFunction. *) //Поиск строки в массивах //Wide-версии нет, поскольку TWideStringArray ==def== TUniStringArray function AnsiStrInArray(a: TAnsiStringArray; s: AnsiString): integer; function AnsiTextInArray(a: TAnsiStringArray; s: AnsiString): integer; function UniStrInArray(a: TUniStringArray; s: UniString): integer; function UniTextInArray(a: TUniStringArray; s: UniString): integer; function StrInArray(a: TStringArray; s: string): integer; function TextInArray(a: TStringArray; s: string): integer; //Splits a string by a single type of separators. Ansi version. function StrSplitA(s: PAnsiChar; sep: AnsiChar): TAnsiStringArray; function StrSplitW(s: PUniChar; sep: UniChar): TUniStringArray; function StrSplit(s: PChar; sep: char): TStringArray; //Same, just with Strings function AnsiSepSplit(s: AnsiString; sep: AnsiChar): TAnsiStringArray; function WideSepSplit(s: UniString; sep: UniChar): TUniStringArray; function SepSplit(s: string; sep: char): TStringArray; //Бьёт строку по нескольким разделителям, с учётом кавычек function StrSplitExA(s: PAnsiChar; sep: PAnsiChar; quote: AnsiChar): TAnsiStringArray; function StrSplitExW(s: PUnichar; sep: PUniChar; quote: UniChar): TUniStringArray; function StrSplitEx(s: PChar; sep: PChar; quote: Char): TStringArray; //Joins a string array usng the specified separator function AnsiSepJoin(s: TAnsiStringArray; sep: AnsiChar): AnsiString; overload; function WideSepJoin(s: TUniStringArray; sep: UniChar): UniString; overload; function SepJoin(s: TStringArray; sep: Char): string; overload; //Same, just receives a point to a first string, and their number function AnsiSepJoin(s: PAnsiString; cnt: integer; sep: AnsiChar): AnsiString; overload; function WideSepJoin(s: PUniString; cnt: integer; sep: UniChar): UniString; overload; function SepJoin(s: PString; cnt: integer; sep: Char): string; overload; //Возвращает в виде WideString строку PWideChar, но не более N символов //Полезно для чтения всяких буферов фиксированного размера, где не гарантирован ноль. function AnsiStrFromBuf(s: PAnsiChar; MaxLen: integer): AnsiString; function WideStrFromBuf(s: PUniChar; MaxLen: integer): UniString; function StrFromBuf(s: PChar; MaxLen: integer): string; //Checks if a char is a number function AnsiCharIsNumber(c: AnsiChar): boolean; inline; function WideCharIsNumber(c: UniChar): boolean; inline; function CharIsNumber(c: char): boolean; inline; //Check if a char is a latin symbol function AnsiCharIsLatinSymbol(c: AnsiChar): boolean; inline; function WideCharIsLatinSymbol(c: UniChar): boolean; inline; function CharIsLatinSymbol(c: char): boolean; inline; //Check if a string is composed only from numbers and latin symbols function AnsiStrIsLnOnly(str: AnsiString): boolean; function WideStrIsLnOnly(str: UniString): boolean; function StrIsLnOnly(str: string): boolean; //These have significantly different implementation when working with Ansi code page, //so they're implemented only in Unicode yet. function IsHiragana(c: UniChar): boolean; function IsKatakana(c: UniChar): boolean; function IsKana(c: UniChar): boolean; function IsKanji(c: UniChar): boolean; //Возвращает номер символа, на который указывает ptr, в строке str function AnsiPcharInd(str, ptr: PAnsiChar): integer; function WidePcharInd(str, ptr: PUniChar): integer; function PcharInd(str, ptr: PChar): integer; //Возвращает длину отрезка PChar в символах. function CharLenA(p1, p2: PAnsiChar): integer; function CharLenW(p1, p2: PUniChar): integer; function CharLen(p1, p2: PChar): integer; //Находит конец строки function StrEndA(s: PAnsiChar): PAnsiChar; function StrEndW(s: PUniChar): PUniChar; function StrEnd(s: PChar): PChar; //Быстрое обращение к следующему-предыдущему символу function NextChar(p: PAnsiChar; c: integer = 1): PAnsiChar; overload; function PrevChar(p: PAnsiChar; c: integer = 1): PAnsiChar; overload; function NextChar(p: PWideChar; c: integer = 1): PWideChar; overload; function PrevChar(p: PWideChar; c: integer = 1): PWideChar; overload; { Арифметика указателей } function PwcOff(var a; n: integer): PWideChar; inline; function PwcCmp(var a; var b): integer; inline; overload; function PwcCmp(var a; an: integer; var b; bn: integer): integer; inline; overload; //Возвращает подстроку с заданного места и нужного размера. function StrSubLA(beg: PAnsiChar; len: integer): AnsiString; function StrSubLW(beg: PUniChar; len: integer): UniString; function StrSubL(beg: PChar; len: integer): string; //Возвращает подстроку с заданного места и до заданного места не включительно. function StrSubA(beg: PAnsiChar; en: PAnsiChar): AnsiString; function StrSubW(beg: PUniChar; en: PUniChar): UniString; function StrSub(beg: PChar; en: PChar): string; //Обратная совместимость function SubStrPchA(beg, en: PAnsiChar): AnsiString; function SubStrPchW(beg, en: PUniChar): UniString; function SubStrPch(beg, en: pchar): string; //Scans the specified string for the specfied character. Starts at position <start_at>. //Ends at <end_at> - 1 symbols. Returns first symbol index in string or -1 if not found any. function AnsiFindChar(s: AnsiString; c: AnsiChar; start_at: integer = 1; end_at: integer = -1): integer; function WideFindChar(s: UniString; c: UniChar; start_at: integer = 1; end_at: integer = -1): integer; function FindChar(s: string; c: char; start_at: integer = 1; end_at: integer = -1): integer; //Дополнения к стандартной дельфийской StrScan function StrScanA(str: PAnsiChar; chr: AnsiChar): PAnsiChar; function StrScanW(str: PUniChar; chr: UniChar): PUniChar; //Ищет любой из перечисленных символов, иначе возвращает nil. function StrScanAnyA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar; function StrScanAnyW(str: PUniChar; symbols: PUniChar): PUniChar; function StrScanAny(str: PChar; symbols: PChar): PChar; //Ищет любой из перечисленных символов, иначе возвращает указатель на конец строки. function StrScanEndA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar; function StrScanEndW(str: PUniChar; symbols: PUniChar): PWideChar; function StrScanEnd(str: PChar; symbols: PChar): PChar; (* Обратная совместимость: 1. Функции StrScanAny раньше назывались StrPosAny. 2. Функции StrScanDef раньше назывались StrScan. Оба переименования совершены с целью унификации названий с Дельфи. StrScanAny ведёт себя в точности как StrScan, только для нескольких символов. *) //Находит первый символ из набора cs, возвращает ссылку на него и кусок текста до него. //Если такого символа нет, возвращает остаток строки и nil. function AnsiReadUpToNext(str: PAnsiChar; cs: AnsiString; out block: AnsiString): PAnsiChar; function WideReadUpToNext(str: PUniChar; cs: UniString; out block: UniString): PUniChar; function ReadUpToNext(str: PChar; cs: string; out block: string): PChar; //Сравнивает строки до окончания любой из них. function StrCmpNext(a, b: PChar): boolean; inline; //Возвращает длину совпадающего участка c начала строк, в символах, включая нулевой. function StrMatch(a, b: PChar): integer; inline; //Пропускает все символы до первого, не входящего в chars (null-term string) procedure SkipChars(var pc: PChar; chars: PChar); //Removes quote characters from around the string, if they exist. //Duplicate: UniDequotedStr, although this one is more powerful function AnsiStripQuotes(s: AnsiString; qc1, qc2: AnsiChar): AnsiString; function WideStripQuotes(s: UniString; qc1, qc2: UniChar): UniString; function StripQuotes(s: string; qc1, qc2: char): string; //Удаляет пробелы из конца строки - версия для String function STrimStartA(s: AnsiString; sep: AnsiChar = ' '): AnsiString; function STrimStartW(s: UniString; sep: UniChar = ' '): UniString; function STrimStart(s: string; sep: Char = ' '): string; function STrimEndA(s: AnsiString; sep: AnsiChar = ' '): AnsiString; function STrimEndW(s: UniString; sep: UniChar = ' '): UniString; function STrimEnd(s: string; sep: Char = ' '): string; function STrimA(s: AnsiString; sep: AnsiChar = ' '): AnsiString; function STrimW(s: UniString; sep: UniChar = ' '): UniString; function STrim(s: string; sep: Char = ' '): string; //Удаляет пробелы из конца строки - версия для PChar function PTrimStartA(s: PAnsiChar; sep: AnsiChar = ' '): AnsiString; function PTrimStartW(s: PUniChar; sep: UniChar = ' '): UniString; function PTrimStart(s: PChar; sep: Char = ' '): string; function PTrimEndA(s: PAnsiChar; sep: AnsiChar = ' '): AnsiString; function PTrimEndW(s: PUniChar; sep: UniChar = ' '): UniString; function PTrimEnd(s: PChar; sep: Char = ' '): string; function PTrimA(s: PAnsiChar; sep: AnsiChar = ' '): AnsiString; function PTrimW(s: PUniChar; sep: UniChar = ' '): UniString; function PTrim(s: PChar; sep: Char = ' '): string; //Удаляет пробелы из начала и конца строки, заданных прямо. function BETrimA(beg, en: PAnsiChar; sep: AnsiChar = ' '): AnsiString; function BETrimW(beg, en: PUniChar; sep: UniChar = ' '): UniString; function BETrim(beg, en: PChar; sep: Char = ' '): string; { Binary/string conversion } //Преобразует данные в цепочку hex-кодов. function BinToHex(ptr: pbyte; sz: integer): AnsiString; //Преобразует массив байт в цепочку hex-кодов. function DataToHex(data: array of byte): AnsiString; //Декодирует один hex-символ в число от 1 до 16 function HexCharValue(c: AnsiChar): byte; inline; //Декодирует строку из hex-пар в данные. Место под данные должно быть выделено заранее procedure HexToBin(s: AnsiString; p: pbyte; size: integer); { Codepage utils } //Превращает один символ в Wide/Ansi function ToWideChar(c: AnsiChar; cp: cardinal): WideChar; function ToChar(c: WideChar; cp: cardinal): AnsiChar; //Превращает строку в Wide/Ansi function ToWideString(s: AnsiString; cp: cardinal): WideString; function ToString(s: WideString; cp: cardinal): AnsiString; //Превращает буфер заданной длины в Wide/Ansi function BufToWideString(s: PAnsiChar; len: integer; cp: cardinal): WideString; function BufToString(s: PWideChar; len: integer; cp: cardinal): AnsiString; //Меняет кодировку Ansi-строки function Convert(s: AnsiString; cpIn, cpOut: cardinal): AnsiString; //Меняет кодировку Ansi-строки с системной на консольную и наоборот function WinToOEM(s: AnsiString): AnsiString; inline; function OEMToWin(s: AnsiString): AnsiString; inline; type (* StringBuilder. Сбросьте перед работой с помощью Clear. Добавляйте куски с помощью Add. В конце либо используйте, как есть (длина в Used), либо обрежьте с помощью Pack. *) TAnsiStringBuilder = record Data: AnsiString; Used: integer; procedure Clear; function Pack: AnsiString; procedure Add(c: AnsiChar); overload; procedure Add(pc: PAnsiChar); overload; procedure Add(s: AnsiString); overload; procedure Pop(SymbolCount: integer = 1); end; PAnsiStringBuilder = ^TAnsiStringBuilder; TUniStringBuilder = record Data: UniString; Used: integer; procedure Clear; function Pack: UniString; procedure Add(c: UniChar); overload; procedure Add(pc: PUniChar); overload; procedure Add(s: UniString); overload; procedure Pop(SymbolCount: integer = 1); end; PUniStringBuilder = ^TUniStringBuilder; //Обратная совместимость TWideStringBuilder = TUniStringBuilder; PWideStringBuilder = PUniStringBuilder; {$IFDEF UNICODE} TStringBuilder = TUniStringBuilder; PStringBuilder = ^TStringBuilder; {$ELSE} TStringBuilder = TAnsiStringBuilder; PStringBuilder = ^TStringBuilder; {$ENDIF} { Html encoding } type TUrlEncodeOption = ( ueNoSpacePlus //Encode space as %20, not "+" ); TUrlEncodeOptions = set of TUrlEncodeOption; function UrlEncode(s: UniString; options: TUrlEncodeOptions = []): AnsiString; function HtmlEscape(s: UniString): UniString; function HtmlEscapeObvious(s: UniString): UniString; function HtmlEscapeToAnsi(s: UniString): AnsiString; implementation //////////////////////////////////////////////////////////////////////////////// {$IFDEF UNICODE} (* Все реализации скопированы у Борланд. *) function AnsiPos(const Substr, S: AnsiString): Integer; var P: PAnsiChar; begin Result := 0; P := AnsiStrPos(PAnsiChar(S), PAnsiChar(SubStr)); if P <> nil then Result := (Integer(P) - Integer(PAnsiChar(S))) div SizeOf(AnsiChar) + 1; end; function AnsiStringReplace(const S, OldPattern, NewPattern: AnsiString; Flags: TReplaceFlags): AnsiString; var SearchStr, Patt, NewStr: AnsiString; Offset: Integer; begin if rfIgnoreCase in Flags then begin SearchStr := AnsiUpperCase(S); Patt := AnsiUpperCase(OldPattern); end else begin SearchStr := S; Patt := OldPattern; end; NewStr := S; Result := ''; while SearchStr <> '' do begin Offset := AnsiPos(Patt, SearchStr); if Offset = 0 then begin Result := Result + NewStr; Break; end; Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern; NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt); if not (rfReplaceAll in Flags) then begin Result := Result + NewStr; Break; end; SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt); end; end; function AnsiReplaceStr(const AText, AFromText, AToText: AnsiString): AnsiString; begin Result := AnsiStringReplace(AText, AFromText, AToText, [rfReplaceAll]); end; function AnsiReplaceText(const AText, AFromText, AToText: AnsiString): AnsiString; begin Result := AnsiStringReplace(AText, AFromText, AToText, [rfReplaceAll, rfIgnoreCase]); end; function AnsiUpperCase(const S: AnsiString): AnsiString; var Len: Integer; begin Len := Length(S); SetString(Result, PAnsiChar(S), Len); if Len > 0 then CharUpperBuffA(PAnsiChar(Result), Len); end; function AnsiLowerCase(const S: AnsiString): AnsiString; var Len: Integer; begin Len := Length(S); SetString(Result, PAnsiChar(S), Len); if Len > 0 then CharLowerBuffA(PAnsiChar(Result), Len); end; function AnsiCompareStr(const S1, S2: AnsiString): Integer; begin Result := CompareStringA(LOCALE_USER_DEFAULT, 0, PAnsiChar(S1), Length(S1), PAnsiChar(S2), Length(S2)) - CSTR_EQUAL; end; function AnsiSameStr(const S1, S2: AnsiString): Boolean; begin Result := AnsiCompareStr(S1, S2) = 0; end; function AnsiCompareText(const S1, S2: AnsiString): Integer; begin Result := CompareStringA(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PAnsiChar(S1), Length(S1), PAnsiChar(S2), Length(S2)) - CSTR_EQUAL; end; function AnsiSameText(const S1, S2: AnsiString): Boolean; begin Result := AnsiCompareText(S1, S2) = 0; end; {$ENDIF} (* Unicode versions of WideStrUtils functions. *) function UStrPCopy(Dest: PUniChar; const Source: UniString): PUniChar; begin {Copied from WideStrUtils} Result := WStrLCopy(Dest, PWideChar(Source), Length(Source)); end; function UStrPLCopy(Dest: PUniChar; const Source: UniString; MaxLen: Cardinal): PUniChar; begin {Copied from WideStrUtils} Result := WStrLCopy(Dest, PWideChar(Source), MaxLen); end; function UniLastChar(const S: UniString): PUniChar; begin {Copied from WideStrUtils for speed} if S = '' then Result := nil else Result := @S[Length(S)]; end; function UniQuotedStr(const S: UniString; Quote: UniChar): UniString; begin {$IFDEF UNICODE} //There's no "agnostic" version of QuotedStr. This one works for "strings" on Unicode. Result := AnsiQuotedStr(S, Quote); {$ELSE} Result := WideQuotedStr(S, Quote); {$ENDIF} end; function UniExtractQuotedStr(var Src: PUniChar; Quote: UniChar): UniString; begin {$IFDEF UNICODE} //There's no "agnostic" version of ExtractQuotedStr. Result := AnsiExtractQuotedStr(Src, Quote); {$ELSE} Result := WideExtractQuotedStr(Src, Quote); {$ENDIF} end; function UniDequotedStr(const S: UniString; AQuote: UniChar): UniString; begin {$IFDEF UNICODE} //There's no "agnostic" version of DequotedStr. Result := AnsiDequotedStr(S, AQuote); {$ELSE} Result := WideDequotedStr(S, AQuote); {$ENDIF} end; function UniAdjustLineBreaks(const S: UniString; Style: TTextLineBreakStyle = tlbsCRLF): UniString; begin {$IFDEF UNICODE} Result := AdjustLineBreaks(S, Style); {$ELSE} Result := WideAdjustLineBreaks(S, Style); {$ENDIF} end; function UniStringReplace(const S, OldPattern, NewPattern: UniString; Flags: TReplaceFlags): UniString; begin {$IFDEF UNICODE} Result := StringReplace(S, OldPattern, NewPattern, Flags); {$ELSE} Result := WideStringReplace(S, OldPattern, NewPattern, Flags); {$ENDIF} end; function UniReplaceStr(const AText, AFromText, AToText: UniString): UniString; begin {$IFDEF UNICODE} Result := ReplaceStr(AText, AFromText, AToText); {$ELSE} Result := WideReplaceStr(AText, AFromText, AToText); {$ENDIF} end; function UniReplaceText(const AText, AFromText, AToText: UniString): UniString; begin {$IFDEF UNICODE} Result := ReplaceText(AText, AFromText, AToText); {$ELSE} Result := WideReplaceText(AText, AFromText, AToText); {$ENDIF} end; function UniUpperCase(const S: UniString): UniString; begin {$IFDEF UNICODE} Result := UpperCase(S); {$ELSE} Result := WideUpperCase(S); {$ENDIF} end; function UniLowerCase(const S: UniString): UniString; begin {$IFDEF UNICODE} Result := LowerCase(S); {$ELSE} Result := WideLowerCase(S); {$ENDIF} end; function UniCompareStr(const S1, S2: UniString): Integer; begin {$IFDEF UNICODE} Result := CompareStr(S1, S2); {$ELSE} Result := WideCompareStr(S1, S2); {$ENDIF} end; function UniSameStr(const S1, S2: UniString): Boolean; begin {$IFDEF UNICODE} Result := SameStr(S1, S2); {$ELSE} Result := WideSameStr(S1, S2); {$ENDIF} end; function UniCompareText(const S1, S2: UniString): Integer; begin {$IFDEF UNICODE} Result := CompareText(S1, S2); {$ELSE} Result := WideCompareText(S1, S2); {$ENDIF} end; function UniSameText(const S1, S2: UniString): Boolean; begin {$IFDEF UNICODE} Result := SameText(S1, S2); {$ELSE} Result := WideSameText(S1, S2); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// //Wide versions of standard routines. //На новых компиляторах все функции линкуются к системным. На старых реализованы с нуля. //Ansi-версии и дефолтные версии присутствовали и присутствуют в хедерах. function WidePos(const Substr, S: UniString): Integer; {$IFDEF UNICODE} begin Result := Pos(SubStr, S); end; {$ELSE} var P: PWideChar; begin Result := 0; P := WStrPos(PWideChar(S), PWideChar(SubStr)); if P <> nil then Result := Integer(P) - Integer(PWideChar(S)) + 1; end; {$ENDIF} //Returns substring of s, starting at <start> characters and continuing <length> of them. function WideMidStr(const AText: UniString; const AStart: integer; const ACount: integer): UniString; {$IFDEF UNICODE} begin Result := StrUtils.MidStr(AText, AStart, ACount); end; {$ELSE} begin SetLength(Result, ACount); if ACount <= Length(AText) - AStart then //If there's enough symbols in s, copy len of them Move(AText[AStart], Result[1], ACount*SizeOf(AText[1])) else //Else just copy everything that we can Move(AText[AStart], Result[1], (Length(AText)-AStart)*SizeOf(AText[1])); end; {$ENDIF} function WideStrComp(S1, S2: PWideChar): Integer; begin {$IFDEF UNICODE} //На Unicode-компиляторах эта функция существует под Ansi-названием в Wide-конфигурации. Result := AnsiStrComp(S1, S2); {$ELSE} Result := CompareStringW(LOCALE_USER_DEFAULT, 0, S1, -1, S2, -1) - 2; {$ENDIF} end; function WideStrIComp(S1, S2: PWideChar): Integer; begin {$IFDEF UNICODE} //На Unicode-компиляторах эта функция существует под Ansi-названием в Wide-конфигурации. Result := AnsiStrIComp(S1, S2); {$ELSE} Result := CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE, S1, -1, S2, -1) - 2; {$ENDIF} end; function WideStartsStr(const ASubText: UniString; const AText: UniString): boolean; {$IFDEF UNICODE} begin Result := StrUtils.StartsStr(ASubText, AText); end; {$ELSE} begin if Length(ASubText) > Length(AText) then Result := false else //Сравниваем только начало Result := CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PWideChar(ASubText), -1, PWideChar(AText), Length(ASubText)) = 2; end; {$ENDIF} function WideEndsStr(const ASubText: UniString; const AText: UniString): boolean; {$IFDEF UNICODE} begin Result := StrUtils.EndsStr(ASubText, AText); end; {$ELSE} var SubTextLocation: Integer; begin SubTextLocation := Length(AText) - Length(ASubText) + 1; if (SubTextLocation > 0) and (ASubText <> '') then Result := WideStrComp(Pointer(ASubText), Pointer(@AText[SubTextLocation])) = 0 else Result := False; end; {$ENDIF} //Аргументы в обратном порядке, как и у AnsiContainsStr function WideContainsStr(const AText: UniString; const ASubText: UniString): boolean; begin {$IFDEF UNICODE} Result := StrUtils.ContainsStr(AText, ASubText); {$ELSE} Result := (WStrPos(PWideChar(AText), PWideChar(ASubText)) <> nil); {$ENDIF} end; function WideStartsText(const ASubText: UniString; const AText: UniString): boolean; begin {$IFDEF UNICODE} Result := StrUtils.StartsText(ASubText, AText); {$ELSE} Result := WideStartsStr(WideLowerCase(ASubText), WideLowerCase(AText)); {$ENDIF} end; function WideEndsText(const ASubText: UniString; const AText: UniString): boolean; begin {$IFDEF UNICODE} Result := StrUtils.EndsText(ASubText, AText); {$ELSE} Result := WideEndsStr(WideLowerCase(ASubText), WideLowerCase(AText)); {$ENDIF} end; //Аргументы в обратном порядке, как и у AnsiContainsText function WideContainsText(const AText: UniString; const ASubText: UniString): boolean; begin {$IFDEF UNICODE} Result := StrUtils.StartsText(AText, ASubText); {$ELSE} Result := WideContainsStr(WideLowerCase(AText), WideLowerCase(ASubText)); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// /// Находит индекс первого появления строки в массиве function AnsiStrInArray(a: TAnsiStringArray; s: AnsiString): integer; var i: integer; begin Result := -1; for i := 0 to Length(a)-1 do if AnsiSameStr(s, a[i]) then begin Result := i; break; end; end; function AnsiTextInArray(a: TAnsiStringArray; s: AnsiString): integer; var i: integer; begin Result := -1; s := AnsiUpperCase(s); for i := 0 to Length(a)-1 do if AnsiSameStr(s, a[i]) then begin Result := i; break; end; end; function UniStrInArray(a: TUniStringArray; s: UniString): integer; var i: integer; begin Result := -1; for i := 0 to Length(a)-1 do if UniSameStr(s, a[i]) then begin Result := i; break; end; end; function UniTextInArray(a: TUniStringArray; s: UniString): integer; var i: integer; begin Result := -1; s := UniUpperCase(s); for i := 0 to Length(a)-1 do if UniSameStr(s, a[i]) then begin Result := i; break; end; end; function StrInArray(a: TStringArray; s: string): integer; begin {$IFDEF UNICODE} Result := UniStrInArray(a, s); {$ELSE} Result := AnsiStrInArray(a, s); {$ENDIF} end; function TextInArray(a: TStringArray; s: string): integer; begin {$IFDEF UNICODE} Result := UniTextInArray(a, s); {$ELSE} Result := AnsiTextInArray(a, s); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// (* Splits a string by a single type of separators. A,,,B => five items (A,,,B) *) function StrSplitA(s: PAnsiChar; sep: AnsiChar): TAnsiStringArray; var pc: PAnsiChar; i: integer; begin //Count the number of separator characters i := 1; pc := s; while pc^ <> #00 do begin if pc^=sep then Inc(i); Inc(pc); end; //Reserve array SetLength(Result, i); //Parse i := 0; pc := s; while pc^<>#00 do if pc^=sep then begin Result[i] := StrSubA(s, pc); Inc(i); Inc(pc); s := pc; end else Inc(pc); //Last time Result[i] := StrSubA(s, pc); end; function StrSplitW(s: PUniChar; sep: UniChar): TUniStringArray; var pc: PUniChar; i: integer; begin //Count the number of separator characters i := 1; pc := s; while pc^ <> #00 do begin if pc^=sep then Inc(i); Inc(pc); end; //Reserve array SetLength(Result, i); //Parse i := 0; pc := s; while pc^<>#00 do if pc^=sep then begin Result[i] := StrSubW(s, pc); Inc(i); Inc(pc); s := pc; end else Inc(pc); //Last time Result[i] := StrSubW(s, pc); end; function StrSplit(s: PChar; sep: char): TStringArray; begin {$IFDEF UNICODE} Result := StrSplitW(PWideChar(s), sep); {$ELSE} Result := StrSplitA(PAnsiChar(s), sep); {$ENDIF} end; function AnsiSepSplit(s: AnsiString; sep: AnsiChar): TAnsiStringArray; begin Result := StrSplitA(PAnsiChar(s), sep); end; function WideSepSplit(s: UniString; sep: UniChar): TUniStringArray; begin Result := StrSplitW(PWideChar(s), sep); end; function SepSplit(s: string; sep: char): TStringArray; begin {$IFDEF UNICODE} Result := StrSplitW(PWideChar(s), sep); {$ELSE} Result := StrSplitA(PAnsiChar(s), sep); {$ENDIF} end; function StrSplitExA(s: PAnsiChar; sep: PAnsiChar; quote: AnsiChar): TAnsiStringArray; var pc: PAnsiChar; i: integer; in_q: boolean; function match_q(c: AnsiChar): boolean; var sc: PAnsiChar; begin sc := sep; while (sc^<>#00) and (sc^<>c) do Inc(sc); Result := (sc^=c); end; begin //Count the number of separator characters not between i := 1; pc := s; in_q := false; while pc^ <> #00 do begin if pc^=quote then in_q := not in_q else if (not in_q) and match_q(pc^) then Inc(i); Inc(pc); end; //Reserve array SetLength(Result, i); //Parse i := 0; pc := s; in_q := false; while pc^<>#00 do begin if pc^=quote then begin in_q := not in_q; Inc(pc); end else if (not in_q) and match_q(pc^) then begin Result[i] := StrSubA(s, pc); Inc(i); Inc(pc); s := pc; end else Inc(pc); end; //Last time Result[i] := StrSubA(s, pc); end; function StrSplitExW(s: PUnichar; sep: PUniChar; quote: UniChar): TUniStringArray; var pc: PUniChar; i: integer; in_q: boolean; function match_q(c: UniChar): boolean; var sc: PUniChar; begin sc := sep; while (sc^<>#00) and (sc^<>c) do Inc(sc); Result := (sc^=c); end; begin //Count the number of separator characters not between i := 1; pc := s; in_q := false; while pc^ <> #00 do begin if pc^=quote then in_q := not in_q else if (not in_q) and match_q(pc^) then Inc(i); Inc(pc); end; //Reserve array SetLength(Result, i); //Parse i := 0; pc := s; in_q := false; while pc^<>#00 do begin if pc^=quote then begin in_q := not in_q; Inc(pc); end else if (not in_q) and match_q(pc^) then begin Result[i] := StrSubW(s, pc); Inc(i); Inc(pc); s := pc; end else Inc(pc); end; //Last time Result[i] := StrSubW(s, pc); end; function StrSplitEx(s: PChar; sep: PChar; quote: Char): TStringArray; begin {$IFDEF UNICODE} Result := StrSplitExW(PWideChar(s), PWideChar(sep), quote); {$ELSE} Result := StrSplitExA(PAnsiChar(s), PAnsiChar(sep), quote); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// //Joins a string array usng the specified separator. function AnsiSepJoin(s: TAnsiStringArray; sep: AnsiChar): AnsiString; begin Result := AnsiSepJoin(@s[1], Length(s), sep); end; function WideSepJoin(s: TUniStringArray; sep: UniChar): UniString; begin Result := WideSepJoin(@s[1], Length(s), sep); end; function SepJoin(s: TStringArray; sep: Char): string; begin {$IFDEF UNICODE} Result := WideSepJoin(@s[1], Length(s), sep); {$ELSE} Result := AnsiSepJoin(@s[1], Length(s), sep); {$ENDIF} end; function AnsiSepJoin(s: PAnsiString; cnt: integer; sep: AnsiChar): AnsiString; var si: PAnsiString; ci: integer; len, li: integer; begin //Считаем общий размер len := cnt - 1; //число разделителей si := s; ci := cnt; while ci>0 do begin len := len + Length(si^); Inc(si); Dec(ci); end; //Выделяем память SetLength(Result, len); li := 1; while cnt>1 do begin Move(s^[1], Result[li], Length(s^)*SizeOf(AnsiChar)); li := li + Length(s^); Result[li] := sep; li := li + 1; Inc(s); Dec(cnt); end; //Последний кусок if cnt >= 1 then Move(s^[1], Result[li], Length(s^)*SizeOf(AnsiChar)); end; function WideSepJoin(s: PUniString; cnt: integer; sep: UniChar): UniString; var si: PUniString; ci: integer; len, li: integer; begin //Считаем общий размер len := cnt - 1; //число разделителей si := s; ci := cnt; while ci>0 do begin len := len + Length(si^); Inc(si); Dec(ci); end; //Выделяем память SetLength(Result, len); li := 1; while cnt>1 do begin Move(s^[1], Result[li], Length(s^)*SizeOf(UniChar)); li := li + Length(s^); Result[li] := sep; li := li + 1; Inc(s); Dec(cnt); end; //Последний кусок if cnt >= 1 then Move(s^[1], Result[li], Length(s^)*SizeOf(UniChar)); end; function SepJoin(s: PString; cnt: integer; sep: Char): string; begin {$IFDEF UNICODE} Result := WideSepJoin(s, cnt, sep); {$ELSE} Result := AnsiSepJoin(s, cnt, sep); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// //Возвращает в виде WideString строку PWideChar, но не более N символов //Полезно для чтения всяких буферов фиксированного размера, где не гарантирован ноль. function AnsiStrFromBuf(s: PAnsiChar; MaxLen: integer): AnsiString; var p: PAnsiChar; begin p := s; while (p^ <> #00) and (MaxLen > 0) do begin Inc(p); Dec(MaxLen); end; //p указывает на символ, копировать который уже не надо Result := SubStrPchA(s, p); end; function WideStrFromBuf(s: PUniChar; MaxLen: integer): UniString; var p: PWideChar; begin p := s; while (p^ <> #00) and (MaxLen > 0) do begin Inc(p); Dec(MaxLen); end; //p указывает на символ, копировать который уже не надо Result := SubStrPchW(s, p); end; function StrFromBuf(s: PChar; MaxLen: integer): string; begin {$IFDEF UNICODE} Result := WideStrFromBuf(s, MaxLen); {$ELSE} Result := AnsiStrFromBuf(s, MaxLen); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// /// Character checks //Checks if char is a number function AnsiCharIsNumber(c: AnsiChar): boolean; begin Result := (Ord(c) >= Ord('0')) and (Ord(c) <= Ord('9')); end; function WideCharIsNumber(c: UniChar): boolean; begin Result := (Ord(c) >= Ord('0')) and (Ord(c) <= Ord('9')); end; function CharIsNumber(c: char): boolean; begin Result := (Ord(c) >= Ord('0')) and (Ord(c) <= Ord('9')); end; //Checks if char is a latin symbol function AnsiCharIsLatinSymbol(c: AnsiChar): boolean; begin Result := ((Ord(c) >= Ord('A')) and (Ord(c) <= Ord('Z'))) or ((Ord(c) >= Ord('a')) and (Ord(c) <= Ord('z'))); end; function WideCharIsLatinSymbol(c: UniChar): boolean; begin Result := ((Ord(c) >= Ord('A')) and (Ord(c) <= Ord('Z'))) or ((Ord(c) >= Ord('a')) and (Ord(c) <= Ord('z'))); end; function CharIsLatinSymbol(c: char): boolean; begin Result := ((Ord(c) >= Ord('A')) and (Ord(c) <= Ord('Z'))) or ((Ord(c) >= Ord('a')) and (Ord(c) <= Ord('z'))); end; //Check if string is composed only from numbers and latin symbols function AnsiStrIsLnOnly(str: AnsiString): boolean; var i: integer; begin Result := true; for i := 1 to Length(str) do if not AnsiCharIsNumber(str[i]) and not AnsiCharIsLatinSymbol(str[i]) then begin Result := false; exit; end; end; function WideStrIsLnOnly(str: UniString): boolean; var i: integer; begin Result := true; for i := 1 to Length(str) do if not WideCharIsNumber(str[i]) and not WideCharIsLatinSymbol(str[i]) then begin Result := false; exit; end; end; function StrIsLnOnly(str: string): boolean; begin {$IFDEF UNICODE} Result := WideStrIsLnOnly(str); {$ELSE} Result := AnsiStrIsLnOnly(str); {$ENDIF} end; (* Following stuff isn't precise. 1. We don't include repetition marks etc in Hiragana/Katakana 2. There are both unique to H/K and shared H-K marks 3. Unicode includes copies of H/K with effects: - Normal [included] - Small [included] - Circled - Other? 4. Unicode has various special symbols for KIROGURAMU in H/K, for instance. Not included. 5. Kanjis are included only from Basic Plane. *) function IsHiragana(c: UniChar): boolean; begin Result := (Ord(c) >= $3041) and (Ord(c) <= $3094); end; function IsKatakana(c: UniChar): boolean; begin Result := (Ord(c) >= $30A1) and (Ord(c) <= $30FA); end; function IsKana(c: UniChar): boolean; begin Result := IsKatakana(c) or IsHiragana(c); end; function IsKanji(c: UniChar): boolean; begin Result := (Ord(c) >= $4E00) and (Ord(c) <= $9FA5); end; //////////////////////////////////////////////////////////////////////////////// /// Indexing and lengths // Возвращает номер символа, на который указывает ptr, в строке str function AnsiPcharInd(str, ptr: PAnsiChar): integer; begin Result := integer(ptr)-integer(str)+1; end; function WidePcharInd(str, ptr: PUniChar): integer; begin Result := (integer(ptr)-integer(str)) div SizeOf(UniChar) + 1; end; function PcharInd(str, ptr: PChar): integer; begin Result := (integer(ptr)-integer(str)) div SizeOf(char) + 1; end; //Возвращает длину отрезка в символах function CharLenA(p1, p2: PAnsiChar): integer; begin Result := (cardinal(p2) - cardinal(p1)) div SizeOf(AnsiChar); end; function CharLenW(p1, p2: PUniChar): integer; begin Result := (cardinal(p2) - cardinal(p1)) div SizeOf(UniChar); end; function CharLen(p1, p2: PChar): integer; begin Result := (cardinal(p2) - cardinal(p1)) div SizeOf(Char); end; //Находит конец строки function StrEndA(s: PAnsiChar): PAnsiChar; begin Result := s; while Result^ <> #00 do Inc(Result); end; function StrEndW(s: PUniChar): PUniChar; begin Result := s; while Result^ <> #00 do Inc(Result); end; function StrEnd(s: PChar): PChar; begin Result := s; while Result^ <> #00 do Inc(Result); end; //////////////////////////////////////////////////////////////////////////////// /// Быстрое обращение к следующему-предыдущему символу function NextChar(p: PAnsiChar; c: integer = 1): PAnsiChar; begin Result := PAnsiChar(integer(p) + SizeOf(AnsiChar)*c); end; function PrevChar(p: PAnsiChar; c: integer = 1): PAnsiChar; begin Result := PAnsiChar(integer(p) - SizeOf(AnsiChar)*c); end; function NextChar(p: PWideChar; c: integer = 1): PWideChar; begin Result := PWideChar(integer(p) + SizeOf(WideChar)*c); end; function PrevChar(p: PWideChar; c: integer = 1): PWideChar; begin Result := PWideChar(integer(p) - SizeOf(WideChar)*c); end; //////////////////////////////////////////////////////////////////////////////// /// Арифметика указателей //Возвращает указатель на n-й знак строки. Быстрее и безопасней, чем дельфийская хрень. //Отступ считает с единицы. function PwcOff(var a; n: integer): PWideChar; begin Result := PWideChar(integer(a) + (n-1)*SizeOf(WideChar)); end; //Сравнивает указатели. Больше нуля, если a>b. function PwcCmp(var a; var b): integer; begin Result := integer(a)-integer(b); end; //Отступ считает с единицы. function PwcCmp(var a; an: integer; var b; bn: integer): integer; begin Result := integer(a)+(an-1)*SizeOf(WideChar)-integer(b)-(bn-1)*SizeOf(WideChar); end; //////////////////////////////////////////////////////////////////////////////// /// Возвращает строку между заданными позициями, или заданной длины function StrSubLA(beg: PAnsiChar; len: integer): AnsiString; var i: integer; begin SetLength(Result, len); i := 1; while i <= len do begin Result[i] := beg^; Inc(beg); Inc(i); end; end; function StrSubLW(beg: PUniChar; len: integer): UniString; var i: integer; begin SetLength(Result, len); i := 1; while i <= len do begin Result[i] := beg^; Inc(beg); Inc(i); end; end; function StrSubL(beg: PChar; len: integer): string; begin {$IFDEF UNICODE} Result := StrSubLW(beg, len); {$ELSE} Result := StrSubLA(beg, len); {$ENDIF} end; function StrSubA(beg: PAnsiChar; en: PAnsiChar): AnsiString; begin Result := StrSubLA(beg, (integer(en)-integer(beg)) div SizeOf(AnsiChar)); end; function StrSubW(beg: PUniChar; en: PUniChar): UniString; begin Result := StrSubLW(beg, (integer(en)-integer(beg)) div SizeOf(WideChar)); end; function StrSub(beg: PChar; en: PChar): string; begin {$IFDEF UNICODE} Result := StrSubW(beg, en); {$ELSE} Result := StrSubA(beg, en); {$ENDIF} end; //Обратная совместимость function SubStrPchA(beg, en: PAnsiChar): AnsiString; begin Result := StrSubA(beg, en); end; function SubStrPchW(beg, en: PUniChar): UniString; begin Result := StrSubW(beg, en); end; function SubStrPch(beg, en: pchar): string; begin //Редиректим сразу на нужные функции, без проводников {$IFDEF UNICODE} Result := StrSubW(beg, en); {$ELSE} Result := StrSubA(beg, en); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// /// Поиск символов в строке //Scans the specified string for the specfied character. Starts at position <start_at>. //Ends at <end_at> symbols - 1. Returns first symbol index in string or -1 if not found any. function AnsiFindChar(s: AnsiString; c: AnsiChar; start_at: integer; end_at: integer): integer; var i: integer; begin if end_at=-1 then end_at := Length(s); Result := -1; for i := start_at to end_at - 1 do if (s[i]=c) then begin Result := i; exit; end; end; function WideFindChar(s: UniString; c: UniChar; start_at: integer; end_at: integer): integer; var i: integer; begin if end_at=-1 then end_at := Length(s); Result := -1; for i := start_at to end_at - 1 do if (s[i]=c) then begin Result := i; exit; end; end; function FindChar(s: string; c: char; start_at: integer; end_at: integer): integer; begin {$IFDEF UNICODE} Result := WideFindChar(s, c, start_at, end_at); {$ELSE} Result := AnsiFindChar(s, c, start_at, end_at); {$ENDIF} end; //Дополнения к стандартной дельфийской StrScan function StrScanA(str: PAnsiChar; chr: AnsiChar): PAnsiChar; begin Result := StrScan(str, chr); end; function StrScanW(str: PUniChar; chr: UniChar): PUniChar; begin {$IFDEF UNICODE} Result := StrScan(str, chr); //has unicode version {$ELSE} { Copied from SysUtils } Result := Str; while Result^ <> #0 do begin if Result^ = Chr then Exit; Inc(Result); end; if Chr <> #0 then Result := nil; {$ENDIF} end; //Ищет любой из перечисленных символов, иначе возвращает nil. function StrScanAnyA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar; var smb: PAnsiChar; begin Result := nil; while str^ <> #00 do begin smb := symbols; while smb^ <> #00 do if smb^ = str^ then begin Result := str; exit; end else Inc(smb); Inc(str); end; end; function StrScanAnyW(str: PUniChar; symbols: PUniChar): PUniChar; var smb: PWideChar; begin Result := nil; while str^ <> #00 do begin smb := symbols; while smb^ <> #00 do if smb^ = str^ then begin Result := str; exit; end else Inc(smb); Inc(str); end; end; function StrScanAny(str: PChar; symbols: PChar): PChar; begin {$IFDEF UNICODE} Result := StrScanAnyW(str, symbols); {$ELSE} Result := StrScanAnyA(str, symbols); {$ENDIF} end; //Ищет любой из перечисленных символов, иначе возвращает указатель на конец строки. //Для скорости алгоритмы скопированы из StrScanAny function StrScanEndA(str: PAnsiChar; symbols: PAnsiChar): PAnsiChar; var smb: PAnsiChar; begin while str^ <> #00 do begin smb := symbols; while smb^ <> #00 do if smb^ = str^ then begin Result := str; exit; end else Inc(smb); Inc(str); end; //If nothing is found, return endstr Result := str; end; function StrScanEndW(str: PUniChar; symbols: PUniChar): PUniChar; var smb: PWideChar; begin while str^ <> #00 do begin smb := symbols; while smb^ <> #00 do if smb^ = str^ then begin Result := str; exit; end else Inc(smb); Inc(str); end; //If nothing is found, return endstr Result := str; end; function StrScanEnd(str: PChar; symbols: PChar): PChar; begin {$IFDEF UNICODE} Result := StrScanEndW(str, symbols); {$ELSE} Result := StrScanEndA(str, symbols); {$ENDIF} end; //Находит первый символ из набора cs, возвращает ссылку на него и кусок текста до него. //Если такого символа нет, возвращает остаток строки и nil. function AnsiReadUpToNext(str: PAnsiChar; cs: AnsiString; out block: AnsiString): PAnsiChar; begin Result := StrScanAnyA(str, PAnsiChar(cs)); if Result <> nil then SetLength(block, AnsiPcharInd(str, Result)-1) else SetLength(block, StrLen(str)); if Length(block) > 0 then StrLCopy(@block[1], str, Length(block)); //null not included end; //Находит первый символ из набора cs, возвращает ссылку на него и кусок текста до него. //Если такого символа нет, возвращает остаток строки и nil. function WideReadUpToNext(str: PUniChar; cs: UniString; out block: UniString): PUniChar; begin Result := StrScanAnyW(str, PWideChar(cs)); if Result <> nil then SetLength(block, WidePCharInd(str, Result)-1) else SetLength(block, WStrLen(str)); if Length(block) > 0 then WStrLCopy(@block[1], str, Length(block)); //null not included end; function ReadUpToNext(str: PChar; cs: string; out block: string): PChar; begin {$IFDEF UNICODE} Result := WideReadUpToNext(str, cs, block); {$ELSE} Result := AnsiReadUpToNext(str, cs, block); {$ENDIF} end; //Проверяет, что строки совпадают до окончания одной из них function StrCmpNext(a, b: PChar): boolean; begin while (a^ = b^) and (a^<>#00) do begin //#00 не выедаем даже общий Inc(a); Inc(b); end; Result := (a^=#00) or (b^=#00); end; //Возвращает длину совпадающего участка c начала строк, в символах, включая нулевой. function StrMatch(a, b: PChar): integer; begin Result := 0; while (a^ = b^) and (a^<>#00) do begin //#00 не выедаем даже общий Inc(a); Inc(b); Inc(Result); end; //сверяем #00 if (a^=b^) then Inc(Result); end; procedure SkipChars(var pc: PChar; chars: PChar); var pcc: PChar; begin while pc^<>#00 do begin pcc := chars; while pcc^<>#00 do if pcc^=pc^ then begin pcc := nil; break; end else Inc(pcc); if pcc=nil then //skip char Inc(pc) else exit; //non-skip char end; end; //////////////////////////////////////////////////////////////////////////////// /// Удаление лишних символов по краям //Removes quote characters around the string, if they exist. function AnsiStripQuotes(s: AnsiString; qc1, qc2: AnsiChar): AnsiString; begin Result := s; if Length(Result) < 2 then exit; //Если кавычки есть, убираем их. if (Result[1]=qc1) and (Result[Length(Result)-1]=qc2) then begin Move(Result[2], Result[1], (Length(Result)-2)*SizeOf(Result[1])); SetLength(Result, Length(Result)-2); end; end; function WideStripQuotes(s: UniString; qc1, qc2: UniChar): UniString; begin Result := s; if Length(Result) < 2 then exit; //Если кавычки есть, убираем их. if (Result[1]=qc1) and (Result[Length(Result)-1]=qc2) then begin Move(Result[2], Result[1], (Length(Result)-2)*SizeOf(Result[1])); SetLength(Result, Length(Result)-2); end; end; function StripQuotes(s: string; qc1, qc2: char): string; begin {$IFDEF UNICODE} Result := WideStripQuotes(s, qc1, qc2); {$ELSE} Result := AnsiStripQuotes(s, qc1, qc2); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// /// Тримы - версия для String function STrimStartA(s: AnsiString; sep: AnsiChar): AnsiString; var ps, pe: PAnsiChar; begin if s='' then begin Result := ''; exit; end; ps := @s[1]; if ps^<>sep then begin Result := s; //короткая версия exit; end; //Длинная версия pe := @s[Length(s)]; while (cardinal(ps) <= cardinal(pe)) and (ps^=sep) do Inc(ps); if cardinal(ps) > cardinal(pe) then begin Result := ''; exit; end; SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(AnsiChar) + 1); Move(s[1], Result[1], Length(Result)*SizeOf(AnsiChar)); end; function STrimStartW(s: UniString; sep: UniChar): UniString; var ps, pe: PWideChar; begin if s='' then begin Result := ''; exit; end; ps := @s[1]; if ps^<>sep then begin Result := s; //короткая версия exit; end; //Длинная версия pe := @s[Length(s)]; while (cardinal(ps) <= cardinal(pe)) and (ps^=sep) do Inc(ps); if cardinal(ps) > cardinal(pe) then begin Result := ''; exit; end; SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(WideChar) + 1); Move(s[1], Result[1], Length(Result)*SizeOf(WideChar)); end; function STrimStart(s: string; sep: Char): string; begin {$IFDEF UNICODE} Result := STrimStartW(s, sep); {$ELSE} Result := STrimStartA(s, sep); {$ENDIF} end; function STrimEndA(s: AnsiString; sep: AnsiChar): AnsiString; var ps, pe: PAnsiChar; begin if s='' then begin Result := ''; exit; end; pe := @s[Length(s)]; if pe^<>sep then begin Result := s; //короткая версия exit; end; //Длинная версия ps := @s[1]; while (cardinal(pe) > cardinal(ps)) and (pe^=sep) do Dec(pe); if cardinal(ps) > cardinal(pe) then begin Result := ''; exit; end; SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(AnsiChar) + 1); Move(s[1], Result[1], Length(Result)*SizeOf(AnsiChar)); end; function STrimEndW(s: UniString; sep: UniChar): UniString; var ps, pe: PWideChar; begin if s='' then begin Result := ''; exit; end; pe := @s[Length(s)]; if pe^<>sep then begin Result := s; //короткая версия exit; end; //Длинная версия ps := @s[1]; while (cardinal(pe) > cardinal(ps)) and (pe^=sep) do Dec(pe); if cardinal(ps) > cardinal(pe) then begin Result := ''; exit; end; SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(WideChar) + 1); Move(s[1], Result[1], Length(Result)*SizeOf(WideChar)); end; function STrimEnd(s: string; sep: Char): string; begin {$IFDEF UNICODE} Result := STrimEndW(s, sep); {$ELSE} Result := STrimEndA(s, sep); {$ENDIF} end; function STrimA(s: AnsiString; sep: AnsiChar): AnsiString; var ps, pe: PAnsiChar; begin if s='' then begin Result := ''; exit; end; ps := @s[1]; pe := @s[Length(s)]; while (cardinal(pe) >= cardinal(ps)) and (pe^ = sep) do Dec(pe); while (cardinal(ps) <= cardinal(pe)) and (ps^ = sep) do Inc(ps); if cardinal(ps) > cardinal(pe) then begin Result := ''; exit; end; SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(AnsiChar) + 1); Move(ps^, Result[1], Length(Result)*SizeOf(AnsiChar)); end; function STrimW(s: UniString; sep: UniChar): UniString; var ps, pe: PWideChar; begin if s='' then begin Result := ''; exit; end; ps := @s[1]; pe := @s[Length(s)]; while (cardinal(pe) >= cardinal(ps)) and (pe^ = sep) do Dec(pe); while (cardinal(ps) <= cardinal(pe)) and (ps^ = sep) do Inc(ps); if cardinal(ps) > cardinal(pe) then begin Result := ''; exit; end; SetLength(Result, (cardinal(pe)-cardinal(ps)) div SizeOf(WideChar) + 1); Move(ps^, Result[1], Length(Result)*SizeOf(WideChar)); end; function STrim(s: string; sep: Char): string; begin {$IFDEF UNICODE} Result := STrimW(s, sep); {$ELSE} Result := STrimA(s, sep); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// /// Тримы - версия для PChar function PTrimStartA(s: PAnsiChar; sep: AnsiChar): AnsiString; begin while s^=sep do Inc(s); Result := s; end; function PTrimStartW(s: PUniChar; sep: UniChar): UniString; begin while s^=sep do Inc(s); Result := s; end; function PTrimStart(s: PChar; sep: Char): string; begin {$IFDEF UNICODE} Result := PTrimStartW(s, sep); {$ELSE} Result := PTrimStartA(s, sep); {$ENDIF} end; function PTrimEndA(s: PAnsiChar; sep: AnsiChar): AnsiString; var se: PAnsiChar; begin //Конец строки se := s; while se^<>#00 do Inc(se); //Откатываемся назад Dec(se); while (se^=sep) and (integer(se) > integer(s)) do Dec(se); //Пустая строка if integer(se) <= integer(s) then begin Result := ''; exit; end; Inc(se); Result := StrSubA(s, se); end; function PTrimEndW(s: PUniChar; sep: UniChar): UniString; var se: PWideChar; begin //Конец строки se := s; while se^<>#00 do Inc(se); //Откатываемся назад Dec(se); while (se^=sep) and (integer(se) > integer(s)) do Dec(se); //Пустая строка if integer(se) < integer(s) then begin Result := ''; exit; end; Inc(se); Result := StrSubW(s, se); end; function PTrimEnd(s: PChar; sep: Char): string; begin {$IFDEF UNICODE} Result := PTrimEndW(s, sep); {$ELSE} Result := PTrimEndA(s, sep); {$ENDIF} end; function PTrimA(s: PAnsiChar; sep: AnsiChar): AnsiString; begin //Пробелы в начале while s^=sep do Inc(s); if s^=#00 then begin Result := ''; exit; end; Result := PTrimEndA(s, sep); end; function PTrimW(s: PUniChar; sep: UniChar): UniString; begin //Пробелы в начале while s^=sep do Inc(s); if s^=#00 then begin Result := ''; exit; end; Result := PTrimEndW(s, sep); end; function PTrim(s: PChar; sep: Char): string; begin {$IFDEF UNICODE} Result := PTrimW(s, sep); {$ELSE} Result := PTrimA(s, sep); {$ENDIF} end; function BETrimA(beg, en: PAnsiChar; sep: AnsiChar): AnsiString; begin //Trim spaces Dec(en); while (integer(en) > integer(beg)) and (en^=sep) do Dec(en); Inc(en); while (integer(en) > integer(beg)) and (beg^=sep) do Inc(beg); Result := StrSubA(beg, en); end; function BETrimW(beg, en: PUniChar; sep: UniChar): UniString; begin //Trim spaces Dec(en); while (integer(en) > integer(beg)) and (en^=sep) do Dec(en); Inc(en); while (integer(en) > integer(beg)) and (beg^=sep) do Inc(beg); Result := StrSubW(beg, en); end; function BETrim(beg, en: PChar; sep: Char): string; begin {$IFDEF UNICODE} Result := BETrimW(beg, en, sep); {$ELSE} Result := BETrimA(beg, en, sep); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// // Binary/string conversions const sHexSymbols: AnsiString = '0123456789ABCDEF'; function ByteToHex(b: byte): AnsiString; inline; begin SetLength(Result, 2); Result[1] := sHexSymbols[(b shr 4) + 1]; Result[2] := sHexSymbols[(b mod 16) + 1]; end; function BinToHex(ptr: pbyte; sz: integer): AnsiString; var i: integer; begin SetLength(Result, sz*2); i := 0; while i < sz do begin Result[i*2+1] := sHexSymbols[(ptr^ shr 4) + 1]; Result[i*2+2] := sHexSymbols[(ptr^ mod 16) + 1]; Inc(ptr); Inc(i); end; end; function DataToHex(data: array of byte): AnsiString; begin Result := BinToHex(@data[0], Length(data)); end; function HexCharValue(c: AnsiChar): byte; inline; begin if c in ['0'..'9'] then Result := Ord(c) - Ord('0') else if c in ['a'..'f'] then Result := 10 + Ord(c) - Ord('a') else if c in ['A'..'F'] then Result := 10 + Ord(c) - Ord('A') else raise Exception.Create('Illegal hex symbol: '+c); end; //Буфер должен быть выделен заранее. //Переведено будет лишь столько, сколько влезло в указанный размер. procedure HexToBin(s: AnsiString; p: pbyte; size: integer); var i: integer; begin if size > (Length(s) div 2) then size := (Length(s) div 2); for i := 0 to size-1 do begin p^ := HexCharValue(s[2*i+1]) * 16 + HexCharValue(s[2*i+2]); Inc(p); end; end; //////////////////////////////////////////////////////////////////////////////// /// Codepage utils function ToWideChar(c: AnsiChar; cp: cardinal): WideChar; begin if MultiByteToWideChar(cp, 0, @c, 1, @Result, 2) = 0 then RaiseLastOsError; end; function ToChar(c: WideChar; cp: cardinal): AnsiChar; begin if WideCharToMultiByte(cp, 0, @c, 2, @Result, 1, nil, nil) = 0 then RaiseLastOsError; end; function ToWideString(s: AnsiString; cp: cardinal): WideString; begin Result := BufToWideString(PAnsiChar(s), Length(s), cp); end; function ToString(s: WideString; cp: cardinal): AnsiString; begin Result := BufToString(PWideChar(s), Length(s), cp); end; function BufToWideString(s: PAnsiChar; len: integer; cp: cardinal): WideString; var size: integer; begin if s^=#00 then begin Result := ''; exit; end; size := MultiByteToWideChar(cp, 0, s, len, nil, 0); if size=0 then RaiseLastOsError; SetLength(Result, size); if MultiByteToWideChar(cp, 0, s, len, pwidechar(Result), size) = 0 then RaiseLastOsError; end; function BufToString(s: PWideChar; len: integer; cp: cardinal): AnsiString; var size: integer; begin if s^=#00 then begin Result := ''; exit; end; size := WideCharToMultiByte(cp, 0, s, len, nil, 0, nil, nil); if size=0 then RaiseLastOsError; SetLength(Result, size); if WideCharToMultiByte(cp, 0, s, len, PAnsiChar(Result), size, nil, nil) = 0 then RaiseLastOsError; end; function Convert(s: AnsiString; cpIn, cpOut: cardinal): AnsiString; begin Result := ToString(ToWideString(s, cpIn), cpOut); end; //Переводит строку из текущей кодировки системы в текущую кодировку консоли. function WinToOEM(s: AnsiString): AnsiString; begin Result := Convert(s, CP_ACP, CP_OEMCP); end; //Переводит строку из текущей кодировки консоли в текущую кодировку системы. function OEMToWin(s: AnsiString): AnsiString; begin Result := Convert(s, CP_OEMCP, CP_ACP); end; //////////////////////////////////////////////////////////////////////////////// /// StringBuilder procedure TAnsiStringBuilder.Clear; begin Used := 0; end; function TAnsiStringBuilder.Pack: AnsiString; begin SetLength(Data, Used); Result := Data; end; procedure TAnsiStringBuilder.Add(c: AnsiChar); begin if Used >= Length(Data) then SetLength(Data, Length(Data)*2 + 20); Inc(Used); Data[Used] := c; end; procedure TAnsiStringBuilder.Add(pc: PAnsiChar); var len, i: integer; begin len := StrLen(pc); if Used+len >= Length(Data) then if len > Length(Data)+20 then SetLength(Data, Length(Data)+len+20) else SetLength(Data, Length(Data)*2 + 20); for i := 1 to len do begin Data[Used+i] := pc^; Inc(pc); end; Inc(Used, len); end; procedure TAnsiStringBuilder.Add(s: AnsiString); var len, i: integer; begin len := Length(s); if Used+len >= Length(Data) then if len > Length(Data)+20 then SetLength(Data, Length(Data)+len+20) else SetLength(Data, Length(Data)*2 + 20); for i := 1 to len do Data[Used+i] := s[i]; Inc(Used, len); end; procedure TAnsiStringBuilder.Pop(SymbolCount: integer = 1); begin if SymbolCount >= Used then Used := 0 else Used := Used - SymbolCount; end; procedure TUniStringBuilder.Clear; begin Used := 0; end; function TUniStringBuilder.Pack: UniString; begin SetLength(Data, Used); Result := Data; end; procedure TUniStringBuilder.Add(c: UniChar); begin if Used >= Length(Data) then SetLength(Data, Length(Data)*2 + 20); Inc(Used); Data[Used] := c; end; procedure TUniStringBuilder.Add(pc: PUniChar); var len, i: integer; begin len := WStrLen(pc); if Used+len >= Length(Data) then if len > Length(Data)+20 then SetLength(Data, Length(Data)+len+20) else SetLength(Data, Length(Data)*2 + 20); for i := 1 to len do begin Data[Used+i] := pc^; Inc(pc); end; Inc(Used, len); end; procedure TUniStringBuilder.Add(s: UniString); var len, i: integer; begin len := Length(s); if Used+len >= Length(Data) then if len > Length(Data)+20 then SetLength(Data, Length(Data)+len+20) else SetLength(Data, Length(Data)*2 + 20); for i := 1 to len do Data[Used+i] := s[i]; Inc(Used, len); end; procedure TUniStringBuilder.Pop(SymbolCount: integer = 1); begin if SymbolCount >= Used then Used := 0 else Used := Used - SymbolCount; end; { Функции кодирования в HTML-форматы. Пока сделаны медленно и просто, при необходимости можно ускорить. } //Кодирует строку в URI-форме: "(te)(su)(to) str" -> "%E3%83%86%E3%82%B9%E3%83%88+str" //Пока сделано медленно и просто, при необходимости можно ускорить function UrlEncode(s: UniString; options: TUrlEncodeOptions): AnsiString; var i, j: integer; U: UTF8String; begin Result := ''; for i := 1 to Length(s) do if CharInSet(s[i], ['a'..'z', 'A'..'Z', '1'..'9', '0']) then Result := Result + AnsiChar(s[i]) else if s[i]=' ' then if ueNoSpacePlus in options then Result := Result + '%20' else Result := Result + '+' else begin //Вообще говоря, символ в UTF-16 может занимать несколько пар... //Но мы здесь это игнорируем. U := UTF8String(s[i]); // explicit Unicode->UTF8 conversion for j := 1 to Length(U) do Result := Result + '%' + AnsiString(IntToHex(Ord(U[j]), 2)); end; end; //Кодирует строку в HTML-форме. Заменяет только символы, которые не могут //встречаться в правильном HTML. //Все остальные юникод-символы остаются в нормальной форме. function HtmlEscape(s: UniString): UniString; var i: integer; begin Result := ''; for i := 1 to Length(s) do if s[i]='&' then Result := Result + '&amp;' else if s[i]='''' then Result := Result + '&apos;' else if s[i]='"' then Result := Result + '&quot;' else if s[i]='<' then Result := Result + '&lt;' else if s[i]='>' then Result := Result + '&gt;' else Result := Result + s[i]; end; //Кодирует строку в HTML-форме. Неизвестно, была ли строка закодирована до сих пор. //Пользователь мог закодировать некоторые последовательности, но забыть другие. //Поэтому кодируются только те символы, которые встречаться в итоговой строке //не могут никак: // "asd &amp; bsd <esd>" --> "asd &amp; bsd &lt;esd&gt;" function HtmlEscapeObvious(s: UniString): UniString; var i: integer; begin Result := ''; for i := 1 to Length(s) do //& не кодируем if s[i]='''' then Result := Result + '&apos;' else if s[i]='"' then Result := Result + '&quot;' else if s[i]='<' then Result := Result + '&lt;' else if s[i]='>' then Result := Result + '&gt;' else Result := Result + s[i]; end; //Кодирует строку в HTML-форме. Заменяет все символы, не входящие в Ansi-набор. // "(te)(su)(to) str" -> "&12486;&12473;&12488; str" //При необходимости можно сделать флаг "эскейпить в 16-ричные коды: &#x30DB;" function HtmlEscapeToAnsi(s: UniString): AnsiString; var i: integer; begin Result := ''; for i := 1 to Length(s) do if s[i]='&' then Result := Result + '&amp;' else if s[i]='''' then Result := Result + '&apos;' else if s[i]='"' then Result := Result + '&quot;' else if s[i]='<' then Result := Result + '&lt;' else if s[i]='>' then Result := Result + '&gt;' else //ANSI-символы if CharInSet(s[i], ['a'..'z', 'A'..'Z', '1'..'9', '0', ' ']) then Result := Result + AnsiChar(s[i]) else Result := Result + '&#'+AnsiString(IntToStr(word(s[i])))+';' end; end.
unit ufrmLogin; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.jpeg, Vcl.Imaging.pngimage, uJSONUser; type TfrmLogin = class(TForm) pnlImgLogin: TGridPanel; pnlImage: TPanel; pnlBody: TGridPanel; pnlUser: TPanel; lblUser: TLabel; pnlRemember: TPanel; ckbRememberme: TCheckBox; pnlEnter: TPanel; pnlLogin: TPanel; pnlEdtUserBorder: TPanel; pnlEdtUser: TPanel; edtUser: TEdit; imgUser: TImage; pnlPassword: TPanel; lblPassword: TLabel; pnlEdtPasswordBorder: TPanel; pnlEdtPassword: TPanel; imgPassword: TImage; edtPassword: TEdit; lblSignup: TLabel; pnlCircle: TPanel; imgLogin: TImage; procedure edtUserEnter(Sender: TObject); procedure edtUserExit(Sender: TObject); procedure edtPasswordEnter(Sender: TObject); procedure edtPasswordExit(Sender: TObject); procedure lblSignupMouseEnter(Sender: TObject); procedure lblSignupMouseLeave(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure pnlLoginMouseEnter(Sender: TObject); procedure pnlLoginMouseLeave(Sender: TObject); procedure lblSignupClick(Sender: TObject); procedure pnlImageMouseEnter(Sender: TObject); procedure pnlImageMouseLeave(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure pnlLoginClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure edtPasswordKeyPress(Sender: TObject; var Key: Char); procedure FormDestroy(Sender: TObject); private { Private declarations } UserPath, Path: TFileName; BMP: TBitmap; JPG: TJPEGImage; PNG: TPngImage; FUser: TUsersClass; FMaxLength: Integer; procedure ChangeImage(const Path: TFileName); procedure Login(const Login, Senha: string); public { Public declarations } property User: TUsersClass read FUser write FUser; property MaxLength: Integer read FMaxLength write FMaxLength; end; var frmLogin: TfrmLogin; implementation {$R *.dfm} uses ufrmSignUp, System.IniFiles; procedure TfrmLogin.edtPasswordEnter(Sender: TObject); begin if (lblPassword.Font.Color = clRed) then pnlEdtPasswordBorder.Color := clRed else pnlEdtPasswordBorder.Color := clHighlight; if (edtPassword.Text = 'Password') then edtPassword.Clear; end; procedure TfrmLogin.edtPasswordExit(Sender: TObject); begin pnlEdtPasswordBorder.Color := clBtnFace; if (edtPassword.Text = EmptyStr) then edtPassword.Text := 'Password'; end; procedure TfrmLogin.edtPasswordKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) then pnlLoginClick(pnlLogin); end; procedure TfrmLogin.edtUserEnter(Sender: TObject); begin if (lblUser.Font.Color = clRed) then pnlEdtUserBorder.Color := clRed else pnlEdtUserBorder.Color := clHighlight; if (edtUser.Text = 'Username') then edtUser.Clear; end; procedure TfrmLogin.edtUserExit(Sender: TObject); begin pnlEdtUserBorder.Color := clBtnFace; if (edtUser.Text = EmptyStr) then edtUser.Text := 'Username'; if (edtUser.Text <> 'Username') then begin if FileExists(UserPath + '\' + edtUser.Text) then ChangeImage(UserPath + '\' + edtUser.Text); end; end; procedure TfrmLogin.ChangeImage(const Path: TFileName); var User: TUsersClass; lFile: TStringList; begin lFile := TStringList.Create; try lFile.LoadFromFile(Path); User := TUsersClass.FromJsonString(lFile.Text); try if (ExtractFileExt(User.user.path) = '.bmp') then begin if Assigned(BMP) then FreeAndNil(BMP); BMP := TBitmap.Create; BMP.LoadFromFile(User.user.path); imgLogin.Picture.Graphic := BMP; end else if (ExtractFileExt(User.user.path) = '.png') then begin if Assigned(PNG) then FreeAndNil(PNG); PNG := TPngImage.Create; PNG.LoadFromFile(User.user.path); imgLogin.Picture.Graphic := PNG; end else if (ExtractFileExt(User.user.path) = '.jpeg') or ((ExtractFileExt(User.user.path) = '.jpg')) then begin if Assigned(JPG) then FreeAndNil(JPG); JPG := TJPEGImage.Create; JPG.LoadFromFile(User.user.path); imgLogin.Picture.Graphic := JPG; end; finally FreeAndNil(User); end; finally FreeAndNil(lFile); end; end; procedure TfrmLogin.FormClose(Sender: TObject; var Action: TCloseAction); var IniFile: TIniFile; Attributes: Integer; begin if Assigned(BMP) then FreeAndNil(BMP); if Assigned(PNG) then FreeAndNil(PNG); if Assigned(JPG) then FreeAndNil(JPG); if ckbRememberme.Checked and Assigned(FUser) then begin Attributes := faArchive + faNormal; FileSetAttr(Path + 'remember.ini', Attributes); IniFile := TIniFile.Create(Path + 'remember.ini'); try IniFile.WriteString('Login', 'Username', FUser.user.name); finally FreeAndNil(IniFile); end; Attributes := faArchive + faHidden + faReadOnly; FileSetAttr(Path + 'remember.ini', Attributes); end; end; procedure TfrmLogin.FormDestroy(Sender: TObject); begin if Assigned(FUser) then FreeAndNil(FUser); end; procedure TfrmLogin.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_ESCAPE) then Close; end; procedure TfrmLogin.FormKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) then Perform(WM_NEXTDLGCTL,0,0); end; procedure TfrmLogin.FormShow(Sender: TObject); var Attributes: Integer; BX: TRect; mdo: HRGN; IniFile: TIniFile; begin edtUser.MaxLength := FMaxLength; Path := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); UserPath := Path + 'users'; if not DirectoryExists(UserPath) then ForceDirectories(UserPath); Attributes := faDirectory + faHidden; FileSetAttr(UserPath, Attributes); with pnlCircle do begin BX := ClientRect; mdo := CreateRoundRectRgn(BX.Left, BX.Top, BX.Right, BX.Bottom, 100, 100); Perform(EM_GETRECT, 0, lParam(@BX)); InflateRect(BX, - 4, - 4); Perform(EM_SETRECTNP, 0, lParam(@BX)); SetWindowRgn(Handle, mdo, True); Invalidate; end; IniFile := TIniFile.Create(Path + 'remember.ini'); try edtUser.Text := IniFile.ReadString('Login', 'Username', 'Username'); ckbRememberme.Checked := (edtUser.Text <> 'Username'); finally FreeAndNil(IniFile); end; end; procedure TfrmLogin.lblSignupClick(Sender: TObject); var frmSignUp: TfrmSignUp; begin frmSignUp := TfrmSignUp.Create(Self); try frmSignUp.MaxLength := FMaxLength; frmSignUp.ShowModal; finally FreeAndNil(frmSignUp); end; end; procedure TfrmLogin.lblSignupMouseEnter(Sender: TObject); begin lblSignup.Cursor := crHandPoint; end; procedure TfrmLogin.lblSignupMouseLeave(Sender: TObject); begin lblSignup.Cursor := crDefault; end; procedure TfrmLogin.pnlImageMouseEnter(Sender: TObject); begin imgLogin.Margins.Left := 0; imgLogin.Margins.Top := 0; imgLogin.Margins.Right := 0; imgLogin.Margins.Bottom := 0; end; procedure TfrmLogin.pnlImageMouseLeave(Sender: TObject); begin imgLogin.Margins.Left := 1; imgLogin.Margins.Top := 1; imgLogin.Margins.Right := 1; imgLogin.Margins.Bottom := 1; end; procedure TfrmLogin.pnlLoginClick(Sender: TObject); begin if (edtUser.Text <> 'Username') then begin if FileExists(UserPath + '\' + edtUser.Text) then begin lblUser.Caption := 'User name or Email Adress'; lblUser.Font.Color := clGray; if (edtUser.Focused) then pnlEdtUserBorder.Color := clHighlight else pnlEdtUserBorder.Color := clBtnFace; ChangeImage(UserPath + '\' + edtUser.Text); Login(edtUser.Text, edtPassword.Text); end else begin lblUser.Caption := 'Username does not exist'; lblUser.Font.Color := clRed; pnlEdtUserBorder.Color := clRed; edtUser.SetFocus; end; end; end; procedure TfrmLogin.Login(const Login, Senha: string); var lUser: TUsersClass; lFile: TStringList; begin lFile := TStringList.Create; try lFile.LoadFromFile(UserPath + '\' + Login); lUser := TUsersClass.FromJsonString(lFile.Text); try if (lUser.user.password = edtPassword.Text) then begin lblPassword.Caption := 'Password'; lblPassword.Font.Color := clGray; if (edtPassword.Focused) then pnlEdtPasswordBorder.Color := clHighlight else pnlEdtPasswordBorder.Color := clBtnFace; if Assigned(lUser) then FreeAndNil(lUser); FUser := TUsersClass.FromJsonString(lFile.Text); ModalResult := mrOk; end else begin lblPassword.Caption := 'Incorrect password'; lblPassword.Font.Color := clRed; pnlEdtPasswordBorder.Color := clRed; end; finally FreeAndNil(lUser); end; finally FreeAndNil(lFile); end; end; procedure TfrmLogin.pnlLoginMouseEnter(Sender: TObject); begin pnlLogin.Cursor := crHandPoint; pnlLogin.Margins.Left := 8; pnlLogin.Margins.Top := 8; pnlLogin.Margins.Right := 8; pnlLogin.Margins.Bottom := 8; end; procedure TfrmLogin.pnlLoginMouseLeave(Sender: TObject); begin pnlLogin.Cursor := crDefault; pnlLogin.Margins.Left := 10; pnlLogin.Margins.Top := 10; pnlLogin.Margins.Right := 10; pnlLogin.Margins.Bottom := 10; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Options.Search; interface uses DPM.Core.Types, DPM.Core.Options.Base; type TSearchOptions = class(TOptionsBase) private FSources : string; FSearchTerms : string; FSkip : integer; FTake : integer; FCompilerVersion : TCompilerVersion; FPlatforms : TDPMPlatforms; FVersion : TPackageVersion; FPrerelease : boolean; FCommercial : boolean; FTrial : boolean; FIncludeDelisted : boolean; FForce : boolean; FUseSource : boolean; FDebugMode : boolean; protected FExact : boolean; constructor CreateClone(const original : TSearchOptions); reintroduce; public constructor Create; override; function Clone : TSearchOptions; virtual; property Prerelease : boolean read FPrerelease write FPrerelease; property Commercial : boolean read FCommercial write FCommercial; property Trial : boolean read FTrial write FTrial; //IncludeDelisted not implemented. yet. property IncludeDelisted : boolean read FIncludeDelisted write FIncludeDelisted; //comma separated list of sources, empty means all. property Sources : string read FSources write FSources; property SearchTerms : string read FSearchTerms write FSearchTerms; property Skip : integer read FSkip write FSkip; property Take : integer read FTake write FTake; property CompilerVersion : TCompilerVersion read FCompilerVersion write FCompilerVersion; property Platforms : TDPMPlatforms read FPlatforms write FPlatforms; property Version : TPackageVersion read FVersion write FVersion; property Exact : boolean read FExact write FExact; //search term is a package id. property Force : boolean read FForce write FForce; //needed by the package installer. property UseSource : boolean read FUseSource write FUseSource; //only used by install but we need it here. property DebugMode : boolean read FDebugMode write FDebugMode; end; implementation { TSearchOptions } function TSearchOptions.Clone : TSearchOptions; begin result := TSearchOptions.CreateClone(Self); result.FUseSource := FUseSource; end; constructor TSearchOptions.Create; begin inherited; FCompilerVersion := TCompilerVersion.UnknownVersion; FSkip := 0; FTake := 0; FPlatforms := []; FVersion := TPackageVersion.Empty; FExact := false; end; constructor TSearchOptions.CreateClone(const original : TSearchOptions); begin inherited CreateClone(original); FSources := original.FSources; FSearchTerms := original.FSearchTerms; FSkip := original.FSkip; FTake := original.FTake; FCompilerVersion := original.FCompilerVersion; FPlatforms := original.FPlatforms; FVersion := original.FVersion; FPrerelease := original.FPrerelease; FIncludeDelisted := original.FIncludeDelisted; FUseSource := original.UseSource; FDebugMode := original.DebugMode; FTrial := original.Trial; FCommercial := original.Commercial; end; end.
unit UnitConexao; interface uses Windows, Messages, SysUtils, Variants, Classes, SyncObjs, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, IdContext, IdThreadComponent, IdAntiFreezeBase, IdAntiFreeze, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdGlobal, IdIOHandler, IdSchedulerOfThreadDefault, AdvProgressBar, VirtualTrees, IdTCPConnection, IdYarn; type pConexaoNew = ^TConexaoNew; TConexaoNew = class(TIdServerContext) private // we use critical section to ensure a single access on the connection // at a time _CriticalSection: TCriticalSection; _MasterIdentification: int64; _EnviandoString: boolean; _ValidConnection: boolean; _AContext: TConexaoNew; _Item: TListItem; _PassID: string; _ImagemBandeira: integer; _ImagemDesktop: integer; _DesktopBitmap: TBitmap; _GroupName: string; _ImagemCam: integer; _ImagemPing: integer; _SendPingTime: integer; _RAMSize: int64; _FontColor: integer; _RARPlugin: boolean; _NomeDoServidor: string; _Pais: string; _IPWAN: string; _IPLAN: string; _Account: string; _NomeDoComputador: string; _NomeDoUsuario: string; _CAM: string; _SistemaOperacional: string; _CPU: string; _RAM: string; _AV: string; _FW: string; _Versao: string; _Porta: string; _Ping: string; _Idle: string; _PrimeiraExecucao: string; _JanelaAtiva: string; _Node: PVirtualNode; _BrotherID: string; _ConnectionID: string; _WebcamList: string; _FormProcessos: TForm; _FormWindows: TForm; _FormServices: TForm; _FormRegedit: TForm; _FormShell: TForm; _FormFileManager: TForm; _FormClipboard: TForm; _FormListarDispositivos: TForm; _FormActivePorts: TForm; _FormProgramas: TForm; _FormDiversos: TForm; _FormDesktop: TForm; _FormWebcam: TForm; _FormAudioCapture: TForm; _FormCHAT: TForm; _FormKeylogger: TForm; _FormServerSettings: TForm; _FormMSN: TForm; _FormAll: TForm; _Transfer_Status: string; _Transfer_Velocidade: string; _Transfer_TempoRestante: string; _Transfer_ImagemIndex: integer; _Transfer_RemoteFileName: string; _Transfer_LocalFileName: string; _Transfer_RemoteFileSize: int64; _Transfer_RemoteFileSize_string: string; _Transfer_LocalFileSize: int64; _Transfer_LocalFileSize_string: string; _Transfer_VT: TVirtualStringTree; _Transfer_TransferPosition: int64; _Transfer_TransferPosition_string: string; _Transfer_TransferComplete: boolean; _Transfer_IsDownload: boolean; // if Download then = true / if Upload then = false public constructor Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil); override; destructor Destroy; override; public //procedure Lock; //procedure Unlock; procedure BroadcastBuffer(const ABuffer: TidBytes); procedure SendBuffer(const ABuffer: TidBytes; const AReceiverID: string); procedure EnviarString(Str: string); function ReceberString(NotifyWindow: THandle = 0): string; function TotalConnections: integer; function FindBrother(ConID: string): TIdContext; procedure DownloadFile(AContext: TConexaoNew); procedure UploadFile(AContext: TConexaoNew); procedure CreateTransfer(RemoteFile, LocalFile: string; RemoteSize, LocalSize: int64; xIsDownload: boolean; VT: TVirtualStringTree); public property MasterIdentification: int64 read _MasterIdentification write _MasterIdentification; property AContext: TConexaoNew read _AContext write _AContext; property Item: TListItem read _Item write _Item; property ImagemBandeira: integer read _ImagemBandeira write _ImagemBandeira; property EnviandoString: boolean read _EnviandoString write _EnviandoString; property ValidConnection: boolean read _ValidConnection write _ValidConnection; property ImagemDesktop: integer read _ImagemDesktop write _ImagemDesktop; property DesktopBitmap: TBitmap read _DesktopBitmap write _DesktopBitmap; property GroupName: string read _GroupName write _GroupName; property ImagemCam: integer read _ImagemCam write _ImagemCam; property PassID: string read _PassID write _PassID; property ImagemPing: integer read _ImagemPing write _ImagemPing; property SendPingTime: integer read _SendPingTime write _SendPingTime; property RAMSize: int64 read _RAMSize write _RAMSize; property FontColor: integer read _FontColor write _FontColor; property NomeDoServidor: string read _NomeDoServidor write _NomeDoServidor; property Pais: string read _Pais write _Pais; property IPWAN: string read _IPWAN write _IPWAN; property IPLAN: string read _IPLAN write _IPLAN; property Account: string read _Account write _Account; property NomeDoComputador: string read _NomeDoComputador write _NomeDoComputador; property NomeDoUsuario: string read _NomeDoUsuario write _NomeDoUsuario; property CAM: string read _CAM write _CAM; property SistemaOperacional: string read _SistemaOperacional write _SistemaOperacional; property CPU: string read _CPU write _CPU; property RAM: string read _RAM write _RAM; property AV: string read _AV write _AV; property FW: string read _FW write _FW; property Versao: string read _Versao write _Versao; property Porta: string read _Porta write _Porta; property Ping: string read _Ping write _Ping; property Idle: string read _Idle write _Idle; property PrimeiraExecucao: string read _PrimeiraExecucao write _PrimeiraExecucao; property JanelaAtiva: string read _JanelaAtiva write _JanelaAtiva; property Node: PVirtualNode read _Node write _Node; property BrotherID: string read _BrotherID write _BrotherID; property ConnectionID: string read _ConnectionID write _ConnectionID; property WebcamList: string read _WebcamList write _WebcamList; property RARPlugin: boolean read _RARPlugin write _RARPlugin; property FormProcessos: TForm read _FormProcessos write _FormProcessos; property FormWindows: TForm read _FormWindows write _FormWindows; property FormServices: TForm read _FormServices write _FormServices; property FormRegedit: TForm read _FormRegedit write _FormRegedit; property FormShell: TForm read _FormShell write _FormShell; property FormFileManager: TForm read _FormFileManager write _FormFileManager; property FormClipboard: TForm read _FormClipboard write _FormClipboard; property FormListarDispositivos: TForm read _FormListarDispositivos write _FormListarDispositivos; property FormActivePorts: TForm read _FormActivePorts write _FormActivePorts; property FormProgramas: TForm read _FormProgramas write _FormProgramas; property FormDiversos: TForm read _FormDiversos write _FormDiversos; property FormDesktop: TForm read _FormDesktop write _FormDesktop; property FormWebcam: TForm read _FormWebcam write _FormWebcam; property FormAudioCapture: TForm read _FormAudioCapture write _FormAudioCapture; property FormCHAT: TForm read _FormCHAT write _FormCHAT; property FormKeylogger: TForm read _FormKeylogger write _FormKeylogger; property FormServerSettings: TForm read _FormServerSettings write _FormServerSettings; property FormMSN: TForm read _FormMSN write _FormMSN; property FormAll: TForm read _FormAll write _FormAll; property Transfer_Status: string read _Transfer_Status write _Transfer_Status; property Transfer_Velocidade: string read _Transfer_Velocidade write _Transfer_Velocidade; property Transfer_TempoRestante: string read _Transfer_TempoRestante write _Transfer_TempoRestante; property Transfer_ImagemIndex: integer read _Transfer_ImagemIndex write _Transfer_ImagemIndex; property Transfer_RemoteFileName: string read _Transfer_RemoteFileName write _Transfer_RemoteFileName; property Transfer_LocalFileName: string read _Transfer_LocalFileName write _Transfer_LocalFileName; property Transfer_RemoteFileSize_string: string read _Transfer_RemoteFileSize_string write _Transfer_RemoteFileSize_string; property Transfer_LocalFileSize_string: string read _Transfer_LocalFileSize_string write _Transfer_LocalFileSize_string; property Transfer_TransferPosition_string: string read _Transfer_TransferPosition_string write _Transfer_TransferPosition_string; property Transfer_RemoteFileSize: int64 read _Transfer_RemoteFileSize write _Transfer_RemoteFileSize; property Transfer_LocalFileSize: int64 read _Transfer_LocalFileSize write _Transfer_LocalFileSize; property Transfer_TransferPosition: int64 read _Transfer_TransferPosition write _Transfer_TransferPosition; property Transfer_TransferComplete: boolean read _Transfer_TransferComplete write _Transfer_TransferComplete; property Transfer_IsDownload: boolean read _Transfer_IsDownload write _Transfer_IsDownload; property Transfer_VT: TVirtualStringTree read _Transfer_VT write _Transfer_VT; end; Const NewNodeSize = SizeOf(TConexaoNew); PBM_SETPOS = WM_USER + 2; PBM_STEPIT = WM_USER + 5; PBM_SETRANGE32 = WM_USER + 6; PBM_SETSTEP = WM_USER + 4; var ConnectionPass: int64; IdTCPServers: array [0..65535] of TIdTCPServer; IdSchedulerOfThreadDefault: array [0..65535] of TIdSchedulerOfThreadDefault; function IniciarNovaConexao(Porta: integer): boolean; procedure DesativarPorta(Porta: Integer); Function GetIPAddress: String; procedure AddUPnPEntry(LAN_IP: string; Port: Integer; const Name: ShortString); function DeleteUPnPEntry(Port: Integer): boolean; function CheckUPNPAvailable: boolean; type TConnectionHeader = record Password: int64; PacketSize: int64; end; implementation uses UnitMain, UnitConstantes, unitStrings, ActiveX, ComObj, Winsock, UnitCompressString, UnitSelectPort, NATUPNPLib_TLB, UnitCommonProcedures; type TNewUPnPEntry = class(TThread) private Port: integer; LAN_IP: string; Name: shortstring; protected procedure Execute; override; public constructor Create(xPort: integer; xLAN_IP: string; xName: shortstring); end; constructor TNewUPnPEntry.Create(xPort: integer; xLAN_IP: string; xName: shortstring); begin Port := xPort; LAN_IP := xLAN_IP; Name := xName; inherited Create(True); end; procedure TNewUPnPEntry.Execute; var Upnp: UPnPNAT; Begin UnitSelectPort.TerminouUPnP := False; DeleteUPnPEntry(Port); if (LAN_IP <> '127.0.0.1') and (LAN_IP <> 'localhost') and (LAN_IP <> '') then begin try CoInitialize(nil); Upnp := CoUPnPNAT.Create; Upnp.StaticPortMappingCollection.Add(port, 'TCP', port, LAN_IP, True, name); CoUnInitialize; Except FormMain.UseUPnP := False; end; end; UnitSelectPort.TerminouUPnP := True; end; Function GetIPAddress: String; type pu_long = ^u_long; var varTWSAData : TWSAData; varPHostEnt : PHostEnt; varTInAddr : TInAddr; namebuf : Array[0..255] of ansichar; begin If WSAStartup($101,varTWSAData) <> 0 Then Result := '' Else Begin gethostname(namebuf,sizeof(namebuf)); varPHostEnt := gethostbyname(namebuf); varTInAddr.S_addr := u_long(pu_long(varPHostEnt^.h_addr_list^)^); Result := inet_ntoa(varTInAddr); End; WSACleanup; end; procedure AddUPnPEntry(LAN_IP: string; Port: Integer; const Name: ShortString); var NewUPnPEntry: TNewUPnPEntry; begin NewUPnPEntry := TNewUPnPEntry.Create(Port, LAN_IP, Name); NewUPnPEntry.Resume; end; function DeleteUPnPEntry(Port: Integer): boolean; var Upnp: UPnPNAT; Begin result := false; try CoInitialize(nil); Upnp := CoUPnPNAT.Create; Upnp.StaticPortMappingCollection.Remove(port, 'TCP'); except CoUnInitialize; exit; end; result := True; end; function CheckUPNPAvailable: boolean; var Nat : Variant; Ports: Variant; foreach: IEnumVariant; enum: IUnknown; Port : OleVariant; b:cardinal; begin b:=0; result := True; CoInitialize(nil); try Nat := CreateOleObject('HNetCfg.NATUPnP'); Ports := Nat.StaticPortMappingCollection; Enum := Ports._NewEnum; foreach := enum as IEnumVariant; foreach.Next(1, Port, b); except result := false; end; CoUnInitialize; end; function IniciarNovaConexao(Porta: integer): boolean; begin result := false; if (Porta < 0) or (Porta > 65535) then exit; if IdTCPServers[porta] <> nil then exit; IdTCPServers[porta] := TIdTCPServer.Create; IdTCPServers[porta].ContextClass := TConexaoNew; IdSchedulerOfThreadDefault[porta] := TIdSchedulerOfThreadDefault.Create; IdTCPServers[porta].OnException := FormMain.IdTCPServer1.OnException; IdTCPServers[porta].OnExecute := FormMain.IdTCPServer1.OnExecute; IdTCPServers[porta].OnDisconnect := FormMain.IdTCPServer1.OnDisconnect; IdTCPServers[porta].OnConnect := FormMain.IdTCPServer1.OnConnect; IdTCPServers[porta].Scheduler := IdSchedulerOfThreadDefault[porta]; IdTCPServers[porta].DefaultPort := Porta; try IdTCPServers[porta].Active := true; except IdTCPServers[Porta].Free; IdTCPServers[Porta] := nil; exit; end; result := true; end; procedure DesativarPorta(Porta: Integer); var i, j: integer; ConAux: TConexaoNew; begin if (IdTCPServers[Porta] <> nil) and (IdTCPServers[Porta].Active) then begin IdTCPServers[Porta].OnExecute := FormMain.IdTCPServerExecuteAlternative; IdTCPServers[Porta].OnConnect := FormMain.IdTCPServerConnectAlternative; //FormMain.DisconnectAll(Porta); MessageBox(0, pwidechar(Traduzidos[125] + ' ' + inttostr(Porta) + ' ' + traduzidos[126]), pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma), MB_OK or MB_ICONWARNING or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST); FormMain.AtualizarQuantidade; IdTCPServers[Porta].Active := False; IdTCPServers[Porta].Free; IdTCPServers[Porta] := nil; IdSchedulerOfThreadDefault[Porta].Free; IdSchedulerOfThreadDefault[porta] := nil; end else begin IdTCPServers[Porta].Free; IdTCPServers[Porta] := nil; IdSchedulerOfThreadDefault[Porta].Free; IdSchedulerOfThreadDefault[porta] := nil; end; end; procedure TConexaoNew.BroadcastBuffer(const ABuffer: TidBytes); var Index: Integer; LClients: TList; LConexao: TConexaoNew; begin LClients := FContextList.LockList; try for Index := 0 to LClients.Count -1 do begin LConexao := TConexaoNew(LClients[Index]); //LConexao.Lock; try LConexao.Connection.IOHandler.Write(ABuffer); finally //LConexao.Unlock; end; end; finally FContextList.UnlockList; end; end; constructor TConexaoNew.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList); begin inherited Create(AConnection, AYarn, AList); _CriticalSection := TCriticalSection.Create; _EnviandoString := False; _RARPlugin := False; _AContext := Self; _Item := nil; end; function TConexaoNew.TotalConnections: integer; begin with FContextList.LockList do Result := Count; FContextList.UnLockList; end; function TConexaoNew.FindBrother(ConID: string): TIdContext; var Index: Integer; LClients: TList; LConexao: TConexaoNew; begin Result := nil; LClients := FContextList.LockList; try for Index := 0 to LClients.Count -1 do begin LConexao := TConexaoNew(LClients[Index]); if LConexao.ConnectionID = ConID then begin Result := LClients[Index]; Break; end; end; finally FContextList.UnlockList; end; end; destructor TConexaoNew.Destroy; var LClients: TList; LConexao: TConexaoNew; Index: integer; begin FreeAndNil(_CriticalSection); inherited; end; { procedure TConexaoNew.Lock; begin _CriticalSection.Enter; end; procedure TConexaoNew.Unlock; begin _CriticalSection.Leave; end; } procedure TConexaoNew.SendBuffer(const ABuffer: TidBytes; const AReceiverID: string); var Index: Integer; LClients: TList; LConexao: TConexaoNew; begin LClients := FContextList.LockList; try for Index := 0 to LClients.Count -1 do begin LConexao := TConexaoNew(LClients[Index]); if LConexao.ConnectionID = AReceiverID then begin //LConexao.Lock; try LConexao.Connection.IOHandler.Write(ABuffer); finally //LConexao.Unlock; end; Break; end; end; finally FContextList.UnlockList; end; end; procedure TConexaoNew.EnviarString(Str: string); var Bytes, BytesHeader: TidBytes; ConnectionHeader: TConnectionHeader; begin if MasterIdentification <> 1234567890 then Exit; if IdTCPServers[StrToInt(Porta)] = nil then Exit; Connection.CheckForGracefulDisconnect(false); if Connection.Connected = False then exit; Connection.IOHandler.CheckForDisconnect(false, true); if Connection.Connected = False then exit; Str := CompressString(Str); ConnectionHeader.Password := ConnectionPass; ConnectionHeader.PacketSize := Length(Str) * 2; //UNICODE Bytes := RawToBytes(Str[1], ConnectionHeader.PacketSize); BytesHeader := RawToBytes(ConnectionHeader, SizeOf(TConnectionHeader)); while (EnviandoString = True) and (Connection.Connected = True) do Application.ProcessMessages; if Connection.Connected = True then begin //Lock; EnviandoString := True; try Connection.IOHandler.WriteLn('X'); Connection.IOHandler.Write(BytesHeader, SizeOf(TConnectionHeader)); Connection.IOHandler.Write(Bytes, ConnectionHeader.PacketSize); finally EnviandoString := False; Connection.IOHandler.WriteBufferClear; //Unlock; end; end; end; function TConexaoNew.ReceberString(NotifyWindow: THandle = 0): string; var Bytes, BytesHeader: TidBytes; ConnectionHeader: TConnectionHeader; currRead, Transfered: int64; MaxBufferSize: integer; begin MaxBufferSize := 1024; result := ''; if MasterIdentification <> 1234567890 then begin result := 'InvalidConnection'; exit; end; if IdTCPServers[StrToInt(Porta)] = nil then Exit; ZeroMemory(@BytesHeader, SizeOf(BytesHeader)); Connection.IOHandler.ReadBytes(BytesHeader, SizeOf(TConnectionHeader)); BytesToRaw(BytesHeader, ConnectionHeader, SizeOf(TConnectionHeader)); if ConnectionHeader.Password <> ConnectionPass then begin result := 'InvalidConnection'; exit; end; if ConnectionHeader.PacketSize <= 0 then exit; if NotifyWindow = 0 then begin Connection.IOHandler.ReadBytes(Bytes, ConnectionHeader.PacketSize, True); SetLength(Result, ConnectionHeader.PacketSize div 2); BytesToRaw(Bytes, Result[1], ConnectionHeader.PacketSize); end else try Transfered := 0; PostMessage(NotifyWindow, PBM_SETRANGE32, 0, ConnectionHeader.PacketSize); PostMessage(NotifyWindow, PBM_SETPOS, 0, 0); while (Transfered < ConnectionHeader.PacketSize) and (Connection.Connected) do begin sleep(5); Application.ProcessMessages; if (ConnectionHeader.PacketSize - Transfered) >= MaxBufferSize then currRead := MaxBufferSize else currRead := (ConnectionHeader.PacketSize - Transfered); Connection.IOHandler.ReadBytes(Bytes, CurrRead, True); Transfered := Length(Bytes); PostMessage(NotifyWindow, PBM_SETPOS, Transfered, 0); Application.ProcessMessages; end; finally PostMessage(NotifyWindow, PBM_SETPOS, Transfered, 0); SetLength(Result, Transfered div 2); BytesToRaw(Bytes, Result[1], Transfered); Application.ProcessMessages; end; result := DeCompressString(Result); ZeroMemory(Bytes, Length(Bytes)); ZeroMemory(BytesHeader, Length(BytesHeader)); ZeroMemory(@ConnectionHeader, SizeOf(ConnectionHeader)); end; procedure TConexaoNew.DownloadFile(AContext: TConexaoNew); var AStream: TFileStream; hFile: cardinal; i: integer; begin Self.AContext := AContext; if FileExists(Transfer_LocalFileName) = false then begin hFile := CreateFile(PChar(Transfer_LocalFileName), GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0); CloseHandle(hFile); end; try Transfer_Status := Traduzidos[127]; Transfer_RemoteFileSize_string := FileSizeToStr(Transfer_RemoteFileSize); AStream := TFileStream.Create(Transfer_LocalFileName, fmOpenReadWrite + fmShareDenyNone); Astream.Seek(Transfer_LocalFileSize, 0); AContext.Connection.IOHandler.LargeStream := True; AContext.Connection.IOHandler.ReadStream(AStream, Transfer_RemoteFileSize - Transfer_LocalFileSize, False, self); finally FreeAndNil(AStream); try AContext.Connection.Disconnect; except end; if Transfer_TransferPosition >= Transfer_RemoteFileSize then begin Transfer_Status := Traduzidos[128]; Transfer_TempoRestante := ''; Transfer_TransferComplete := True; DeleteFile(Transfer_LocalFileName + '.xtreme'); end else begin Transfer_Status := Traduzidos[129]; Transfer_TempoRestante := ''; Transfer_TransferComplete := False; end; end; end; procedure TConexaoNew.UploadFile(AContext: TConexaoNew); var AStream: TFileStream; hFile: cardinal; i: integer; begin Self.AContext := AContext; if FileExists(Transfer_LocalFileName) = false then begin try AContext.Connection.Disconnect; except end; exit; end; try Transfer_Status := Traduzidos[130]; Transfer_RemoteFileSize_string := FileSizeToStr(Transfer_LocalFileSize); AStream := TFileStream.Create(Transfer_LocalFileName, fmOpenReadWrite + fmShareDenyNone); AContext.EnviarString(FMUPLOAD); AContext.Connection.IOHandler.LargeStream := True; AContext.Connection.IOHandler.Write(AStream, Transfer_LocalFileSize, False, self); finally FreeAndNil(AStream); if Transfer_TransferPosition >= Transfer_LocalFileSize then begin Transfer_Status := Traduzidos[128]; Transfer_TempoRestante := ''; Transfer_TransferComplete := True; end else begin Transfer_Status := Traduzidos[129]; Transfer_TempoRestante := ''; Transfer_TransferComplete := False; end; end; end; procedure TConexaoNew.CreateTransfer(RemoteFile: string; LocalFile: string; RemoteSize: Int64; LocalSize: Int64; xIsDownload: Boolean; VT: TVirtualStringTree); var Node: PVirtualNode; i: integer; begin try Self.Transfer_VT := VT; if xIsDownload then Self.Transfer_Status := Traduzidos[127] else Self.Transfer_Status := Traduzidos[130]; Self.Transfer_Velocidade := '0 KB/s'; Self.Transfer_TempoRestante := ''; if xIsDownload then Self.Transfer_ImagemIndex := 8 else Self.Transfer_ImagemIndex := 9; Self.Transfer_RemoteFileName := RemoteFile; Self.Transfer_RemoteFileSize := RemoteSize; Self.Transfer_RemoteFileSize_string := FileSizeToStr(RemoteSize); Self.Transfer_LocalFileName := LocalFile; Self.Transfer_LocalFileSize := LocalSize; Self.Transfer_LocalFileSize_string := FileSizeToStr(LocalSize); Self.Transfer_IsDownload := xIsDownload; Self.Transfer_TransferComplete := False; if Transfer_IsDownload then begin if Transfer_LocalFileSize > 0 then Self.Transfer_TransferPosition_string := IntToStr(round((Transfer_LocalFileSize / Transfer_RemoteFileSize) * 100)) + '%' else Self.Transfer_TransferPosition_string := '0%'; end else Self.Transfer_TransferPosition_string := '0%'; finally Self.Node := VT.AddChild(nil, Self); end; end; end.
unit UFont; (*==================================================================== Workaround for Delphi 2.0 inability to work with font scripts ======================================================================*) interface uses {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, {$ENDIF} Graphics; type TLogFontStyle = (lfsNormal, lfsBold, lfsItalic); function QGetScriptString (CharSet: byte): ShortString; function QGetScriptNumber (ScriptString: ShortString): byte; function QSelectLogFontDialog (var LogFont: TLogFont; MinSize, MaxSize: longint; ForPrinter: boolean; var LogFontSize: Integer): boolean; function QHeightFromSize(Size: integer): longint; procedure InitLogFontStruct (var LogFont: TLogFont; Name: ShortString; Size: integer; Bold: boolean; Italics: boolean; Script: ShortString); procedure SetFontFromLogFont(Font: TFont; var LogFont: TLogFont); //----------------------------------------------------------- implementation uses Forms, {CommDlg,} SysUtils{, Printers}; //----------------------------------------------------------- (* TChooseFont = packed record lStructSize: DWORD; hWndOwner: HWnd; { caller's window handle } hDC: HDC; { printer DC/IC or nil } lpLogFont: PLogFontA; { pointer to a LOGFONT struct } iPointSize: Integer; { 10 * size in points of selected font } Flags: DWORD; { dialog flags } rgbColors: COLORREF; { returned text color } lCustData: LPARAM; { data passed to hook function } lpfnHook: function(Wnd: HWND; Message: UINT; wParam: WPARAM; lParam: LPARAM): UINT stdcall; { pointer to hook function } lpTemplateName: PAnsiChar; { custom template name } hInstance: HINST; { instance handle of EXE that contains custom dialog template } lpszStyle: PAnsiChar; { return the style field here must be lf_FaceSize or bigger } nFontType: Word; { same value reported to the EnumFonts call back with the extra fonttype_ bits added } wReserved: Word; nSizeMin: Integer; { minimum point size allowed and } nSizeMax: Integer; { maximum point size allowed if cf_LimitSize is used } end; //----------------------------------------------------------- TLogFont = packed record lfHeight: Longint; lfWidth: Longint; lfEscapement: Longint; lfOrientation: Longint; lfWeight: Longint; lfItalic: Byte; lfUnderline: Byte; lfStrikeOut: Byte; lfCharSet: Byte; lfOutPrecision: Byte; lfClipPrecision: Byte; lfQuality: Byte; lfPitchAndFamily: Byte; lfFaceName: array[0..LF_FACESIZE - 1] of AnsiChar; end; *) //----------------------------------------------------------- function QTaskModalDialog(DialogFunc: Pointer; var DialogData): Bool; type TDialogFunc = function(var DialogData): Bool stdcall; var ActiveWindow: HWnd; WindowList: Pointer; begin ActiveWindow := GetActiveWindow; ///WindowList := DisableTaskWindows(0); try Result := TDialogFunc(DialogFunc)(DialogData); finally ///EnableTaskWindows(WindowList); SetActiveWindow(ActiveWindow); end; end; //----------------------------------------------------------- function QGetScriptString (CharSet: byte): ShortString; begin case CharSet of ANSI_CHARSET : Result := 'Ansi'; DEFAULT_CHARSET : Result := 'Default'; SYMBOL_CHARSET : Result := 'Symbol'; SHIFTJIS_CHARSET : Result := 'ShiftJis'; HANGEUL_CHARSET : Result := 'Hangeul'; GB2312_CHARSET : Result := 'GB2312'; CHINESEBIG5_CHARSET: Result := 'ChineseBig5'; OEM_CHARSET : Result := 'OEM'; JOHAB_CHARSET : Result := 'Johab'; HEBREW_CHARSET : Result := 'Hebrew'; ARABIC_CHARSET : Result := 'Arabic'; GREEK_CHARSET : Result := 'Greek'; TURKISH_CHARSET : Result := 'Turkish'; THAI_CHARSET : Result := 'Thai'; EASTEUROPE_CHARSET : Result := 'CentralEurope'; RUSSIAN_CHARSET : Result := 'Russian'; MAC_CHARSET : Result := 'Mac'; BALTIC_CHARSET : Result := 'Baltic'; end; end; //----------------------------------------------------------- function QGetScriptNumber (ScriptString: ShortString): byte; begin if AnsiLowerCase(ScriptString) = 'centraleurope' then begin Result := EASTEUROPE_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'ansi' then begin Result := ANSI_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'default' then begin Result := DEFAULT_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'symbol' then begin Result := SYMBOL_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'shiftjis' then begin Result := SHIFTJIS_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'hangeul' then begin Result := HANGEUL_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'gb2312' then begin Result := GB2312_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'chinesebig5' then begin Result := CHINESEBIG5_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'oem' then begin Result := OEM_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'johab' then begin Result := JOHAB_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'hebrew' then begin Result := HEBREW_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'arabic' then begin Result := ARABIC_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'greek' then begin Result := GREEK_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'turkish' then begin Result := TURKISH_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'thai' then begin Result := THAI_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'russian' then begin Result := RUSSIAN_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'mac' then begin Result := MAC_CHARSET; exit; end; if AnsiLowerCase(ScriptString) = 'baltic' then begin Result := BALTIC_CHARSET; exit; end; Result := DEFAULT_CHARSET; end; //----------------------------------------------------------- function QHeightFromSize(Size: integer): longint; var DC: HDC; begin DC := GetDC(0); Result := -MulDiv(Size, GetDeviceCaps(DC, LOGPIXELSY), 72); ReleaseDC(0,DC); end; //----------------------------------------------------------- function QSizeFromHeight(Height: longint): integer; var DC: HDC; begin DC := GetDC(0); Result := -MulDiv(Height, 72, GetDeviceCaps(DC, LOGPIXELSY)); ReleaseDC(0,DC); end; //----------------------------------------------------------- function QSelectLogFontDialog (var LogFont: TLogFont; MinSize, MaxSize: longint; ForPrinter: boolean; var LogFontSize: Integer): boolean; {$ifdef mswindows} var ChooseFontRec: TChooseFont; begin FillChar(ChooseFontRec, SizeOf(ChooseFontRec), 0); with ChooseFontRec do begin lStructSize := SizeOf(ChooseFontRec); hDC := 0; lpLogFont := @LogFont; Flags := Flags or CF_INITTOLOGFONTSTRUCT; nSizeMin := MinSize; nSizeMax := MaxSize; Flags := Flags or CF_LIMITSIZE; Flags := Flags or CF_NOVECTORFONTS or CF_NOSIMULATIONS or CF_BOTH; if ForPrinter then Flags := Flags or CF_SCALABLEONLY; hWndOwner := Application.Handle; Result := QTaskModalDialog(@ChooseFont, ChooseFontRec); LogFontSize := iPointSize div 10; end; end; {$endif} begin end; //----------------------------------------------------------- procedure InitLogFontStruct (var LogFont: TLogFont; Name: ShortString; Size: integer; Bold: boolean; Italics: boolean; Script: ShortString); begin FillChar(LogFont, SizeOf(LogFont), 0); StrPCopy(LogFont.lfFaceName, Name); LogFont.lfHeight := QHeightFromSize(Size); LogFont.lfWeight := FW_NORMAL; if Bold then LogFont.lfWeight := FW_BOLD; if Italics then LogFont.lfItalic := 1; LogFont.lfCharSet := QGetScriptNumber (Script); end; //----------------------------------------------------------- procedure SetFontFromLogFont(Font: TFont; var LogFont: TLogFont); begin Font.Name := StrPas(LogFont.lfFaceName); Font.Height := LogFont.lfHeight; Font.Style := []; if LogFont.lfWeight = FW_BOLD then Font.Style := Font.Style + [fsBold]; if LogFont.lfItalic = 1 then Font.Style := Font.Style + [fsItalic]; Font.Handle := CreateFontIndirect(LogFont); end; //----------------------------------------------------------- end.
unit frmGIWorkerOption; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, DB, DBClient, frmBase; type TWorkerOptionForm = class(TForm) PnlOption: TPanel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; LstWaitWorker: TListBox; LstWorker: TListBox; SBtnSelect: TSpeedButton; SBtnSelectAll: TSpeedButton; SBtnCleanAll: TSpeedButton; SBtnClean: TSpeedButton; cdsWorkerList: TClientDataSet; PnlInfo: TPanel; SBtnSave: TSpeedButton; SBtnExit: TSpeedButton; Label1: TLabel; EdtWorkerID: TEdit; SBtnQuery: TSpeedButton; Label2: TLabel; CBBDepartment: TComboBox; btnLocalQuery: TButton; cdsFNWorkerList: TClientDataSet; procedure FormShow(Sender: TObject); procedure LstWaitWorkerDblClick(Sender: TObject); procedure LstWorkerDblClick(Sender: TObject); procedure SBtnSelectClick(Sender: TObject); procedure SBtnCleanClick(Sender: TObject); procedure SBtnSelectAllClick(Sender: TObject); procedure SBtnCleanAllClick(Sender: TObject); procedure SBtnSaveClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure SBtnExitClick(Sender: TObject); procedure SBtnQueryClick(Sender: TObject); procedure btnLocalQueryClick(Sender: TObject); procedure CBBDepartmentChange(Sender: TObject); private { Private declarations } procedure init; procedure FullWorker(aCDS : TClientDataSet; aLst : TStrings); function GetWorkerData(aWorkerID, aQueryWorkerID : String) : Boolean; function GetNowWorkerData(aWorkerID, aDepartment : String) : Boolean; procedure Move(srcList , destList : TStrings; moveIndex : integer); procedure MoveAll(srcList , destList : TStrings); procedure Save; procedure Query; procedure LocalQuery(aWorkerID : string); function CheckWorker(workerList : String) : Boolean; public { Public declarations } end; var WorkerOptionForm: TWorkerOptionForm; implementation uses ServerDllPub, uLogin, uGlobal, uFNMResource, uShowMessage; {$R *.dfm} { TWorkerOptionForm } function TWorkerOptionForm.GetWorkerData(aWorkerID, aQueryWorkerID : String) : Boolean; //aDepartment var sql : string; sErrorMsg : WideString; vData : OleVariant; begin Result := False; cdsFNWorkerList.Close; cdsFNWorkerList.Filter := ''; sql := aWorkerID; //aDepartment + '|' + if aQueryWorkerID <> '' then sql := sql + '|' + aQueryWorkerID; FNMServerObj.GetQueryData(vData, 'GiFullCarFabricsData', 'GetWorkerList,' + QuotedStr(sql), sErrorMsg); if Trim(sErrorMsg) <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); Exit; end;//if cdsFNWorkerList.Data := vData; if(cdsFNWorkerList.Active) and (cdsFNWorkerList.RecordCount > 0) then begin FullWorker(cdsFNWorkerList, LstWaitWorker.Items); Result := True; end;//if end; function TWorkerOptionForm.GetNowWorkerData(aWorkerID, aDepartment: String): Boolean; var sErrorMsg : WideString; vData : OleVariant; s : String; begin Result := False; cdsWorkerList.Close; FNMServerObj.GetQueryData(vData, 'GiFullCarFabricsData', QuotedStr('GetNowWorkerList') + ',' + QuotedStr(aDepartment + '|' + aWorkerID), sErrorMsg); if Trim(sErrorMsg) <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); Exit; end;//if cdsWorkerList.Data := vData; LstWorker.Items.Clear; if(cdsWorkerList.Active) and (cdsWorkerList.RecordCount > 0) then begin FullWorker(cdsWorkerList, LstWorker.Items); Result := True; end;//if end; procedure TWorkerOptionForm.init; begin Self.Width := 698; SBtnExit.Glyph.LoadFromResourceName(HInstance, RES_EXIT); SBtnQuery.Glyph.LoadFromResourceName(HInstance, RES_QUERY); CBBDepartment.Items.Add('G1'); CBBDepartment.Items.Add('G2'); CBBDepartment.Items.Add('G3'); CBBDepartment.ItemIndex := 0; end; procedure TWorkerOptionForm.FullWorker(aCDS: TClientDataSet; aLst: TStrings); begin aLst.Clear; aCDS.First; while not aCDS.Eof do begin aLst.Add(aCDS.FieldByName('Worker_ID').AsString + '->' + aCDS.FieldByName('Worker_Name').AsString); aCDS.Next; end;//while end; procedure TWorkerOptionForm.FormShow(Sender: TObject); begin init; end; procedure TWorkerOptionForm.Move(srcList, destList: TStrings; moveIndex : integer); begin if srcList.Count > 0 then begin if moveIndex < 0 then moveIndex := 0; if destList.IndexOf(srcList.Strings[moveIndex]) = -1 then //检查是否有重复 destList.Add(srcList.Strings[moveIndex]); srcList.Delete(moveIndex); end;//if end; procedure TWorkerOptionForm.MoveAll(srcList, destList: TStrings); var i : Integer; begin for i := 0 to srcList.Count -1 do Move(srcList, destList, 0); end; procedure TWorkerOptionForm.LstWaitWorkerDblClick(Sender: TObject); begin Move(LstWaitWorker.Items, LstWorker.Items, LstWaitWorker.ItemIndex); end; procedure TWorkerOptionForm.LstWorkerDblClick(Sender: TObject); begin Move(LstWorker.Items, LstWaitWorker.Items, LstWorker.ItemIndex); end; procedure TWorkerOptionForm.SBtnSelectClick(Sender: TObject); begin Move(LstWaitWorker.Items, LstWorker.Items, LstWaitWorker.ItemIndex); end; procedure TWorkerOptionForm.SBtnCleanClick(Sender: TObject); begin Move(LstWorker.Items, LstWaitWorker.Items,LstWorker.ItemIndex); end; procedure TWorkerOptionForm.SBtnSelectAllClick(Sender: TObject); begin MoveAll(LstWaitWorker.Items, LstWorker.Items); end; procedure TWorkerOptionForm.SBtnCleanAllClick(Sender: TObject); begin MoveAll(LstWorker.Items, LstWaitWorker.Items); end; procedure TWorkerOptionForm.Save; var i : Integer; workerID, sql, sErrorMsg : WideString; vData : OleVariant; begin if LstWorker.Items.Count = 0 then Exit; if CBBDepartment.Text = '' then begin TMsgDialog.ShowMsgDialog('请选择人员班组部门',mtWarning); CBBDepartment.SetFocus; Exit; end;//if for i := 0 to LstWorker.Items.Count - 1 do workerID := workerID + copy(LstWorker.Items.Strings[i], 1, pos('->', LstWorker.Items.Strings[i]) - 1) + ','; if CheckWorker(workerID) then begin sql := QuotedStr('SaveWorker') + ',' + QuotedStr(CBBDepartment.Text + '|' + Login.LoginID + '|' + workerID);//Login.CurrentDepartment FNMServerObj.GetQueryData(vData,'GiFullCarFabricsData', sql, sErrorMsg); if Trim(sErrorMsg) <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); Exit; end else TMsgDialog.ShowMsgDialog('班组人员数据保存成功', mtInformation); end;//if end; procedure TWorkerOptionForm.SBtnSaveClick(Sender: TObject); begin Save; end; procedure TWorkerOptionForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TWorkerOptionForm.FormDestroy(Sender: TObject); begin WorkerOptionForm := nil; end; procedure TWorkerOptionForm.SBtnExitClick(Sender: TObject); begin inherited; Close; end; procedure TWorkerOptionForm.Query; begin if GetWorkerData(Login.LoginID, '') then //Login.CurrentDepartment //if GetWorkerData('0002', 'G2', EdtWorkerID.Text) then begin SBtnSave.Glyph.LoadFromResourceName(HInstance, RES_SAVE); SBtnSave.Enabled := True; GetNowWorkerData(Login.LoginID, CBBDepartment.Text); end;//if end; procedure TWorkerOptionForm.SBtnQueryClick(Sender: TObject); begin Query; end; procedure TWorkerOptionForm.LocalQuery(aWorkerID: string); begin if cdsFNWorkerList.Active then begin if trim(aWorkerID) <> '' then begin cdsFNWorkerList.Filtered := False; cdsFNWorkerList.Filter := 'Worker_ID = ' + QuotedStr(aWorkerID); cdsFNWorkerList.Filtered := True; end else begin cdsFNWorkerList.Filtered := False; cdsFNWorkerList.Filter := ''; end;//else FullWorker(cdsFNWorkerList, LstWaitWorker.Items); end;//if end; procedure TWorkerOptionForm.btnLocalQueryClick(Sender: TObject); begin LocalQuery(EdtWorkerID.Text); end; procedure TWorkerOptionForm.CBBDepartmentChange(Sender: TObject); begin GetNowWorkerData(Login.LoginID, CBBDepartment.Text); end; function TWorkerOptionForm.CheckWorker(workerList: String): Boolean; var sql, sErrorMsg : WideString; vData : OleVariant; begin Result := False; sql := QuotedStr('CheckWorker') + ',' + QuotedStr(CBBDepartment.Text + '|' + workerList); FNMServerObj.GetQueryData(vData, 'GiFullCarFabricsData', sql, sErrorMsg); if Trim(sErrorMsg) <> '' then begin TMsgDialog.ShowMsgDialog(sErrorMsg, mtError); Exit; end; Result := True; end; end.
unit tvl_udatabinders; interface uses Classes, SysUtils, trl_irttibroker, Controls, StdCtrls, ExtCtrls, fgl, Graphics, Grids, MaskEdit, lmessages, LCLProc, LCLType, Menus, SynEdit, trl_ipersist, trl_upersist, tvl_messages, lclintf, messages, Forms, EditBtn, tvl_ucontrolbinder, ComCtrls, tvl_ibindings; type { TEditBinder } TEditBinder = class(TControlBinder) private fDataItem: IRBDataItem; fChangeEvents: TBinderChangeEvents; function GetControl: TWinControl; protected procedure BindControl; override; procedure UnbindControl; override; procedure NotifyChangeEvents; public constructor Create; destructor Destroy; override; procedure DataToControl; virtual; abstract; procedure ControlToData; virtual; abstract; procedure Bind(const AControl: TWinControl; const ADataItem: IRBDataItem); reintroduce; procedure RegisterChangeEvent(AEvent: TBinderChangeEvent); procedure UnregisterChangeEvent(AEvent: TBinderChangeEvent); property Control: TWinControl read GetControl; property DataItem: IRBDataItem read fDataItem; end; { TTextBinder } TTextBinder = class(TEditBinder) private function GetControl: TCustomEdit; procedure OnChangeHandler(Sender: TObject); protected procedure BindControl; override; procedure UnbindControl; override; property Control: TCustomEdit read GetControl; public procedure DataToControl; override; procedure ControlToData; override; end; { TTextBtnBinder } TTextBtnBinder = class(TEditBinder) private function GetControl: TCustomEditButton; procedure OnChangeHandler(Sender: TObject); protected procedure BindControl; override; procedure UnbindControl; override; property Control: TCustomEditButton read GetControl; public procedure DataToControl; override; procedure ControlToData; override; end; { TMemoBinder } TMemoBinder = class(TEditBinder) private function GetControl: TCustomSynEdit; procedure OnChangeHandler(Sender: TObject); protected procedure BindControl; override; procedure UnbindControl; override; property Control: TCustomSynEdit read GetControl; public procedure DataToControl; override; procedure ControlToData; override; end; { TBoolBinder } TBoolBinder = class(TEditBinder) private function GetControl: TCustomCheckBox; procedure OnChangeHandler(Sender: TObject); protected procedure BindControl; override; procedure UnbindControl; override; property Control: TCustomCheckBox read GetControl; public procedure DataToControl; override; procedure ControlToData; override; end; { TOfferBinder } TOfferBinder = class(TEditBinder) private fKeyDownText: string; function GetControl: TCustomComboBox; procedure OnChangeHandler(Sender: TObject); protected procedure FillOffer; virtual; abstract; procedure OfferToData; virtual; abstract; procedure DataToOffer; virtual; abstract; protected procedure BindControl; override; procedure UnbindControl; override; procedure DoControlWndProc(var TheMessage: TLMessage); override; property Control: TCustomComboBox read GetControl; public procedure DataToControl; override; procedure ControlToData; override; end; { TOfferRefBinder } TOfferRefBinder = class(TOfferBinder) private fOffer: IPersistRefList; function GetAsRef: IPersistRef; function GetItemForCombo(AData: IRBData): string; protected procedure FillOffer; override; procedure OfferToData; override; procedure DataToOffer; override; protected procedure FillControlItems; property AsRef: IPersistRef read GetAsRef; end; { TOfferEnumBinder } TOfferEnumBinder = class(TOfferBinder) protected procedure FillOffer; override; procedure OfferToData; override; procedure DataToOffer; override; end; { TTabSheetBinder } TTabSheetBinder = class(TEditBinder) private function GetControl: TCustomPage; protected property Control: TCustomPage read GetControl; public procedure DataToControl; override; procedure ControlToData; override; end; { TListBinder } TListBinder = class(TEditBinder) protected type { TGridEditorSupport } TGridEditorSupport = class protected type TOnGetEditorSupportGrid = function: TCustomGrid of object; { TSupportBinder } TSupportBinder = class(TControlBinder) protected fOnEditorSupportGrid: TOnGetEditorSupportGrid; procedure DoControlWndProc(var TheMessage: TLMessage); override; public property OnEditorSupportGrid: TOnGetEditorSupportGrid read fOnEditorSupportGrid write fOnEditorSupportGrid; end; private fEditor: TWinControl; fGrid: TCustomGrid; fCol, fRow:Integer; fSupportBinder: TSupportBinder; protected procedure KeyDown(var Key : Word; Shift : TShiftState); procedure EditingDone; function GetRect: TRect; procedure SetGrid(var Msg: TGridMessage); procedure SetPos(var Msg: TGridMessage); procedure GetGrid(var Msg: TGridMessage); function GetEditorSupportGridEvent: TCustomGrid; public constructor Create(AEditor: TWinControl); destructor Destroy; override; property Col: integer read fCol; property Row: integer read fRow; end; { TOfferEditor } TOfferEditor = class(TCustomComboBox) private fSupport: TGridEditorSupport; protected procedure KeyDown(var Key : Word; Shift : TShiftState); override; procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); override; procedure msg_SetGrid(var Msg: TGridMessage); message GM_SETGRID; procedure msg_SetPos(var Msg: TGridMessage); message GM_SETPOS; procedure msg_GetGrid(var Msg: TGridMessage); message GM_GETGRID; procedure msg_SetValue(var Msg: TGridMessage); message GM_SETVALUE; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure EditingDone; override; end; { TTextEditor } TTextEditor = class(TCustomMaskEdit) private fSupport: TGridEditorSupport; protected procedure KeyDown(var Key : Word; Shift : TShiftState); override; procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); override; procedure msg_SetGrid(var Msg: TGridMessage); message GM_SETGRID; procedure msg_SetPos(var Msg: TGridMessage); message GM_SETPOS; procedure msg_GetGrid(var Msg: TGridMessage); message GM_GETGRID; procedure msg_SetValue(var Msg: TGridMessage); message GM_SETVALUE; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure EditingDone; override; end; private fCellEditor: TWinControl; fCellValueData: IRBData; fCellBinder: TEditBinder; fObjectData: IRBData; fCol, fRow: Integer; fOfferEditor: TOfferEditor; fTextEditor: TTextEditor; function GetAsMany: IPersistMany; function GetControl: TCustomStringGrid; procedure FillRowFromObject(ARow: integer; AObjectData: IRBData); procedure EmptyRow(ARow: integer); function CreateEditor(const ADataItem: IRBDataItem): TWinControl; function CreateBinder(const ADataItem: IRBDataItem): TEditBinder; procedure NilEditor; procedure OnColRowDeletedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); procedure OnColRowInsertedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); procedure OnEditingDoneHandler(Sender: TObject); procedure OnSelectEditorHandler(Sender: TObject; aCol, aRow: Integer; var Editor: TWinControl); procedure OnKeyDownHandler(Sender: TObject; var Key: Word; Shift: TShiftState); procedure OnSelectionHandler(Sender: TObject; aCol, aRow: Integer); protected procedure BindControl; override; procedure UnbindControl; override; procedure DoControlWndProc(var TheMessage: TLMessage); override; property Control: TCustomStringGrid read GetControl; property AsMany: IPersistMany read GetAsMany; protected procedure DispatchTextToEditor; procedure SetRowAutoInsertToFalse; function GetOfferEditor: TOfferEditor; function GetTextEditor: TTextEditor; property OfferEditor: TOfferEditor read GetOfferEditor; property TextEditor: TTextEditor read GetTextEditor; public procedure DataToControl; override; procedure ControlToData; override; end; implementation type { TControlHelper } TControlHelper = class helper for TControl private function GetH_OnEditingDone: TNotifyEvent; procedure SetH_OnEditingDone(AValue: TNotifyEvent); public property H_OnEditingDone: TNotifyEvent read GetH_OnEditingDone write SetH_OnEditingDone; end; { TWinControlHelper } TWinControlHelper = class helper for TWinControl public function H_FindNextControl(CurrentControl: TWinControl; GoForward, CheckTabStop, CheckParent: Boolean): TWinControl; end; { TGridHelper } TGridHelper = class helper for TCustomGrid private function GetH_FastEditing: boolean; procedure SetH_FastEditing(AValue: boolean); public procedure H_EditorTextChanged(const aCol,aRow: Integer; const aText:string); function H_EditorIsReadOnly: boolean; procedure H_SetEditText(ACol, ARow: Longint; const Value: string); procedure H_KeyDown(var Key : Word; Shift : TShiftState); procedure H_DoOPDeleteColRow(IsColumn: Boolean; index: Integer); property H_FastEditing: boolean read GetH_FastEditing write SetH_FastEditing; function H_GetEditText(ACol, ARow: Longint): string; procedure H_SetOptions(const AValue: TGridOptions); end; { TCustomComboBoxHelper } TCustomComboBoxHelper = class helper for TCustomComboBox private function GetOnChange: TNotifyEvent; procedure SetOnChange(AValue: TNotifyEvent); public property OnChange: TNotifyEvent read GetOnChange write SetOnChange; end; { TTabSheetBinder } function TTabSheetBinder.GetControl: TCustomPage; begin Result := inherited Control as TCustomPage; end; procedure TTabSheetBinder.DataToControl; begin Control.Caption := DataItem.AsString; end; procedure TTabSheetBinder.ControlToData; begin // for now leave readonly end; { TListBinder.TGridEditorSupport.TSupportBinder } procedure TListBinder.TGridEditorSupport.TSupportBinder.DoControlWndProc( var TheMessage: TLMessage); begin case TheMessage.Msg of LM_KEYDOWN: begin Exit; end; LM_CLEAR, LM_CUT, LM_PASTE: begin if (OnEditorSupportGrid <> nil) and (OnEditorSupportGrid.H_EditorIsReadOnly) then exit; end; end; inherited DoControlWndProc(TheMessage); end; { TTextBtnBinder } function TTextBtnBinder.GetControl: TCustomEditButton; begin Result := inherited Control as TCustomEditButton; end; procedure TTextBtnBinder.OnChangeHandler(Sender: TObject); begin DataItem.AsString := Control.Text; NotifyChangeEvents; end; procedure TTextBtnBinder.BindControl; begin inherited; Control.OnChange := @OnChangeHandler; end; procedure TTextBtnBinder.UnbindControl; begin Control.OnChange := nil; inherited UnbindControl; end; procedure TTextBtnBinder.DataToControl; begin Control.Text := DataItem.AsString end; procedure TTextBtnBinder.ControlToData; begin DataItem.AsString := Control.Text; end; { TWinControlHelper } function TWinControlHelper.H_FindNextControl(CurrentControl: TWinControl; GoForward, CheckTabStop, CheckParent: Boolean): TWinControl; begin Result := FindNextControl(CurrentControl, GoForward, CheckTabStop, CheckParent); end; { TControlHelper } function TControlHelper.GetH_OnEditingDone: TNotifyEvent; begin Result := OnEditingDone; end; procedure TControlHelper.SetH_OnEditingDone(AValue: TNotifyEvent); begin OnEditingDone := AValue; end; { TMemoBinder } function TMemoBinder.GetControl: TCustomSynEdit; begin Result := inherited Control as TCustomSynEdit; end; procedure TMemoBinder.OnChangeHandler(Sender: TObject); begin DataItem.AsString := Control.Text; NotifyChangeEvents; end; procedure TMemoBinder.BindControl; begin inherited; Control.OnChange := @OnChangeHandler; end; procedure TMemoBinder.UnbindControl; begin Control.OnChange := nil; inherited UnbindControl; end; procedure TMemoBinder.DataToControl; begin Control.Text := DataItem.AsString; end; procedure TMemoBinder.ControlToData; begin DataItem.AsString := Control.Text; end; { TBoolBinder } function TBoolBinder.GetControl: TCustomCheckBox; begin Result := inherited Control as TCustomCheckBox; end; procedure TBoolBinder.OnChangeHandler(Sender: TObject); begin DataItem.AsBoolean := Control.State = cbChecked; NotifyChangeEvents; end; procedure TBoolBinder.BindControl; begin inherited; Control.OnChange := @OnChangeHandler; end; procedure TBoolBinder.UnbindControl; begin Control.OnChange := nil; inherited UnbindControl; end; procedure TBoolBinder.DataToControl; begin if DataItem.AsBoolean then Control.State := cbChecked else Control.State := cbUnchecked; end; procedure TBoolBinder.ControlToData; begin DataItem.AsBoolean := Control.State = cbChecked; end; { TOfferEnumBinder } procedure TOfferEnumBinder.FillOffer; var i: integer; begin Control.Items.Clear; for i := 0 to DataItem.EnumNameCount - 1 do begin Control.Items.Add(DataItem.EnumName[i]); end; end; procedure TOfferEnumBinder.OfferToData; begin if Control.ItemIndex <> -1 then begin DataItem.AsString := Control.Items[Control.ItemIndex]; end; end; procedure TOfferEnumBinder.DataToOffer; var i: integer; begin for i := 0 to Control.Items.Count - 1 do begin if DataItem.AsString = Control.Items[i] then begin Control.ItemIndex := i; Exit; end; end; Control.ItemIndex := -1; end; { TListBinder.TTextEditor } procedure TListBinder.TTextEditor.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key,Shift); if fSupport <> nil then fSupport.KeyDown(Key, Shift); end; procedure TListBinder.TTextEditor.DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); var m: TRect; begin if fSupport <> nil then begin m := fSupport.GetRect; inherited DoSetBounds(m.Left, m.Top, m.Right - m.Left + 1, m.Bottom - m.Top + 1); end else inherited; end; procedure TListBinder.TTextEditor.msg_SetGrid(var Msg: TGridMessage); begin if fSupport <> nil then fSupport.SetGrid(Msg); end; procedure TListBinder.TTextEditor.msg_SetPos(var Msg: TGridMessage); begin if fSupport <> nil then fSupport.SetPos(Msg); end; procedure TListBinder.TTextEditor.msg_GetGrid(var Msg: TGridMessage); begin if fSupport <> nil then fSupport.GetGrid(Msg); end; procedure TListBinder.TTextEditor.msg_SetValue(var Msg: TGridMessage); var mSkipEnd: Boolean; begin mSkipEnd := Text = ''; Text := Msg.Value; if mSkipEnd then SelStart := Length(Text) + 1; end; constructor TListBinder.TTextEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); fSupport := TGridEditorSupport.Create(Self); AutoSize := false; BorderStyle := bsNone; end; destructor TListBinder.TTextEditor.Destroy; begin FreeAndNil(fSupport); inherited Destroy; end; procedure TListBinder.TTextEditor.EditingDone; begin inherited EditingDone; if fSupport <> nil then fSupport.EditingDone; end; { TListBinder.TGridEditorSupport } procedure TListBinder.TGridEditorSupport.KeyDown(var Key: Word; Shift: TShiftState); procedure doEditorKeyDown; begin if FGrid<>nil then FGrid.EditorkeyDown(Self, key, shift); end; procedure doGridKeyDown; begin if FGrid<>nil then FGrid.H_KeyDown(Key, shift); end; function GetFastEntry: boolean; begin if FGrid<>nil then Result := FGrid.H_FastEditing else Result := False; end; procedure CheckEditingKey; begin if (FGrid=nil) or FGrid.H_EditorIsReadOnly then Key := 0; end; var IntSel: boolean; begin case Key of VK_DELETE: CheckEditingKey; VK_BACK: CheckEditingKey; VK_UP: doGridKeyDown; VK_DOWN: begin EditingDone; doGridKeyDown; end; VK_LEFT, VK_RIGHT:; //if GetFastEntry then begin { IntSel:= ((Key=VK_LEFT) and not AtStart) or ((Key=VK_RIGHT) and not AtEnd); if not IntSel then begin} VK_END, VK_HOME: ; else doEditorKeyDown; end; end; procedure TListBinder.TGridEditorSupport.EditingDone; begin if fGrid <> nil then fGrid.EditingDone; end; function TListBinder.TGridEditorSupport.GetRect: TRect; begin if (FGrid <> nil) and (fCol >= 0) and (fRow >= 0) then Result := FGrid.CellRect(fCol, fRow) else begin Result := Bounds(fEditor.Left, fEditor.Top, fEditor.Width, fEditor.Height); end; //InflateRect(Result, -2, -2); Result.Top := Result.Top; Result.Left := Result.Left; Result.Bottom := Result.Bottom - 2; Result.Right := Result.Right - 2; end; procedure TListBinder.TGridEditorSupport.SetGrid(var Msg: TGridMessage); begin fGrid := Msg.Grid; Msg.Options := EO_AUTOSIZE or EO_SELECTALL {or EO_HOOKKEYPRESS or EO_HOOKKEYUP}; end; procedure TListBinder.TGridEditorSupport.SetPos(var Msg: TGridMessage); begin fCol := Msg.Col; fRow := Msg.Row; end; procedure TListBinder.TGridEditorSupport.GetGrid(var Msg: TGridMessage); begin Msg.Grid := FGrid; Msg.Options:= EO_IMPLEMENTED; end; function TListBinder.TGridEditorSupport.GetEditorSupportGridEvent: TCustomGrid; begin Result := fGrid; end; constructor TListBinder.TGridEditorSupport.Create(AEditor: TWinControl); begin fEditor := AEditor; fSupportBinder := TSupportBinder.Create; fSupportBinder.OnEditorSupportGrid := @GetEditorSupportGridEvent; fSupportBinder.Bind(fEditor); end; destructor TListBinder.TGridEditorSupport.Destroy; begin fSupportBinder.Unbind; FreeAndNil(fSupportBinder); inherited Destroy; end; { TListBinder.TOfferEditor } procedure TListBinder.TOfferEditor.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key,Shift); if not DroppedDown then if fSupport <> nil then fSupport.KeyDown(Key, Shift); end; procedure TListBinder.TOfferEditor.DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); var m: TRect; begin if fSupport <> nil then begin m := fSupport.GetRect; inherited DoSetBounds(m.Left, m.Top, m.Right - m.Left + 1, m.Bottom - m.Top + 1); end else inherited; end; procedure TListBinder.TOfferEditor.msg_SetGrid(var Msg: TGridMessage); begin if fSupport <> nil then fSupport.SetGrid(Msg); end; procedure TListBinder.TOfferEditor.msg_SetPos(var Msg: TGridMessage); begin if fSupport <> nil then fSupport.SetPos(Msg); end; procedure TListBinder.TOfferEditor.msg_GetGrid(var Msg: TGridMessage); begin if fSupport <> nil then fSupport.GetGrid(Msg); end; procedure TListBinder.TOfferEditor.msg_SetValue(var Msg: TGridMessage); var mSkipEnd: Boolean; begin mSkipEnd := Text = ''; Text := Msg.Value; if mSkipEnd then SelStart := Length(Text) + 1; end; constructor TListBinder.TOfferEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); fSupport := TGridEditorSupport.Create(Self); AutoSize := false; BorderStyle := bsNone; end; destructor TListBinder.TOfferEditor.Destroy; begin FreeAndNil(fSupport); inherited Destroy; end; procedure TListBinder.TOfferEditor.EditingDone; begin inherited EditingDone; if fSupport <> nil then fSupport.EditingDone; end; { TOfferRefBinder } function TOfferRefBinder.GetAsRef: IPersistRef; begin Result := DataItem.AsInterface as IPersistRef; end; function TOfferRefBinder.GetItemForCombo(AData: IRBData): string; begin if not SameText(AData[0].Name, 'id') or (AData.Count = 1) then Result := AData[0].AsString else Result := AData[1].AsString; end; procedure TOfferRefBinder.FillOffer; begin fOffer := (AsRef.Store as IPersistQuery).SelectClass(AsRef.ClassName); Control.Items.Clear; FillControlItems; end; procedure TOfferRefBinder.OfferToData; var mOfferIndex: NativeInt; i: integer; mData: IRBData; mText: string; begin if Control.ItemIndex <> -1 then begin mOfferIndex := NativeInt(Control.Items.Objects[Control.ItemIndex]); AsRef.SID := fOffer[mOfferIndex].SID; end else begin mText := Control.Text; for i := 0 to fOffer.Count - 1 do begin mData := fOffer[i].Data; if GetItemForCombo(mData) = mText then begin AsRef.SID := fOffer[i].SID; end; end; end; end; procedure TOfferRefBinder.DataToOffer; var i: integer; begin Control.ItemIndex := -1; for i := 0 to fOffer.Count - 1 do begin if AsRef.SID = fOffer[i].SID then begin Control.ItemIndex := i; Break; end; end; end; procedure TOfferRefBinder.FillControlItems; var i: NativeInt; mData: IRBData; begin for i := 0 to fOffer.Count - 1 do begin mData := fOffer[i].Data; Control.Items.AddObject(GetItemForCombo(mData), TObject(i)) end; end; { TCustomComboBoxHelper } function TCustomComboBoxHelper.GetOnChange: TNotifyEvent; begin Result := inherited OnChange; end; procedure TCustomComboBoxHelper.SetOnChange(AValue: TNotifyEvent); begin inherited OnChange := AValue; end; { TOfferBinder } function TOfferBinder.GetControl: TCustomComboBox; begin Result := inherited Control as TCustomComboBox; end; procedure TOfferBinder.OnChangeHandler(Sender: TObject); begin OfferToData; NotifyChangeEvents; end; procedure TOfferBinder.BindControl; begin inherited; FillOffer; Control.OnChange := @OnChangeHandler; Control.AutoComplete := True; end; procedure TOfferBinder.UnbindControl; begin Control.OnChange := nil; inherited UnbindControl; end; procedure TOfferBinder.DoControlWndProc(var TheMessage: TLMessage); var mMsg: TLMKey; mLMCmd: TLMCommand absolute TheMessage; begin case TheMessage.Msg of CN_Command: case mLMCmd.NotifyCode of CBN_CLOSEUP: begin // when binded around combo in grid, by this is Grid.FRowAutoInserted // reset to false ... otherwise adding of new row is prevented // (do not now why I did it, but edit combo in grid has second binder, // which prevent LM_KEYDOWN message to go further) mMsg.Msg := CN_KEYDOWN; mMsg.CharCode := VK_RETURN; mMsg.KeyData := 0; Control.Dispatch(mMsg); end; end; end; inherited; case TheMessage.Msg of LM_KEYDOWN, CN_KEYDOWN: fKeyDownText := Control.Text; LM_KEYUP, CN_KEYUP: if fKeyDownText <> Control.Text then begin // key can cause autcomplete and via that change of ItemIndex // and this is not reported via OnChange event OnChangeHandler(Control); end; end; end; procedure TOfferBinder.DataToControl; begin DataToOffer; end; procedure TOfferBinder.ControlToData; begin OfferToData; end; function TGridHelper.GetH_FastEditing: boolean; begin Result := FastEditing; end; procedure TGridHelper.SetH_FastEditing(AValue: boolean); begin FastEditing := AValue; end; procedure TGridHelper.H_EditorTextChanged(const aCol, aRow: Integer; const aText: string); begin EditorTextChanged(aCol, aRow, aText); end; function TGridHelper.H_EditorIsReadOnly: boolean; begin Result := EditorIsReadOnly; end; procedure TGridHelper.H_SetEditText(ACol, ARow: Longint; const Value: string); begin SetEditText(ACol, ARow, Value); end; procedure TGridHelper.H_KeyDown(var Key: Word; Shift: TShiftState); begin KeyDown(Key, Shift); end; procedure TGridHelper.H_DoOPDeleteColRow(IsColumn: Boolean; index: Integer); begin DoOPDeleteColRow(IsColumn, index); end; function TGridHelper.H_GetEditText(ACol, ARow: Longint): string; begin Result := GetEditText(ACol, ARow); end; procedure TGridHelper.H_SetOptions(const AValue: TGridOptions); begin Options := AValue; end; { TListBinder } function TListBinder.GetControl: TCustomStringGrid; begin Result := inherited Control as TCustomStringGrid; end; function TListBinder.GetAsMany: IPersistMany; var m: boolean; mm: string; begin mm := self.ClassName; m := DataItem.IsObject; if m then Result := DataItem.AsObject as IPersistMany else if DataItem.IsInterface then Result := DataItem.AsInterface as IPersistMany else raise Exception.Create('not object nor interface property for TLIST, unable retrieve IPersistMany'); if Result = nil then raise Exception.Create(DataItem.Name + ' is not assigned'); end; procedure TListBinder.FillRowFromObject(ARow: integer; AObjectData: IRBData); var i: integer; begin if AObjectData = nil then EmptyRow(ARow) else begin if Control.ColCount <> AObjectData.Count then begin Control.ColCount := AObjectData.Count; end; for i := 0 to AObjectData.Count - 1 do begin if AObjectData[i].IsObject then begin Control.Cells[i, ARow] := '[Object]'; end else //if AObjectData[i].IsList then //begin // Control.Cells[i, ARow] := '[List]'; //end //else begin Control.Cells[i, ARow] := AObjectData[i].AsString; end; end; end; end; procedure TListBinder.EmptyRow(ARow: integer); var i: integer; begin for i := 0 to Control.ColCount - 1 do Control.Cells[i, ARow] := ''; end; function TListBinder.CreateEditor(const ADataItem: IRBDataItem): TWinControl; begin Result := nil; if Supports(AsMany, IPersistManyRefs) then begin Result := OfferEditor; end else begin if ADataItem.EnumNameCount > 0 then begin Result := OfferEditor; end else begin Result := TextEditor; end; end; end; function TListBinder.CreateBinder(const ADataItem: IRBDataItem): TEditBinder; begin Result := nil; if Supports(AsMany, IPersistManyRefs) then begin Result := TOfferRefBinder.Create; end else if ADataItem.EnumNameCount > 0 then begin Result := TOfferEnumBinder.Create; end else begin Result := TTextBinder.Create; end; end; procedure TListBinder.NilEditor; begin if Control.Editor = fCellEditor then Control.Editor := nil; fCellEditor := nil; end; function TListBinder.GetOfferEditor: TOfferEditor; begin if fOfferEditor = nil then fOfferEditor := TOfferEditor.Create(Control); Result := fOfferEditor; end; function TListBinder.GetTextEditor: TTextEditor; begin if fTextEditor = nil then fTextEditor := TTextEditor.Create(Control); Result := fTextEditor; end; procedure TListBinder.OnColRowDeletedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); var mFrom, mCount: integer; begin if AsMany.Count = 0 then Exit; mFrom := sIndex - 1; mCount := tIndex - sIndex + 1; while (mCount > 0) and (mFrom <= AsMany.Count - 1) do begin AsMany.Delete(mFrom); Dec(mCount); end; end; procedure TListBinder.OnColRowInsertedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); begin AsMany.Count := AsMany.Count + 1; PostMessage(Control.Handle, TVLM_GRIDSETPOS, -1, Control.FixedCols); end; procedure TListBinder.OnEditingDoneHandler(Sender: TObject); begin if fCellBinder = nil then Exit; if fCellBinder.DataItem = nil then Exit; if fCellBinder.DataItem.IsInterface and Supports(fCellBinder.DataItem.AsInterface, IPersistRef) then begin Control.Cells[Control.Col, Control.Row] := (fCellBinder.DataItem.AsInterface as IPersistRef).Data[0].AsString; end else if fCellBinder.DataItem.IsObject then DataToControl else Control.Cells[Control.Col, Control.Row] := fCellBinder.DataItem.AsString; end; procedure TListBinder.OnSelectEditorHandler(Sender: TObject; aCol, aRow: Integer; var Editor: TWinControl); var mDataItem: IRBDataItem; begin FreeAndNil(fCellBinder); if aRow >= Control.FixedRows then begin mDataItem := TPersistManyDataItem.Create(AsMany, aRow - 1); if mDataItem.IsObject then begin fObjectData := AsMany.AsPersistData[aRow - 1]; mDataItem := fObjectData[aCol]; end; NilEditor; fCellEditor := CreateEditor(mDataItem); fCellBinder := CreateBinder(mDataItem); fCellBinder.Bind(fCellEditor, mDataItem); end else begin fCellBinder.Unbind; NilEditor; end; Editor := fCellEditor; fCol := aCol; fRow := aRow; end; procedure TListBinder.OnKeyDownHandler(Sender: TObject; var Key: Word; Shift: TShiftState); var mNextControl: TWinControl; mParentF: TCustomForm; begin if (Key = VK_DELETE) and (Shift = [ssCtrl]) then begin if Control.Row >= Control.FixedRows then Control.H_DoOPDeleteColRow(False, Control.Row); Key := 0; end else if (Key = VK_TAB) and (Shift = [ssCtrl]) then begin mParentF := GetParentForm(Control); if mParentF <> nil then begin mNextControl := mParentF.H_FindNextControl(Control, True, True, False); if mNextControl <> nil then begin mNextControl.SetFocus; Key := 0; end end; end; inherited; end; procedure TListBinder.OnSelectionHandler(Sender: TObject; aCol, aRow: Integer); begin if (fCol <> aCol) or (fRow <> aRow) then FreeAndNil(fCellBinder); end; procedure TListBinder.BindControl; var mData: IRBData; i: integer; begin Control.RowCount := 1 + AsMany.Count; Control.FixedRows := 1; Control.FixedCols := 0; if AsMany.IsObject then begin mData := AsMany.AsPersistDataClass; Control.ColCount := mData.Count; for i := 0 to mData.Count - 1 do begin Control.Cells[i,0] := mData[i].Name; end; end else begin Control.ColCount := 1; Control.Cells[0,0] := DataItem.Name; end; // on the end, otherway are called when assign collcount - rowcount Control.AutoFillColumns := True; Control.Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goEditing, goAutoAddRows, goTabs, {goAlwaysShowEditor,} goSmoothScroll]; Control.OnColRowInserted := @OnColRowInsertedHandler; Control.OnColRowDeleted := @OnColRowDeletedHandler; Control.OnSelectEditor := @OnSelectEditorHandler; Control.OnKeyDown := @OnKeyDownHandler; Control.H_OnEditingDone := @OnEditingDoneHandler; end; procedure TListBinder.UnbindControl; begin Control.OnColRowInserted := nil; Control.OnColRowDeleted := nil; Control.OnSelectEditor := nil; Control.OnKeyDown := nil; Control.H_OnEditingDone := nil; NilEditor; FreeAndNil(fCellBinder); FreeAndNil(fOfferEditor); FreeAndNil(fTextEditor); inherited UnbindControl; end; procedure TListBinder.DoControlWndProc(var TheMessage: TLMessage); begin case TheMessage.Msg of TVLM_GRIDSETPOS: begin if TheMessage.WParam <> -1 then Control.Row := TheMessage.WParam; if TheMessage.LParam <> -1 then Control.Col := TheMessage.LParam; end; LM_KEYDOWN: begin inherited; if (TLMKey(TheMessage).CharCode = VK_V) and ([ssModifier] = MsgKeyDataToShiftState(TLMKey(TheMessage).KeyData)) then begin // in case of paste editor could be hidden, so clipboard // is inserted into grid cell DispatchTextToEditor; SetRowAutoInsertToFalse; end; end; else inherited; end; end; procedure TListBinder.DispatchTextToEditor; var msg: TGridMessage; begin if fCellEditor = nil then Exit; msg.LclMsg.msg := GM_SETVALUE; msg.Grid := Control; msg.Col := Control.Col; msg.Row := Control.Row; msg.Value := Control.H_GetEditText(Fcol, FRow); fCellEditor.Dispatch(msg); end; procedure TListBinder.SetRowAutoInsertToFalse; var mOptions: TGridOptions; begin // will cause set of fRowAutoInsert to false (because after paste from clipoboard // is not set to false and auto row insert do not work otherwise) if goAutoAddRowsSkipContentCheck in Control.Options then begin mOptions := Control.Options - [goAutoAddRowsSkipContentCheck]; Control.H_SetOptions(mOptions); mOptions := Control.Options + [goAutoAddRowsSkipContentCheck]; Control.H_SetOptions(mOptions); end else begin mOptions := Control.Options + [goAutoAddRowsSkipContentCheck]; Control.H_SetOptions(mOptions); mOptions := Control.Options - [goAutoAddRowsSkipContentCheck]; Control.H_SetOptions(mOptions); end; end; procedure TListBinder.DataToControl; var i: integer; mData: IRBData; begin // possible change of rowcount UnbindControl; BindControl; for i := 0 to AsMany.Count - 1 do begin if Supports(AsMany, IPersistManyRefs) then begin mData := (AsMany.AsInterface[i] as IPersistRef).Data; if mData <> nil then Control.Cells[0, i + 1] := mData[0].AsString else Control.Cells[0, i + 1] := ''; end else if AsMany.IsObject then begin FillRowFromObject(i + 1, AsMany.AsPersistData[i]); end else begin Control.Cells[0, i + 1] := AsMany.AsString[i]; end; end; end; procedure TListBinder.ControlToData; begin end; { TTextBinder } function TTextBinder.GetControl: TCustomEdit; begin Result := inherited Control as TCustomEdit; end; procedure TTextBinder.OnChangeHandler(Sender: TObject); begin DataItem.AsString := Control.Text; NotifyChangeEvents; end; procedure TTextBinder.BindControl; begin inherited; Control.OnChange := @OnChangeHandler; end; procedure TTextBinder.UnbindControl; begin Control.OnChange := nil; inherited UnbindControl; end; procedure TTextBinder.DataToControl; begin Control.Text := DataItem.AsString end; procedure TTextBinder.ControlToData; begin DataItem.AsString := Control.Text; end; { TEditBinder } function TEditBinder.GetControl: TWinControl; begin Result := inherited Control as TWinControl; end; procedure TEditBinder.BindControl; begin inherited; end; procedure TEditBinder.UnbindControl; begin ControlToData; inherited; end; procedure TEditBinder.NotifyChangeEvents; var mEvent: TBinderChangeEvent; begin for mEvent in fChangeEvents do mEvent(DataItem, Control); end; constructor TEditBinder.Create; begin fChangeEvents := TBinderChangeEvents.Create; end; destructor TEditBinder.Destroy; begin FreeAndNil(fChangeEvents); inherited Destroy; end; procedure TEditBinder.Bind(const AControl: TWinControl; const ADataItem: IRBDataItem); begin fDataItem := ADataItem; inherited Bind(AControl); DataToControl; end; procedure TEditBinder.RegisterChangeEvent(AEvent: TBinderChangeEvent); var mIndex: integer; begin mIndex := fChangeEvents.IndexOf(AEvent); if mIndex = -1 then fChangeEvents.Add(AEvent); end; procedure TEditBinder.UnregisterChangeEvent(AEvent: TBinderChangeEvent); var mIndex: integer; begin mIndex := fChangeEvents.IndexOf(AEvent); if mIndex <> -1 then fChangeEvents.Delete(mIndex); end; end.
unit Draw; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, GraphMath, Dialogs, Menus, ExtCtrls, LCLIntf, LCLType, Spin, ActnList, Buttons, StdCtrls, Help, Figures, tools, Scale; type { TDForm } TDForm = class(TForm) RedoItem: TMenuItem; EditItem: TMenuItem; ClearItem: TMenuItem; DeleteSelectedItem: TMenuItem; CopyItem: TMenuItem; UpItem: TMenuItem; DownItem: TMenuItem; Saveitem: TMenuItem; OpenItem: TMenuItem; PasteItem: TMenuItem; UndoItem: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; SelectUpItem: TMenuItem; SelectDownItem: TMenuItem; SelectedAllItem: TMenuItem; ScrollBarHorizontal: TScrollBar; ShowItem: TMenuItem; ZoomSpinEdit: TSpinEdit; ScrollBarVertical: TScrollBar; ToolPanel: TPanel; MainMenu: TMainMenu; FileItem: TMenuItem; CloseItem: TMenuItem; HelpItem: TMenuItem; PaintBox: TPaintBox; Panel: TPanel; procedure ClearAllClick(Sender: TObject); procedure DeleteSelectedItemClick(Sender: TObject); procedure OpenItemClick(Sender: TObject); procedure SaveItemClick(Sender: TObject); procedure SelectUpItemClick(Sender: TObject); procedure SelectDownItemClick(Sender: TObject); procedure SelectedAllItemClick(Sender: TObject); procedure ShowAllButtonClick(Sender: TObject); procedure HelpItemClick(Sender: TObject); procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure CloseItemClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBoxPaint(Sender: TObject); procedure BackActionExecute(Sender: TObject); procedure ToolButtonClick(Sender: TObject); procedure ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: integer); procedure ZoomSpinEditChange(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure OpenButtonClick(Sender: TObject); procedure RedoClick(Sender: TObject); procedure UndoClick(Sender: TObject); procedure PasteSelectedClick(Sender: TObject); procedure CopySelectedClick(Sender: TObject); private { private declarations } public { public declarations } end; TRecPolyLine = record Vert: array of TPoint; Color: TColor; Width: integer; end; procedure SavePicture(PName: string); procedure OpenPicture(PName: string); const Sign: string = 'OwnPaint'; var DForm: TDForm; IsDrawing, BufferFlag: boolean; CurrentTool, TPawTool: TFigureTool; Param: array of TParam; CanvasItems, History: array of TFigure; CurrentPicture: string; implementation {$R *.lfm} { TDForm } procedure TDForm.FormCreate(Sender: TObject); var b: TSpeedButton; i: integer; CurrentIcon: TPicture; begin zoom:=1; IsDrawing := False; DForm.DoubleBuffered := True; DForm.Caption := ApplicationName; CurrentTool := TPolyLineTool.Create(); AWidth := 1; ARadiusX := 30; ARadiusY := 30; for i := Low(Tool) to High(Tool) do begin b := TSpeedButton.Create(ToolPanel); b.Parent := ToolPanel; b.Name := Tool[i].ClassName; b.Width := 32; b.Height := 32; b.Top := (i div 3) * 32; b.Left := (i mod 3) * 32; b.GroupIndex := 1; b.Tag := i; b.OnClick := @ToolButtonClick; CurrentIcon := TPicture.Create; CurrentIcon.LoadFromFile('./icons/' + Tool[i].ClassName + '.png'); b.Glyph := CurrentIcon.Bitmap; CurrentIcon.Free; end; end; procedure TDForm.ToolButtonClick(Sender: TObject); var ParamsPanel: TPanel; i: integer; begin CurrentTool := Tool[(Sender as TSpeedButton).tag]; ParamsPanel := TPanel.Create(DForm); ParamsPanel.Parent := Panel; ParamsPanel.Width := 110; ParamsPanel.Height := 300; ParamsPanel.Left := 8; ParamsPanel.Top := 248; CurrentTool.ParamsCreate(ParamsPanel); if not ((Sender as TSpeedbutton).tag = 8) then for i := 0 to High(CurrentFigures) do CurrentFigures[i].Selected := False; Invalidate; end; procedure TDForm.CloseItemClick(Sender: TObject); begin DForm.Close; end; procedure TDForm.HelpItemClick(Sender: TObject); begin HelpForm.ShowModal; end; procedure TDForm.ShowAllButtonClick(Sender: TObject); begin RectZoom(PaintBox.Height, PaintBox.Width, MinPoint, MaxPoint); Invalidate; ScrollBarVertical.Max := trunc(MaxPoint.Y); ScrollBarVertical.Min := trunc(MinPoint.Y); ScrollBarHorizontal.Max := trunc(MaxPoint.X); ScrollBarHorizontal.Min := trunc(MinPoint.X); Offset.X := 0; Offset.Y := 0; end; procedure TDForm.ClearAllClick(Sender: TObject); begin SetLength(CurrentFigures, 0); PaintBox.Invalidate; end; procedure TDForm.DeleteSelectedItemClick(Sender: TObject); var i, j: integer; begin j := 0; for i := 0 to high(CurrentFigures) do begin if (CurrentFigures[i].Selected) then FreeAndNil(CurrentFigures[i]) else begin CurrentFigures[j] := CurrentFigures[i]; j := j + 1; end; end; setLength(CurrentFigures, j); Invalidate; end; procedure TDForm.OpenItemClick(Sender: TObject); begin end; procedure TDForm.SaveItemClick(Sender: TObject); begin end; procedure TDForm.SelectDownItemClick(Sender: TObject); var i, j, k: Integer; Figure: TFigure; begin k := 0; for i := high(CurrentFigures) downto 0 do begin if (CurrentFigures[i].Selected) then begin for j := i downto k + 1 do begin Figure := CurrentFigures[j]; CurrentFigures[j] := CurrentFigures[j-1]; CurrentFigures[j-1] := Figure; k := j end; end; end; Invalidate; end; procedure TDForm.SelectUpItemClick(Sender: TObject); var i, j, k: integer; Figure: TFigure; begin k := high(CurrentFigures); for i := 0 to high(CurrentFigures) do begin if (CurrentFigures[i].Selected) then begin for j := i to k - 1 do begin Figure := CurrentFigures[j]; CurrentFigures[j] := CurrentFigures[j + 1]; CurrentFigures[j + 1] := Figure; k := j; end; end; end; Invalidate; end; procedure TDForm.SelectedAllItemClick(Sender: TObject); var i: integer; begin for i := 0 to High(CurrentFigures) do CurrentFigures[i].Selected := True; Invalidate; end; procedure TDForm.PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin if Button = mbLeft then begin IsDrawing := True; CurrentTool.MouseDown(X, Y); MaxMin(ScreenToWorld(Point(X, Y))); end; end; procedure TDForm.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); begin if IsDrawing then begin CurrentTool.MouseMove(X, Y); MaxMin(ScreenToWorld(Point(X, Y))); PaintBox.Invalidate; end; end; procedure TDForm.PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); var ParamsPanel: TPanel; i: integer; begin if Button = mbLeft then begin IsDrawing := False; CurrentTool.MouseUp(X, Y, PaintBox.Canvas); if SelectedCreateParamFlag then begin ParamsPanel := TPanel.Create(DForm); ParamsPanel.Parent := Panel; ParamsPanel.Width := 110; ParamsPanel.Height := 300; ParamsPanel.Left := 8; ParamsPanel.Top := 248; //SelectedFigure.ParamsCreate(ParamsPanel); end; SelectedCreateParamFlag := False; PaintBox.Invalidate; end; end; procedure TDForm.PaintBoxPaint(Sender: TObject); var i: integer; begin for i := 0 to high(CurrentFigures) do begin CurrentFigures[i].Draw(PaintBox.Canvas); if CurrentFigures[i].Selected then CurrentFigures[i].DrawSelection(CurrentFigures[i], PaintBox.Canvas, (CurrentFigures[I] as TLineFigure).Width); end; ScrollBarVertical.Max := trunc(MaxPoint.Y); ScrollBarVertical.Min := trunc(MinPoint.Y); ScrollBarHorizontal.Max := trunc(MaxPoint.X); ScrollBarHorizontal.Min := trunc(MinPoint.X); ZoomSpinEdit.Value := Zoom; AHeightPB := PaintBox.Height; AWidthPB := PaintBox.Width; end; procedure TDForm.BackActionExecute(Sender: TObject); begin end; procedure TDForm.ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: integer); begin Offset := Point(ScrollBarHorizontal.Position, ScrollBarVertical.Position); PaintBox.Invalidate; end; procedure TDForm.ZoomSpinEditChange(Sender: TObject); begin ZoomSpinEdit.Value := Zoom; Invalidate; end; procedure TDForm.OpenButtonClick(Sender: TObject); begin if OpenDialog.Execute then begin OpenPicture(OpenDialog.Filename); end; Invalidate; end; procedure OpenPicture(PName: string); var Picture: text; i, j: integer; s, l: String; a: StringArray; begin assign(Picture, PName); reset(Picture); readln(Picture, s); if s = Sign then begin CurrentPicture := PName; readln(Picture, l); SetLength(CurrentFigures, StrToInt(l) + 1); for i := 0 to StrToInt(l) do begin readln(Picture, s); readln(Picture); if (s = 'TPolyLine') then begin setlength(a, 4); for j:=0 to 3 do readln(Picture, a[j]); if (s = 'TLine') then begin SetLength(a, 7); for j:=4 to 6 do readln(Picture, a[j]); TLine.Download(i, a) ; end; if (s = 'TRectangle') then begin SetLength(a, 9); for j:=4 to 8 do readln(Picture, a[j]); TRectangle.Download(i,a); end; if (s = 'TEllipce') then begin SetLength(a, 9); for j:=4 to 8 do readln(Picture, a[j]); TEllipce.Download(i, a); end; if (s = 'TRoundedRectangle') then begin SetLength(a, 11); for j:=4 to 10 do readln(Picture, a[j]); TRoundedRectangle.Download(i, a); end; end else begin readln(Picture); read(Picture, s); SetLength(a, StrToInt(s) + 2); a[0] := S; for j := 1 to high(a) do readln(Picture, a[j]); TPolyline.Download(i, a); readln(Picture); end; ReadLn(Picture); end; end; end; procedure SavePicture(PName: string); var Picture: text; a: array of string; i, j: integer; begin assign(Picture, PName); rewrite(Picture); writeln(Picture, Sign); writeln(Picture, high(CurrentFigures)); for i:=0 to High(CurrentFigures) do begin writeln(Picture, CurrentFigures[i].ClassName); writeln(Picture, '{'); a := CurrentFigures[i].Save (CurrentFigures[i]); for j:=0 to high(a) do writeln(Picture, a[j]); writeln(Picture, '}'); end; CloseFile(Picture); end; procedure TDForm.SaveButtonClick(Sender: TObject); begin if SaveDialog.Execute then begin CurrentPicture := SaveDialog.FileName; end; SavePicture(CurrentPicture); end; procedure TDForm.RedoClick(Sender: TObject); begin if UndoFlag and not (Now = Length(ArrayOfActions)) then begin Now := Now + 1; CurrentFigures := RefreshArrays(ArrayOfActions[Now]); end; PaintBox.Invalidate; end; procedure TDForm.UndoClick(Sender: TObject); begin if Length(ArrayOfActions) <> 0 then begin Now := Now - 1; RefreshFigures(Now); UndoFlag := True; end; PaintBox.Invalidate; end; procedure TDForm.PasteSelectedClick(Sender: TObject); var i, q: Integer; a: StringArray; begin if (Length(Buffer) <> 0) and BufferFlag then begin SetLength(CurrentFigures, Length(CurrentFigures) + Length(Buffer)); for i := 0 to high(Buffer) do begin case Buffer[i].ClassName of 'TPolyLine': CurrentFigures[Length(CurrentFigures) + i] := TPolyLine.Create; 'TLine' : CurrentFigures[Length(CurrentFigures) + i] := TLine.Create; 'TEllipce' : begin CurrentFigures[Length(CurrentFigures) + i] := TEllipce.Create; (CurrentFigures[Length(CurrentFigures) + i] as TObjectFigure).BrushColor := (Buffer[i] as TObjectFigure).BrushColor; (CurrentFigures[Length(CurrentFigures) + i] as TObjectFigure).BrushStyle := (Buffer[i] as TObjectFigure).BrushStyle; end; 'TRectangle': begin CurrentFigures[Length(CurrentFigures) + i] := TRectangle.Create; (CurrentFigures[Length(CurrentFigures) + i] as TObjectFigure).BrushColor := (Buffer[i] as TObjectFigure).BrushColor; (CurrentFigures[Length(CurrentFigures) + i] as TObjectFigure).BrushStyle := (Buffer[i] as TObjectFigure).BrushStyle; end; 'TRoundedRectangle': begin CurrentFigures[Length(CurrentFigures) + i] := TRoundedRectangle.Create; (CurrentFigures[Length(CurrentFigures) + i] as TObjectFigure).BrushColor := (Buffer[i] as TObjectFigure).BrushColor; (CurrentFigures[Length(CurrentFigures) + i] as TObjectFigure).BrushStyle := (Buffer[i] as TObjectFigure).BrushStyle; (CurrentFigures[Length(CurrentFigures) + i] as TRoundedRectangle).RoundingRadiusX := (Buffer[i] as TRoundedRectangle).RoundingRadiusX; (CurrentFigures[Length(CurrentFigures) + i] as TRoundedRectangle).RoundingRadiusY := (Buffer[i] as TRoundedRectangle).RoundingRadiusY; end; end; for q := 0 to Length(Buffer[i].Points) do begin SetLength(CurrentFigures[Length(CurrentFigures) + i].Points, Length(CurrentFigures[Length(CurrentFigures) + i].Points) + 1); CurrentFigures[Length(CurrentFigures) + i].Points[q] := Buffer[i].Points[q]; end; (CurrentFigures[Length(CurrentFigures) + i] as TLineFigure).PenColor := (Buffer[i] as TLineFigure).PenColor; (CurrentFigures[Length(CurrentFigures) + i] as TLineFigure).PenStyle := (Buffer[i] as TLineFigure).PenStyle; (CurrentFigures[Length(CurrentFigures) + i] as TLineFigure).Width := (Buffer[i] as TLineFigure).Width; end; end; Invalidate; end; procedure TDForm.CopySelectedClick(Sender: TObject); var i, q: Integer; a: StringArray; begin SetLength(Buffer, 0); for i := 0 to High(CurrentFigures) do begin BufferFlag := True; if CurrentFigures[i].Selected then begin SetLength(Buffer, Length(Buffer) + 1); case CurrentFigures[i].ClassName of 'TPolyLine': Buffer[High(Buffer)] := TPolyLine.Create; 'TLine' : Buffer[High(Buffer)] := TLine.Create; 'TEllipce' : begin Buffer[High(Buffer)] := TEllipce.Create; (Buffer[High(Buffer)] as TObjectFigure).BrushColor := (CurrentFigures[i] as TObjectFigure).BrushColor; (Buffer[High(Buffer)] as TObjectFigure).BrushStyle := (CurrentFigures[i] as TObjectFigure).BrushStyle; end; 'TRectangle': begin Buffer[High(Buffer)] := TRectangle.Create; (Buffer[High(Buffer)] as TObjectFigure).BrushColor := (CurrentFigures[i] as TObjectFigure).BrushColor; (Buffer[High(Buffer)] as TObjectFigure).BrushStyle := (CurrentFigures[i] as TObjectFigure).BrushStyle; end; 'TRoundedRectangle': begin Buffer[High(Buffer)] := TRoundedRectangle.Create; (Buffer[High(Buffer)] as TObjectFigure).BrushColor := (CurrentFigures[i] as TObjectFigure).BrushColor; (Buffer[High(Buffer)] as TObjectFigure).BrushStyle := (CurrentFigures[i] as TObjectFigure).BrushStyle; (Buffer[High(Buffer)] as TRoundedRectangle).RoundingRadiusX := (CurrentFigures[i] as TRoundedRectangle).RoundingRadiusX; (Buffer[High(Buffer)] as TRoundedRectangle).RoundingRadiusY := (CurrentFigures[i] as TRoundedRectangle).RoundingRadiusY; end; end; for q := 0 to Length(CurrentFigures[i].Points) do begin SetLength(Buffer[High(Buffer)].Points, Length(Buffer[High(Buffer)].Points) + 1); Buffer[High(Buffer)].Points[q] := CurrentFigures[i].Points[q]; end; (Buffer[High(Buffer)] as TLineFigure).PenColor := (CurrentFigures[i] as TLineFigure).PenColor; (Buffer[High(Buffer)] as TLineFigure).PenStyle := (CurrentFigures[i] as TLineFigure).PenStyle; (Buffer[High(Buffer)] as TLineFigure).Width := (CurrentFigures[i] as TLineFigure).Width; end; end; end; end.
// 350. 两个数组的交集 II // // 给定两个数组,编写一个函数来计算它们的交集。 // // 示例 1: // // 输入: nums1 = [1,2,2,1], nums2 = [2,2] // 输出: [2,2] // 示例 2: // // 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] // 输出: [4,9] // 说明: // // 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。 // 我们可以不考虑输出结果的顺序。 // 进阶: // // 如果给定的数组已经排好序呢?你将如何优化你的算法? // 如果 nums1 的大小比 nums2 小很多,哪种方法更优? // 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到 // 内存中,你该怎么办? // // class Solution { // public int[] intersect(int[] nums1, int[] nums2) { // // } // } unit DSA.LeetCode._350; interface uses System.SysUtils, DSA.Utils, DSA.Tree.BSTMap; type { Solution } TSolution = class function intersect(nums1, nums2: TArray_int): TArray_int; end; procedure Main; implementation procedure Main; var slt: TSolution; nums1, nums2, tempNums: TArray_int; i: integer; begin slt := TSolution.Create; nums1 := [1, 2, 2, 1]; nums2 := [2, 2]; tempNums := slt.intersect(nums1, nums2); for i := 0 to Length(tempNums) - 1 do write(tempNums[i], #9); WriteLn; nums1 := [4, 9, 5]; nums2 := [9, 4, 9, 8, 4]; tempNums := slt.intersect(nums1, nums2); for i := 0 to Length(tempNums) - 1 do write(tempNums[i], #9); WriteLn; end; type TBSTMap_int_int = TBSTMap<integer, integer>; { Solution } function TSolution.intersect(nums1, nums2: TArray_int): TArray_int; var map: TBSTMap_int_int; i, n: integer; arr: TArrayList_int; begin map := TBSTMap_int_int.Create; for i := 0 to Length(nums1) - 1 do begin if not map.Contains(nums1[i]) then map.Add(nums1[i], 1) else map.Set_(nums1[i], map.Get(nums1[i]).PValue^ + 1); end; arr := TArrayList_int.Create; for i := 0 to Length(nums2) - 1 do begin if map.Contains(nums2[i]) then begin n := map.Get(nums2[i]).PValue^; if n > 0 then begin arr.AddLast(nums2[i]); Dec(n); map.Set_(nums2[i], n); end; if n <= 0 then map.Remove(nums2[i]); end; end; Result := arr.ToArray; end; end.
unit GLDUserCameraPickerForm; interface uses Windows, Classes, Controls, Forms, Dialogs, StdCtrls, Buttons, GL, GLDTypes, GLDObjects, GLDCamera; type TGLDUserCameraPickerForm = class(TForm) BB_Ok: TBitBtn; BB_Cancel: TBitBtn; LB_Cameras: TListBox; procedure FormCreate(Sender: TObject); procedure LB_CamerasMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BitBtnClick(Sender: TObject); private FOldCamera: TGLDUserCamera; FCameraOwner: TGLDCameraSystem; FCameras: TGLDUserCameraList; FCloseMode: GLubyte; FModified: TGLDMethod; procedure Modified; procedure SetCameraOwner(Value: TGLDCameraSystem); procedure SetCameras(Value: TGLDUserCameraList); public property CameraOwner: TGLDCameraSystem read FCameraOwner write SetCameraOwner; property SourceCameraList: TGLDUserCameraList read FCameras write SetCameras; property ModifiedMethod: TGLDMethod read FModified write FModified; end; function GLDGetUserCameraPickerForm: TGLDUserCameraPickerForm; procedure GLDReleaseUserCameraPickerForm; implementation {$R *.dfm} uses SysUtils, GLDConst; var vUserCamreraPickerForm: TGLDUserCameraPickerForm = nil; function GLDGetUserCameraPickerForm: TGLDUserCameraPickerForm; begin if not Assigned(vUserCamreraPickerForm) then vUserCamreraPickerForm := TGLDUserCameraPickerForm.Create(nil); Result := vUserCamreraPickerForm; end; procedure GLDReleaseUserCameraPickerForm; begin if Assigned(vUserCamreraPickerForm) then vUserCamreraPickerForm.Free; vUserCamreraPickerForm := nil; end; procedure TGLDUserCameraPickerForm.FormCreate(Sender: TObject); begin FCloseMode := GLD_CLOSEMODE_CANCEL; FCameraOwner := nil; FCameras := nil; FModified := nil; LB_Cameras.Clear; end; procedure TGLDUserCameraPickerForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if FCloseMode = GLD_CLOSEMODE_OK then ModalResult := idOk else if FCloseMode = GLD_CLOSEMODE_CANCEL then if Assigned(FCameraOwner) then begin FCameraOwner.UserCamera := FOldCamera; ModalResult := idCancel; end; end; procedure TGLDUserCameraPickerForm.Modified; begin if Assigned(FModified) then FModified; end; procedure TGLDUserCameraPickerForm.SetCameraOwner(Value: TGLDCameraSystem); begin FCameraOwner := Value; if Assigned(FCameraOwner) then FOldCamera := FCameraOwner.UserCamera else FOldCamera := nil; end; procedure TGLDUserCameraPickerForm.SetCameras(Value: TGLDUserCameraList); var i: GLuint; begin FCameras := Value; LB_Cameras.Clear; if FCameras <> nil then begin if FCameras.Count > 0 then for i := 1 to FCameras.Count do LB_Cameras.AddItem(FCameras[i].Name, FCameras[i]); end; end; procedure TGLDUserCameraPickerForm.LB_CamerasMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Index: GLint; begin Index := LB_Cameras.ItemAtPos(Point(X, Y), True); if (Index <> -1) and Assigned(FCameraOwner) and Assigned(FCameras) then begin FCameraOwner.UserCamera := FCameras[Index + 1]; Modified; end; end; procedure TGLDUserCameraPickerForm.BitBtnClick(Sender: TObject); begin FCloseMode := TBitBtn(Sender).Tag; Close; end; initialization finalization GLDReleaseUserCameraPickerForm; end.
unit fmain; (*##*) (*************************************************************************** * * * i 2 w b m p m a i n * * * * Copyright © 2002 Andrei Ivanov. All rights reserved. * * wbmp image convertor * * Conditional defines: * * * * Default path: /2wbmp/ * * * * Parameters: * * src=[alias|folder]filename * * [dither=Nearest|FloydSteinberg|Stucki|Sierra|JaJuNI|SteveArche|Burkes] * * [negative=1|0] * * [noAlign=1|0] * * * * Registry: * * HKEY_LOCAL_MACHINE\Software\ensen\i2wbmp\1.0\ * * DefDitherMode, as dither parameter, default 'nearest' * * DefWBMP default wbmp image up to 4016 bytes long binary * * (if errors occured) * * \Virtual Roots - contains aliases in addition ti IIS (PWS) * * * * * * HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\ * * Parameters\Virtual Roots * * * * E:\Inetpub\Scripts\i2wbmp.dll * * * * Revisions : Apr 15 2002 * * Last fix : Apr 15 2002 * * Lines : 188 * * History : * * Printed : --- * * * ***************************************************************************) (*##*) interface uses SysUtils, Classes, HTTPApp, Windows, Registry, GifImage, util1, secure, wmleditutil, wbmpimage, cmdcvrt; type TWebModule1 = class(TWebModule) procedure WebModule1WebActionItem1Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModuleCreate(Sender: TObject); procedure WebModuleDestroy(Sender: TObject); procedure WebModule1WebActionItem2Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); private { Private declarations } PathsList, SLAlias: TStrings; DefDitherMode: TDitherMode; procedure ValidateW3SvcColon; function Alias2FileName(const AFn: String): String; function GetQueryField(const AName: String): String; function IsRegistered: Boolean; public { Public declarations } FRegistered: Boolean; property QFld[const name: String]: String read GetQueryField; end; var WebModule1: TWebModule1; implementation {$R *.DFM} const fpSCRIPT = 0; fpPatternPath = 1; fpDefDitherMode = 2; fpUser = 3; fpCode = 4; fpDefWBMP = 5; LNVERSION = '1.0'; RGPATH = '\Software\ensen\i2wbmp\'+ LNVERSION; // RGW2SVCALIAS = '\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\Virtual Roots'; CVRTRGPATH = '\Software\ensen\cvrt2wbmp\1.0'; procedure TWebModule1.ValidateW3SvcColon; var i, L: Integer; S: String; begin for i:= 0 to SLAlias.Count - 1 do begin repeat S:= SLAlias.Names[i]; L:= Length(S); if (L < 0) or (not(S[L] in [#0..#32, ','])) then Break; S:= SLAlias[i]; Delete(S, L, 1); SLAlias[i]:= S; until False; end; // set default "current" directory if SLAlias.Values[''] = '' then SLAlias.Add('=' + PathsList[fpPatternPath]); // set default "root" directory if SLAlias.Values['/'] = '' then SLAlias.Add('/=' + PathsList[fpPatternPath]); end; const DitherModeStr: array[TDitherMode] of String[15] = ('Nearest', // Nearest color matching w/o error correction 'FloydSteinberg', // Floyd Steinberg Error Diffusion dithering 'Stucki', // Stucki Error Diffusion dithering 'Sierra', // Sierra Error Diffusion dithering 'JaJuNI', // Jarvis, Judice & Ninke Error Diffusion dithering 'SteveArche', // Stevenson & Arche Error Diffusion dithering 'Burkes' // Burkes Error Diffusion dithering ); function GetDitherModeByName(const S: String; ADefDitherMode: TDitherMode): TDitherMode; begin Result:= ADefDitherMode; if CompareText(s, 'Nearest') = 0 then Result:= dmNearest; // Nearest color matching w/o error correction if CompareText(s, 'FloydSteinberg') = 0 then Result:= dmFloydSteinberg; // Floyd Steinberg Error Diffusion dithering if CompareText(s, 'Stucki') = 0 then Result:= dmStucki; // Stucki Error Diffusion dithering if CompareText(s, 'Sierra') = 0 then Result:= dmSierra; // Sierra Error Diffusion dithering if CompareText(s, 'JaJuNI') = 0 then Result:= dmJaJuNI; // Jarvis, Judice & Ninke Error Diffusion dithering if CompareText(s, 'SteveArche') = 0 then Result:= dmSteveArche; // Stevenson & Arche Error Diffusion dithering if CompareText(s, 'Burkes') = 0 then Result:= dmBurkes; // Stevenson & Arche Error Diffusion dithering end; function GetDitherModeName(ADitherMode: TDitherMode): String; begin case ADitherMode of dmNearest: // Nearest color matching w/o error correction Result:= 'Nearest'; dmFloydSteinberg: // Floyd Steinberg Error Diffusion dithering Result:= 'FloydSteinberg'; dmStucki: // Stucki Error Diffusion dithering Result:= 'Stucki'; dmSierra: // Sierra Error Diffusion dithering Result:= 'Sierra'; dmJaJuNI: // Jarvis, Judice & Ninke Error Diffusion dithering Result:= 'JaJuNI'; dmSteveArche: // Stevenson & Arche Error Diffusion dithering Result:= 'SteveArche'; dmBurkes: // Burkes Error Diffusion dithering Result:= 'Burkes'; end; { case } end; procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var s: String; DitherMode: TDitherMode; TransformOptions: TTransformOptions; ImageSize: TPoint; strm: TStream; begin Handled:= True; Response.ContentType:= 'image/vnd.wap.wbmp'; Response.Title:= 'i2wbmp'; DitherMode:= GetDitherModeByName(QFld['dither'], DefDitherMode); TransformOptions:= [toAlign8]; if not FRegistered then TransformOptions:= TransformOptions + [toUnregistered]; if StrToIntDef(QFld['negative'], 0) > 0 then TransformOptions:= TransformOptions + [toNegative]; if StrToIntDef(QFld['noAlign'], 0) > 0 then TransformOptions:= TransformOptions - [toAlign8]; strm:= TStringStream.Create(''); s:= Alias2FileName(QFld['src']); Response.DerivedFrom:= ReplaceExt('wbmp', s); if ConvertImage2WBMP(s, strm, DitherMode, TransformOptions, ImageSize) then begin Response.Content:= TStringStream(strm).DataString; end; if Length(Response.Content) = 0 then begin Response.StatusCode:= 404; Response.ReasonString:= 'iwbmp error: file "' + s +'" not found.'; Response.LogMessage:= Response.LogMessage + ' , error: file "' + s +'" not found.'; Response.Content:= PathsList[fpDefWBMP]; end; Response.ContentLength:= Length(Response.Content); // Response.Content:= s + #13#10 + QFld['src'] + #13#10 + Request.QueryFields.Values['src']; strm.Free; end; procedure TWebModule1.WebModule1WebActionItem2Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); const RegisteredStr: array[Boolean] of String = ('Evaluation version', 'This version is registered to %s'); begin Handled:= True; Response.ContentType:= 'text/plain'; Response.Content:= 'Bitmap image to wbmp convertor ' + LNVERSION + #13#10 + Format(RegisteredStr[FRegistered], [PathsList[fpUser]]) + #13#10 + 'Copyright © 2002 Andrei Ivanov. All rights reserved.'#13#10 + 'Should you have any questions concerning this program, please contact: mailto:ensen_andy@yahoo.com'#13#10#13#10 + 'Default ContentType: image/vnd.wap.wbmp'#13#10#13#10 + 'src (file name (virtual roots available listed below)): bmp, jpeg, ico, wmf and wbmp'#13#10 + ' Note: if relative file name used, DLL looking for Referer, Referer: ' + Request.Referer + #13#10 + 'dither (dithering modes available): Nearest|FloydSteinberg|Stucki|Sierra|JaJuNI|SteveArche|Burkes'#13#10 + 'noalign (disable align width to 8 pixels): 1|0'#13#10 + 'negative (produce negative image): 1|0'#13#10#13#10 + 'Settings:'#13#10#13#10+ 'Default dithering: '+ GetDitherModeName(DefDitherMode) + #13#10#13#10+ 'web server aliases: '#13#10 + SLAlias.Text + #13#10; { 'User: ' + PathsList[fpUser] + #13#10 + 'Code: ' + PathsList[fpCode] + #13#10; } end; procedure TWebModule1.WebModuleCreate(Sender: TObject); var S: String; FN: array[0..MAX_PATH- 1] of Char; rg: TRegistry; begin rg:= TRegistry.Create; Rg.RootKey:= HKEY_LOCAL_MACHINE; Rg.OpenKeyReadOnly(RGPATH); PathsList:= TStringList.Create; SetString(S, FN, GetModuleFileName(hInstance, FN, SizeOf(FN))); // fpSCRIPT (0) Script name используется для ссылок в HTML PathsList.Add(S); // fpPatternPath (1), if not specified or wrong folder - is2sql.DLL location PathsList.Add(ExtractFilePath(S)); // fpDefDitherMode (2) default dithering mode PathsList.Add(rg.ReadString('DefDitherMode')); Rg.OpenKeyReadOnly(CVRTRGPATH); // fpUser (3) user name PathsList.Add(rg.ReadString('Name')); // fpCode (4) code PathsList.Add(rg.ReadString('Code')); // fpDefWBMP (5) default SetLength(s, 4016); SetLength(s, rg.ReadBinaryData('DefWBMP', s[1], Length(s))); // set default dithering mode DefDitherMode:= GetDitherModeByName(PathsList[fpDefDitherMode], dmNearest); SLAlias:= TStringList.Create; AddEntireKey(RGW2SVCALIAS, SLAlias); AddEntireKey(RGPATH+'\Virtual Roots', SLAlias); ValidateW3SvcColon; rg.Free; FRegistered:= IsRegistered; end; function TWebModule1.Alias2FileName(const AFn: String): String; begin if util1.IsAbsolutePath(AFn) then begin // absolute path i.e. /icons or \path or E:\path Result:= util1.ConCatAliasPath(SLAlias, PathsList[fpPatternPath], AFn); end else begin // relative path Result:= util1.ConcatPath(Self.Request.Referer, AFn, '/') //if Pos('..', AFn) > 0 then Result:= '' // return nothing, no '../..' end; end; function TWebModule1.GetQueryField(const AName: String): String; begin with Request do begin if MethodType = mtPost then Result:= ContentFields.Values[AName] else Result:= QueryFields.Values[AName]; end; end; function TWebModule1.IsRegistered: Boolean; var S: String; begin // calculate hash S:= 'enzi' + 'cvrt2wbmp' + PathsList[fpUser]; Result:= PathsList[fpCode] = secure.GetMD5Digest(PChar(S), Length(S), 36); end; procedure TWebModule1.WebModuleDestroy(Sender: TObject); begin SLAlias.Free; PathsList.Free; end; end.
unit Counters; interface uses Windows, Forms, Classes, DAQDefs, pwrdaq32, pdfw_def; const UCT_SQUARE = $36; UCT_IMPULSE = $34; type // base acquisition thread TCounter = class(TThread) private hAdapter: DWORD; dwError: DWORD; FModes: array [0..2] of DWORD; FClocks: array [0..2] of DWORD; FGates: array [0..2] of DWORD; FUpdateView: TThreadMethod; procedure SetValue(Index: Integer; Value: DWORD); function GetValue(Index: Integer): DWORD; procedure SetClock(Index: Integer; Value: DWORD); procedure SetGate(Index: Integer; Value: DWORD); procedure SetMode(Index: Integer; Value: DWORD); public constructor Create(Adapter: THandle); procedure Execute; override; property OnUpdateView: TThreadMethod read FUpdateView write FUpdateView; property Clocks[Index: Integer]: DWORD write SetClock; property Gates[Index: Integer]: DWORD write SetGate; property Modes[Index: Integer]: DWORD write SetMode; property Values[Index: Integer]: DWORD read GetValue write SetValue; end; implementation constructor TCounter.Create(Adapter: THandle); begin try inherited Create(True); hAdapter := Adapter; FillChar(FModes, SizeOf(FModes), 0); FillChar(FClocks, SizeOf(FClocks), 0); FillChar(FGates, SizeOf(FGates), 0); except Application.HandleException(Self); end; end; procedure TCounter.Execute; begin try // counter output - init sequence try // get subsystem in use if not PdAdapterAcquireSubsystem(hAdapter, @dwError, CounterTimer, 1) then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError); // reset timers if not _PdUctReset(hAdapter, @dwError) then raise TPwrDaqException.Create('_PdUctReset', dwError); // start timers if not _PdUctSetCfg(hAdapter, @dwError, FClocks[0] or FClocks[1] or FClocks[2] or FGates[0] or FGates[1] or FGates[2]) then raise TPwrDaqException.Create('_PdUctSetCfg', dwError); // thread loop while not Terminated do begin Sleep(10); if Assigned(OnUpdateView) then Synchronize(OnUpdateView); end; // release UCTnp subsystem if not _PdUctReset(hAdapter, @dwError) then raise TPwrDaqException.Create('_PdUctReset', dwError); except Application.HandleException(Self); end; finally // Release AOut subsystem and close adapter if not PdAdapterAcquireSubsystem(hAdapter, @dwError, CounterTimer, 0) then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError); end; end; procedure TCounter.SetMode(Index: Integer; Value: DWORD); begin FModes[Index] := Value; end; procedure TCounter.SetClock(Index: Integer; Value: DWORD); begin FClocks[Index] := Value; end; procedure TCounter.SetGate(Index: Integer; Value: DWORD); begin FGates[Index] := Value; end; procedure TCounter.SetValue(Index: Integer; Value: DWORD); begin { Timer programming: square wave for channel 0 Control Word Format =================== 0x36 - 0011 0110 00 - select counter N 0 11 - write LSB, then MSB (order) 011 - mode select (mode 3) 0 - use bynary counter (0-65536) } _PdUctWrite(hAdapter, @dwError, (Value SHL 8) or (Index SHL 6) or FModes[Index]); end; function TCounter.GetValue(Index: Integer): DWORD; var FValue: DWORD; begin { Timer programming: reading counter value from channel 0 Control Word Format =================== 0x30 - 0011 0000 00 - select counter N 0 11 - write LSB, then MSB (order) 011 - mode select (mode 3) 0 - use bynary counter (0-65536) } // _PdUctSwSetGate(hAdapter, @dwError, $00); _PdUctRead(hAdapter, @dwError, $1000 or (Index SHL 9) or (Index SHL 6) or $30, @FValue); // _PdUctSwSetGate(hAdapter, @dwError, $FF); if FValue > $FFFF then FValue := FValue - $FFFF; Result := ($FFFF - FValue) shr 1; end; end.
function TPipeCommand_Grep.Compile( args: TStrArray ): string; begin if length( args ) <> 1 then exit( 'bad grep command usage. please type "man grep" in order to see help!' ); _arguments := args; exit(''); // no error end; procedure TPipeCommand_Grep.Run; var i: integer = 0; n: integer = 0; begin n := length( _input ); for i:=0 to n - 1 do begin //writeln( 'grep: ', _arguments[0], ' in ', _input[i] ); if pos( _arguments[0], _input[i] ) > 0 then push( _output, StringReplace( _input[i], _arguments[0], colorize( _arguments[0], term_fg_red ), [ rfReplaceAll ] ) ); end; end;
unit uParentSub; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, siComp, siLangRT; type TOnDataChange = procedure of object; TOnSelectData = procedure (AParams: String) of object; TOnParamChange = procedure of object; TOnGetSQLEvent = function(): String of object; TOnGetFchParam = function(): String of object; TOnTestFillEvent = function(): boolean of object; TParentSub = class(TForm) siLang: TsiLangRT; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private FOnSelectData: TOnSelectData; protected fLangLoaded : Boolean; FOnGetSQL: TOnGetSQLEvent; FParam: String; FButtonNewEnabled, FButtonOpenEnabled, FButtonRemoveEnabled: Boolean; FOnDataChange: TOnDataChange; FOnGetFchParam: TOnGetFchParam; FOnTestFillEvent: TOnTestFillEvent; FFilterFields : TStringList; { campos do filtro } FFilterValues : TStringList; { valores do filtro } procedure SetFilterFields(Value : TStringList); procedure SetFilterValues(Value : TStringList); procedure AfterSetParam; virtual; procedure SetLock(AReadOnly: boolean); virtual; procedure NotifyChanges(Changes: String); virtual; public procedure SetButtonNewEnabled(Value : boolean); procedure SetButtonOpenEnabled(Value : boolean); procedure SetButtonRemoveEnabled(Value : boolean); procedure SetLayoutProperties; virtual; procedure GetLayoutProperties; virtual; procedure SetParam(Value: String); function GetDatasetIsEmpty: boolean; virtual; function GetRecordCount: integer; virtual; function GetCurrentKey: integer; virtual; procedure DataSetOpen; virtual; procedure DataSetClose; virtual; procedure DataSetNew; virtual; procedure SubListRefresh; virtual; function GiveInfo(InfoString: String): String; virtual; abstract; published property Param : String read FParam write SetParam; property OnGetSQL : TOnGetSQLEvent read FOnGetSQL write FOnGetSQL; property OnDataChange : TOnDataChange read FOnDataChange write FOnDataChange; property OnSelectData : TOnSelectData read FOnSelectData write FOnSelectData; property OnGetFchParam : TOnGetFchParam read FOnGetFchParam write FOnGetFchParam; property OnTestFillEvent : TOnTestFillEvent read FOnTestFillEvent write FOnTestFillEvent; property FilterFields : TStringList read FFilterFields write SetFilterFields; property FilterValues : TStringList read FFilterValues write SetFilterValues; end; implementation uses uMsgBox, uMsgConstant, uDMGlobal, SubListPanel; {$R *.DFM} procedure TParentSub.DataSetOpen; begin // Para ser sobrescrito end; procedure TParentSub.DataSetClose; begin // Para ser sobrescrito end; procedure TParentSub.SetFilterFields(Value : TStringList); begin FFilterFields := Value; end; procedure TParentSub.SetFilterValues(Value : TStringList); begin FFilterValues := Value; end; procedure TParentSub.FormCreate(Sender: TObject); begin // FFilterFields := TStringList.Create; // FFilterValues := TStringList.Create; fLangLoaded := (DMGlobal.IDLanguage = LANG_ENGLISH); end; procedure TParentSub.FormDestroy(Sender: TObject); begin // FFilterFields.Free; // FFilterValues.Free; end; procedure TParentSub.SetLock(AReadOnly: boolean); begin // para ser herdado end; procedure TParentSub.DataSetNew; begin // Pare ser herdado end; function TParentSub.GetDatasetIsEmpty: boolean; begin // Para ser herdado Result := False; end; function TParentSub.GetRecordCount: integer; begin // Para ser escrino nos descendentes Result := -1; end; function TParentSub.GetCurrentKey: integer; begin // Para ser escrino nos descendentes Result := -1; end; procedure TParentSub.SetButtonNewEnabled(Value: boolean); begin if FButtonNewEnabled <> Value then FButtonNewEnabled := Value; end; procedure TParentSub.SetButtonOpenEnabled(Value: boolean); begin if FButtonOpenEnabled <> Value then FButtonOpenEnabled := Value; end; procedure TParentSub.SetButtonRemoveEnabled(Value: boolean); begin if FButtonRemoveEnabled <> Value then FButtonRemoveEnabled := Value; end; procedure TParentSub.SetParam(Value: String); begin FParam := Value; AfterSetParam; end; procedure TParentSub.AfterSetParam; begin // Para ser Herdado end; procedure TParentSub.SubListRefresh; begin // Para ser herdado end; procedure TParentSub.FormShow(Sender: TObject); begin //Load Translation if (not fLangLoaded) and (siLang.StorageFile <> '') and (DMGlobal.IDLanguage <> LANG_ENGLISH) then begin if FileExists(DMGlobal.LangFilesPath + siLang.StorageFile) then siLang.LoadAllFromFile(DMGlobal.LangFilesPath + siLang.StorageFile, True) else MsgBox(MSG_INF_DICTIONARI_NOT_FOUND ,vbOKOnly + vbInformation); fLangLoaded := True; end; end; procedure TParentSub.NotifyChanges(Changes: String); begin if Parent is TSubListPanel then TSubListPanel(Parent).DoParamChanged(Changes); end; procedure TParentSub.SetLayoutProperties; begin // para ser herdado end; procedure TParentSub.GetLayoutProperties; begin // para ser herdado end; end.
procedure TNASKeyboard.debug(fString :string; clear:boolean=false); begin if(self.z_debug) then begin if clear then ClearDebug(); fString:=formatDateTime('tt',time())+' | '+ 'NAS_Keyboard ' +' > ' +fString; WriteLn(fString); end; end; procedure TNASKeyboard.typeString(const s: string; pressEnter: boolean=false; keyWait: integer=50); begin self.debug('typeString > "'+s+ '" > pressEnter > '+toStr(pressEnter)+' > keyWait > '+toStr(keyWait)); SendKeys(s, keyWait, 0); if(pressEnter) then PressKey(VK_RETURN); end;
unit uwinmanager; // Windows and desktops manager - only for MS Windows system { TODO -cWM : only for MS Windows} {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs, uMenuItem, windows, JwaPsApi, LConvEncoding; procedure LoadMenuWindows(const aFilter, aSelfExe: String); function ActivateWindow(const aWindowHandle: String): Boolean; function ActivateProcess(const aExe: String): Boolean; function GetCurrentWindow: Hwnd; //function GetCurrentDesktopName(): string; implementation uses uMainForm; //// https://github.com/Ciantic/VirtualDesktopAccessor //function GetWindowDesktopNumber(hWindow: HWND): Integer; stdcall; external 'VirtualDesktopAccessor.dll'; //function IsPinnedWindow(hwnd: HWND): Integer; stdcall; external 'VirtualDesktopAccessor.dll'; //function GetCurrentDesktopNumber(): Integer; stdcall; external 'VirtualDesktopAccessor.dll'; function GetCurrentActiveProcessPath(hWindow: Hwnd): String; var pid : DWORD; hProcess: THandle; path : array[0..4095] of Char; begin GetWindowThreadProcessId(hWindow, pid); hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, FALSE, pid); if hProcess <> 0 then try if GetModuleFileNameEx(hProcess, 0, @path[0], Length(path)) = 0 then RaiseLastOSError; result := path; finally CloseHandle(hProcess); end else RaiseLastOSError; end; function LongHexToDec(Str: string): QWord; var Counter : Integer; DecValue: QWord; begin Result :=0; DecValue:=1; Str :=AnsiUpperCase(Str); for Counter:=Length(Str) downto 1 do begin case Str[Counter] of '1'..'9': Result:=Result+(Ord(Str[Counter])-Ord('0'))*DecValue; 'A'..'F': Result:=Result+(Ord(Str[Counter])-Ord('A')+10)*DecValue; end; DecValue:=DecValue shl 4; end; end; procedure LoadMenuWindows(const aFilter, aSelfExe: String); var hDesktop, hWindow: Hwnd; Buffer: array[0..255] of char; lTitle, lClass, lMenuTitle, lExeFile, lFullExe, i, lShortCut: String; //lDesktop, lIsPined: Integer; lMenuItemParser: TMenuItemParser; lIsAppWindow, lIsWindowVisible: Boolean; begin // load list windows hDesktop := GetDeskTopWindow; hWindow := GetWindow(hDesktop, GW_CHILD); while hWindow <> 0 do begin lShortCut := ''; // initialize value GetWindowText(hWindow, Buffer, 255); //ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_HIDE); //lDesktop := GetWindowDesktopNumber(hWindow); //lIsPined := IsPinnedWindow(hWindow); lIsAppWindow := GetWindowLongPtr(hWindow, GWL_STYLE) and WS_EX_APPWINDOW<>0; lIsWindowVisible := IsWindowVisible(hWindow); if (Buffer <> '') and lIsWindowVisible and lIsAppWindow then begin lTitle := Buffer; //lTitle:= AnsiToUtf8(lTitle); lTitle:= CP1250ToUTF8(lTitle); // Hack for czech encoding :-( GetClassName(hWindow, Buffer, 255); lClass := buffer; //List.Add(IntToStr(lDesktop + 1) + ' | ' + lTitle + ' | ' + GetCurrentActiveProcessPath(hWindow) + ' | ' + lClass + ' | '+ IntToHex(hWindow,4)); try // https://stackoverflow.com/questions/5951631/how-to-get-captions-of-actual-windows-currently-running lFullExe := GetCurrentActiveProcessPath(hWindow); Except lFullExe := 'ADMIN' end; lExeFile := ExtractFileName(lFullExe); lMenuTitle := (* '[' + IntToStr(lDesktop + 1) + '] ' *) '(' + lExeFile +') ' + lTitle; MainForm.SQLMenuItemsShortcutByCmd.ParamByName('cmd').AsString := '%'+lExeFile+'%'; MainForm.SQLMenuItemsShortcutByCmd.ParamByName('name').AsString := lExeFile; MainForm.SQLMenuItemsShortcutByCmd.open; if MainForm.SQLMenuItemsShortcutByCmd.RecordCount >= 1 then begin MainForm.SQLMenuItemsShortcutByCmd.First; lShortCut := MainForm.SQLMenuItemsShortcutByCmd.FieldByName('shortcut').AsString; end; MainForm.SQLMenuItemsShortcutByCmd.close; if lExeFile <> ExtractFileName(aSelfExe) then // not add to menu self begin lMenuItemParser := TMenuItemParser.Create(lMenuTitle, IntToHex(hWindow,4), lShortCut); try MainForm.AddMenuItem(lMenuItemParser); finally FreeAndNil(lMenuItemParser); end; end; end; hWindow := GetWindow(hWindow, GW_HWNDNEXT); end; end; function ActivateProcess(const aExe: String): Boolean; var hDesktop, hWindow: Hwnd; Buffer: array[0..255] of char; lTitle, lClass, lMenuTitle, lExeFile, lFullExe: String; //lDesktop, lIsPined: Integer; lMenuItemParser: TMenuItemParser; begin Result := False; // load list windows hDesktop := GetDeskTopWindow; hWindow := GetWindow(hDesktop, GW_CHILD); while hWindow <> 0 do begin //GetWindowText(hWindow, Buffer, 255); //ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_HIDE); //lDesktop := GetWindowDesktopNumber(hWindow); //lIsPined := IsPinnedWindow(hWindow); if IsWindowVisible(hWindow) (* and ((lDesktop = GetCurrentDesktopNumber()) or (lIsPined = 1)) *) then begin lFullExe := GetCurrentActiveProcessPath(hWindow); if lFullExe.Contains(aExe) then // not menu itself begin Result := ActivateWindow(IntToHex(hWindow,4)); exit; end; end; hWindow := GetWindow(hWindow, GW_HWNDNEXT); end; end; function GetCurrentWindow: Hwnd; begin result := GetActiveWindow; end; //function GetCurrentDesktopName(): string; //begin //Result := IntToStr(GetCurrentDesktopNumber() + 1); // numbering from 0, bad name from 1 //end; function ActivateWindow(const aWindowHandle: String): Boolean; var hWindow: Hwnd; { TODO : test and delete death code } //actHandle: Hwnd; //lCnt: Integer; begin Result := False; //lCnt := 0; hWindow := LongHexToDec(aWindowHandle); //actHandle := GetFocus; //while ((actHandle <> hWindow) and (lCnt < 10)) do { TODO : const for max cnt } begin if IsIconic(hWindow) then ShowWindow(hWindow,SW_RESTORE); SetForegroundWindow(hWindow); SetActiveWindow(hWindow); SetFocus(hWindow); //Sleep(50); //Inc(lCnt); end; Result := True; end; end.
// Copyright 2014 Asbjørn Heid // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. unit Compute; interface uses Compute.Common, Compute.ExprTrees, Compute.OpenCL, Compute.Future.Detail; type Expr = Compute.ExprTrees.Expr; TLogProc = Compute.OpenCL.TLogProc; ComputeDeviceSelection = (PreferCPUDevice, PreferGPUDevice); Buffer<T> = record strict private FCmdQueue: Compute.OpenCL.CLCommandQueue; FBuffer: Compute.OpenCL.CLBuffer; function GetNumElements: UInt64; function GetSize: UInt64; private property CmdQueue: Compute.OpenCL.CLCommandQueue read FCmdQueue; property Buffer: Compute.OpenCL.CLBuffer read FBuffer; public class function Create(const NumElements: UInt64): Buffer<T>; overload; static; class function Create(const InitialData: TArray<T>): Buffer<T>; overload; static; procedure CopyTo(const DestBuffer: Buffer<T>); procedure SwapWith(var OtherBuffer: Buffer<T>); function ToArray: TArray<T>; property NumElements: UInt64 read GetNumElements; property Size: UInt64 read GetSize; // underlying buffer property Handle: Compute.OpenCL.CLBuffer read FBuffer; end; Future<T> = record strict private FImpl: IFuture<T>; function GetDone: boolean; function GetValue: T; private class function CreateReady(const Value: T): Future<T>; static; property Impl: IFuture<T> read FImpl; public class operator Implicit(const Impl: IFuture<T>): Future<T>; // makes a ready-future class operator Implicit(const Value: T): Future<T>; procedure SwapWith(var OtherFuture: Future<T>); procedure Wait; property Done: boolean read GetDone; property Value: T read GetValue; end; function Constant(const Value: double): Expr.Constant; function Variable(const Name: string): Expr.Variable; function ArrayVariable(const Name: string; const Count: integer): Expr.ArrayVariable; function Func1(const Name: string; const FuncBody: Expr): Expr.Func1; function Func2(const Name: string; const FuncBody: Expr): Expr.Func2; function Func3(const Name: string; const FuncBody: Expr): Expr.Func3; function _1: Expr.LambdaParam; function _2: Expr.LambdaParam; function _3: Expr.LambdaParam; procedure InitializeCompute(const DeviceSelection: ComputeDeviceSelection = PreferGPUDevice; const LogProc: TLogProc = nil; const DebugLogProc: TLogProc = nil); function AsyncTransform(const InputBuffer: Buffer<double>; const Expression: Expr): Future<Buffer<double>>; overload; // queues the async transform to execute as soon as the input buffer is ready, output buffer is returned in the future function AsyncTransform(const InputBuffer, OutputBuffer: Future<Buffer<double>>; const Expression: Expr): Future<Buffer<double>>; overload; // two inputs function AsyncTransform(const InputBuffer1, InputBuffer2, OutputBuffer: Future<Buffer<double>>; const Expression: Expr): Future<Buffer<double>>; overload; // three inputs function AsyncTransform(const InputBuffer1, InputBuffer2, InputBuffer3, OutputBuffer: Future<Buffer<double>>; const Expression: Expr): Future<Buffer<double>>; overload; function AsyncTransform(const Input: TArray<double>; const Expression: Expr): Future<TArray<double>>; overload; function Transform(const Input: TArray<double>; const Expression: Expr): TArray<double>; implementation uses Winapi.Windows, System.SysUtils, System.Math, Compute.Detail; function Constant(const Value: double): Expr.Constant; begin result := Compute.ExprTrees.Constant(Value); end; function Variable(const Name: string): Expr.Variable; begin result := Compute.ExprTrees.Variable(Name); end; function ArrayVariable(const Name: string; const Count: integer): Expr.ArrayVariable; begin result := Compute.ExprTrees.ArrayVariable(Name, Count); end; function Func1(const Name: string; const FuncBody: Expr): Expr.Func1; begin result := Compute.ExprTrees.Func1(Name, FuncBody); end; function Func2(const Name: string; const FuncBody: Expr): Expr.Func2; begin result := Compute.ExprTrees.Func2(Name, FuncBody); end; function Func3(const Name: string; const FuncBody: Expr): Expr.Func3; begin result := Compute.ExprTrees.Func3(Name, FuncBody); end; function _1: Expr.LambdaParam; begin result := Compute.ExprTrees._1; end; function _2: Expr.LambdaParam; begin result := Compute.ExprTrees._2; end; function _3: Expr.LambdaParam; begin result := Compute.ExprTrees._3; end; { Future<T> } class function Future<T>.CreateReady(const Value: T): Future<T>; begin result.FImpl := TReadyFutureImpl<T>.Create(Value); end; function Future<T>.GetDone: boolean; begin result := Impl.Done; end; function Future<T>.GetValue: T; begin result := Impl.Value; end; class operator Future<T>.Implicit(const Value: T): Future<T>; begin result := CreateReady(Value); end; procedure Future<T>.SwapWith(var OtherFuture: Future<T>); var f: IFuture<T>; begin f := OtherFuture.FImpl; OtherFuture.FImpl := FImpl; FImpl := f; end; class operator Future<T>.Implicit(const Impl: IFuture<T>): Future<T>; begin result.FImpl := Impl; end; procedure Future<T>.Wait; begin Impl.Wait; end; procedure InitializeCompute(const DeviceSelection: ComputeDeviceSelection; const LogProc, DebugLogProc: TLogProc); begin Algorithms.Initialize(DeviceSelection, LogProc, DebugLogProc); end; { Buffer<T> } class function Buffer<T>.Create(const NumElements: UInt64): Buffer<T>; begin result.FCmdQueue := Algorithms.CmdQueue; result.FBuffer := Algorithms.Context.CreateHostBuffer(BufferAccessReadWrite, SizeOf(T) * NumElements); end; class function Buffer<T>.Create(const InitialData: TArray<T>): Buffer<T>; var size: UInt64; begin size := SizeOf(T) * Length(InitialData); result.FCmdQueue := Algorithms.CmdQueue; result.FBuffer := Algorithms.Context.CreateHostBuffer(BufferAccessReadWrite, size, InitialData); end; function Buffer<T>.GetNumElements: UInt64; begin result := FBuffer.Size div SizeOf(T); end; function Buffer<T>.GetSize: UInt64; begin result := FBuffer.Size; end; procedure Buffer<T>.SwapWith(var OtherBuffer: Buffer<T>); var t: CLBuffer; begin t := OtherBuffer.FBuffer; OtherBuffer.FBuffer := FBuffer; FBuffer := t; end; function Buffer<T>.ToArray: TArray<T>; var len: UInt64; begin len := NumElements; SetLength(result, len); FCmdQueue.EnqueueReadBuffer(FBuffer, BufferCommandBlocking, 0, len * SizeOf(T), result, []); end; procedure Buffer<T>.CopyTo(const DestBuffer: Buffer<T>); var event: CLEvent; begin event := DestBuffer.CmdQueue.EnqueueCopyBuffer( Buffer, DestBuffer.Buffer, 0, 0, Min(Buffer.Size, DestBuffer.Buffer.Size), []); event.Wait; end; function AsyncTransform(const InputBuffer: Buffer<double>; const Expression: Expr): Future<Buffer<double>>; var outputBuffer: Buffer<double>; begin outputBuffer := Buffer<double>.Create(InputBuffer.NumElements); result := AsyncTransform(InputBuffer, outputBuffer, Expression); end; function AsyncTransform(const Input: TArray<double>; const Expression: Expr): Future<TArray<double>>; var output: TArray<double>; begin SetLength(output, Length(Input)); result := Algorithms.Transform(Input, output, Expression); end; function Transform(const Input: TArray<double>; const Expression: Expr): TArray<double>; var f: Future<TArray<double>>; begin f := AsyncTransform(Input, Expression); result := f.Value; end; function AsyncTransform(const InputBuffer, OutputBuffer: Future<Buffer<double>>; const Expression: Expr): Future<Buffer<double>>; begin result := Algorithms.Transform(InputBuffer.Impl, 0, InputBuffer.Impl.PeekValue.NumElements, OutputBuffer.Impl, Expression); end; function AsyncTransform(const InputBuffer1, InputBuffer2, OutputBuffer: Future<Buffer<double>>; const Expression: Expr): Future<Buffer<double>>; begin result := Algorithms.Transform([InputBuffer1.Impl, InputBuffer2.Impl], 0, InputBuffer1.Impl.PeekValue.NumElements, OutputBuffer.Impl, Expression); end; function AsyncTransform(const InputBuffer1, InputBuffer2, InputBuffer3, OutputBuffer: Future<Buffer<double>>; const Expression: Expr): Future<Buffer<double>>; begin result := Algorithms.Transform([InputBuffer1.Impl, InputBuffer2.Impl, InputBuffer3.Impl], 0, InputBuffer1.Impl.PeekValue.NumElements, OutputBuffer.Impl, Expression); end; end.
unit frmFishmain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Fmx.Bind.Editors, FMX.Layouts, Fmx.Bind.Navigator, Data.Bind.Components, FMX.Objects, Data.Bind.DBScope, Data.DB, Datasnap.DBClient, FMX.Memo, FMX.Edit, System.Rtti, System.Bindings.Outputs, FMX.StdCtrls; type TForm1 = class(TForm) EditSpeciesName: TEdit; EditLengthCM: TEdit; MemoNotes: TMemo; cbWordWrap: TCheckBox; BindingsList1: TBindingsList; LinkControlToProperty1: TLinkControlToProperty; ClientDataSet1: TClientDataSet; BindSourceDB1: TBindSourceDB; LinkControlToField2: TLinkControlToField; LinkControlToField5: TLinkControlToField; LinkControlToField6: TLinkControlToField; rctFishLengthCM: TRectangle; LinkPropertyToField1: TLinkPropertyToField; BindNavigator1: TBindNavigator; EditCategory: TEdit; Label1: TLabel; LinkControlToField9: TLinkControlToField; EditLength_In: TEdit; Label2: TLabel; LinkControlToField10: TLinkControlToField; ImageControlGraphic: TImageControl; Label3: TLabel; LinkControlToField11: TLinkControlToField; private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} end.
unit Base; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface var ServerHost: string; // our hostname IRCPort, HTTPPort, WormNATPort: Integer; IRCOperPassword: string; IRCChannel: string; procedure Log(S: string; DiskOnly: Boolean=False); procedure EventLog(S: string); function WinSockErrorCodeStr(Code: Integer): string; implementation uses {$IFNDEF WIN32} UnixUtils, {$ENDIF} SysUtils, IRCServer; procedure Log(S: string; DiskOnly: Boolean=False); var F: text; begin if Copy(S, 1, 1)<>'-' then S:='['+TimeToStr(Now)+'] '+S; // logging to disk will work only if the file WNServer.log exists {$I-} Assign(F, ExtractFilePath(ParamStr(0))+'WNServer.log'); Append(F); WriteLn(F, S); Close(f); {$I+} if IOResult<>0 then ; if not DiskOnly then begin // logging to console, if it's enabled {$I-} WriteLn(S); {$I+} if IOResult<>0 then ; // echo to IRC OPERs LogToOper(S); end; end; procedure EventLog(S: string); var F: text; begin Log(S, True); if Copy(S, 1, 1)<>'-' then S:='['+DateTimeToStr(Now)+'] '+S; // logging to disk will work only if the file EventLog.log exists {$I-} Assign(F, ExtractFilePath(ParamStr(0))+'EventLog.log'); Append(F); WriteLn(F, S); Close(f); {$I+} if IOResult<>0 then ; end; {$IFDEF WIN32} {$INCLUDE WinSockCodes.inc} function WinSockErrorCodeStr(Code: Integer): string; var I: Integer; begin Result:='Error #'+IntToStr(Code); for I:=1 to High(WinSockErrors) do if (WinSockErrors[I].Code=Code)or(WinSockErrors[I].Code=Code+10000) then Result:=WinSockErrors[I].Text; end; {$ELSE} function WinSockErrorCodeStr(Code: Integer): string; begin Result:=StrError(Code); end; {$ENDIF} end.
unit Share; interface uses Common, Classes, DBTables, Windows; type TStdItem = packed record Name: string[14];//物品名称 StdMode: Byte; //0/1/2/3:药, 5/6:武器,10/11:盔甲,15:头盔,22/23:戒指,24/26:手镯,19/20/21:项链 Shape: Byte; Weight: Byte; AniCount: Byte; Source: ShortInt; Reserved: Byte; //0x14 NeedIdentify: Byte; //0x15 需要 Looks: Word; //0x16 外观,即Items.WIL中的图片索引 DuraMax: Word; //0x18 最大持久 Reserved1: Word; AC: Integer; //0x1A MAC: Integer; //0x1C DC: Integer; //0x1E MC: Integer; //0x20 SC: Integer; //0x22 Need: Integer; //0x24 NeedLevel: Integer; //0x25 Price: Integer; //0x28 end; pTStdItem = ^TStdItem; const GameMonName = 'QKGameMonList.txt'; FilterFileName = 'GameFilterItemNameList.txt'; g_sProductName = '4BA8CAFEFD5694CDB3D798FEA5C7F363E4CD8B1C084A3260AD4350D2F1F3C7FC'; //IGE科技登陆器客户端(Client) g_sVersion = '480317B2D917A24A2F344FC7EADF5DF90CB049B5C15AFEE8'; //1.00 Build 20081130 g_sUpDateTime = '0F5FC1F777D336933EFB2AAFA12355F8'; //2008/06/03 g_sProgram = 'C0CB995DE0C2A55814577F81CCE3A3BD'; //IGE科技 g_sWebSite = 'E14A1EC77CDEF28A670B57F56B07D834D8758E442B312AF440574B5A981AB1752C73BF5C6670B79C'; // http://www.IGEM2.com(官网站) g_sBbsSite = '2E5A58E761D583C119D6606E0F38D7A9D8758E442B312AF440574B5A981AB17538E97FF2F0C39555'; //http://www.IGEM2.com.cn(程序站) g_sServerAdd = 'A4A488F2C30983EA832726B3D36A30419C771FFC19B5169D'; //56m2vip.vicp.net g_sFtpServerAdd = '83D7FD6174C8CE82BB159BA29AC7242F16C41B949FD21F29'; //ftp.igem2.com g_sFtpUser = 'AA6591AB908100721CCB18FD84556EED';//56m2vip g_sFtpPass = '8F618E113AFF24F7AEB6A37AADB5343181065F6527D024AA'; //werks%*&@&@# // _sProductAddress ='B1A6AE5FFAB8A3F8476A0071DCA6679A17672C9BED267D3E40574B5A981AB175AC9C4E63F0B12F0D';//http://www.66h6.net/ver1.txt 放特殊指令的文本 // _sProductAddress1 ='{{{"5>a>"oca"ob';//www.92m2.com.cn //改版权指令(文本里需加密),即网站文本第一行内容 (*文本内容 {{{"5>a>"oca"ob 本站网站已经修改成XXXXXX|登陆不进去的用户请从新网站从新下载商业配置器 *) var g_MySelf: TUserInfo; g_boConnect: Boolean = False; g_boLogined: Boolean = False; g_sRecvMsg: string; g_sRecvGameMsg: string; g_boBusy: Boolean; btCode: Byte = 1; g_sAccount: string; g_sPassword: string; g_boFirstOpen: Boolean = False; StdItemList: TList; //List_54 Query: TQuery; MakeType: Byte = 0; function LoadItemsDB: Integer; implementation function LoadItemsDB: Integer; var I, Idx: Integer; StdItem: pTStdItem; resourcestring sSQLString = 'select * from StdItems'; begin try for I := 0 to StdItemList.Count - 1 do begin Dispose(pTStdItem(StdItemList.Items[I])); end; StdItemList.Clear; Result := -1; Query.SQL.Clear; Query.SQL.Add(sSQLString); try Query.Open; finally Result := -2; end; for I := 0 to Query.RecordCount - 1 do begin New(StdItem); Idx := Query.FieldByName('Idx').AsInteger; StdItem.Name := Query.FieldByName('Name').AsString; StdItem.StdMode := Query.FieldByName('StdMode').AsInteger; StdItem.Shape := Query.FieldByName('Shape').AsInteger; StdItem.Weight := Query.FieldByName('Weight').AsInteger; StdItem.AniCount := Query.FieldByName('AniCount').AsInteger; StdItem.Source := Query.FieldByName('Source').AsInteger; StdItem.Reserved := Query.FieldByName('Reserved').AsInteger; StdItem.Looks := Query.FieldByName('Looks').AsInteger; StdItem.DuraMax := Word(Query.FieldByName('DuraMax').AsInteger); StdItem.AC := MakeLong(Round(Query.FieldByName('Ac').AsInteger * (10 / 10)), Round(Query.FieldByName('Ac2').AsInteger * (10 / 10))); StdItem.MAC := MakeLong(Round(Query.FieldByName('Mac').AsInteger * (10 / 10)), Round(Query.FieldByName('MAc2').AsInteger * (10 / 10))); StdItem.DC := MakeLong(Round(Query.FieldByName('Dc').AsInteger * (10 / 10)), Round(Query.FieldByName('Dc2').AsInteger * (10 / 10))); StdItem.MC := MakeLong(Round(Query.FieldByName('Mc').AsInteger * (10 / 10)), Round(Query.FieldByName('Mc2').AsInteger * (10 / 10))); StdItem.SC := MakeLong(Round(Query.FieldByName('Sc').AsInteger * (10 / 10)), Round(Query.FieldByName('Sc2').AsInteger * (10 / 10))); StdItem.Need := Query.FieldByName('Need').AsInteger; StdItem.NeedLevel := Query.FieldByName('NeedLevel').AsInteger; StdItem.Price := Query.FieldByName('Price').AsInteger; //StdItem.NeedIdentify := GetGameLogItemNameList(StdItem.Name); if StdItemList.Count = Idx then begin StdItemList.Add(StdItem); Result := 1; end else begin //Memo.Lines.Add(Format('加载物品(Idx:%d Name:%s)数据失败!!!', [Idx, StdItem.Name])); Result := -100; Exit; end; Query.Next; end; finally Query.Close; end; end; initialization begin StdItemList := TList.Create; Query := TQuery.Create(nil); end; finalization begin //StdItemList.Free; 不知道为什么 一释放就出错 Query.Free; end; end.
unit uDB1Data; interface uses Data.SQLExpr, System.Classes, FireDAC.Comp.Client, Data.DB, System.StrUtils, System.Types; type TDB1Data = class(TFDQuery) private FsListaCampos: TStringDynArray; FsListaTabela: TStringDynArray; FsListaCondicoes: TStringDynArray; public procedure Open; published property ListaCampos: TStringDynArray read FsListaCampos write FsListaCampos; property ListaTabela: TStringDynArray read FsListaTabela write FsListaTabela; property ListaCondicoes: TStringDynArray read FsListaCondicoes write FsListaCondicoes; end; procedure Register; implementation uses System.SysUtils; procedure Register; begin RegisterComponents('DB1 Avaliação',[TDB1Data]); end; { TDB1Data } procedure TDB1Data.Open; var sSQL: string; sCampo: string; nContador: integer; begin for nContador := Low(FsListaCampos) to High(FsListaCampos) do begin sCampo := Trim(FsListaCampos[nContador]); if sCampo = EmptyStr then continue; if nContador = Low(FsListaCampos) then sSQL := 'select ' + sCampo else sSQL := sSQL + ' ,' + sCampo; end; for nContador := Low(FsListaTabela) to High(FsListaTabela) do begin sCampo := Trim(FsListaTabela[nContador]); if sCampo = EmptyStr then continue; if nContador = Low(FsListaTabela) then sSQL := sSQL + ' from ' + sCampo else sSQL := sSQL + ' ,' + sCampo; end; for nContador := Low(FsListaCondicoes) to High(FsListaCondicoes) do begin sCampo := Trim(FsListaCondicoes[nContador]); if sCampo = EmptyStr then continue; if nContador = Low(FsListaCondicoes) then sSQL := sSQL + ' where ' + sCampo else sSQL := sSQL + ' and ' + sCampo; end; if sSQL = EmptyStr then Exit; Self.SQL.Text := sSQL; Self.Active := True; end; end.
PROGRAM kette; (* Implementation with lists *) TYPE nodePtr = ^listElement; listElement = RECORD next: nodePtr; c: Char; END; (* RECORD *) (* Creates a new node*) FUNCTION NewNode(c : Char): nodePtr; VAR node : nodePtr; BEGIN New(node); node^.next := NIL; node^.c := c; NewNode := node; END; (* Appends a Node to a List *) PROCEDURE Append(var list : nodePtr; element : nodePtr); VAR tmp : nodePtr; BEGIN if list = NIL THEN list := element ELSE BEGIN tmp := list; WHILE tmp^.next <> NIL DO tmp := tmp^.next; tmp^.next := element; END; END; (* recursive; disposes every node in a list *) PROCEDURE ClearList(var list : nodePtr); BEGIN IF list <> NIL THEN BEGIN IF list^.next = NIL THEN dispose(list) ELSE ClearList(list^.next); END; END; (* Counts nodes in a list *) FUNCTION CountNodes(n : nodePtr) : INTEGER; VAR count : INTEGER; BEGIN count := 0; WHILE n <> NIL DO BEGIN Inc(count); n := n^.next; END; CountNodes := count; END; (* Removes the first node of a list *) PROCEDURE RemoveFirst(var list : nodePtr); VAR temp : nodePtr; BEGIN IF list <> NIL THEN BEGIN temp := list; list := list^.next; Dispose(temp); END; END; (* Check if char exists in the list; Returns TRUE OR FALSE *) FUNCTION CharExists(list : nodePtr; c : Char): Boolean; VAR n : nodePtr; BEGIN n := list; WHILE n <> NIL DO BEGIN IF n^.c = c THEN BEGIN CharExists := TRUE; break; END; n := n^.next; END; IF n = NIL THEN CharExists := FALSE; END; (* Counts different chars in a list; RETURNS 0 if empty*) FUNCTION CountDistinct(list: nodePtr): Integer; VAR temp, temp2 : nodePtr; BEGIN IF list <> NIL THEN BEGIN temp := list; temp2 := NIL; WHILE temp <> NIL DO BEGIN IF NOT CharExists(temp2,temp^.c) THEN Append(temp2, NewNode(temp^.c)); temp := temp^.next; END; CountDistinct := CountNodes(temp2); ClearList(temp2); END ELSE CountDistinct := 0; END; (* Prints out list *) PROCEDURE PrintList(list : nodePtr); VAR n : nodePtr; BEGIN n := list; WHILE n <> NIL DO BEGIN Write(n^.c); n := n^.next; END; WriteLn; END; (* Insert to string from a list RETURNS STRING*) FUNCTION InsertinString(list : nodePtr): STRING; VAR n : nodePtr; s : STRING; BEGIN n := list; s := ''; WHILE n <> NIL DO BEGIN s := Concat(s,n^.c); n := n^.next; END; InsertinString := s; END; (* Implementation with Single Linked List *) FUNCTION MinM(s: STRING) : Integer; VAR i : Integer; list : nodePtr; BEGIN list := NIL; FOR i := 1 TO Length(s) DO BEGIN IF NOT CharExists(list,s[i]) THEN Append(list, NewNode(s[i])); END; MinM := CountNodes(list); END; (* Implementation with Single Linked List *) FUNCTION MaxMStringLen(var longestS: STRING; s: STRING; m: Integer): Integer; VAR i, count, tempCount, maxLength : Integer; list : nodePtr; BEGIN list := NIL; count := 0; maxLength := 0; FOR i := 1 TO Length(s) DO BEGIN Append(list, NewNode(s[i])); tempCount := CountDistinct(list); IF tempCount > m THEN BEGIN RemoveFirst(list); END ELSE count := count + 1; IF count > maxLength THEN BEGIN maxLength := count; longestS := InsertinString(list); END; END; MaxMStringLen := maxLength; END; VAR s1, s2, s3, longest : String; BEGIN s1 := 'abcbaac'; s2 := 'abcd'; s3 := 'abcdefgggggggggggggggggraabbcdertzuiogaaaaaaaaaaaaaaaaaaaaa'; s3 := 'abcdefgggggggggggggggggraabbcdertzuiogaaaaaaaaaaaaaaaaaaaaa'; longest := ''; WriteLn('String 1: ', s1, #13#10#9, 'Min m: ', MinM(s1)); WriteLn('String 2: ', s2, #13#10#9, 'Min m: ', MinM(s2)); WriteLn('String 3: ', s3, #13#10#9, 'Min m: ', MinM(s3)); WriteLn('---------------------------------------------'); WriteLn('String 1 mit m 2: ', s1, #13#10#9,'MaxM: ', MaxMStringLen(longest,s1,2), #13#10#9, 'Longest substring: ', longest, #13#10); WriteLn('String 2 mit m 4: ', s2, #13#10#9,'MaxM: ', MaxMStringLen(longest,s2,4), #13#10#9, 'Longest substring: ', longest, #13#10); WriteLn('String 3 mit m 5: ', s3, #13#10#9,'MaxM: ', MaxMStringLen(longest,s3,5), #13#10#9, 'Longest substring: ', longest, #13#10); WriteLn('String 3 mit m 7: ', s3, #13#10#9,'MaxM: ', MaxMStringLen(longest,s3,7), #13#10#9, 'Longest substring: ', longest, #13#10); END.
unit uMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, uModel, ComCtrls, StdCtrls, System.Actions; type TMainForm = class(TForm) alActions: TActionList; acNewStudent: TAction; acEditStudent: TAction; acDeleteStudent: TAction; lvStudents: TListView; btnAddStudent: TButton; btnEditStudent: TButton; btnDeleteStudent: TButton; procedure FormCreate(Sender: TObject); procedure lvStudentsData(Sender: TObject; Item: TListItem); procedure acNewStudentExecute(Sender: TObject); procedure acDeleteStudentUpdate(Sender: TObject); procedure acEditStudentUpdate(Sender: TObject); procedure lvStudentsEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure acDeleteStudentExecute(Sender: TObject); procedure acEditStudentExecute(Sender: TObject); procedure lvStudentsDblClick(Sender: TObject); strict private FCurrentCourse: ICourse; function Confirm(const AMessage: string): Boolean; function EditStudent(const AStudent: IStudent): Boolean; function GetCurrentStudent: IStudent; function ListItemToStudent(AItem: TListItem): IStudent; procedure UpdateStudentView(const AStudent: IStudent); procedure UpdateView; procedure SetCurrentStudent(const Value: IStudent); procedure EditCurrentStudent; public { Public declarations } property CurrentCourse: ICourse read FCurrentCourse; property CurrentStudent: IStudent read GetCurrentStudent write SetCurrentStudent; end; var MainForm: TMainForm; implementation uses Menus, uStudentEditDialog; {$R *.dfm} procedure TMainForm.acDeleteStudentExecute(Sender: TObject); var student: IStudent; begin student := CurrentStudent; Assert(student <> nil); if (student <> nil) and Confirm('Tem certeza?') then begin CurrentCourse.RemoveStudent(student); UpdateView; end; end; procedure TMainForm.acDeleteStudentUpdate(Sender: TObject); begin (Sender as TAction).Enabled := CurrentStudent <> nil end; procedure TMainForm.acEditStudentExecute(Sender: TObject); begin EditCurrentStudent; end; procedure TMainForm.acEditStudentUpdate(Sender: TObject); begin (Sender as TAction).Enabled := CurrentStudent <> nil end; procedure TMainForm.acNewStudentExecute(Sender: TObject); var student: IStudent; begin student := TModel.CreateStudent; if EditStudent(student) then begin CurrentCourse.AddStudent(student); UpdateView; end; end; function TMainForm.Confirm(const AMessage: string): Boolean; begin Result := MessageBox(Handle, PChar(AMessage), PChar(Caption), MB_ICONQUESTION or MB_YESNO) = ID_YES end; procedure TMainForm.EditCurrentStudent; var student: IStudent; begin student := CurrentStudent; if (student <> nil) then begin if EditStudent(student) then UpdateStudentView(student); end; end; function TMainForm.EditStudent(const AStudent: IStudent): Boolean; begin Result := TStudentEditDialog.Edit(AStudent) end; procedure TMainForm.FormCreate(Sender: TObject); begin FCurrentCourse := TModel.CreateCourse; end; function TMainForm.GetCurrentStudent: IStudent; begin Result := ListItemToStudent(lvStudents.Selected); end; function TMainForm.ListItemToStudent(AItem: TListItem): IStudent; begin if AItem = nil then Result := nil else Result := CurrentCourse.Students[AItem.Index] end; procedure TMainForm.lvStudentsData(Sender: TObject; Item: TListItem); var student: IStudent; begin student := ListItemToStudent(Item); if student <> nil then begin Item.Caption := student.Name; Item.SubItems.Add(student.Email); Item.SubItems.Add(DateToStr(student.DateOfBirth)); end; end; procedure TMainForm.lvStudentsDblClick(Sender: TObject); begin EditCurrentStudent; end; procedure TMainForm.lvStudentsEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); begin AllowEdit := False; end; procedure TMainForm.UpdateStudentView(const AStudent: IStudent); var idx: Integer; begin idx := CurrentCourse.IndexOfStudent(AStudent); if idx > -1 then begin lvStudents.Items[idx].Update; end; end; procedure TMainForm.SetCurrentStudent(const Value: IStudent); var idx: Integer; begin idx := CurrentCourse.IndexOfStudent(Value); if idx = -1 then lvStudents.Selected := nil else lvStudents.Selected := lvStudents.Items[idx] end; procedure TMainForm.UpdateView; begin lvStudents.Items.Count := CurrentCourse.StudentsCount; end; end.
unit StreamUnit; interface {$WARNINGS OFF} uses Windows; const soFromBeginning = 0; soFromCurrent = 1; soFromEnd = 2; type TNotifyEvent = procedure(Sender: TObject) of object; TSeekOrigin = (soBeginning, soCurrent, soEnd); TStream = class(TObject) private function GetPosition: Int64; procedure SetPosition(const Pos: Int64); function GetSize: Int64; procedure SetSize64(const NewSize: Int64); protected procedure SetSize(NewSize: Longint); overload; virtual; procedure SetSize(const NewSize: Int64); overload; virtual; public function Read(var Buffer; Count: Longint): Longint; virtual; abstract; function Write(const Buffer; Count: Longint): Longint; virtual; abstract; function Seek(Offset: Longint; Origin: Word): Longint; overload; virtual; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload; virtual; procedure ReadBuffer(var Buffer; Count: Longint); procedure WriteBuffer(const Buffer; Count: Longint); function CopyFrom(Source: TStream; Count: Int64): Int64; property Position: Int64 read GetPosition write SetPosition; property Size: Int64 read GetSize write SetSize64; end; TCustomMemoryStream = class(TStream) private FMemory: Pointer; FData: Pointer; FSize, FPosition: Longint; protected procedure SetPointer(Ptr: Pointer; Size: Longint); public function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); property Memory: Pointer read FMemory; property Data: Pointer read FData write FData; end; TMemoryStream = class(TCustomMemoryStream) private FCapacity: Longint; procedure SetCapacity(NewCapacity: Longint); protected function Realloc(var NewCapacity: Longint): Pointer; virtual; property Capacity: Longint read FCapacity write SetCapacity; public destructor Destroy; override; procedure Clear; procedure LoadFromStream(Stream: TStream); procedure LoadFromFile(const FileName: string); procedure SetSize(NewSize: Longint); override; function Write(const Buffer; Count: Longint): Longint; override; end; THandleStream = class(TStream) protected FHandle: Integer; procedure SetSize(NewSize: Longint); override; procedure SetSize(const NewSize: Int64); override; public constructor Create(AHandle: Integer); function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; property Handle: Integer read FHandle; end; TFileStream = class(THandleStream) public constructor Create(const FileName: string; Mode: Word); overload; constructor Create(const FileName: string; Mode: Word; Rights: Cardinal); overload; destructor Destroy; override; end; TAlloc = function(Opaque: Pointer; Items, Size: Integer): Pointer; TFree = procedure(Opaque, Block: Pointer); procedure StrToStream(S: TStream; const SS: string); function StreamToStr(S: TStream): string; implementation const fmCreate = $FFFF; fmOpenRead = $0000; fmOpenWrite = $0001; fmOpenReadWrite = $0002; fmShareCompat = $0000; fmShareExclusive = $0010; fmShareDenyWrite = $0020; fmShareDenyRead = $0030; fmShareDenyNone = $0040; function StreamToStr(S: TStream):string; var SizeStr: integer; begin S.Position := 0; SizeStr := S.Size; SetLength(Result, SizeStr); S.Read(Result[1], SizeStr); end; procedure StrToStream(S: TStream; const SS: string); var SizeStr: integer; begin S.Position := 0; SizeStr := Length(SS); S.Write(SS[1], SizeStr); end; function FileOpen(const FileName: string; Mode: LongWord): Integer; const AccessMode: array[0..2] of LongWord = ( GENERIC_READ, GENERIC_WRITE, GENERIC_READ or GENERIC_WRITE); ShareMode: array[0..4] of LongWord = ( 0, 0, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE); begin Result := -1; if ((Mode and 3) <= $0002) and (((Mode and $F0) shr 4) <= $0040) then Result := Integer(CreateFile(PChar(FileName), AccessMode[Mode and 3], ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)); end; procedure FileClose(Handle: Integer); begin CloseHandle(THandle(Handle)); end; function FileCreate(const FileName: string): Integer; begin Result := Integer(CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)); end; function FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer; begin if not ReadFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then Result := -1; end; function FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer; begin if not WriteFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then Result := -1; end; function FileSeek(Handle, Offset, Origin: Integer): Integer; begin Result := SetFilePointer(THandle(Handle), Offset, nil, Origin); end; function zcalloc(opaque: Pointer; items, size: Integer): Pointer; begin GetMem(Result, items * size); end; procedure zcfree(opaque, block: Pointer); begin FreeMem(block); end; procedure _memset(p: Pointer; b: Byte; Count: Integer); cdecl; begin FillChar(p^, Count, b); end; procedure _memcpy(dest, source: Pointer; Count: Integer); cdecl; begin move(source^, dest^, Count); end; function TStream.GetPosition: Int64; begin Result := Seek(0, soCurrent); end; procedure TStream.SetPosition(const Pos: Int64); begin Seek(Pos, soBeginning); end; function TStream.GetSize: Int64; var Pos: Int64; begin Pos := Seek(0, soCurrent); Result := Seek(0, soEnd); Seek(Pos, soBeginning); end; procedure TStream.SetSize(NewSize: Longint); begin SetSize(NewSize); end; procedure TStream.SetSize64(const NewSize: Int64); begin SetSize(NewSize); end; procedure TStream.SetSize(const NewSize: Int64); begin if (NewSize < Low(Longint)) or (NewSize > High(Longint)) then Exit; SetSize(Longint(NewSize)); end; function TStream.Seek(Offset: Longint; Origin: Word): Longint; type TSeek64 = function (const Offset: Int64; Origin: TSeekOrigin): Int64 of object; var Impl: TSeek64; Base: TSeek64; ClassTStream: TClass; begin Impl := Seek; ClassTStream := Self.ClassType; while (ClassTStream <> nil) and (ClassTStream <> TStream) do ClassTStream := ClassTStream.ClassParent; Base := TStream(@ClassTStream).Seek; Result := Seek(Int64(Offset), TSeekOrigin(Origin)); end; function TStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Result := 0; if (Offset < Low(Longint)) or (Offset > High(Longint)) then Exit; Result := Seek(Longint(Offset), Ord(Origin)); end; procedure TStream.ReadBuffer(var Buffer; Count: Longint); begin if (Count <> 0) and (Read(Buffer, Count) <> Count) then Exit; end; procedure TStream.WriteBuffer(const Buffer; Count: Longint); begin if (Count <> 0) and (Write(Buffer, Count) <> Count) then Exit; end; function TStream.CopyFrom(Source: TStream; Count: Int64): Int64; const MaxBufSize = $F000; var BufSize, N: Integer; Buffer: PChar; begin if Count = 0 then begin Source.Position := 0; Count := Source.Size; end; Result := Count; if Count > MaxBufSize then BufSize := MaxBufSize else BufSize := Count; GetMem(Buffer, BufSize); try while Count <> 0 do begin if Count > BufSize then N := BufSize else N := Count; Source.ReadBuffer(Buffer^, N); WriteBuffer(Buffer^, N); Dec(Count, N); end; finally FreeMem(Buffer, BufSize); end; end; constructor THandleStream.Create(AHandle: Integer); begin inherited Create; FHandle := AHandle; end; function THandleStream.Read(var Buffer; Count: Longint): Longint; begin Result := FileRead(FHandle, Buffer, Count); if Result = -1 then Result := 0; end; function THandleStream.Write(const Buffer; Count: Longint): Longint; begin Result := FileWrite(FHandle, Buffer, Count); if Result = -1 then Result := 0; end; function THandleStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin Result := FileSeek(FHandle, Offset, Ord(Origin)); end; procedure THandleStream.SetSize(NewSize: Longint); begin SetSize(Int64(NewSize)); end; procedure THandleStream.SetSize(const NewSize: Int64); begin Seek(NewSize, soBeginning); end; constructor TFileStream.Create(const FileName: string; Mode: Word); begin Create(Filename, Mode, 0); end; constructor TFileStream.Create(const FileName: string; Mode: Word; Rights: Cardinal); begin if Mode = $FFFF then begin inherited Create(FileCreate(FileName)); end else begin inherited Create(FileOpen(FileName, Mode)); end; end; destructor TFileStream.Destroy; begin if FHandle >= 0 then FileClose(FHandle); inherited Destroy; end; procedure TCustomMemoryStream.SetPointer(Ptr: Pointer; Size: Longint); begin FMemory := Ptr; FSize := Size; end; function TCustomMemoryStream.Read(var Buffer; Count: Longint): Longint; begin if (FPosition >= 0) and (Count >= 0) then begin Result := FSize - FPosition; if Result > 0 then begin if Result > Count then Result := Count; Move(Pointer(Longint(FMemory) + FPosition)^, Buffer, Result); Inc(FPosition, Result); Exit; end; end; Result := 0; end; function TCustomMemoryStream.Seek(Offset: Longint; Origin: Word): Longint; begin case Origin of soFromBeginning: FPosition := Offset; soFromCurrent: Inc(FPosition, Offset); soFromEnd: FPosition := FSize + Offset; end; Result := FPosition; end; procedure TCustomMemoryStream.SaveToStream(Stream: TStream); begin if FSize <> 0 then Stream.WriteBuffer(FMemory^, FSize); end; procedure TCustomMemoryStream.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; const MemoryDelta = $2000; destructor TMemoryStream.Destroy; begin Clear; inherited Destroy; end; procedure TMemoryStream.Clear; begin SetCapacity(0); FSize := 0; FPosition := 0; end; procedure TMemoryStream.LoadFromStream(Stream: TStream); var Count: Longint; begin Stream.Position := 0; Count := Stream.Size; SetSize(Count); if Count <> 0 then Stream.ReadBuffer(FMemory^, Count); end; procedure TMemoryStream.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TMemoryStream.SetCapacity(NewCapacity: Longint); begin SetPointer(Realloc(NewCapacity), FSize); FCapacity := NewCapacity; end; procedure TMemoryStream.SetSize(NewSize: Longint); var OldPosition: Longint; begin OldPosition := FPosition; SetCapacity(NewSize); FSize := NewSize; if OldPosition > NewSize then Seek(0, soFromEnd); end; function TMemoryStream.Realloc(var NewCapacity: Longint): Pointer; begin if (NewCapacity > 0) and (NewCapacity <> FSize) then NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1); Result := Memory; if NewCapacity <> FCapacity then begin if NewCapacity = 0 then begin GlobalFreePtr(Memory); Result := nil; end else begin if Capacity = 0 then Result := GlobalAllocPtr(HeapAllocFlags, NewCapacity) else Result := GlobalReallocPtr(Memory, NewCapacity, HeapAllocFlags); end; end; end; function TMemoryStream.Write(const Buffer; Count: Longint): Longint; var Pos: Longint; begin if (FPosition >= 0) and (Count >= 0) then begin Pos := FPosition + Count; if Pos > 0 then begin if Pos > FSize then begin if Pos > FCapacity then SetCapacity(Pos); FSize := Pos; end; System.Move(Buffer, Pointer(Longint(FMemory) + FPosition)^, Count); FPosition := Pos; Result := Count; Exit; end; end; Result := 0; end; end.
unit uDASDDriver; {$I DataAbstract.inc} {$DEFINE MAX_SUPPORT} interface uses Classes, DB, uDAEngine, uDAInterfaces, uROClasses, SDEngine, uDAUtils, SDConsts, uDASQLDirUtils, uROBinaryHelpers, uDAIBInterfaces, uDAEConnection, uDAServerInterfaces, uROStrings, uDASQLMacroProcessor, uDAFields, uDAADOInterfaces, uDAOracleInterfaces, uDACore, variants; const stSQLBaseId = 'SQLBase'; stOracleId = 'Oracle'; stSQLServerId = 'SQLServer'; stSybaseId = 'Sybase'; stDB2Id = 'DB2'; stInformixId = 'Informix'; stODBCId = 'ODBC'; stInterbaseId = 'Interbase'; stFirebirdId = 'Firebird'; stMySQLId = 'MySQL'; stPostgreSQLId= 'PostgreSQL'; stOLEDBId = 'OLEDB'; type TDASDDriverType = (stSQLBase, stOracle, stSQLServer, stSybase, stDB2, stInformix, stODBC, stInterbase, stFirebird, stMySQL, stPostgreSQL, stOLEDB); const // Standard dbExpress driver identifier array (useful for lookups) SDDrivers: array[TDASDDriverType] of string = ( stSQLBaseID, stOracleId, stSQLServerID, stSybaseID, stDB2Id, stInformixId, stODBCId, stInterbaseId, stFirebirdId, stMySQLId, stPostgreSQLId, stOLEDBID); type { TDASDDriver } TDASDDriver = class(TDADriverReference) end; { TDAESDDriver } TDAESDDriver = class(TDAEDriver,IDADriver40 ) protected function GetConnectionClass: TDAEConnectionClass; override; function GetDriverID: string; override; function GetDescription: string; override; procedure GetAuxDrivers(out List: IROStrings); override; procedure GetAuxParams(const AuxDriver: string; out List: IROStrings); override; function GetAvailableDriverOptions: TDAAvailableDriverOptions; override; function GetDefaultConnectionType(const AuxDriver: string): string; override; safecall; function GetProviderDefaultCustomParameters(Provider: string): string; safecall; public end; { ISDConnection For identification purposes. } ISDConnection = interface ['{D24A86BE-F7B1-404E-81AF-C932A8A598AC}'] function GetDriverName: string; function GetDriverType: TDASDDriverType; property DriverName: string read GetDriverName; property DriverType: TDASDDriverType read GetDriverType; end; { TSDConnection } TSDConnection = class(TDAConnectionWrapper) private fSDDatabase: TSDDatabase; fSDSession: tSDSession; protected function GetConnected: Boolean; override; procedure SetConnected(Value: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Database: TSDDatabase read fSDDatabase; property Session: tSDSession read fSDSession; end; { TDAESDConnection } TDAESDConnection = class(TDAEConnection, ISDConnection,IDATestableObject ) private fNativeConnection: TSDConnection; fDriverName: string; fDriverType: TDASDDriverType; protected // TDAEConnection function CreateCustomConnection: TCustomConnection; override; function CreateMacroProcessor: TDASQLMacroProcessor; override; function GetDatasetClass: TDAEDatasetClass; override; function GetStoredProcedureClass: TDAEStoredProcedureClass; override; procedure DoApplyConnectionString(aConnStrParser: TDAConnectionStringParser; aConnectionObject: TCustomConnection); override; function DoBeginTransaction: integer; override; procedure DoCommitTransaction; override; procedure DoRollbackTransaction; override; function DoGetInTransaction: boolean; override; function GetUserID: string; override; safecall; procedure SetUserID(const Value: string); override; safecall; function GetPassword: string; override; safecall; procedure SetPassword(const Value: string); override; safecall; procedure DoGetTableNames(out List: IROStrings); override; procedure DoGetStoredProcedureNames(out List: IROStrings); override; procedure DoGetTableFields(const aTableName: string; out Fields: TDAFieldCollection); override; function GetDriverName: string; function GetDriverType: TDASDDriverType; function GetSPSelectSyntax(HasArguments: Boolean): String; override; safecall; public end; { TDAESDQuery } TDAESDQuery = class(TDAEDataset, IDAMustSetParams) private protected function CreateDataset(aConnection: TDAEConnection): TDataset; override; procedure ClearParams; override; function DoExecute: integer; override; function DoGetSQL: string; override; procedure DoSetSQL(const Value: string); override; procedure DoPrepare(Value: boolean); override; procedure RefreshParams; override; procedure SetParamValues(AParams: TDAParamCollection); override;{$IFNDEF FPC_SAFECALL_BUG}safecall;{$ENDIF} procedure GetParamValues(AParams: TDAParamCollection); override;{$IFNDEF FPC_SAFECALL_BUG}safecall;{$ENDIF} public end; { TDASDStoredProcedure } TDASDStoredProcedure = class(TDAEStoredProcedure{, IDAMustSetParams}) protected function CreateDataset(aConnection: TDAEConnection): TDataset; override; procedure RefreshParams; override; function GetStoredProcedureName: string; override; procedure SetStoredProcedureName(const Name: string); override; function Execute: integer; override; procedure SetParamValues(AParams: TDAParamCollection); override;{$IFNDEF FPC_SAFECALL_BUG}safecall;{$ENDIF} procedure GetParamValues(AParams: TDAParamCollection); override;{$IFNDEF FPC_SAFECALL_BUG}safecall;{$ENDIF} end; procedure Register; function SDDriverIdToSDDriverType(const anID: string): TDASDDriverType; function GetDriverObject: IDADriver; stdcall; implementation uses SysUtils, INIFiles, uDADriverManager, uDARes, SqlTimSt; var _driver: TDAEDriver = nil; procedure Register; begin RegisterComponents(DAPalettePageName, [TDASDDriver]); end; {$IFDEF DataAbstract_SchemaModelerOnly} {$INCLUDE ..\DataAbstract_SchemaModelerOnly.inc} {$ENDIF DataAbstract_SchemaModelerOnly} function GetDriverObject: IDADriver; begin {$IFDEF DataAbstract_SchemaModelerOnly} if not RunningInSchemaModeler then begin result := nil; exit; end; {$ENDIF} if (_driver = nil) then _driver := TDAESDDriver.Create(nil); result := _driver; end; function SDDriverIdToSDDriverType(const anID: string): TDASDDriverType; var x: TDASDDriverType; begin result := stSQLBase; for x := Low(TDASDDriverType) to High(TDASDDriverType) do if SameText(SDDrivers[x], anID) then begin result := x; Exit; end; end; { TSDConnection } constructor TSDConnection.Create(AOwner: TComponent); begin inherited; fSDSession := tSDSession.Create(NIL); fSDSession.AutoSessionName := True; fSDDatabase := TSDDatabase.Create(NIL); fSDDatabase.SessionName := fSDSession.SessionName; end; destructor TSDConnection.destroy; begin inherited destroy; If Assigned(fSDDatabase) then fSDDatabase.Free; If Assigned(fSDSession) then fSDSession.Free; end; function TSDConnection.GetConnected: Boolean; begin result := fSDDatabase.Connected; end; procedure TSDConnection.SetConnected(Value: Boolean); begin Try fSDDatabase.Connected := Value; Except raise EDADriverException.Create(Trim(TuDSQLDirUtils.WindowsExceptMess)); End; end; { TDAESDConnection } procedure TDAESDConnection.DoApplyConnectionString( aConnStrParser: TDAConnectionStringParser; aConnectionObject: TCustomConnection); var lsAliasName: string; lsSQLLibrary: String; lParams: tStringList; I: Integer; begin inherited; with aConnStrParser do begin lParams := tStringList.Create; for I := 0 to aConnStrParser.AuxParamsCount - 1 do begin if Uppercase(aConnStrParser.AuxParamNames[i]) = 'SQLLIBRARY' then lsSQLLibrary := aConnStrParser.AuxParams[AuxParamNames[i]] else lParams.Add(AuxParamNames[i] + '=' + aConnStrParser.AuxParams[AuxParamNames[i]]); end; with TSDConnection(aConnectionObject).Database do begin if AuxDriver = '' then raise EDADriverException.Create('No aux driver specified for SD connection'); fDriverType := SDDriverIdToSDDriverType(AuxDriver); lsAliasName := Self.fNativeConnection.fSDDatabase.DatabaseName; TuDSQLDirUtils.SetupSDDatabase(TSDConnection(aConnectionObject).Database, Server, Database, lsAliasName, TuDSQLDirUtils.GetServerTypeAsInteger(AuxDriver), Userid, Password, lParams, lsSQLLibrary); end; lParams.Free; end; end; function TDAESDConnection.DoBeginTransaction: integer; begin result := -1; fNativeConnection.fSDdatabase.StartTransaction; end; procedure TDAESDConnection.DoCommitTransaction; begin fNativeConnection.fSDdatabase.Commit; end; function TDAESDConnection.CreateCustomConnection: TCustomConnection; begin fNativeConnection := TSDConnection.Create(nil); fNativeConnection.fSDdatabase.LoginPrompt := FALSE; fNativeConnection.fSDdatabase.DatabaseName := copy(NewStrippedGuidAsString, 1, 30); result := fNativeConnection; end; function TDAESDConnection.GetDatasetClass: TDAEDatasetClass; begin result := TDAESDQuery; end; function TDAESDConnection.GetStoredProcedureClass: TDAEStoredProcedureClass; begin result := TDASDStoredProcedure; end; procedure TDAESDConnection.DoGetStoredProcedureNames(out List: IROStrings); begin List := TROStrings.Create; fNativeConnection.Database.GetStoredProcNames(List.Strings); end; procedure TDAESDConnection.DoGetTableNames(out List: IROStrings); Var I: Integer; lsTableName: String; begin List := TROStrings.Create; fNativeConnection.Database.GetTableNames('', False,List.Strings); For I := 0 to List.Strings.Count - 1 do begin If pos(Userid + '.', List.Strings[i]) > 0 then begin lsTableName := copy(List.Strings[i], pos('.', List.Strings[i]) + 1, Length(List.Strings[i])); List.Strings[i] := lsTableName; end; end; end; procedure TDAESDConnection.DoGetTableFields(const aTableName: string; out Fields: TDAFieldCollection); begin inherited DoGetTableFields(QuoteIdentifierIfNeeded(aTableName), Fields); end; procedure TDAESDConnection.DoRollbackTransaction; begin fNativeConnection.fSDdatabase.Rollback; end; function TDAESDConnection.DoGetInTransaction: boolean; begin Result := fNativeConnection.fSDdatabase.InTransaction; end; function TDAESDConnection.GetDriverName: string; begin result := fDriverName end; function TDAESDConnection.GetDriverType: TDASDDriverType; begin result := fDriverType end; function TDAESDConnection.CreateMacroProcessor: TDASQLMacroProcessor; begin result := nil; case fDriverType of stSQLServer, stOLEDB: result := MSSQL_CreateMacroProcessor; stFirebird, stInterbase: result := IB_CreateMacroProcessor((fDriverType= stFirebird)); stOracle: result := Oracle_CreateMacroProcessor; else result := TDASQLMacroProcessor.Create(); end; end; function TDAESDConnection.GetPassword: string; begin Result := fNativeConnection.Database.Params.Values[szPASSWORD]; end; function TDAESDConnection.GetUserID: string; begin Result := fNativeConnection.Database.Params.Values[szUSERNAME]; end; procedure TDAESDConnection.SetPassword(const Value: string); begin fNativeConnection.Database.Params.Values[szPASSWORD] := Value; end; procedure TDAESDConnection.SetUserID(const Value: string); begin fNativeConnection.Database.Params.Values[szUSERNAME] := Value; end; function TDAESDConnection.GetSPSelectSyntax( HasArguments: Boolean): String; begin case fDriverType of stInterbase: if HasArguments then Result := 'SELECT * FROM {0}({1})' else result := 'SELECT * FROM {0}'; stOracle: if HasArguments then Result := 'CALL {0}({1})' else result := 'CALL {0}'; else Result := 'EXEC {0} {1}'; end; end; { TDAESDDriver } function TDAESDDriver.GetAvailableDriverOptions: TDAAvailableDriverOptions; begin result := [doAuxDriver, doServerName, doDatabaseName, doLogin, doCustom]; end; function TDAESDDriver.GetDefaultConnectionType( const AuxDriver: string): string; begin Result := inherited GetDefaultConnectionType(AuxDriver); end; function TDAESDDriver.GetProviderDefaultCustomParameters(Provider: string): string; begin Result := ''; end; function TDAESDDriver.GetConnectionClass: TDAEConnectionClass; begin result := TDAESDConnection; end; function TDAESDDriver.GetDescription: string; begin result := 'SQLDirect Driver'; end; function TDAESDDriver.GetDriverID: string; begin result := 'SD'; end; procedure TDAESDDriver.GetAuxDrivers(out List: IROStrings); var x: TDASDDriverType; begin List := NewROStrings; for x := Low(TDASDDriverType) to High(TDASDDriverType) do List.Add(SDDrivers[x]); end; procedure TDAESDDriver.GetAuxParams(const AuxDriver: string; out List: IROStrings); begin inherited; List.Add('SQLLibrary='); end; { TDAESDQuery } function TDAESDQuery.CreateDataset(aConnection: TDAEConnection): TDataset; begin result := TSDQuery.Create(nil); TSDQuery(result).DatabaseName := TDAESDConnection(aConnection).fNativeConnection.Database.DatabaseName; TSDQuery(result).SessionName := TDAESDConnection(aConnection).fNativeConnection.Session.SessionName; end; function GetBlobValue(const val: Variant): string; var lsize: integer; p: Pointer; begin if VarType(val) = 8209 then begin lSize := VarArrayHighBound(val, 1)-VarArrayLowBound(val, 1)+1; p := VarArrayLock(val); try setlength(REsult, lSize); move(p^, Result[1], lSize); finally VarArrayUnlock(val); end; end else if vartype(val) = varEmpty then result := '' else result := val; end; function TDAESDQuery.DoExecute: integer; begin Try TSDQuery(Dataset).ExecSQL; result := TSDQuery(Dataset).RowsAffected; Except raise EDADriverException.Create(TuDSQLDirUtils.WindowsExceptMess + '-' + TSDStoredProc(Dataset).StoredProcName); End; end; procedure TDAESDQuery.ClearParams; begin inherited; TSDQuery(Dataset).Params.Clear; end; function TDAESDQuery.DoGetSQL: string; begin result := TSDQuery(Dataset).SQL.Text; end; procedure TDAESDQuery.DoPrepare(Value: boolean); begin TSDQuery(Dataset).Prepared := Value; end; procedure TDAESDQuery.RefreshParams; begin inherited; end; procedure TDAESDQuery.SetParamValues(AParams: TDAParamCollection); var Counter : Integer; P : TDAParam; O : TParam; begin SetParamValuesStd(AParams,TSDQuery(Dataset).Params); // BG 30/11/2015 - correct blob parameters as the default VariantToAnsiString loses data in binary for Counter := 0 to AParams.Count - 1 do begin P := AParams[Counter]; O := FindParameter(TSDQuery(DataSet).Params, P.Name); if P.DataType <> datBlob then begin continue; end; if (P.ParamType in [daptOutput, daptResult]) then begin continue; end; if VarIsEmpty(P.Value) or VarIsNull(P.Value) then begin O.Value := Null; end else begin O.Value := P.Value; // don't do any conversion - casting using VariantToAnsiString loses data end; end; end; procedure TDAESDQuery.GetParamValues(AParams: TDAParamCollection); begin GetParamValuesStd(AParams,TSDQuery(Dataset).Params); end; procedure TDAESDQuery.DoSetSQL(const Value: string); begin TSDQuery(Dataset).SQL.Text := Value; end; { TDASDStoredProcedure } function TDASDStoredProcedure.CreateDataset(aConnection: TDAEConnection): TDataset; begin result := TSDStoredProc.Create(nil); TSDStoredProc(result).DatabaseName := TDAESDConnection(aConnection).fNativeConnection.Database.DatabaseName; TSDStoredProc(result).SessionName := TDAESDConnection(aConnection).fNativeConnection.Session.SessionName; end; function TDASDStoredProcedure.Execute: integer; var i: integer; _params: TDAParamCollection; begin Try _params := GetParams; With TSDStoredProc(Dataset) do begin SetParamValues(_params) ; ExecProc; result := -1; for i := 0 to ParamCount - 1 do if (Params[i].ParamType in [ptOutput, ptInputOutput, ptResult]) then _params[i].Value := Params[i].Value; end; Except raise EDADriverException.Create(TuDSQLDirUtils.WindowsExceptMess + '-' + TSDStoredProc(Dataset).StoredProcName); End; end; procedure TDASDStoredProcedure.SetParamValues(AParams: TDAParamCollection); var i: integer; begin SetParamValuesStd(AParams, TSDStoredProc(Dataset).Params); end; procedure TDASDStoredProcedure.GetParamValues(AParams: TDAParamCollection); var i: integer; begin GetParamValuesStd(AParams, TSDStoredProc(Dataset).Params); end; function TDASDStoredProcedure.GetStoredProcedureName: string; begin result := TSDStoredProc(Dataset).StoredProcName; end; procedure TDASDStoredProcedure.SetStoredProcedureName( const Name: string); begin TSDStoredProc(Dataset).StoredProcName := Name; end; procedure TDASDStoredProcedure.RefreshParams; var FParams: TParams; FDAParam: TDAParam; FDAParams: TDAParamCollection; i: integer; FsParamName: String; begin TSDStoredProc(Dataset).Prepare; FParams := TSDStoredProc(Dataset).Params; FDAParams := GetParams; FDAParams.Clear; for i := 0 to (FParams.Count - 1) do begin FDAParam := FDAParams.Add; FsParamName := FParams[i].Name; if Pos('@', FsParamName) > 0 then System.Delete(FsParamName, Pos('@', FsParamName), 1); FDAParam.Name := FsParamName; FDAParam.DataType := VCLTypeToDAType(FParams[i].DataType); FDAParam.ParamType := TDAParamType(FParams[i].ParamType); FDAParam.Size := FParams[i].Size; end; end; exports GetDriverObject name func_GetDriverObject; initialization _driver := nil; RegisterDriverProc(GetDriverObject); finalization UnregisterDriverProc(GetDriverObject); FreeAndNIL(_driver); end.
unit uAutoNewtonDivider; {$I ..\Include\IntXLib.inc} interface uses uNewtonHelper, uMultiplyManager, uIMultiplier, uIDivider, uConstants, uEnums, uDividerBase, uDigitHelper, uDigitOpHelper, uIntXLibTypes; type /// <summary> /// Divides using Newton approximation approach. /// </summary> TAutoNewtonDivider = class sealed(TDividerBase) private /// <summary> /// divider to use if Newton approach is unapplicable. /// </summary> F_classicDivider: IIDivider; public /// <summary> /// Creates new <see cref="AutoNewtonDivider" /> instance. /// </summary> /// <param name="classicDivider">Divider to use if Newton approach is unapplicable.</param> constructor Create(classicDivider: IIDivider); /// <summary> /// Destructor. /// </summary> destructor Destroy(); override; /// <summary> /// Returns true if it's better to use classic algorithm for given big integers. /// </summary> /// <param name="length1">First big integer length.</param> /// <param name="length2">Second big integer length.</param> /// <returns>True if classic algorithm is better.</returns> class function IsClassicAlgorithmNeeded(length1: UInt32; length2: UInt32) : Boolean; static; inline; /// <summary> /// Divides two big integers. /// Also modifies <paramref name="digits1" /> and <paramref name="length1"/> (it will contain remainder). /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="digitsBuffer1">Buffer for first big integer digits. May also contain remainder. Can be null - in this case it's created if necessary.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="digitsBuffer2">Buffer for second big integer digits. Only temporarily used. Can be null - in this case it's created if necessary.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <param name="resultFlags">Which operation results to return.</param> /// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param> /// <returns>Resulting big integer length.</returns> function DivMod(digits1: TIntXLibUInt32Array; digitsBuffer1: TIntXLibUInt32Array; var length1: UInt32; digits2: TIntXLibUInt32Array; digitsBuffer2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array; resultFlags: TDivModResultFlags; cmpResult: Integer): UInt32; overload; override; /// <summary> /// Divides two big integers. /// Also modifies <paramref name="digitsPtr1" /> and <paramref name="length1"/> (it will contain remainder). /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="digitsBufferPtr1">Buffer for first big integer digits. May also contain remainder.</param> /// <param name="length1">First big integer length.</param> /// <param name="digitsPtr2">Second big integer digits.</param> /// <param name="digitsBufferPtr2">Buffer for second big integer digits. Only temporarily used.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsResPtr">Resulting big integer digits.</param> /// <param name="resultFlags">Which operation results to return.</param> /// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param> /// <returns>Resulting big integer length.</returns> function DivMod(digitsPtr1: PCardinal; digitsBufferPtr1: PCardinal; var length1: UInt32; digitsPtr2: PCardinal; digitsBufferPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal; resultFlags: TDivModResultFlags; cmpResult: Integer): UInt32; overload; override; end; implementation constructor TAutoNewtonDivider.Create(classicDivider: IIDivider); begin inherited Create; F_classicDivider := classicDivider; end; destructor TAutoNewtonDivider.Destroy(); begin F_classicDivider := Nil; inherited Destroy; end; class function TAutoNewtonDivider.IsClassicAlgorithmNeeded(length1: UInt32; length2: UInt32): Boolean; begin result := ((length1 < TConstants.AutoNewtonLengthLowerBound) or (length2 < TConstants.AutoNewtonLengthLowerBound) or (length1 > TConstants.AutoNewtonLengthUpperBound) or (length2 > TConstants.AutoNewtonLengthUpperBound)); end; function TAutoNewtonDivider.DivMod(digits1: TIntXLibUInt32Array; digitsBuffer1: TIntXLibUInt32Array; var length1: UInt32; digits2: TIntXLibUInt32Array; digitsBuffer2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array; resultFlags: TDivModResultFlags; cmpResult: Integer): UInt32; var digitsPtr1, digitsBufferPtr1, digitsPtr2, digitsBufferPtr2, digitsResPtr, tempA, tempB: PCardinal; begin // Maybe immediately use classic algorithm here if (IsClassicAlgorithmNeeded(length1, length2)) then begin result := F_classicDivider.DivMod(digits1, digitsBuffer1, length1, digits2, digitsBuffer2, length2, digitsRes, resultFlags, cmpResult); Exit; end; // Create some buffers if necessary if (digitsBuffer1 = Nil) then begin SetLength(digitsBuffer1, length1 + 1); end; digitsPtr1 := @digits1[0]; digitsBufferPtr1 := @digitsBuffer1[0]; digitsPtr2 := @digits2[0]; if digitsBuffer2 <> Nil then digitsBufferPtr2 := @digitsBuffer2[0] else begin digitsBufferPtr2 := @digits1[0]; end; if digitsRes <> Nil then digitsResPtr := @digitsRes[0] else begin digitsResPtr := @digits1[0]; end; if digitsBufferPtr2 = digitsPtr1 then tempA := Nil else begin tempA := digitsBufferPtr2; end; if digitsResPtr = digitsPtr1 then tempB := Nil else begin tempB := digitsResPtr; end; result := DivMod(digitsPtr1, digitsBufferPtr1, length1, digitsPtr2, tempA, length2, tempB, resultFlags, cmpResult); Exit; end; function TAutoNewtonDivider.DivMod(digitsPtr1: PCardinal; digitsBufferPtr1: PCardinal; var length1: UInt32; digitsPtr2: PCardinal; digitsBufferPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal; resultFlags: TDivModResultFlags; cmpResult: Integer): UInt32; var resultLength, int2OppositeLength, quotLength, shiftOffset, highestLostBit, quotDivLength: UInt32; int2OppositeRightShift: UInt64; int2OppositeDigits, quotDigits, quotDivDigits: TIntXLibUInt32Array; multiplier: IIMultiplier; oppositePtr, quotPtr, quotDivPtr: PCardinal; shiftCount, cmpRes: Integer; begin // Maybe immediately use classic algorithm here if (IsClassicAlgorithmNeeded(length1, length2)) then begin result := F_classicDivider.DivMod(digitsPtr1, digitsBufferPtr1, length1, digitsPtr2, digitsBufferPtr2, length2, digitsResPtr, resultFlags, cmpResult); Exit; end; // Call base (for special cases) resultLength := inherited DivMod(digitsPtr1, digitsBufferPtr1, length1, digitsPtr2, digitsBufferPtr2, length2, digitsResPtr, resultFlags, cmpResult); if (resultLength <> TConstants.MaxUInt32Value) then begin result := resultLength; Exit; end; // First retrieve opposite for the divider int2OppositeDigits := TNewtonHelper.GetIntegerOpposite(digitsPtr2, length2, length1, digitsBufferPtr1, int2OppositeLength, int2OppositeRightShift); // We will need to multiply it by divident now to receive quotient. // Prepare digits for multiply result SetLength(quotDigits, length1 + int2OppositeLength); multiplier := TMultiplyManager.GetCurrentMultiplier(); // Fix some arrays oppositePtr := @int2OppositeDigits[0]; quotPtr := @quotDigits[0]; // Multiply quotLength := multiplier.Multiply(oppositePtr, int2OppositeLength, digitsPtr1, length1, quotPtr); // Calculate shift shiftOffset := UInt32((int2OppositeRightShift div TConstants.DigitBitCount)); shiftCount := Integer(int2OppositeRightShift mod TConstants.DigitBitCount); // Get the very first bit of the shifted part if (shiftCount = 0) then begin highestLostBit := quotPtr[shiftOffset - 1] shr 31; end else begin highestLostBit := quotPtr[shiftOffset] shr (shiftCount - 1) and UInt32(1); end; // After this result must be shifted to the right - this is required quotLength := TDigitOpHelper.ShiftRight(quotPtr + shiftOffset, quotLength - shiftOffset, quotPtr, shiftCount, false); // Maybe quotient must be corrected if (highestLostBit = UInt32(1)) then begin quotLength := TDigitOpHelper.Add(quotPtr, quotLength, @highestLostBit, UInt32(1), quotPtr); end; // Check quotient - finally it might be too big. // For this we must multiply quotient by divider SetLength(quotDivDigits, quotLength + length2); quotDivPtr := @quotDivDigits[0]; quotDivLength := multiplier.Multiply(quotPtr, quotLength, digitsPtr2, length2, quotDivPtr); cmpRes := TDigitOpHelper.Cmp(quotDivPtr, quotDivLength, digitsPtr1, length1); if (cmpRes > 0) then begin highestLostBit := 1; quotLength := TDigitOpHelper.Sub(quotPtr, quotLength, @highestLostBit, UInt32(1), quotPtr); quotDivLength := TDigitOpHelper.Sub(quotDivPtr, quotDivLength, digitsPtr2, length2, quotDivPtr); end; // Now everything is ready and prepared to return results // First maybe fill remainder if ((Ord(resultFlags) and Ord(TDivModResultFlags.dmrfMod)) <> 0) then begin length1 := TDigitOpHelper.Sub(digitsPtr1, length1, quotDivPtr, quotDivLength, digitsBufferPtr1); end; // And finally fill quotient if ((Ord(resultFlags) and Ord(TDivModResultFlags.dmrfDiv)) <> 0) then begin TDigitHelper.DigitsBlockCopy(quotPtr, digitsResPtr, quotLength); end else begin quotLength := 0; end; result := quotLength; end; end.
(* Weak enemy with simple AI, no pathfinding will attack and drain health *) unit hyena; {$mode objfpc}{$H+} interface uses SysUtils, map; (* Create a hyena *) procedure createHyena(uniqueid, npcx, npcy: smallint); (* check to see if entity can move to a square *) function checkSpaceFree(x, y: smallint): boolean; (* Take a turn *) procedure takeTurn(id, spx, spy: smallint); (* Move in a random direction *) procedure wander(id, spx, spy: smallint); (* Chase the player *) procedure chasePlayer(id, spx, spy: smallint); (* Check if player is next to NPC *) function isNextToPlayer(spx, spy: smallint): boolean; (* Combat *) procedure combat(idOwner, idTarget: smallint); implementation uses entities, globalutils, ui, los; function checkSpaceFree(x, y: smallint): boolean; begin (* Set boolean to false *) Result := False; (* Check that not blocked by map tiles *) if (map.canMove(x, y) = True) and (* Check not occupied by player *) (x <> entities.entityList[0].posX) and (y <> entities.entityList[0].posY) and (* Check that not occupied by another entity *) (map.isOccupied(x, y) = False) then Result := True; end; procedure takeTurn(id, spx, spy: smallint); begin (* Can the NPC see the player *) if (los.inView(spx, spy, entities.entityList[0].posX, entities.entityList[0].posY, entities.entityList[id].visionRange) = True) then begin (* Reset move counter *) entities.entityList[id].moveCount := entities.entityList[id].trackingTurns; (* If NPC has low health... *) if (entities.entityList[id].currentHP < 2) then begin if (entities.entityList[id].abilityTriggered = False) and (isNextToPlayer(spx, spy) = True) then begin ui.bufferMessage('The hyena howls'); entities.entityList[id].abilityTriggered := True; entities.entityList[id].attack := entities.entityList[id].attack + 2; entities.entityList[id].defense := entities.entityList[id].defense - 2; end else if (entities.entityList[id].abilityTriggered = True) and (isNextToPlayer(spx, spy) = True) then begin ui.bufferMessage('The hyena snarls'); combat(id, 0); end else chasePlayer(id, spx, spy); end else chasePlayer(id, spx, spy); end (* Cannot see the player *) else if (entities.entityList[id].moveCount > 0) then begin (* The NPC is still in pursuit *) Dec(entities.entityList[id].moveCount); chasePlayer(id, spx, spy); end else wander(id, spx, spy); end; procedure createHyena(uniqueid, npcx, npcy: smallint); begin // Add a Hyena to the list of creatures entities.listLength := length(entities.entityList); SetLength(entities.entityList, entities.listLength + 1); with entities.entityList[entities.listLength] do begin npcID := uniqueid; race := 'blood hyena'; description := 'a drooling, blood hyena'; glyph := 'h'; maxHP := randomRange(entityList[0].maxHP - 15, entityList[0].maxHP - 13); currentHP := maxHP; attack := randomRange(entityList[0].attack - 1, entityList[0].attack + 2); defense := randomRange(entityList[0].defense, entityList[0].attack - 3); weaponDice := 0; weaponAdds := 0; xpReward := maxHP; visionRange := 5; NPCsize := 2; trackingTurns := 3; moveCount := 0; targetX := 0; targetY := 0; inView := False; blocks := False; discovered := False; weaponEquipped := False; armourEquipped := False; isDead := False; abilityTriggered := False; stsDrunk := False; stsPoison := False; tmrDrunk := 0; tmrPoison := 0; posX := npcx; posY := npcy; end; (* Occupy tile *) map.occupy(npcx, npcy); end; procedure wander(id, spx, spy: smallint); var direction, attempts, testx, testy: smallint; begin attempts := 0; repeat // Reset values after each failed loop so they don't keep dec/incrementing testx := spx; testy := spy; direction := random(6); // limit the number of attempts to move so the game doesn't hang if NPC is stuck Inc(attempts); if attempts > 10 then begin entities.moveNPC(id, spx, spy); exit; end; case direction of 0: Dec(testy); 1: Inc(testy); 2: Dec(testx); 3: Inc(testx); 4: testx := spx; 5: testy := spy; end until (map.canMove(testx, testy) = True) and (map.isOccupied(testx, testy) = False); entities.moveNPC(id, testx, testy); end; procedure chasePlayer(id, spx, spy: smallint); var newX, newY: smallint; begin newX := 0; newY := 0; (* Get new coordinates to chase the player *) if (spx > entities.entityList[0].posX) and (spy > entities.entityList[0].posY) then begin newX := spx - 1; newY := spy - 1; end else if (spx < entities.entityList[0].posX) and (spy < entities.entityList[0].posY) then begin newX := spx + 1; newY := spy + 1; end else if (spx < entities.entityList[0].posX) then begin newX := spx + 1; newY := spy; end else if (spx > entities.entityList[0].posX) then begin newX := spx - 1; newY := spy; end else if (spy < entities.entityList[0].posY) then begin newX := spx; newY := spy + 1; end else if (spy > entities.entityList[0].posY) then begin newX := spx; newY := spy - 1; end; (* New coordinates set. Check if they are walkable *) if (map.canMove(newX, newY) = True) then begin (* Do they contain the player *) if (map.hasPlayer(newX, newY) = True) then begin (* Remain on original tile and attack *) entities.moveNPC(id, spx, spy); combat(id, 0); end (* Else if tile does not contain player, check for another entity *) else if (map.isOccupied(newX, newY) = True) then begin if (entities.entityList[entities.getCreatureID(newX, newY)].NPCsize < entities.entityList[id].NPCsize) then begin combat(id, entities.getCreatureID(newX, newY)); ui.bufferMessage('Hyena attacks ' + entities.getCreatureName(newX, newY)); end else ui.bufferMessage('Hyena bumps into a ' + entities.getCreatureName(newX, newY)); (* Remain on original tile *) entities.moveNPC(id, spx, spy); end (* if map is unoccupied, move to that tile *) else if (map.isOccupied(newX, newY) = False) then entities.moveNPC(id, newX, newY); end // wall hugging code else if (spx < entities.entityList[0].posX) and (checkSpaceFree(spx + 1, spy) = True) then entities.moveNPC(id, spx + 1, spy) else if (spx > entities.entityList[0].posX) and (checkSpaceFree(spx - 1, spy) = True) then entities.moveNPC(id, spx - 1, spy) else if (spy < entities.entityList[0].posY) and (checkSpaceFree(spx, spy + 1) = True) then entities.moveNPC(id, spx, spy + 1) else if (spy > entities.entityList[0].posY) and (checkSpaceFree(spx, spy - 1) = True) then entities.moveNPC(id, spx, spy - 1) else wander(id, spx, spy); end; function isNextToPlayer(spx, spy: smallint): boolean; begin Result := False; if (map.hasPlayer(spx, spy - 1) = True) then // NORTH Result := True; if (map.hasPlayer(spx + 1, spy - 1) = True) then // NORTH EAST Result := True; if (map.hasPlayer(spx + 1, spy) = True) then // EAST Result := True; if (map.hasPlayer(spx + 1, spy + 1) = True) then // SOUTH EAST Result := True; if (map.hasPlayer(spx, spy + 1) = True) then // SOUTH Result := True; if (map.hasPlayer(spx - 1, spy + 1) = True) then // SOUTH WEST Result := True; if (map.hasPlayer(spx - 1, spy) = True) then // WEST Result := True; if (map.hasPlayer(spx - 1, spy - 1) = True) then // NORTH WEST Result := True; end; procedure combat(idOwner, idTarget: smallint); var damageAmount: smallint; begin damageAmount := globalutils.randomRange(1, entities.entityList[idOwner].attack) - entities.entityList[idTarget].defense; if (damageAmount > 0) then begin entities.entityList[idTarget].currentHP := (entities.entityList[idTarget].currentHP - damageAmount); if (entities.entityList[idTarget].currentHP < 1) then begin if (idTarget = 0) then begin if (killer = 'empty') then killer := entityList[idOwner].race; exit; end else begin ui.displayMessage('The hyena kills the ' + entities.entityList[idTarget].race); entities.killEntity(idTarget); (* The Hyena levels up *) Inc(entities.entityList[idOwner].xpReward, 2); Inc(entities.entityList[idOwner].attack, 2); ui.bufferMessage('The hyena appears to grow stronger'); exit; end; end else begin // if attack causes slight damage if (damageAmount = 1) then begin if (idTarget = 0) then // if target is the player begin ui.writeBufferedMessages; ui.displayMessage('The hyena slightly wounds you'); end else begin ui.writeBufferedMessages; ui.displayMessage('The hyena slightly wounds the ' + entities.entityList[idTarget].race); end; end else // if attack causes more damage begin if (idTarget = 0) then // if target is the player begin ui.bufferMessage('The hyena bites you, inflicting ' + IntToStr(damageAmount) + ' damage'); end else ui.bufferMessage('The hyena bites the ' + entities.entityList[idTarget].race); end; end; end else ui.bufferMessage('The hyena attacks but misses'); end; end.
unit ViewPessoaCliente; {$mode objfpc}{$H+} interface uses HTTPDefs, BrookRESTActions, BrookUtils; type TViewPessoaClienteOptions = class(TBrookOptionsAction) end; TViewPessoaClienteRetrieve = class(TBrookRetrieveAction) procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override; end; TViewPessoaClienteShow = class(TBrookShowAction) end; TViewPessoaClienteCreate = class(TBrookCreateAction) end; TViewPessoaClienteUpdate = class(TBrookUpdateAction) end; TViewPessoaClienteDestroy = class(TBrookDestroyAction) end; implementation procedure TViewPessoaClienteRetrieve.Request(ARequest: TRequest; AResponse: TResponse); var Campo: String; Filtro: String; begin Campo := Values['campo'].AsString; Filtro := Values['filtro'].AsString; Values.Clear; Table.Where(Campo + ' LIKE "%' + Filtro + '%"'); inherited Request(ARequest, AResponse); end; initialization TViewPessoaClienteOptions.Register('view_pessoa_cliente', '/view_pessoa_cliente'); TViewPessoaClienteRetrieve.Register('view_pessoa_cliente', '/view_pessoa_cliente/:campo/:filtro/'); TViewPessoaClienteShow.Register('view_pessoa_cliente', '/view_pessoa_cliente/:id'); TViewPessoaClienteCreate.Register('view_pessoa_cliente', '/view_pessoa_cliente'); TViewPessoaClienteUpdate.Register('view_pessoa_cliente', '/view_pessoa_cliente/:id'); TViewPessoaClienteDestroy.Register('view_pessoa_cliente', '/view_pessoa_cliente/:id'); end.
unit DUnitXMLParser; interface uses System.SysUtils, System.Variants, Xml.xmldom, Xml.XMLIntf, Xml.Win.msxmldom, Xml.XMLDoc, TestStructureUnit, RTTI, System.Generics.Collections; type TTestsXMLParser = class private FXMLFileName: string; FXMLDocument: IXMLDocument; function LoadXML: Boolean; function LoadSuite(ASuiteNode: IXMLNode): Boolean; procedure LoadTestCase(ASuiteName: string; ASuiteClassName: string; ATestCaseNode: IXMLNode); procedure LoadTestData(ATestNode: IXMLNode; out AData: TDataArray); public constructor Create(aXMLFileName: string); procedure RunXMLParsing(var aTestCaseList: TTestCaseDictionary; var aSuiteList: TSuiteList); end; procedure LoadTestsFromXML(aXMLFileName: string; var aSuiteList: TSuiteList; var aTestCaseList: TTestCaseDictionary); implementation constructor TTestsXMLParser.Create(aXMLFileName: string); begin FXMLDocument := TXMLDocument.Create(nil); FXMLFileName := aXMLFileName; end; function TTestsXMLParser.LoadSuite(ASuiteNode: IXMLNode): Boolean; var SuiteRec: TSuiteRec; i: Integer; begin if ASuiteNode.NodeName = 'TestSuite' then begin SuiteRec.SuiteName := ASuiteNode.Attributes['Name']; SuiteRec.SuiteClassName := ASuiteNode.Attributes['ClassName']; SuiteList.Add(SuiteRec); for i := 0 to ASuiteNode.ChildNodes.Count - 1 do if ASuiteNode.ChildNodes[i].NodeName = 'TestCase' then LoadTestCase(SuiteRec.SuiteName, SuiteRec.SuiteClassName, ASuiteNode.ChildNodes[i]); Result := True; end else Result := False; end; procedure TTestsXMLParser.LoadTestData(ATestNode: IXMLNode; out AData: TDataArray); var i, j: Integer; a: TDataArray; begin if ATestNode.AttributeNodes.Count > 0 then begin SetLength(AData, ATestNode.AttributeNodes.Count); for i := 0 to ATestNode.AttributeNodes.Count - 1 do begin AData[i].DataType := dtString; AData[i].ValueName := ATestNode.AttributeNodes[i].NodeName; AData[i].Value := ATestNode.AttributeNodes[i].NodeValue; end end else begin SetLength(AData, ATestNode.ChildNodes.Count); for i := 0 to ATestNode.ChildNodes.Count - 1 do begin AData[i].DataType := dtData; AData[i].ValueName := ATestNode.ChildNodes[i].NodeName; LoadTestData(ATestNode.ChildNodes[i], a); SetLength(AData[i].Value2, Length(a)); for j := Low(AData[i].Value2) to High(AData[i].Value2) do AData[i].Value2[j] := a[j]; end end; end; procedure TTestsXMLParser.LoadTestCase(ASuiteName: string; ASuiteClassName: string; ATestCaseNode: IXMLNode); var TestCaseRec: TTestCaseRec; TestRec: TTestRec; i, j: Integer; begin TestCaseRec.TestCaseName := ATestCaseNode.Attributes['Name']; TestCaseRec.TestClassName := ASuiteClassName; TestCaseRec.MethodName := ATestCaseNode.Attributes['MethodName']; TestCaseRec.SuiteName := ASuiteName; TestCaseRec.Tests := TTestList.Create(); for i := 0 to ATestCaseNode.ChildNodes.Count - 1 do if ATestCaseNode.ChildNodes[i].NodeName = 'Test' then begin TestRec.Name := ATestCaseNode.ChildNodes[i].Attributes['Name']; TestRec.TestCaseName := TestCaseRec.TestCaseName; TestRec.Operation := ATestCaseNode.ChildNodes[i].Attributes['Operation']; for j := 0 to ATestCaseNode.ChildNodes[i].ChildNodes.Count - 1 do if ATestCaseNode.ChildNodes[i].ChildNodes[j].NodeName = 'InputData' then LoadTestData(ATestCaseNode.ChildNodes[i].ChildNodes[j], TestRec.InputParameters) else if ATestCaseNode.ChildNodes[i].ChildNodes[j].NodeName = 'OutputData' then LoadTestData(ATestCaseNode.ChildNodes[i].ChildNodes[j], TestRec.OutputParameters) else if ATestCaseNode.ChildNodes[i].ChildNodes[j].NodeName = 'ExpectedResult' then TestRec.FailedMessageText := ATestCaseNode.ChildNodes[i].ChildNodes[j].Attributes['FailMessageText']; TestCaseRec.Tests.Add(TestRec); end; // TestCaseDictionary.Add(ATestCaseNode.Attributes['MethodName'], TestCaseRec); TestCaseDictionary.Add(ATestCaseNode.Attributes['Name'], TestCaseRec); end; function TTestsXMLParser.LoadXML: Boolean; begin Result := false; try if FileExists(FXMLFileName) then begin FXMLDocument.LoadFromFile(FXMLFileName); if not FXMLDocument.IsEmptyDoc then Result := True; end else Result := False; FXMLDocument.Active := Result; except FreeAndNil(FXMLDocument); end; end; procedure TTestsXMLParser.RunXMLParsing(var aTestCaseList: TTestCaseDictionary; var aSuiteList: TSuiteList); var RootNode: IXMLNode; i: Integer; begin if not LoadXML or (FXMLDocument.ChildNodes.Count <> 1) then Exit; RootNode := FXMLDocument.ChildNodes[0]; for i := 0 to RootNode.ChildNodes.Count - 1 do LoadSuite(RootNode.ChildNodes[i]); FXMLDocument.Active := false; end; procedure LoadTestsFromXML(aXMLFileName: string; var aSuiteList: TSuiteList; var aTestCaseList: TTestCaseDictionary); var XMLParser: TTestsXMLParser; begin XMLParser := TTestsXMLParser.Create(aXMLFileName); try XMLParser.RunXMLParsing(aTestCaseList, aSuiteList); finally FreeAndNil(XMLParser); end; end; end.
unit VirtualUtilities; // Version 1.3.0 // // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ // // Alternatively, you may redistribute this library, use and/or modify it under the terms of the // GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/. // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the // specific language governing rights and limitations under the License. // // The initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Menus, Math; // Helpers to create a callback function out of a object method function CreateStub(ObjectPtr: Pointer; MethodPtr: Pointer): Pointer; procedure DisposeStub(Stub: Pointer); // function AbsRect(Rect: TRect): TRect; function DiffRectHorz(Rect1, Rect2: TRect): TRect; function DiffRectVert(Rect1, Rect2: TRect): TRect; function DragDetectPlus(Handle: HWND; Pt: TPoint): Boolean; procedure FreeMemAndNil(var P: Pointer); function IsUnicode: Boolean; // OS supports Unicode functions (basiclly means IsWinNT or XP) function IsWin2000: Boolean; function IsWin95_SR1: Boolean; function IsWinME: Boolean; function IsWinNT4: Boolean; function IsWinXP: Boolean; {$EXTERNALSYM MAKE_HRESULT} function MAKE_HRESULT(sev, fac: LongWord; code: Word): HResult; function WinMsgBox(const Text: WideString; const Caption: WideString; uType: integer): integer; {$IFNDEF DELPHI_5_UP} procedure FreeAndNil(var Obj); procedure ClearMenuItems(Menu: TMenu); {$ENDIF DELPHI_5_UP} implementation // Helpers to create a callback function out of a object method { ----------------------------------------------------------------------------- } { This is a piece of magic by Jeroen Mineur. Allows a class method to be used } { as a callback. Create a stub using CreateStub with the instance of the object } { the callback should call as the first parameter and the method as the second } { parameter, ie @TForm1.MyCallback or declare a type of object for the callback } { method and then use a variable of that type and set the variable to the } { method and pass it: } { } { DON'T FORGET TO DEFINE THE FUNCTION METHOD AS "STDCALL" FOR A WINDOWS } { CALLBACK. ALL KINDS OF WEIRD THINGS CAN HAPPEN IF YOU DON'T } { } { type } { TEnumWindowsFunc = function (AHandle: hWnd; Param: lParam): BOOL of object; stdcall; } { } { TForm1 = class(TForm) } { private } { function EnumWindowsProc(AHandle: hWnd; Param: lParam): BOOL; stdcall; } { end; } { } { var } { MyFunc: TEnumWindowsFunc; } { Stub: pointer; } { begin } { MyFunct := EnumWindowsProc; } { Stub := CreateStub(Self, MyFunct); } { .... } { or } { } { var } { Stub: pointer; } { begin } { Stub := CreateStub(Self, @TForm1.EnumWindowsProc); } { .... } { Now Stub can be passed as the callback pointer to any windows API } { Don't forget to call Dispose Stub when not needed } { ----------------------------------------------------------------------------- } {$IFNDEF T2H} const AsmPopEDX = $5A; AsmMovEAX = $B8; AsmPushEAX = $50; AsmPushEDX = $52; AsmJmpShort = $E9; type TStub = packed record PopEDX: Byte; MovEAX: Byte; SelfPointer: Pointer; PushEAX: Byte; PushEDX: Byte; JmpShort: Byte; Displacement: Integer; end; { ----------------------------------------------------------------------------- } function CreateStub(ObjectPtr: Pointer; MethodPtr: Pointer): Pointer; var Stub: ^TStub; begin // Allocate memory for the stub // 1/10/04 Support for 64 bit, executable code must be in virtual space // currently New/Dispose use Virtual space but a replacement memory manager // may not Stub := VirtualAlloc(nil, SizeOf(TStub), MEM_COMMIT, PAGE_EXECUTE_READWRITE); // Pop the return address off the stack Stub^.PopEDX := AsmPopEDX; // Push the object pointer on the stack Stub^.MovEAX := AsmMovEAX; Stub^.SelfPointer := ObjectPtr; Stub^.PushEAX := AsmPushEAX; // Push the return address back on the stack Stub^.PushEDX := AsmPushEDX; // Jump to the 'real' procedure, the method. Stub^.JmpShort := AsmJmpShort; Stub^.Displacement := (Integer(MethodPtr) - Integer(@(Stub^.JmpShort))) - (SizeOf(Stub^.JmpShort) + SizeOf(Stub^.Displacement)); // Return a pointer to the stub Result := Stub; end; { ----------------------------------------------------------------------------- } { ----------------------------------------------------------------------------- } procedure DisposeStub(Stub: Pointer); begin // 1/10/04 Support for 64 bit, executable code must be in virtual space // currently New/Dispose use Virtual space but a replacement memory manager // may not VirtualFree(Stub, SizeOf(TStub),MEM_DECOMMIT); end; { ----------------------------------------------------------------------------- } {$ENDIF T2H} // MAKE_HRESULT(sev,fac,code) // ((HRESULT) (((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))) ) function MAKE_HRESULT(sev, fac: LongWord; code: Word): HResult; begin Result := LongInt( (sev shl 31) or (fac shl 16) or code) end; {$IFNDEF DELPHI_5_UP} procedure FreeAndNil(var Obj); var Temp: TObject; begin Temp := TObject(Obj); Pointer(Obj) := nil; Temp.Free; end; procedure ClearMenuItems(Menu: TMenu); var I: Integer; begin for I := Menu.Items.Count - 1 downto 0 do Menu.Items[I].Free; end; {$ENDIF DELPHI_5_UP} function DiffRectHorz(Rect1, Rect2: TRect): TRect; // Returns the "difference" rectangle of the passed rects in the Horz direction. // Assumes that one corner is common between the two rects begin Rect1 := ABSRect(Rect1); Rect2 := ABSRect(Rect2); // Make sure we contain every thing horizontally Result.Left := Min(Rect1.Left, Rect2.Left); Result.Right := Max(Rect1.Right, Rect1.Right); // Now find the difference rect height if Rect1.Top = Rect2.Top then begin // The tops are equal so it must be the bottom that contains the difference Result.Bottom := Max(Rect1.Bottom, Rect2.Bottom); Result.Top := Min(Rect1.Bottom, Rect2.Bottom); end else begin // The bottoms are equal so it must be the tops that contains the difference Result.Bottom := Max(Rect1.Top, Rect2.Top); Result.Top := Min(Rect1.Top, Rect2.Top); end end; function DiffRectVert(Rect1, Rect2: TRect): TRect; // Returns the "difference" rectangle of the passed rects in the Vert direction. // Assumes that one corner is common between the two rects begin Rect1 := ABSRect(Rect1); Rect2 := ABSRect(Rect2); // Make sure we contain every thing vertically Result.Top := Min(Rect1.Top, Rect2.Bottom); Result.Bottom := Max(Rect1.Top, Rect1.Bottom); // Now find the difference rect width if Rect1.Left = Rect2.Left then begin // The tops are equal so it must be the bottom that contains the difference Result.Right := Max(Rect1.Right, Rect2.Right); Result.Left := Min(Rect1.Right, Rect2.Right); end else begin // The bottoms are equal so it must be the tops that contains the difference Result.Right := Max(Rect1.Left, Rect2.Left); Result.Left := Min(Rect1.Left, Rect2.Left); end end; function AbsRect(Rect: TRect): TRect; // Makes sure a rectangle's left is less than its right and its top is less than its bottom var Temp: integer; begin Result := Rect; if Result.Right < Result.Left then begin Temp := Result.Right; Result.Right := Rect.Left; Result.Left := Temp; end; if Rect.Bottom < Rect.Top then begin Temp := Result.Top; Result.Top := Rect.Bottom; Result.Bottom := Temp; end end; function DragDetectPlus(Handle: HWND; Pt: TPoint): Boolean; // Replacement for DragDetect API which is buggy. // Pt is in Client Coords of the Handle window var DragRect: TRect; Msg: TMsg; TestPt: TPoint; HadCapture, Done: Boolean; begin Result := False; Done := False; HadCapture := GetCapture = Handle; DragRect.TopLeft := Pt; DragRect.BottomRight := Pt; InflateRect(DragRect, GetSystemMetrics(SM_CXDRAG), GetSystemMetrics(SM_CYDRAG)); SetCapture(Handle); try while (not Result) and (not Done) do if (PeekMessage(Msg, Handle, 0,0, PM_REMOVE)) then begin case (Msg.message) of WM_MOUSEMOVE: begin TestPt := Msg.Pt; // Not sure why this works. The Message point "should" be in client // coordinates but seem to be screen // Windows.ClientToScreen(Msg.hWnd, TestPt); Result := not(PtInRect(DragRect, TestPt)); end; WM_RBUTTONUP, WM_LBUTTONUP, WM_CANCELMODE, WM_QUIT, WM_LBUTTONDBLCLK: begin // Let the window get these messages after we have ended our // local message loop PostMessage(Msg.hWnd, Msg.message, Msg.wParam, Msg.lParam); Done := True; end; else TranslateMessage(Msg); DispatchMessage(Msg) end end else Sleep(0); finally ReleaseCapture; if HadCapture then Mouse.Capture := Handle; end; end; procedure FreeMemAndNil(var P: Pointer); { Frees the memeory allocated with GetMem and nils the pointer } var Temp: Pointer; begin Temp := P; P := nil; FreeMem(Temp); end; function IsUnicode: Boolean; begin Result := Win32Platform = VER_PLATFORM_WIN32_NT end; function IsWin2000: Boolean; begin Result := False; if Win32Platform = VER_PLATFORM_WIN32_NT then Result := LoWord(Win32MajorVersion) >= 5 end; function IsWin95_SR1: Boolean; begin Result := False; if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Result := ((Win32MajorVersion = 4) and (Win32MinorVersion = 0) and (LoWord(Win32BuildNumber) <= 1080)) end; function IsWinME: Boolean; begin Result := False; if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Result := Win32BuildNumber >= $045A0BB8 end; function IsWinNT4: Boolean; begin Result := False; if Win32Platform = VER_PLATFORM_WIN32_NT then Result := Win32MajorVersion < 5 end; function IsWinXP: Boolean; begin Result := (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion = 5) and (Win32MinorVersion > 0) end; function WinMsgBox(const Text: WideString; const Caption: WideString; uType: integer): integer; var TextA, CaptionA: string; begin Result := MessageBoxW(Application.Handle, PWideChar( Text), PWideChar( Caption), uType) end; end.
unit TpPageControl; interface uses Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils, Types, Forms, ThTag, ThPageControl, TpControls, TpInterfaces; type TTpSheet = class(TThSheet) private FOnGenerate: TTpEvent; public procedure CellTag(inTag: TThTag); override; published property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; end; // TTpPageControl = class(TThPageControl, ITpJsWriter) private FOnGenerate: TTpEvent; protected function GetHtmlAsString: string; override; procedure WriteJavaScript(inScript: TStringList); public procedure CellTag(inTag: TThTag); override; function CreateSheet: TThSheet; override; published property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; end; implementation { TTpSheet } procedure TTpSheet.CellTag(inTag: TThTag); begin inherited; with inTag do begin Add(tpClass, 'TTpSheet'); Add('tpName', Name); Add('tpOnGenerate', OnGenerate); end; end; { TTpPageControl } function TTpPageControl.CreateSheet: TThSheet; begin Result := TTpSheet.Create(Owner); Result.Name := TCustomForm(Owner).Designer.UniqueName('TpSheet'); Result.Align := alTop; Result.Parent := Self; end; procedure TTpPageControl.CellTag(inTag: TThTag); begin inherited; with inTag do begin Add(tpClass, 'TTpPageControl'); Add('tpName', Name); Add('tpCount', Count); Add('tpOnGenerate', OnGenerate); end; end; function TTpPageControl.GetHtmlAsString: string; begin Result := inherited GetHtmlAsString; { with TThTag.Create('script') do try Add('language', 'javascript'); Add('type', 'text/javascript'); Content := #13 + 'function ' + Name + 'SelectSheet(inIndex)'#13 + '{'#13 + ' i = 0;'#13 + ' while (true)'#13 + ' {'#13 + ' i++;'#13 + ' sheet = document.getElementById(''' + GetSheetNamePrefix + ''' + i);'#13 + ' if (!sheet)'#13 + ' break;'#13 + ' sheet.style.display = (i==inIndex ? ''block'' : ''none'');'#13 + } //' }'#13 + //'}'#13 { ; Result := Html + Result; finally Free; end; } end; procedure TTpPageControl.WriteJavaScript(inScript: TStringList); begin with inScript do begin Add('function TpPageControlSelectSheet(inPageControl, inIndex)'); // Add('function ' + Name + 'SelectSheet(inIndex)'); Add('{'); Add(' pages = document.getElementById(inPageControl);'); Add(' if (!pages)'); Add(' exit;'); Add(' sheetPrefix = inPageControl + "Sheet_";'); Add(' for (i=1; true; i++)'); Add(' {'); Add(' sheet = document.getElementById(sheetPrefix + i);'); Add(' if (!sheet)'); Add(' break;'); Add(' sheet.style.display = (i==inIndex ? "" : "none");'); Add(' }'); Add('}'); end; end; initialization RegisterClass(TTpSheet); end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Winsock; type TForm1 = class(TForm) GroupBox1: TGroupBox; Memo1: TMemo; GroupBox2: TGroupBox; Edit2: TEdit; Button1: TButton; GroupBox3: TGroupBox; Label1: TLabel; Edit1: TEdit; Button2: TButton; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} Function GetHostName(strIPAddress : String) : String; Var strHost : String ; pszIPAddress : PChar ; pReturnedHostEnt : PHostEnt ; InternetAddr : u_long ; GInitData : TWSADATA ; Begin strHost := ''; If WSAStartup($101, GInitData) = 0 then Begin pszIPAddress := StrAlloc( Length( strIPAddress ) + 1 ) ; StrPCopy( pszIPAddress, strIPAddress ) ; InternetAddr := Inet_Addr(pszIPAddress) ; StrDispose( pszIPAddress ) ; pReturnedHostEnt := GetHostByAddr( PChar(@InternetAddr),4, PF_INET ); try strHost := pReturnedHostEnt^.h_name; WSACleanup; Result := strHost ; except Result := 'Host inválido ou não encontrado'; end; end; end; procedure TForm1.Button1Click(Sender: TObject); begin Memo1.Lines.Add('IP: '+ Edit2.Text); Memo1.Lines.Add('Host: '+ GetHostName(Edit2.Text)); Memo1.Lines.Add(''); end; procedure TForm1.Button2Click(Sender: TObject); var p : PHostEnt; p2 : pchar; begin p := GetHostByName(Pchar(Edit1.Text)); Memo1.Lines.Add('Host: '+ Edit1.Text); Memo1.Lines.Add('Nome: ' + p^.h_Name); p2 := iNet_ntoa(PInAddr(p^.h_addr_list^)^); Memo1.Lines.Add('IP: ' + p2); Memo1.Lines.Add(''); end; procedure TForm1.FormCreate(Sender: TObject); var wVersionRequested : WORD; wsaData : TWSAData; begin wVersionRequested := MAKEWORD(1, 1); WSAStartup(wVersionRequested, wsaData); end; procedure TForm1.FormDestroy(Sender: TObject); begin WSACleanup; end; end.
//--- 256 COLOUR BITMAP COMPRESSOR --------------------------------------------- // // This form contains a simple user interface to take 256 colour bitmaps in // windows BPM format and compress them using RLE8 compression. // // The form itself contains no bitmap compression but attempts to locate // a compressor in the windows system. // // // Version 1.00 // Grahame Marsh 1 October 1997 // // Freeware - you get it for free, I take nothing, I make no promises! // // Please feel free to contact me: grahame.s.marsh@corp.courtaulds.co.uk // // Revison History: // Version 1.00 - initial release 1-10-97 unit Comp2; {$IFNDEF WIN32} Sorry, WIN 32 only! {$ENDIF} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtDlgs, ExtCtrls, StdCtrls, Buttons, ComCtrls; // declare own bitmap file record, specifically for 256 colour bitmaps type T256Palette = array [0..255] of TRGBQuad; P256Bitmap = ^T256Bitmap; T256Bitmap = packed record b256File : TBitmapFileHeader; b256Info : TBitmapInfoHeader; b256Pal : T256Palette; b256Data : record end; end; type TBitmapCompForm = class(TForm) GroupBox1: TGroupBox; InBrowseBtn: TBitBtn; InFilenameEdit: TEdit; InFilesizeLabel: TLabel; InScrollBox: TScrollBox; InImage: TImage; OpenPictureDialog: TOpenPictureDialog; GroupBox2: TGroupBox; OutFilenameEdit: TEdit; OutBrowseBtn: TBitBtn; SaveDialog: TSaveDialog; OutScrollBox: TScrollBox; OutImage: TImage; CompressBtn: TBitBtn; OutFilesizeLabel: TLabel; CompUsingLabel: TLabel; PaletteCheckBox: TCheckBox; QualityTrackBar: TTrackBar; QualityLabel: TLabel; Label1: TLabel; procedure InBrowseBtnClick(Sender: TObject); procedure QualityTrackBarChange(Sender: TObject); procedure OutBrowseBtnClick(Sender: TObject); procedure OutFilenameEditChange(Sender: TObject); procedure CompressBtnClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private InBitmap : P256Bitmap; // copy of bitmap file InSize, // copy of filesize InDataSize, // size of bitmap data InColours : integer; // number of colours procedure FreeStuff; public end; var BitmapCompForm: TBitmapCompForm; implementation {$R *.DFM} //-- calls to video for windopws dll ------------------------------------------- type PICInfo = ^TICInfo; TICInfo = packed record dwSize, // sizeof (TICInfo) fccType, // compressor type eg vidc fccHandler, // compressor subtype eg rle dwFlags, // lo word is type specific dwVersion, // version of driver dwVersionICM : DWORD; // version of the ICM szName : array [0..15] of wchar; // short name szDescription : array [0..127] of wchar; // long name szDriver : array [0..127] of wchar; // driver that contains the compressor end; const ICMODE_COMPRESS = 1; ICTYPE_VIDEO = ord ('v') + ord ('i') shl 8 + ord ('d') shl 16 + ord ('c') shl 24; type TICHandle = THandle; function ICLocate (fccType, fccHandler: DWORD; lpbiIn, lpbmOut : PBitmapInfoHeader; wFlags: word) : TICHandle; stdcall; external 'msvfw32.dll' name 'ICLocate'; function ICGetInfo (Handle: TICHandle; var ICInfo: TICInfo; cb: DWORD): LRESULT; stdcall; external 'msvfw32.dll' name 'ICGetInfo'; function ICImageCompress (Handle: TICHandle; uiFlags: UINT; lpbiIn: PBitmapInfo; lpBits: pointer; lpbiOut: PBitmapInfo; lQuality: integer; plSize: PInteger): HBitmap; stdcall; external 'msvfw32.dll' name 'ICImageCompress'; function ICClose (Handle: TICHandle): LRESULT; stdcall; external 'msvfw32.dll' name 'ICClose'; //--- compressor form ---------------------------------------------------------- const FSStr = 'File size: %d'; CUStr = 'Compressed using: %s'; BitmapSignature = $4D42; procedure TBitmapCompForm.FormDestroy(Sender: TObject); begin FreeStuff end; procedure TBitmapCompForm.FreeStuff; begin if InSize <> 0 then begin FreeMem (InBitmap, InSize); InBitmap := nil; InSize := 0 end end; procedure TBitmapCompForm.InBrowseBtnClick(Sender: TObject); var Bitmap : TBitmap; begin with OpenPictureDialog do if Execute then begin InFilesizeLabel.Caption := Format (FSStr, [0]); InImage.Picture := nil; InFilenameEdit.Text := ''; FreeStuff; with TFileStream.Create (Filename, fmOpenRead) do try InSize := Size; GetMem (InBitmap, InSize); Read (InBitmap^, InSize); with InBitmap^ do if b256File.bfType = BitmapSignature then if b256Info.biBitCount = 8 then if b256Info.biCompression = BI_RGB then begin // Ok, we have a 256 colour, uncompressed bitmap InFilenameEdit.Text := Filename; // determine number of entries in palette if b256Info.biClrUsed = 0 then InColours := 256 else InColours := b256Info.biClrUsed; // determine size of data bits with InBitmap^.b256Info do if biSizeImage = 0 then InDataSize := biWidth * biHeight else InDataSize := biSizeImage end else ShowMessage ('Bitmap already compressed') else ShowMessage ('Not a 256 colour bitmap') else ShowMessage ('Not a bitmap') finally Free end; // show the bitmap and file size if InFileNameEdit.Text <> '' then begin Bitmap := TBitmap.Create; try Bitmap.LoadFromFile (InFilenameEdit.Text); InImage.Picture.Bitmap := Bitmap finally Bitmap.Free end; InScrollBox.VertScrollBar.Range := InBitmap^.b256Info.biHeight; InScrollBox.HorzScrollBar.Range := InBitmap^.b256Info.biWidth; InFilesizeLabel.Caption := Format (FSStr, [InBitmap^.b256File.bfSize]) end end end; procedure TBitmapCompForm.OutBrowseBtnClick(Sender: TObject); begin with SaveDialog do if Execute then OutFilenameEdit.Text := Filename end; //--- Palette Compression ------------------------------------------------------ // compress a 256 colour palette by removing unused entries // returns new number of entries function CompressPalette (var Pal: T256Palette; Data: pointer; DataSize: integer): word; type TPaletteUsed = packed record Used : boolean; NewEntry : byte; end; TPaletteUsedArray = array [0..255] of TPaletteUsed; var PUArray: TPaletteUsedArray; Scan: PByte; NewValue, Loop: integer; NewPal : T256Palette; begin // look through the bitmap data bytes looking for palette entries in use fillchar (PUArray, sizeof (PUArray), 0); Scan:= Data; for Loop:= 1 to DataSize do begin PUArray[Scan^].Used := true; inc (Scan) end; // go through palette and set new entry numbers for those in use NewValue := 0; for Loop:= 0 to 255 do with PUArray[Loop] do if Used then begin NewEntry := NewValue; inc (NewValue); end; Result := NewValue; // return number in use if NewValue = 256 then exit; // QED // go through bitmap data assigninging new palette numbers Scan:= Data; for Loop:= 1 to DataSize do begin Scan^ := PUArray[Scan^].NewEntry; inc (Scan) end; // create a new palette and copy across only those entries in use fillchar (NewPal, sizeof (T256Palette), 0); for Loop := 0 to 255 do with PUArray [Loop] do if Used then NewPal[NewEntry] := Pal [Loop]; // return the new palette Pal := NewPal end; //--- try to compress input image -> output image ------------------------------ procedure TBitmapCompForm.CompressBtnClick(Sender: TObject); var Bitmap: TBitmap; Handle: THandle; CompressHandle: integer; ICInfo: TICInfo; OutBitmap, InBitmapCopy : P256Bitmap; CompressedStuff, OutData, InDataCopy : pointer; OutSize, OutColours : integer; begin // make an output bitmap file GetMem (OutBitmap, sizeof (T256Bitmap)); try // make a copy of the input file as we will play with the data GetMem (InBitmapCopy, InSize); try Move (InBitmap^, InBitmapCopy^, InSize); InDataCopy := pointer (integer(InBitmapCopy) + sizeof (TBitmapFileHeader) + sizeof (TBitmapInfoHeader) + InColours * sizeof (TRGBQuad)); // crunch the palette with InBitmapCopy^ do if PaletteCheckBox.Checked then OutColours := CompressPalette (b256Pal, InDataCopy, InDataSize) else OutColours := InColours; // now copy the input file to fill in most of the output bitmap values Move (InBitmapCopy^, OutBitmap^, sizeof (T256Bitmap)); // set the compression required OutBitmap^.b256Info.biCompression := BI_RLE8; // find a compressor CompressHandle := ICLocate (ICTYPE_VIDEO, 0, @InBitmapCopy^.b256Info, @OutBitmap.b256Info, ICMODE_COMPRESS); try fillchar (ICInfo, sizeof (TICInfo), 0); ICInfo.dwSize := sizeof (TICInfo); // get info on the compressor ICGetInfo (CompressHandle, ICInfo, sizeof (TICInfo)); OutSize := 0; // best compression // now compress the image Handle := ICImageCompress (CompressHandle, 0, @InBitmapCopy^.b256Info, InDataCopy, @OutBitmap^.b256Info, QualityTrackBar.Position*100, @OutSize); finally ICClose (CompressHandle) end; if Handle <> 0 then begin // get the compressed data CompressedStuff := GlobalLock (Handle); try // modify the filesize and offset in case palette has shrunk with OutBitmap^.b256File do begin bfOffBits := sizeof (TBitmapFileHeader) + sizeof(TBitmapInfoHeader) + OutColours * sizeof (TRGBQuad); bfSize := bfOffBits + OutSize end; // locate the data OutData := pointer (integer(CompressedStuff) + sizeof(TBitmapInfoHeader) + InColours * sizeof (TRGBQuad)); // modify the bitmap info header with OutBitmap^.b256Info do begin biSizeImage := OutSize; biClrUsed := OutColours; biClrImportant := 0 end; // save the bitmap to disc with TFileStream.Create (OutFilenameEdit.Text, fmCreate) do try write (OutBitmap^, sizeof (TBitmapFileHeader) + sizeof (TBitmapInfoHeader)); write (InBitmapCopy^.b256Pal, OutColours*sizeof (TRGBQuad)); write (OutData^, OutSize) finally Free end; // view the result Bitmap := TBitmap.Create; try Bitmap.LoadFromFile (OutFilenameEdit.Text); OutImage.Picture.Bitmap := Bitmap finally Bitmap.Free end; // set the scrollbars and give some stats with OutBitmap^ do begin OutScrollBox.VertScrollBar.Range := b256Info.biHeight; OutScrollBox.HorzScrollBar.Range := b256Info.biWidth; OutFileSizeLabel.Caption := Format (FSStr, [b256File.bfSize]); CompUsingLabel.Caption := Format (CUStr, [WideCharToString (ICInfo.szDescription)]) end // now tidy up finally GlobalUnlock (Handle) end end else ShowMessage ('Bitmap could not be compressed') finally FreeMem (InBitmapCopy, InSize) end finally FreeMem (OutBitmap, sizeof (T256Bitmap)) end end; procedure TBitmapCompForm.QualityTrackBarChange(Sender: TObject); begin QualityLabel.Caption := IntToStr (QualityTrackBar.Position) end; procedure TBitmapCompForm.OutFilenameEditChange(Sender: TObject); begin CompressBtn.Enabled := (InFilenameEdit.Text <> '') and (OutFilenameEdit.Text <> '') end; end.
{interface} type TInnerRecord = record Value: string; end; TClassA = class public InnerRecord: TInnerRecord; end; TClassB = class private FInnerRecord: TInnerRecord; public property InnerRecord: TInnerRecord read FInnerRecord write FInnerRecord; end; TClassC = class public procedure DoSomethingA(); procedure DoSomethingB(); procedure DoSomethingB_Error(); end; {implementation} procedure TClassC.DoSomethingA(); var ClassA: TClassA; begin ClassA := TClassA.Create(); try ClassA.InnerRecord.Value := 'correct implementation'; finnaly ClassA.Free(); end; end; procedure TClassC.DoSomethingB(); var ClassB: TClassB; begin ClassB := TClassB.Create(); try with ClassB.InnerRecord do Value := 'correct implementation'; finnaly ClassB.Free(); end; end; procedure TClassC.DoSomethingB_Error(); var ClassB: TClassB; begin ClassB := TClassB.Create(); try ClassB.InnerRecord.Value := 'incorrect implementation'; // ERROR! "Left Side Cannot Be Assigned To" finnaly ClassB.Free(); end; end;
program problem02; uses crt; (* Problem: Even Fibonacci numbers Problem 2 @Author: Chris M. Perez @Date: 5/14/2017 *) var sum: longint = 0; MAX: longint = 4000000; function fib(arg: longint): longint; begin if(arg < 3) then fib := 1 else fib := fib(arg - 1) + fib(arg - 2); end; var i: longint; begin for i := 1 to MAX do begin if(fib(i) > MAX) then break; if(fib(i) mod 2 = 0) then sum := sum + fib(i) end; Writeln(sum); readkey; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmToolWinFormExpt Purpose : Custom Form Expert, used in controlling the TrmToolWinForm and decendants.... Components : TrmToolWinFormExpert Date : 06-15-1999 Author : Ryan J. Mills Version : 1.92 Note : This unit was originally apart of Sergey Orlik's Custom Forms Pack I've included it here with modifications for the rmToolWinForm. I've also left the original file header in to help explain more about it. ================================================================================ } {*******************************************************} { } { Delphi Visual Component Library } { Custom Forms Pack (CFPack) } { } { Copyright (c) 1997-99 Sergey Orlik } { } { Written by: } { Sergey Orlik } { product manager } { Russia, C.I.S. and Baltic States (former USSR) } { Inprise Moscow office } { Internet: sorlik@inprise.ru } { www.geocities.com/SiliconValley/Way/9006/ } { } {*******************************************************} {$I Sergey_Orlik_DEF.INC} {$Warnings OFF} unit rmToolWinFormExpt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ExptIntf, ToolIntf, EditIntf, VirtIntf; type { TrmToolWinFormExpert } TrmToolWinFormExpert = class(TIExpert) private procedure RunExpert(ToolServices: TIToolServices); public function GetName: string; override; function GetAuthor: string; override; function GetComment: string; override; function GetPage: string; override; function GetGlyph: HICON; override; function GetStyle: TExpertStyle; override; function GetState: TExpertState; override; function GetIDString: string; override; function GetMenuText: string; override; procedure Execute; override; end; implementation uses rmToolWin; const CRLF = #13#10; CRLF2 = #13#10#13#10; DefaultModuleFlags = [cmShowSource, cmShowForm, cmMarkModified, cmUnNamed]; resourcestring sCustFormExpertAuthor = 'Ryan J. Mills'; sCustFormExpertName = 'rmToolWin Form'; sCustFormExpertDesc = 'Create a new TrmToolWinForm'; { TrmToolWinFormModuleCreator } type {$IFDEF VER_CB} TrmToolWinFormModuleCreator = class(TIModuleCreatorEx) {$ELSE} TrmToolWinFormModuleCreator = class(TIModuleCreator) {$ENDIF} private FAncestorIdent : string; FAncestorClass : TClass; // FNewFormOption : TNewFormOption; FFormIdent : string; FUnitIdent : string; FFileName : string; public function Existing: Boolean; override; function GetFileName: string; override; function GetFileSystem: string; override; function GetFormName: string; override; function GetAncestorName: string; override; {$IFNDEF VER100} {$IFDEF VER_CB} function GetIntfName: string; override; function NewIntfSource(const UnitIdent, FormIdent, AncestorIdent: string): string; override; {$ENDIF} function NewModuleSource(const UnitIdent, FormIdent, AncestorIdent: string): string; override; {$ELSE} function NewModuleSource(UnitIdent, FormIdent, AncestorIdent: string): string; override; {$ENDIF} procedure FormCreated(Form: TIFormInterface); override; end; function TrmToolWinFormModuleCreator.Existing:boolean; begin Result:=False end; function TrmToolWinFormModuleCreator.GetFileName:string; begin Result:=FFileName; //''; end; function TrmToolWinFormModuleCreator.GetFileSystem:string; begin Result:=''; end; function TrmToolWinFormModuleCreator.GetFormName:string; begin Result:=FFormIdent; end; function TrmToolWinFormModuleCreator.GetAncestorName:string; begin Result:=FAncestorIdent; end; {$IFDEF VER_CB} function UnitName2Namespace(const Value:string):string; var s1,s2 : string; begin s1:=Value[1]; s2:=LowerCase(Value); System.Delete(s2,1,1); Result:=UpperCase(s1)+s2; end; function TrmToolWinFormModuleCreator.GetIntfName: string; begin Result:=''; end; function TrmToolWinFormModuleCreator.NewIntfSource(const UnitIdent, FormIdent, AncestorIdent: string): string; var s : string; begin s:=s+'//---------------------------------------------------------------------------'+ CRLF+ '#ifndef '+UnitIdent+'H'+CRLF+ '#define '+UnitIdent+'H'+CRLF+ '//---------------------------------------------------------------------------'+ CRLF+ '#include <Classes.hpp>'+CRLF+ '#include <Controls.hpp>'+CRLF+ '#include <StdCtrls.hpp>'+CRLF+ '#include <Forms.hpp>'+CRLF; if (AncestorIdent<>'Form') and (AncestorIdent<>'DataModule') then s:=s+ '#include "'+GetCustomFormUnit(FAncestorClass.ClassName)+'.h"'+CRLF; s:=s+'//---------------------------------------------------------------------------'+ CRLF+ 'class T'+FormIdent+' : public '+FAncestorClass.ClassName+CRLF+ '{'+CRLF+ '__published:'+CRLF+ 'private:'+CRLF+ 'protected:'+CRLF+ 'public:'+CRLF+ ' __fastcall T'+FormIdent+'(TComponent* Owner);'+CRLF+ '};'+CRLF; s:=s+ '//---------------------------------------------------------------------------'+ CRLF+ 'extern PACKAGE T'+FormIdent+' *'+FormIdent+';'+CRLF; s:=s+ '//---------------------------------------------------------------------------'+ CRLF+ '#endif'; Result:=s; end; function TrmToolWinFormModuleCreator.NewModuleSource(const UnitIdent, FormIdent, AncestorIdent: string): string; var s : string; begin s:='//---------------------------------------------------------------------------'+ CRLF+ '#include <vcl.h>'+CRLF; s:=s+ '#pragma hdrstop'+CRLF2+ '#include "'+UnitIdent+'.h"'+CRLF+ '//---------------------------------------------------------------------------'+ CRLF+ '#pragma package(smart_init)'+CRLF; if (AncestorIdent<>'Form') and (AncestorIdent<>'DataModule') then s:=s+ '#pragma link "'+GetCustomFormUnit(FAncestorClass.ClassName)+'"'+CRLF; s:=s+ '#pragma resource "*.dfm"'+CRLF+ 'T'+FormIdent+' *'+FormIdent+';'+CRLF; s:=s+ '//---------------------------------------------------------------------------'+ CRLF+ '__fastcall T'+FormIdent+'::T'+FormIdent+'(TComponent* Owner)'+CRLF+ ' : '+FAncestorClass.ClassName+'(Owner)'+CRLF+ '{'+CRLF+ '}'+CRLF+ '//---------------------------------------------------------------------------'+ CRLF; Result:=s; end; {$ELSE} {$IFDEF VER100} function TrmToolWinFormModuleCreator.NewModuleSource(UnitIdent,FormIdent,AncestorIdent:string):string; {$ELSE} function TrmToolWinFormModuleCreator.NewModuleSource(const UnitIdent,FormIdent,AncestorIdent:string):string; {$ENDIF} var s : string; begin s:='unit '+FUnitIdent+';'+CRLF2+ 'interface'+CRLF2+ 'uses'+CRLF+ ' Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs'; if (FAncestorIdent<>'Form') and (FAncestorIdent<>'DataModule') then s:=s+','+CRLF+ // ' '+GetCustomFormUnit(FAncestorClass.ClassName); ' rmToolWin'; s:=s+';'+CRLF2+ 'type'+CRLF+ // ' T'+FFormIdent+' = class('+FAncestorClass.ClassName+')'+CRLF+ ' T'+FFormIdent+' = class(TrmToolWinForm)'+CRLF+ ' private'+CRLF+ ' { Private declarations }'+CRLF+ ' public'+CRLF+ ' { Public declarations }'+CRLF+ ' end;'+CRLF2; s:=s+ 'var'+CRLF+ ' '+FFormIdent+' : T'+FFormIdent+';'+CRLF2; s:=s+ 'implementation'+CRLF2; s:=s+ '{$R *.DFM}'+CRLF2; s:=s+ 'end.'; Result:=s; end; {$ENDIF} procedure TrmToolWinFormModuleCreator.FormCreated(Form:TIFormInterface); begin end; { HandleException } procedure HandleException; begin ToolServices.RaiseException(ReleaseException); end; { TrmToolWinFormExpert } function TrmToolWinFormExpert.GetName: string; begin try Result := sCustFormExpertName; except HandleException; end; end; function TrmToolWinFormExpert.GetComment: string; begin try Result := sCustFormExpertDesc; except HandleException; end; end; function TrmToolWinFormExpert.GetGlyph: HICON; begin try Result := LoadIcon(HInstance, 'NEWRMDOCKFORM'); except HandleException; end; end; function TrmToolWinFormExpert.GetStyle: TExpertStyle; begin try Result := esForm; except HandleException; end; end; function TrmToolWinFormExpert.GetState: TExpertState; begin try Result := [esEnabled]; except HandleException; end; end; function TrmToolWinFormExpert.GetIDString: string; begin try Result := 'MillsEnterprise.'+sCustFormExpertName; except HandleException; end; end; function TrmToolWinFormExpert.GetMenuText: string; begin try result := ''; except HandleException; end; end; function TrmToolWinFormExpert.GetAuthor: string; begin try Result := sCustFormExpertAuthor; except HandleException; end; end; function TrmToolWinFormExpert.GetPage: string; begin try Result := 'New'; except HandleException; end; end; procedure TrmToolWinFormExpert.Execute; begin try RunExpert(ToolServices); except HandleException; end; end; procedure TrmToolWinFormExpert.RunExpert(ToolServices: TIToolServices); var ModuleFlags : TCreateModuleFlags; IModuleCreator : TrmToolWinFormModuleCreator; IModule : TIModuleInterface; begin if ToolServices = nil then Exit; IModuleCreator:=TrmToolWinFormModuleCreator.Create; IModuleCreator.FAncestorIdent:='rmToolWinForm'; IModuleCreator.FAncestorClass:=TrmToolWinForm; ToolServices.GetNewModuleAndClassName(IModuleCreator.FAncestorIdent,IModuleCreator.FUnitIdent,IModuleCreator.FFormIdent,IModuleCreator.FFileName); ModuleFlags:=DefaultModuleFlags; ModuleFlags:=ModuleFlags+[cmAddToProject]; try {$IFDEF VER_CB} IModule:=ToolServices.ModuleCreateEx(IModuleCreator,ModuleFlags); {$ELSE} IModule:=ToolServices.ModuleCreate(IModuleCreator,ModuleFlags); {$ENDIF} IModule.Free; finally IModuleCreator.Free; end; end; end.
//------------------------------------------------------------------------------ //LoginAccountInfo UNIT //------------------------------------------------------------------------------ // What it does- // This class used by Login server to handle each account data in list // // Changes - // April 12th, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ unit LoginAccountInfo; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface type TLoginAccountInfo = class public //Acc id AccountID : LongWord; //Which char server currently on? CharServerID : LongWord; //Still on Select Char Server? OnCharSrvList : Boolean; //Already attempt Duplicate login? UnderKickQuery : Boolean; Constructor Create(AID : LongWord); end; implementation Constructor TLoginAccountInfo.Create(AID : LongWord); begin inherited Create; AccountID := AID; OnCharSrvList := False; UnderKickQuery := False; end; end.
unit UCRC; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface type TCRC=class public Value:integer; constructor Create; procedure Init; procedure Update(const data: array of byte;const offset,size:integer);overload; procedure Update(const data: array of byte);overload; procedure UpdateByte(const b:integer); function GetDigest:integer; end; implementation var Table: array [0..255] of integer; constructor TCRC.Create; begin Value:=-1; end; procedure TCRC.Init; begin Value:=-1; end; procedure TCRC.Update(const data: array of byte;const offset,size:integer); var i:integer; begin for i := 0 to size-1 do value := Table[(value xor data[offset + i]) and $FF] xor (value shr 8); end; procedure TCRC.Update(const data: array of byte); var size:integer; i:integer; begin size := length(data); for i := 0 to size - 1 do value := Table[(value xor data[i]) and $FF] xor (value shr 8); end; procedure TCRC.UpdateByte(const b:integer); begin value := Table[(value xor b) and $FF] xor (value shr 8); end; function TCRC.GetDigest:integer; begin result:=value xor (-1); end; procedure InitCRC; var i,j,r:integer; begin for i := 0 to 255 do begin r := i; for j := 0 to 7 do begin if ((r and 1) <> 0) then r := (r shr 1) xor integer($EDB88320) else r := r shr 1; end; Table[i] := r; end; end; initialization InitCRC; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_CLASSFACT.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_CLASSFACT; interface uses {$I uses.def} SysUtils, Classes, TypInfo, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS, PAXCOMP_MAP, PAXCOMP_CLASSLST; type TPaxClassFactoryRec = class private PaxClassRec: TPaxClassRec; fClassName: ShortString; fParentClass: TClass; Processed: Boolean; fMethodTableSize: Integer; fIntfTableSize: Integer; function GetDelphiClass: TClass; function GetVMTPtr: PVMT; procedure SetMethodTableSize(value: Integer); public pti_parent: PTypeInfo; FieldTableSize: Integer; FieldClassTable: PFieldClassTable; DmtTableSize: Integer; FullClassName: String; constructor Create(const AFullClassName: String); destructor Destroy; override; procedure RenameClass(const NewFullClassName: String); procedure SetInstanceSize(value: Integer); procedure SetParentClass(AClass: TClass); property DelphiClass: TClass read GetDelphiClass; property VMTPtr: PVMT read GetVMTPtr; property MethodTableSize: Integer read fMethodTableSize write SetMethodTableSize; property IntfTableSize: Integer read fIntfTableSize write fIntfTableSize; end; TPaxClassFactory = class(TTypedList) private function GetRecord(I: Integer): TPaxClassFactoryRec; procedure Reset; public ForceCreate: Boolean; constructor Create; function CreatePaxClass(const AFullClassName: String; AnInstanceSize: Integer; ParentClass: TClass; PDestroyObject: Pointer): TClass; function CreateCloneClass(const AFullClassName: String; ParentClass: TClass): TClass; function RenameClass(const OldFullClassName, NewFullClassName: String): Boolean; function FindRecord(AClass: TClass): TPaxClassFactoryRec; function FindRecordByFullName(const AFullClassName: String): TPaxClassFactoryRec; function LookupFullName(const AFullClassName: String): TClass; procedure SetupParents(Prog: Pointer; ClassList: TClassList); procedure SetupStdVirtuals(ClassList: TClassList; CodePtr: Pointer); procedure AddInheritedMethods; overload; procedure AddInheritedMethods(SourceClass: TClass); overload; procedure AddOverridenMethods(AProg: Pointer; ScriptMapTable: TMapTable); procedure AddVirtualMethod(SourceClass: TClass; SourceMethodAddress: Pointer); function AddOverridenMethod(SourceClass: TClass; SourceMethodAddress, InheritedMethodAddress: Pointer): Boolean; procedure RaiseError(const Message: string; params: array of Const); property Records[I: Integer]: TPaxClassFactoryRec read GetRecord; default; end; implementation uses PAXCOMP_BASERUNNER; function _NewInstance(Self: TClass): TObject; var S: Integer; begin S := Self.InstanceSize; result := Self.InitInstance(AllocMem(S)); end; {$IFDEF ARC} const objDisposedFlag = Integer($40000000); type TMyObject = class(TObject); function fake_ObjRelease(Self: Pointer): Integer; var PRefCount: ^Integer; begin PRefCount := ShiftPointer(Pointer(Self), SizeOf(Pointer)); Result := AtomicDecrement(PRefCount^) and not objDisposedFlag; if Result = 0 then TMyObject(Self).Destroy; end; {$ENDIF} // TPaxClassFactoryRec --------------------------------------------------------- constructor TPaxClassFactoryRec.Create(const AFullClassName: String); begin inherited Create; FillChar(PaxClassRec, SizeOf(PaxClassRec), 0); FieldClassTable := nil; FullClassName := AFullClassName; PaxClassRec.PaxInfo.ClassFactoryRec := Self; end; destructor TPaxClassFactoryRec.Destroy; begin if MethodTableSize > 0 then FreeMem(vmtMethodTableSlot(VMTPtr)^, MethodTableSize); if FieldTableSize > 0 then FreeMem(vmtFieldTableSlot(VMTPtr)^, FieldTableSize); if DmtTableSize > 0 then FreeMem(vmtDynamicTableSlot(VMTPtr)^, DmtTableSize); if FieldClassTable <> nil then DestroyFieldClassTable(FieldClassTable); if IntfTableSize > 0 then FreeMem(vmtIntfTableSlot(VMTPtr)^, IntfTableSize); inherited; end; {$IFDEF FPC} function TPaxClassFactoryRec.GetDelphiClass: TClass; begin result := TClass(@PaxClassRec.VMT); end; {$ELSE} function TPaxClassFactoryRec.GetDelphiClass: TClass; begin result := TClass(vmtSelfPtrSlot(@PaxClassRec.VMT)^); end; {$ENDIF} function TPaxClassFactoryRec.GetVMTPtr: PVMT; begin result := @ PaxClassRec.VMT; end; procedure TPaxClassFactoryRec.SetMethodTableSize(value: Integer); begin fMethodTableSize := value; end; procedure TPaxClassFactoryRec.SetInstanceSize(value: Integer); begin PIntPax(vmtInstanceSizeSlot(@PaxClassRec.VMT))^ := value; end; procedure TPaxClassFactoryRec.RenameClass(const NewFullClassName: string); begin PShortStringFromString(@fClassName, ExtractName(NewFullClassName)); FullClassName := NewFullClassName; end; procedure TPaxClassFactoryRec.SetParentClass(AClass: TClass); var ParentVMT: PVMT; begin fParentClass := AClass; ParentVMT := GetVmtFromClass(AClass); // PaxClassRec.VMT.IntfTable := ParentVMT.IntfTable; {$IFDEF FPC} vmtParentSlot(@PaxClassRec.VMT)^ := AClass; {$IFNDEF LINUX} PaxClassRec.VMT.VToString := ParentVMT^.VToString; PaxClassRec.VMT.VGetHashCode := ParentVMT^.VGetHashCode; PaxClassRec.VMT.VEquals := ParentVMT^.VEquals; {$ENDIF} {$ELSE} vmtParentSlot(@PaxClassRec.VMT)^ := @fParentClass; {$ENDIF} vmtAutoTableSlot(@PaxClassRec.VMT)^ := vmtAutoTableSlot(ParentVMT)^; {$IFNDEF LINUX} vmtDispatchSlot(@PaxClassRec.VMT)^ := vmtDispatchSlot(ParentVMT)^; {$ENDIF} vmtInitTableSlot(@PaxClassRec.VMT)^ := vmtInitTableSlot(ParentVMT)^; vmtTypeInfoSlot(@PaxClassRec.VMT)^ := vmtTypeInfoSlot(ParentVMT)^; vmtFieldTableSlot(@PaxClassRec.VMT)^ := vmtFieldTableSlot(ParentVMT)^; vmtMethodTableSlot(@PaxClassRec.VMT)^ := vmtMethodTableSlot(ParentVMT)^; vmtDynamicTableSlot(@PaxClassRec.VMT)^ := vmtDynamicTableSlot(ParentVMT)^; vmtNewInstanceSlot(@PaxClassRec.VMT)^ := vmtNewInstanceSlot(ParentVMT)^; vmtSafeCallExceptionSlot(@PaxClassRec.VMT)^ := vmtSafeCallExceptionSlot(ParentVMT)^; vmtAfterConstructionSlot(@PaxClassRec.VMT)^ := vmtAfterConstructionSlot(ParentVMT)^; vmtBeforeDestructionSlot(@PaxClassRec.VMT)^ := vmtBeforeDestructionSlot(ParentVMT)^; vmtDefaultHandlerSlot(@PaxClassRec.VMT)^ := vmtDefaultHandlerSlot(ParentVMT)^; {$IFDEF UNIC} vmtToStringSlot(@PaxClassRec.VMT)^ := vmtToStringSlot(ParentVMT)^; vmtGetHashCodeSlot(@PaxClassRec.VMT)^ := vmtGetHashCodeSlot(ParentVMT)^; vmtEqualsSlot(@PaxClassRec.VMT)^ := vmtEqualsSlot(ParentVMT)^; {$ENDIF} {$IFDEF ARC} vmt__ObjAddRefSlot(@PaxClassRec.VMT)^ := vmt__ObjAddRefSlot(ParentVMT)^; // vmt__ObjReleaseSlot(@PaxClassRec.VMT)^ := vmt__ObjReleaseSlot(ParentVMT)^; vmt__ObjReleaseSlot(@PaxClassRec.VMT)^ := @ fake_ObjRelease; {$ENDIF} end; // TPaxClassFactory ------------------------------------------------------------ constructor TPaxClassFactory.Create; begin inherited; ForceCreate := false; end; procedure TPaxClassFactory.RaiseError(const Message: string; params: array of Const); begin raise Exception.Create(Format(Message, params)); end; procedure _AfterConstruction(Self: TObject); begin end; procedure _BeforeDestruction(Self: TObject); begin end; function TPaxClassFactory.RenameClass(const OldFullClassName, NewFullClassName: String): Boolean; var R: TPaxClassFactoryRec; begin R := FindRecordByFullName(OldFullClassName); result := R <> nil; if result then R.RenameClass(NewFullClassName); end; function TPaxClassFactory.CreatePaxClass(const AFullClassName: String; AnInstanceSize: Integer; ParentClass: TClass; PDestroyObject: Pointer): TClass; var PaxClassObject: TPaxClassFactoryRec; begin PaxClassObject := TPaxClassFactoryRec.Create(AFullClassName); PShortStringFromString(@PaxClassObject.fClassName, ExtractName(AFullClassName)); PaxClassObject.fParentClass := ParentClass; {$IFDEF FPC} vmtParentSlot(@PaxClassObject.PaxClassRec.VMT)^ := ParentClass; {$ELSE} vmtSelfPtrSlot(@PaxClassObject.PaxClassRec.VMT)^ := GetClassFromVMT(@PaxClassObject.PaxClassRec.VMT); vmtParentSlot(@PaxClassObject.PaxClassRec.VMT)^ := @ PaxClassObject.fParentClass; {$ENDIF} vmtClassNameSlot(@PaxClassObject.PaxClassRec.VMT)^ := @ PaxClassObject.fClassName; PIntPax(vmtInstanceSizeSlot(@PaxClassObject.PaxClassRec.VMT))^ := AnInstanceSize; vmtNewInstanceSlot(@PaxClassObject.PaxClassRec.VMT)^ := @ _NewInstance; vmtAfterConstructionSlot(@PaxClassObject.PaxClassRec.VMT)^ := @ _AfterConstruction; vmtBeforeDestructionSlot(@PaxClassObject.PaxClassRec.VMT)^ := @ _BeforeDestruction; vmtDestroySlot(@PaxClassObject.PaxClassRec.VMT)^ := PDestroyObject; L.Add(PaxClassObject); result := PaxClassObject.DelphiClass; PaxClassObject.PaxClassRec.PaxInfo.PaxSignature := strPaxSignature; end; function TPaxClassFactory.CreateCloneClass(const AFullClassName: String; ParentClass: TClass): TClass; var PaxClassObject: TPaxClassFactoryRec; ParentVMT: PVMT; begin ParentVMT := GetVmtFromClass(ParentClass); PaxClassObject := TPaxClassFactoryRec.Create(AFullClassName); PShortStringFromString(@PaxClassObject.fClassName, ExtractName(AFullClassName)); PaxClassObject.fParentClass := ParentClass; {$IFDEF FPC} raise Exception.Create(errNotImplementedYet); {$ELSE} vmtSelfPtrSlot(@PaxClassObject.PaxClassRec.VMT)^ := GetClassFromVMT(@PaxClassObject.PaxClassRec.VMT); vmtAutoTableSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtAutoTableSlot(ParentVMT)^; {$ENDIF} vmtIntfTableSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtIntfTableSlot(ParentVMT)^; vmtParentSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtParentSlot(ParentVMT)^; vmtClassNameSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtClassNameSlot(ParentVMT)^; vmtInstanceSizeSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtInstanceSizeSlot(ParentVMT)^; vmtNewInstanceSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtNewInstanceSlot(ParentVMT)^; vmtAfterConstructionSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtAfterConstructionSlot(ParentVMT)^; vmtBeforeDestructionSlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtBeforeDestructionSlot(ParentVMT)^; vmtDestroySlot(@PaxClassObject.PaxClassRec.VMT)^ := vmtDestroySlot(ParentVMT)^; L.Add(PaxClassObject); result := PaxClassObject.DelphiClass; PaxClassObject.PaxClassRec.PaxInfo.PaxSignature := strPaxSignature; end; function TPaxClassFactory.GetRecord(I: Integer): TPaxClassFactoryRec; begin result := TPaxClassFactoryRec(L[I]); end; function TPaxClassFactory.FindRecord(AClass: TClass): TPaxClassFactoryRec; var I: Integer; begin result := nil; for I:=0 to Count - 1 do if Records[I].DelphiClass = AClass then begin result := Records[I]; break; end; end; function TPaxClassFactory.FindRecordByFullName(const AFullClassName: String): TPaxClassFactoryRec; var I: Integer; begin result := nil; for I:=0 to Count - 1 do if StrEql(Records[I].FullClassName, AFullClassName) then begin result := Records[I]; break; end; end; function TPaxClassFactory.LookupFullName(const AFullClassName: String): TClass; var I: Integer; begin result := nil; for I:=0 to Count - 1 do if StrEql(Records[I].FullClassName, AFullClassName) then begin result := Records[I].DelphiClass; break; end; end; procedure TPaxClassFactory.Reset; var I: Integer; begin for I:=0 to Count - 1 do Records[I].Processed := false; end; procedure TPaxClassFactory.SetupStdVirtuals(ClassList: TClassList; CodePtr: Pointer); var I: Integer; ClassRec: TClassRec; FactoryRec: TPaxClassFactoryRec; P: Pointer; begin for I:=0 to ClassList.Count - 1 do begin ClassRec := ClassList[I]; if not ClassRec.Host then begin FactoryRec := FindRecord(ClassRec.PClass); if ClassRec.SafeCallExceptionProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.SafeCallExceptionProgOffset); vmtSafeCallExceptionSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.AfterConstructionProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.AfterConstructionProgOffset); vmtAfterConstructionSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.BeforeDestructionProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.BeforeDestructionProgOffset); vmtBeforeDestructionSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.DispatchProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.DispatchProgOffset); vmtDispatchSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.DefaultHandlerProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.DefaultHandlerProgOffset); vmtDefaultHandlerSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.NewInstanceProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.NewInstanceProgOffset); vmtNewInstanceSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.FreeInstanceProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.FreeInstanceProgOffset); vmtFreeInstanceSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.DestructorProgOffset > 0 then begin // P := ShiftPointer(CodePtr, ClassRec.DestructorProgOffset); // FactoryRec.GetVMTPtr^.Destroy := P; end; {$IFDEF UNIC} if ClassRec.ToStringProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.ToStringProgOffset); vmtToStringSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.GetHashCodeProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.GetHashCodeProgOffset); vmtGetHashCodeSlot(FactoryRec.GetVMTPtr)^ := P; end; if ClassRec.EqualsProgOffset > 0 then begin P := ShiftPointer(CodePtr, ClassRec.EqualsProgOffset); vmtEqualsSlot(FactoryRec.GetVMTPtr)^ := P; end; {$ENDIF} end; end; end; procedure TPaxClassFactory.SetupParents(Prog: Pointer; ClassList: TClassList); var I, J: Integer; ClassFactoryRec, ParentFactoryRec: TPaxClassFactoryRec; ClassRec, ParentClassRec: TClassRec; C: TClass; b: Boolean; S: String; begin Reset; repeat b := false; for I:=0 to Count - 1 do begin ClassFactoryRec := Records[I]; if ClassFactoryRec.Processed then continue; C := ClassFactoryRec.DelphiClass; J := ClassList.FindClass(C); if J = -1 then raise Exception.Create(errInternalError); ClassRec := ClassList[J]; ParentClassRec := ClassList.Lookup(ClassRec.ParentFullName); if ParentClassRec = nil then begin RaiseError(errInternalError, []); end; if ParentClassRec.Host then // parent is host begin if ParentClassRec.PClass = nil then begin S := ExtractName(ClassRec.ParentFullName); ParentClassRec.PClass := Classes.GetClass(S); if ParentClassRec.PClass = nil then begin if Prog <> nil then if Assigned(TBaseRunner(Prog).OnMapTableClassRef) then begin TBaseRunner(Prog).OnMapTableClassRef(TBaseRunner(Prog).Owner, ClassRec.ParentFullName, true, ParentClassRec.PClass); if ParentClassRec.PClass = nil then TBaseRunner(Prog).RaiseError(errUnresolvedClassReference, [ClassRec.ParentFullName]); end; if ParentClassRec.PClass = nil then RaiseError(errClassIsNotRegistered, [ClassRec.ParentFullName]); end; end; b := true; ClassFactoryRec.SetParentClass(ParentClassRec.PClass); ClassFactoryRec.Processed := true; end else begin ParentFactoryRec := FindRecord(ParentClassRec.PClass); if ParentFactoryRec = nil then raise Exception.Create(errInternalError); if ParentFactoryRec.Processed then begin b := true; ClassFactoryRec.SetParentClass(ParentClassRec.PClass); ClassFactoryRec.Processed := true; end; end; end; if b = false then break; until false; end; procedure TPaxClassFactory.AddInheritedMethods; var I: Integer; ClassFactoryRec, ParentFactoryRec: TPaxClassFactoryRec; C: TClass; b: Boolean; begin Reset; repeat b := false; for I:=0 to Count - 1 do begin ClassFactoryRec := Records[I]; if ClassFactoryRec.Processed then continue; C := ClassFactoryRec.DelphiClass; ParentFactoryRec := FindRecord(C.ClassParent); if ParentFactoryRec = nil then // parent is host begin b := true; AddInheritedMethods(C); ClassFactoryRec.Processed := true; end else if ParentFactoryRec.Processed then begin b := true; AddInheritedMethods(C); ClassFactoryRec.Processed := true; end; end; if b = false then break; until false; end; procedure TPaxClassFactory.AddOverridenMethods(AProg: Pointer; ScriptMapTable: TMapTable); var I, J, K: Integer; ClassFactoryRec, ParentFactoryRec: TPaxClassFactoryRec; C: TClass; b: Boolean; MapRec, SomeMR: TMapRec; P: Pointer; PC: PPointerArray; Prog: TBaseRunner; S, FileName, ProcName: String; DestProg: Pointer; begin Reset; Prog := TBaseRunner(AProg); repeat b := false; for I:=0 to Count - 1 do begin ClassFactoryRec := Records[I]; if ClassFactoryRec.Processed then continue; C := ClassFactoryRec.DelphiClass; ParentFactoryRec := FindRecord(C.ClassParent); if (ParentFactoryRec = nil) or ((ParentFactoryRec <> nil) and (ParentFactoryRec.Processed)) then begin b := true; ClassFactoryRec.Processed := true; for J:=0 to ScriptMapTable.Count - 1 do begin MapRec := ScriptMapTable[J]; if MapRec.SubDesc.MethodIndex > 0 then begin S := ExtractClassName(MapRec.FullName); if not StrEql(S, StringFromPShortString(@ClassFactoryRec.fClassName)) then continue; if MapRec.Offset = 0 then begin FileName := ExtractOwner(MapRec.FullName) + '.' + PCU_FILE_EXT; ProcName := Copy(MapRec.FullName, PosCh('.', MapRec.FullName) + 1, Length(MapRec.FullName)); P := Prog.LoadAddressEx(FileName, ProcName, false, 0, SomeMR, DestProg); end else P := ShiftPointer(Prog.CodePtr, MapRec.Offset); C := ClassFactoryRec.DelphiClass; PC := GetVArray(C); PC^[MapRec.SubDesc.MethodIndex - 1] := P; for K:=0 to Count - 1 do if K <> I then if Records[K].DelphiClass.InheritsFrom(C) then begin PC := GetVArray(Records[K].DelphiClass); PC^[MapRec.SubDesc.MethodIndex - 1] := P; end; end; end; end; end; if b = false then break; until false; end; { procedure TPaxClassFactory.AddOverridenMethods(AProg: Pointer; ScriptMapTable: TMapTable); var I, J, K: Integer; ClassFactoryRec, ParentFactoryRec: TPaxClassFactoryRec; C: TClass; b: Boolean; MapRec: TMapRec; P: Pointer; Prog: TProgram; S: AnsiString; begin Reset; Prog := TProgram(AProg); repeat b := false; for I:=0 to Count - 1 do begin ClassFactoryRec := Records[I]; if ClassFactoryRec.Processed then continue; C := ClassFactoryRec.DelphiClass; ParentFactoryRec := FindRecord(C.ClassParent); if ParentFactoryRec = nil then // parent is host begin b := true; ClassFactoryRec.Processed := true; end else if ParentFactoryRec.Processed then begin b := true; ClassFactoryRec.Processed := true; for J:=0 to ScriptMapTable.Count - 1 do begin MapRec := ScriptMapTable[J]; if MapRec.MethodIndex > 0 then begin S := ExtractClassName(MapRec.FullName); if not StrEql(S, ClassFactoryRec.fClassName) then continue; P := ShiftPointer(Prog.CodePtr, MapRec.Offset); C := ClassFactoryRec.DelphiClass; GetVArray(C)^[MapRec.MethodIndex - 1] := P; for K:=0 to Count - 1 do if Records[K].DelphiClass.InheritsFrom(C) then GetVArray(Records[K].DelphiClass)^[MapRec.MethodIndex - 1] := P; end; end; end; end; if b = false then break; until false; end; } procedure TPaxClassFactory.AddInheritedMethods(SourceClass: TClass); var P, Q: PPointerArray; I, K: Integer; begin if SourceClass.ClassParent = nil then Exit; P := GetVArray(SourceClass.ClassParent); K := GetVirtualMethodCount(SourceClass.ClassParent); Q := GetVArray(SourceClass); for I:=0 to K - 1 do Q^[I] := P^[I]; end; procedure TPaxClassFactory.AddVirtualMethod(SourceClass: TClass; SourceMethodAddress: Pointer); var P: PPointerArray; K: Integer; begin P := GetVArray(SourceClass); K := GetVirtualMethodCount(SourceClass); P^[K] := SourceMethodAddress; end; function TPaxClassFactory.AddOverridenMethod(SourceClass: TClass; SourceMethodAddress, InheritedMethodAddress: Pointer): Boolean; var P: PPointerArray; I: Integer; begin result := false; if SourceClass.ClassParent = nil then Exit; I := VirtualMethodIndex(SourceClass.ClassParent, InheritedMethodAddress); if I = -1 then Exit; P := GetVArray(SourceClass); P^[I] := SourceMethodAddress; result := true; end; end.
unit uCommonUtils; interface uses GlobalVars, ADODB, cxGridDBBandedTableView, cxGridBandedTableView, cxGridDBCardView, uAttributes, variants, cxVGrid, cxDBVGrid, cxtCustomDataSourceM, cxTableViewCds, cxGridTableView; type TScreenCursor = class protected InternalCount: integer; public procedure IncCursor; procedure DecCursor; constructor Create; virtual; destructor Destroy; override; end; TCopyFromObjectRecord = record EnableCopy: boolean; ObjectID, RecordID, UEID: integer; end; const adAffectCurrent = $00000001; adResyncAllValues = $00000002; adCriteriaKey = $00000000; var ScreenCursor: TScreenCursor; function CreateQuery(sql: string): TAdoQuery; function ExecSQLExpr(sql: string): variant; procedure ExecSQL(sql: string); function BoolToInt(b: boolean): byte; function BoolToString(b: boolean): string; function VarIsNullMy(v: Variant): boolean; function VariantToStrDB(v: variant): string; function nz(IfVariantNull, ThenValue: variant): variant; function IntToVariant(i: integer; NullIntValue: integer = 0): variant; function BooleanToVariant(b: boolean; IsNull: boolean): variant; function StrToVariant(s: string): variant; function FloatToVariant(f: double): variant; function DateToVariant(d: TDateTime): variant; function NullIF_str(v1, v2: variant): string; procedure SetColWidth(view: TcxGridTableView; MaxWidth: integer = 300); function ColumnByName(view: TcxGridBandedTableViewCds; name: string): TcxGridBandedColumnCds; function ColumnByNameOld(view: TcxGridDBBandedTableView; name: string): TcxGridDBBandedColumn; function ColumnByGroupID(view: TcxGridBandedTableViewCds; GroupID: integer; NamePart: string): TcxGridBandedColumnCds; function ColumnByGroupIDOld(view: TcxGridDBBandedTableView; GroupID: integer; NamePart: string): TcxGridDBBandedColumn; function ColumnByGroupIDAndFK(view: TcxGridBandedTableViewCds; GroupID: integer): TcxGridBandedColumnCds; function ColumnByGroupIDAndFKOld(view: TcxGridDBBandedTableView; GroupID: integer): TcxGridDBBandedColumn; function ColumnByParamName(view: TcxGridBandedTableViewCds; ParamName: string): TcxGridBandedColumnCds; function ColumnByParamNameOld(view: TcxGridDBBandedTableView; ParamName: string): TcxGridDBBandedColumn; function RowByName(Grid: TcxDBVerticalGrid; name: string): TcxDBEditorRow; function RowByGroupID(Grid: TcxDBVerticalGrid; GroupID: integer; NamePart: string): TcxDBEditorRow; function RowByGroupIDAndFK(Grid: TcxDBVerticalGrid; GroupID: integer): TcxDBEditorRow; function RowByParamName(Grid: TcxDBVerticalGrid; ParamName: string): TcxDBEditorRow; procedure CreateViewBands(view: TcxGridBandedTableViewCds; Attr: TCustomAttribute; ParentBand: TcxGridBand); procedure AssignColumnsToBands(view: TcxGridBandedTableViewCds; DefaultBand: TcxGridBand = nil); procedure CreateRowCategories(Grid: TcxDBVerticalGrid; Attr: TCustomAttribute; ParentCategory: TcxCategoryRow); procedure AssignRowsToCategories(Grid: TcxDBVerticalGrid); procedure ShowError(cap, text: string; hwnd: integer); procedure InternalRefreshAll(ds: TCustomAdoDataSet); procedure InternalRefreshCurrent(ds: TCustomAdoDataSet; ObjectName: string; view: TcxGridDBBandedTableView; ViewName: string = ''; KeyName: string = ''); procedure InternalRefreshCurrentCash(ResyncCommand: string; View: TcxGridBandedTableViewCds; ObjectName: string = ''; ViewName: string = ''; KeyName: string = ''); function GetMonthName(month: byte): string; function Zeros(count: integer): string; //возвращает GUID в виде ['{D16B83F3-C136-45C4-87AF-52412D88F25C}'] function GetGUID: string; function GetFileVersion(fname: string; var verstr: string): cardinal; function DateTo_MMMMDDDD_Str(d: TDateTime): string; implementation uses windows, uMetaData, uException, Dialogs, Forms, SysUtils, Controls, DB, uCashDataSource; function CreateQuery(sql: string): TAdoQuery; begin result:=TAdoQuery.Create(nil); result.Connection:=Connection; result.SQL.Text:=sql; result.ParamCheck:=false; result.LockType:=ltReadOnly; result.CursorType:=ctOpenForwardOnly; // result.CursorLocation:=clUseServer; end; function ExecSQLExpr(sql: string): variant; var qry: TAdoQuery; begin qry:=CreateQuery(sql); try qry.Open; result:=qry.Fields[0].Value; finally qry.Free; end; end; procedure ExecSQL(sql: string); var qry: TAdoQuery; begin qry:=CreateQuery(sql); ScreenCursor.IncCursor; try qry.ExecSQL; finally ScreenCursor.DecCursor; qry.Free; end; end; function BoolToInt(b: boolean): byte; begin if b then result:=1 else result:=0; end; function BoolToString(b: boolean): string; begin if b then result:='1' else result:='0'; end; function VarIsNullMy(v: Variant): boolean; begin result:=VarIsNull(v) or VarIsEmpty(v); end; function VariantToStrDB(v: variant): string; begin if VarIsNullMy(v) then result:='null' else result:=v; end; function nz(IfVariantNull, ThenValue: variant): variant; begin if VarIsNullMy(IfVariantNull) then result:=ThenValue else result:=IfVariantNull; end; function IntToVariant(i: integer; NullIntValue: integer = 0): variant; begin if i=NullIntValue then result:=null else result:=i; end; function BooleanToVariant(b: boolean; IsNull: boolean): variant; begin if IsNull then result:=null else result:=b; end; function StrToVariant(s: string): variant; begin if trim(s)='' then result:=null else result:=s; end; function FloatToVariant(f: double): variant; begin if f=0 then result:=null else result:=f; end; function DateToVariant(d: TDateTime): variant; begin if d=-700000 then result:=null else result:=d; end; function NullIF_str(v1, v2: variant): string; begin if v1=v2 then result:='null' else result:=v1; end; procedure SetColWidth(view: TcxGridTableView; MaxWidth: integer = 300); var i: integer; begin for i:=0 to view.ColumnCount-1 do if view.Columns[i].Width>MaxWidth then view.Columns[i].Width:=MaxWidth; end; function ColumnByName(view: TcxGridBandedTableViewCds; name: string): TcxGridBandedColumnCds; var i: integer; begin result:=nil; name:=AnsiLowerCase(name); for i:=0 to view.ColumnCount-1 do if AnsiLowerCase(view.Columns[i].DataBinding.FieldName) = name then begin result:=view.Columns[i]; exit; end; end; function ColumnByNameOld(view: TcxGridDBBandedTableView; name: string): TcxGridDBBandedColumn; var i: integer; begin result:=nil; name:=AnsiLowerCase(name); for i:=0 to view.ColumnCount-1 do if AnsiLowerCase(view.Columns[i].DataBinding.FieldName) = name then begin result:=view.Columns[i]; exit; end; end; function ColumnByGroupID(view: TcxGridBandedTableViewCds; GroupID: integer; NamePart: string): TcxGridBandedColumnCds; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to view.ColumnCount-1 do begin mi:=pointer(view.Columns[i].Tag); if (mi.GroupID=GroupID) and (pos(NamePart, mi.ColName)<>0) then begin result:=view.Columns[i]; exit; end; end; end; function ColumnByGroupIDOld(view: TcxGridDBBandedTableView; GroupID: integer; NamePart: string): TcxGridDBBandedColumn; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to view.ColumnCount-1 do begin mi:=pointer(view.Columns[i].Tag); if (mi.GroupID=GroupID) and (pos(NamePart, mi.ColName)<>0) then begin result:=view.Columns[i]; exit; end; end; end; function ColumnByParamName(view: TcxGridBandedTableViewCds; ParamName: string): TcxGridBandedColumnCds; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to view.ColumnCount-1 do begin mi:=pointer(view.Columns[i].Tag); if not Assigned(mi) then raise Exception.Create('ColumnByParamName: не ассоциированы метаданные '+view.Columns[i].Caption); if mi.ParamName=ParamName then begin result:=view.Columns[i]; exit; end; end; end; function ColumnByParamNameOld(view: TcxGridDBBandedTableView; ParamName: string): TcxGridDBBandedColumn; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to view.ColumnCount-1 do begin mi:=pointer(view.Columns[i].Tag); if not Assigned(mi) then raise Exception.Create('ColumnByParamNameOld: не ассоциированы метаданные '+view.Columns[i].Caption); if mi.ParamName=ParamName then begin result:=view.Columns[i]; exit; end; end; end; function ColumnByGroupIDAndFK(view: TcxGridBandedTableViewCds; GroupID: integer): TcxGridBandedColumnCds; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to view.ColumnCount-1 do begin mi:=pointer(view.Columns[i].Tag); if (mi.GroupID=GroupID) and mi.IsForeignKey then begin result:=view.Columns[i]; exit; end; end; end; function ColumnByGroupIDAndFKOld(view: TcxGridDBBandedTableView; GroupID: integer): TcxGridDBBandedColumn; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to view.ColumnCount-1 do begin mi:=pointer(view.Columns[i].Tag); if (mi.GroupID=GroupID) and mi.IsForeignKey then begin result:=view.Columns[i]; exit; end; end; end; procedure CreateViewBands(view: TcxGridBandedTableViewCds; Attr: TCustomAttribute; ParentBand: TcxGridBand); var i: integer; Band, B1: TcxGridBand; begin for i:=0 to Attr.Count-1 do begin if Attr.Attr[i].AttrType in [atAddress, atDocument, atCategory] then begin Band:=view.Bands.Add; Band.Caption:=Attr.Attr[i].Name; if Assigned(ParentBand) then Band.Position.BandIndex:=ParentBand.Index; if Attr.Attr[i].AttrType = atCategory then CreateViewBands(view, Attr.Attr[i], Band); end; end; end; procedure CreateRowCategories(Grid: TcxDBVerticalGrid; Attr: TCustomAttribute; ParentCategory: TcxCategoryRow); var i: integer; cat: TcxCategoryRow; begin for i:=0 to Attr.Count-1 do begin if Attr.Attr[i].AttrType in [atAddress, atDocument, atCategory] then begin cat:=Grid.Add(TcxCategoryRow) as TcxCategoryRow; cat.Properties.Caption:=Attr.Attr[i].Name; if Assigned(ParentCategory) then cat.Parent:=ParentCategory; CreateRowCategories(Grid, Attr.Attr[i], cat); end; end; end; procedure AssignRowsToCategories(Grid: TcxDBVerticalGrid); function FindCategoryByName(Grid: TcxDBVerticalGrid; name: string): TcxCategoryRow; var i: integer; begin result:=nil; for i:=0 to Grid.Rows.Count-1 do if (Grid.Rows[i] is TcxCategoryRow) and ((Grid.Rows[i] as TcxCategoryRow).Properties.Caption = name) then begin result:=Grid.Rows[i] as TcxCategoryRow; exit; end; end; var i: integer; mi: TMetaDataItem; cat: TcxCategoryRow; wasmove: boolean; begin wasmove:=true; while wasmove do begin wasmove:=false; for i:=0 to Grid.Rows.Count-1 do begin if (Grid.Rows[i] is TcxDBEditorRow) and (not Assigned(Grid.Rows[i].Parent)) then mi:=pointer((Grid.Rows[i] as TcxDBEditorRow).Tag) else continue; if Assigned(mi) and (mi.CategoryName<>'') then begin cat:=FindCategoryByName(Grid, mi.CategoryName); if Assigned(cat) then begin Grid.Rows[i].Parent:=cat; wasmove:=true; end; end; end; end; end; procedure AssignColumnsToBands(view: TcxGridBandedTableViewCds; DefaultBand: TcxGridBand = nil); function BandByName(view: TcxGridBandedTableViewCds; ParentBand: TcxGridBand; Name: string): TcxGridBand; var i: integer; begin result:=nil; if not Assigned(ParentBand) then begin for i:=0 to view.Bands.Count-1 do if view.Bands[i].Caption=Name then begin result:=view.Bands[i]; break; end; end else for i:=0 to ParentBand.ChildBandCount-1 do if ParentBand.ChildBands[i].Caption=Name then begin result:=ParentBand.ChildBands[i]; break; end; end; var i : integer; MetaItem: TMetaDataItem; MainBand, B, B1: TcxGridBand; begin MainBand:=view.Bands[1]; for i:=0 to view.ColumnCount-1 do begin MetaItem:=pointer(view.Columns[i].Tag); if not Assigned(MetaItem) then raise Exception.Create('Не найдено поле метаданных для поля с индексом '+IntToStr(i)+' - '+view.Columns[i].Caption); if MetaItem.CategoryName='' then begin if MetaItem.ColName='ForADOInsertCol' then begin view.Columns[i].Position.BandIndex:=0; continue; end; if Assigned(DefaultBand) then begin if DefaultBand.ChildBandCount>0 then begin B1:=BandByName(nil, DefaultBand, ' '); if Assigned(B1) then view.Columns[i].Position.BandIndex:=B1.Index else begin B1:=view.Bands.Add; B1.Caption:=' '; B1.Position.BandIndex:=DefaultBand.Index; B1.Position.ColIndex:=0; view.Columns[i].Position.BandIndex:=B1.Index end; end else view.Columns[i].Position.BandIndex:=DefaultBand.Index // view.Columns[i].Position.BandIndex:=DefaultBand.Index end else view.Columns[i].Position.BandIndex:=MainBand.Index end else begin B:=BandByName(view, nil, MetaItem.CategoryName); if not Assigned(B) then raise EBandNotFoundException.Create('Бэнд "'+MetaItem.CategoryName+'" не найден'); if B.ChildBandCount>0 then begin B1:=BandByName(nil, B, ' '); if Assigned(B1) then view.Columns[i].Position.BandIndex:=B1.Index else begin B1:=view.Bands.Add; B1.Caption:=' '; B1.Position.BandIndex:=B.Index; view.Columns[i].Position.BandIndex:=B1.Index end; end else view.Columns[i].Position.BandIndex:=B.Index end; end; end; function RowByName(Grid: TcxDBVerticalGrid; name: string): TcxDBEditorRow; var i: integer; begin result:=nil; for i:=0 to Grid.Rows.Count-1 do if (Grid.Rows[i] is TcxDBEditorRow) and ((Grid.Rows[i] as TcxDBEditorRow).Properties.DataBinding.FieldName = name) then begin result:=Grid.Rows[i] as TcxDBEditorRow; exit; end; end; function RowByGroupID(Grid: TcxDBVerticalGrid; GroupID: integer; NamePart: string): TcxDBEditorRow; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to Grid.Rows.Count-1 do begin if (Grid.Rows[i] is TcxDBEditorRow) then mi:=pointer((Grid.Rows[i] as TcxDBEditorRow).Tag) else continue; if (mi.GroupID=GroupID) and (pos(NamePart, mi.ColName)<>0) then begin result:=Grid.Rows[i] as TcxDBEditorRow; exit; end; end; end; function RowByGroupIDAndFK(Grid: TcxDBVerticalGrid; GroupID: integer): TcxDBEditorRow; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to Grid.Rows.Count-1 do begin if (Grid.Rows[i] is TcxDBEditorRow) then mi:=pointer((Grid.Rows[i] as TcxDBEditorRow).Tag) else continue; if (mi.GroupID=GroupID) and mi.IsForeignKey then begin result:=Grid.Rows[i] as TcxDBEditorRow; exit; end; end; end; function RowByParamName(Grid: TcxDBVerticalGrid; ParamName: string): TcxDBEditorRow; var i: integer; mi: TMetaDataItem; begin result:=nil; for i:=0 to Grid.Rows.Count-1 do begin if (Grid.Rows[i] is TcxDBEditorRow) then mi:=pointer((Grid.Rows[i] as TcxDBEditorRow).Tag) else continue; if mi.ParamName=ParamName then begin result:=Grid.Rows[i] as TcxDBEditorRow; exit; end; end; end; procedure ShowError(cap, text: string; hwnd: integer); begin if hwnd=-1 then hwnd:=Application.MainForm.Handle; MessageBox(hwnd, pchar(text), pchar(cap), MB_ICONERROR or MB_APPLMODAL); end; procedure InternalRefreshAll(ds: TCustomAdoDataSet); var id: integer; begin if ds.Active and (ds.RecordCount>0) then begin id:=ds.Fields[0].Value; ds.Close; ds.Open; ds.Locate(ds.Fields[0].DisplayName, id, []); end else begin ds.Close; ds.Open; end; end; procedure InternalRefreshCurrent(ds: TCustomAdoDataSet; ObjectName: string; view: TcxGridDBBandedTableView; ViewName: string = ''; KeyName: string = ''); begin ds.Properties['Unique Table'].Value:=ObjectName; if KeyName='' then ds.Properties['Resync Command'].Value:=format('select * from [в_%s] where [%0:s.код_%0:s] = ?', [ObjectName]) else ds.Properties['Resync Command'].Value:=format('select * from [%s] where [%s] = ?', [ViewName, KeyName]); ds.Recordset.Resync(adAffectCurrent, adResyncAllValues); ds.Resync([]); view.DataController.DoUpdateRecord(view.DataController.FocusedRecordIndex); end; procedure RefreshCds(ADt:Tdataset; ACds:TCashDataSource); var KeyFld:TcdField; DtKeyField:TField; KeyVal:Variant; Ridx:Integer; i:integer; TmpFld:TField; begin //ACds.KeyFields - published свойство, для удобства //Оно определяет ключевое поле KeyFld := ACds.FieldByName(ACds.KeyFields); DtKeyField := ADt.FieldByName(ACds.KeyFields); while not ADt.Eof do begin KeyVal := DtKeyField.Value; Ridx := ACds.Locate([KeyFld.Index],KeyVal,[]) ; if Ridx < 0 then Continue; for I := 0 to ACds.FieldCount - 1 do begin TmpFld := ADt.FindField(ACds.Fields[i].FieldName) ; if TmpFld = nil then Continue; //Здесь можно было бы использовать свойство Values, но //при его использовании все измения кешируются, //а метод CashEdit изменяет данные без кеширования изменений ACds.CashEdit(RIdx,i,TmpFld.Value,true, true); end; ADt.Next; end; end; procedure InternalRefreshCurrentCash(ResyncCommand: string; View: TcxGridBandedTableViewCds; ObjectName: string = ''; ViewName: string = ''; KeyName: string = ''); var qry: TAdoQuery; ds: TcxtCustomDataSourceM; begin if View.DataController.FocusedRecordIndex<0 then exit; if ResyncCommand='' then if KeyName='' then ResyncCommand:=format('select * from [в_%s] where [%0:s.код_%0:s] = ?', [ObjectName]) else ResyncCommand:=format('select * from [%s] where [%s] = ?', [ViewName, KeyName]); qry:=CreateQuery(ResyncCommand); try ds:=View.DataController.CashDataSource; qry.Open; //ds.IsLockedGridChange:=true; try RefreshCds(qry, ds); finally // ds.IsLockedGridChange:=false; end; View.DataController.DataControllerInfo.RefreshFocused; //ds.DataChanged(); finally qry.Free; end; end; function GetMonthName(month: byte): string; begin case month of 1: result:='январь'; 2: result:='февраль'; 3: result:='март'; 4: result:='апрель'; 5: result:='май'; 6: result:='июнь'; 7: result:='июль'; 8: result:='август'; 9: result:='сентябрь'; 10: result:='октябрь'; 11: result:='ноябрь'; 12: result:='декабрь'; end end; function Zeros(count: integer): string; begin result:=''; while count>0 do begin result:=result+'0'; dec(count); end; end; //возвращает GUID в виде ['{D16B83F3-C136-45C4-87AF-52412D88F25C}'] function GetGUID: string; var guid: TGUID; begin CreateGUID(guid); result:=GUIDToString(guid); end; function DateTo_MMMMDDDD_Str(d: TDateTime): string; const mm: array[1..12] of string = ('январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь'); var y, m, dd: word; begin DecodeDate(d, y, m, dd); result:=mm[m]+' '+IntToStr(y); end; function GetFileVersion(fname: string; var verstr: string): cardinal; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; v1, v2, v3, v4: cardinal; begin VerInfoSize:=GetFileVersionInfoSize(pchar(fname), Dummy); GetMem(VerInfo, VerInfoSize); GetFileVersionInfo(PChar(fname), 0, VerInfoSize, VerInfo); try VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); except VerValue^.dwFileVersionMS:=0; VerValue^.dwFileVersionLS:=0; end; with VerValue^ do begin v1:=dwFileVersionMS shr 16; v2:=dwFileVersionMS and $FFFF; v3:=dwFileVersionLS shr 16; v4:=dwFileVersionLS and $FFFF; result:=v1 shl 24 + v2 shl 16 + v3 shl 8 + v4; verstr:=IntToStr(v1)+'.'+IntToStr(v2)+'.'+IntToStr(v3)+'.'+IntToStr(v4); end; end; { TScreenCursor } constructor TScreenCursor.Create; begin inherited; InternalCount:=0; end; procedure TScreenCursor.DecCursor; begin dec(InternalCount); if InternalCount=0 then Screen.Cursor:=crDefault; end; destructor TScreenCursor.Destroy; begin Screen.Cursor:=crDefault; inherited; end; procedure TScreenCursor.IncCursor; begin inc(InternalCount); Screen.Cursor:=crHourGlass; end; initialization ScreenCursor:=TScreenCursor.Create; finalization ScreenCursor.Free; end.
unit uFrmDadosFornecedor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmDadosBase, StdCtrls, Buttons, ExtCtrls, Mask, Fornecedor, uFornecedorDAOClient, DBClient; type TFrmDadosFornecedor = class(TFrmDadosBase) Label1: TLabel; edtCodigo: TEdit; Label2: TLabel; edtNome: TEdit; Label3: TLabel; mkdTelefone: TMaskEdit; private { Private declarations } DAOClient: TFornecedorDAOClient; protected procedure OnCreate; override; procedure OnDestroy; override; procedure OnSave; override; procedure OnShow; override; public { Public declarations } Fornecedor: TFornecedor; end; var FrmDadosFornecedor: TFrmDadosFornecedor; implementation uses MensagensUtils, TypesUtils; {$R *.dfm} { TFrmDadosFornecedor } procedure TFrmDadosFornecedor.OnCreate; begin inherited; SetCamposObrigatorios([edtNome]); DAOClient := TFornecedorDAOClient.Create(DBXConnection); end; procedure TFrmDadosFornecedor.OnDestroy; begin inherited; DAOClient.Free; end; procedure TFrmDadosFornecedor.OnSave; var cds: TClientDataSet; begin inherited; cds := TClientDataSet(Owner.FindComponent('cdsCrud')); if (Operacao = opInsert) then begin edtCodigo.Text := DAOClient.NextCodigo; if not(DAOClient.Insert(TFornecedor.Create(edtCodigo.Text, edtNome.Text, mkdTelefone.Text))) then Erro('Ocorreu algum erro durante a inclusão.'); cds.Append; cds.FieldByName('CODIGO').AsString := edtCodigo.Text; cds.FieldByName('NOME').AsString := edtNome.Text; cds.FieldByName('TELEFONE').AsString := mkdTelefone.Text; cds.Post; end else begin if not(DAOClient.Update(TFornecedor.Create(edtCodigo.Text, edtNome.Text, mkdTelefone.Text))) then Erro('Ocorreu algum erro durante a alteração.'); cds.Edit; cds.FieldByName('CODIGO').AsString := edtCodigo.Text; cds.FieldByName('NOME').AsString := edtNome.Text; cds.FieldByName('TELEFONE').AsString := mkdTelefone.Text; cds.Post; end; if (chbContinuarIncluindo.Checked) then LimparControles else Self.Close; end; procedure TFrmDadosFornecedor.OnShow; begin inherited; if (Assigned(Fornecedor)) then begin edtCodigo.Text := Fornecedor.Codigo; edtNome.Text := Fornecedor.Nome; mkdTelefone.Text := Fornecedor.Telefone; end; end; end.
unit uniteReponse; //Encapsule les données renvoyer par le serveur. interface uses SysUtils; //Encapsule les données renvoyées par le serveur. type Reponse = class private //Adresse demandeur adresseDemandeur : String; //Version HTTP 1.0 ou 1.1 versionProtocole : String; //Code d'erreur si necessaire ex : 404 codeReponse : Word; //Message d'erreur message : String; //Reponse HTML --- message d'aide reponseHtml : String; public //Crée un objet Reponse. //Reçoit en paramètres tous les attributs de la classe Reponse. // //@param uneAdresseDemandeur l'adresse ip du demandeur //@param uneVersionProtocole la version du protocole http //@param unCodeReponse le code réponse est un code d’erreur résultant de la requête //@param unMessage un bref message d'erreur //@param uneReponseHtml un message d’erreur plus descriptif constructor create(uneAdresseDemandeur:String;uneVersionProtocole:String;unCodeReponse:Word;unMessage:String;uneReponseHtml:String); //Accesseur adresseDemandeur // //@return retourne l'adresseDemandeur en String function getAdresseDemandeur:String; //Accesseur versionProtocole // //@return retourne la versionProtocole en String function getVersionProtocole:String; //Accesseur codeReponse // //@return retourne le codeReponse en Word function getCodeReponse:Word; //Accesseur message // //@return retourne le message en String function getMessage:String; //Accesseur reponseHtml // //@return retourne la reponseHtml en String function getReponseHtml:String; end; implementation constructor Reponse.create(uneAdresseDemandeur:String;uneVersionProtocole:String;unCodeReponse:Word;unMessage:String;uneReponseHtml:String); begin end; function Reponse.getAdresseDemandeur:String; begin result:=''; end; function Reponse.getVersionProtocole:String; begin result:=''; end; function Reponse.getCodeReponse:Word; begin result:=0; end; function Reponse.getMessage:String; begin result:=''; end; function Reponse.getReponseHtml:String; begin result:=''; end; end.
{...................................................................................} { Summary Converts a monochrome image as a PCB Logo into a series of thin } { PCB tracks that can be placed on a PCB document as a logo. } { } { Scan Pixel algorithm provided by } { Paul D. Fincato } { fincato@infinet.com } { } { Version 1.2 } { Change scale to percentage } { Allow not integer values for scaling (bitmap can be scaled less then 1) } { Make changes to form as the Image Size string was getting clipped } { Don't exit program on non b/w file type } { Add Metric support } { Darren Moore Mar 2005 } { } { Version 1.3 } { Fixed bug flippedX Height, changed to Width } { Fixed bug with scaling } { The way the scaling was done, if the size was less then 100% } { the image was not drawn correctly } { Removed data being saved to an intermediate file } { Made other changes to improve speed (overall speed now x 2) } { Darren Moore Jul 2005 } { } {...................................................................................} {......................................................................................................................} Procedure RunConverterScript; Begin // Set the default layer to Top layer. ConverterForm.ComboBoxLayers.ItemIndex := 0; ConverterForm.ConvertButton.Enabled := False; ConverterForm.ShowModal; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.eScalingFactorChange(Sender: TObject); Begin lImageSize.Caption := IntToStr(Image1.Picture.Width * (eScalingFactor.Text / 100)) + ' x ' + IntToStr(Image1.Picture.Height * (eScalingFactor.Text / 100)) + ' mils'; lImageSizeMM.Caption := IntToStr(Image1.Picture.Width * (eScalingFactor.Text / 3937)) + ' x ' + IntToStr(Image1.Picture.Height * (eScalingFactor.Text / 3937)) + ' mm'; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.loadbuttonClick(Sender: TObject); Begin If OpenPictureDialog1.Execute then Begin XPProgressBar1.Position := 0; XStatusBar1.SimpleText := ' Loading...'; XStatusBar1.Update; // loading a monochrome bitmap only Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName); // Check if image is monochrome, otherwise prompt a warning If Image1.Picture.Bitmap.PixelFormat <> pf1bit Then Begin ShowWarning('The image file must be monochrome!'); Exit; End; lImageSize.Caption := IntToStr(Image1.Picture.Width) + ' x ' + IntToStr(Image1.Picture.Height) + ' mils'; lImageSizeMM.Caption := IntToStr(Image1.Picture.Width * (eScalingFactor.Text / 3937)) + ' x ' + IntToStr(Image1.Picture.Height * (eScalingFactor.Text / 3937)) + ' mm'; convertbutton.Enabled := True; XStatusBar1.SimpleText := ' Ready...'; XStatusBar1.Update; End; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.convertbuttonClick(Sender: TObject); Var x, y, xt, FlipY, FlipX : Integer; PixelColor : TColor; Start : Boolean; PCBBoard : IPCB_Board; PCBLayer : TLayer; ScaleFactor : Integer; PCBTrack : IPCB_Track; Sheet : IPCB_Sheet; OffSet : TCoord; BaseX1, BaseX2, BaseY : TCoord; Begin Screen.Cursor := crHourGlass; XPProgressBar1.Max := Image1.Picture.Height; // Create a standalone blank PCB document CreateNewDocumentFromDocumentKind('PCB'); // GetCurrentPCBBoard returns a IPCB_Board type. PCBBoard := PCBServer.GetCurrentPCBBoard; If PCBBoard = Nil Then Begin ShowWarning('A PCB document was not created properly.'); Exit; End Else Begin PCBBoard := PCBServer.GetCurrentPCBBoard; PCBLayer := String2Layer(ComboBoxLayers.Items[ComboBoxLayers.ItemIndex]); ScaleFactor := StrToInt(eScalingFactor.Text)/100; // ensure the layer selected is displayed in the PCB workspace PCBBoard.LayerIsDisplayed[PCBLayer] := True; Sheet := PCBBoard.PCBSheet; OffSet := MilsToCoord(100); End; xt := 0; // do this calc here once to help speed up the loop.. If (cbMirrorX.Checked) Then Begin BaseX1 := Sheet.SheetX + Offset - MilsToCoord(ScaleFactor/3); BaseX2 := Sheet.SheetX + Offset + MilsToCoord((ScaleFactor/3)); End Else Begin BaseX1 := Sheet.SheetX + Offset + MilsToCoord(ScaleFactor/3); BaseX2 := Sheet.SheetX + Offset - MilsToCoord((ScaleFactor/3)); End; BaseY := Sheet.SheetY + Offset; XStatusBar1.SimpleText := ' Converting...'; XStatusBar1.Update; For Y := 0 to Image1.Picture.Height Do Begin XPProgressBar1.Position := Y; XPProgressBar1.Update; If (cbMirrorY.Checked) Then FlipY := Y Else FlipY := Abs(Y - Image1.Picture.Height); // Denotes the start of a line on a row of an image Start := False; For X := 0 To Image1.Picture.Width Do Begin PixelColor := Image1.Canvas.Pixels[x,y]; If cbMirrorX.Checked Then FlipX := abs(X - Image1.Picture.Width) Else FlipX := X; If (cbNegative.Checked) Then Begin Case PixelColor Of clWhite : If Not (Start) Then Begin xt := FlipX; Start := True; End; clBlack : Begin If (Start) Then Begin // place a new track on the blank PCB PCBTrack := PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default); PCBTrack.Width := MilsToCoord(ScaleFactor); PCBTrack.X1 := BaseX1 + MilsToCoord(xt * ScaleFactor); PCBTrack.Y1 := BaseY + MilsToCoord(FlipY * ScaleFactor); PCBTrack.X2 := BaseX2 + MilsToCoord(FlipX * ScaleFactor); PCBTrack.Y2 := PCBTrack.Y1; PCBTrack.Layer := PCBLayer; PCBBoard.AddPCBObject(PCBTrack); Start := False; End; End; End; End Else Begin Case PixelColor Of clBlack: If Not (Start) Then Begin xt := FlipX; Start := True; End; clWhite: Begin If (Start) Then Begin // place a new track on the blank PCB PCBTrack := PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default); PCBTrack.Width := MilsToCoord(ScaleFactor); PCBTrack.X1 := BaseX1 + MilsToCoord(xt * ScaleFactor); PCBTrack.Y1 := BaseY + MilsToCoord(FlipY * ScaleFactor); PCBTrack.X2 := BaseX2 + MilsToCoord(FlipX * ScaleFactor); PCBTrack.Y2 := PCBTrack.Y1; PCBTrack.Layer := PCBLayer; PCBBoard.AddPCBObject(PCBTrack); Start := False; End; End; End; End; End; If Start Then Begin // place a new track on the blank PCB PCBTrack := PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default); PCBTrack.Width := MilsToCoord(ScaleFactor); PCBTrack.X1 := BaseX1 + MilsToCoord(xt * ScaleFactor); PCBTrack.Y1 := BaseY + MilsToCoord(FlipY * ScaleFactor); PCBTrack.X2 := BaseX2 + MilsToCoord(FlipX * ScaleFactor); PCBTrack.Y2 := PCBTrack.Y1; PCBTrack.Layer := PCBLayer; PCBBoard.AddPCBObject(PCBTrack); End; End; Client.SendMessage('PCB:Zoom', 'Action=All' , 255, Client.CurrentView); Screen.Cursor := crArrow; XStatusBar1.SimpleText := ' Done...'; XStatusBar1.Update; // Hide this form when a PCB document is created and a new logo added.. ConverterForm.Hide; // toggle buttons LoadButton.Enabled := True; // Unhide form ConverterForm.Show; End; {......................................................................................................................} {......................................................................................................................} Procedure TConverterForm.exitbuttonClick(Sender: TObject); Begin Close; End; {......................................................................................................................}
unit uPOSServerConsts; interface uses Messages; const SCH_SERVER = 'ServerSchedule'; SCH_POS = 'POSSchedule'; MR_HST_CONT_FAIL = 'Local Connection fail. '; MR_HST_SVR_CONT_FAIL = 'Server Connection fail. '; MR_HST_JOB_FAIL = 'Job fail : '; MR_HST_VPN_FAIL = 'VPN fail to connect.'; MR_HST_OK = ' succeed. '; MR_HST_ERROR = 'Error: '; HISTORY_FILE = 'history.txt'; ERROR_FILE = 'historyerror.txt'; IMPORT_FILE = 'historyimport.txt'; WM_ICONMESSAGE = WM_USER + 1; REG_PATH = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'; PDV_PERSISTENCE_FILE = 'MRPDVPersistence.ini'; PDV_GLOBAL_DIR = 'PDVFiles\'; POS_DIR_FILES = 'LogFiles\'; POS_DIR_FILES_HISTORY = 'LogFilesHistory\'; POS_PDV_KEY = 'PDVTerminals'; POS_PDV_KEY_LAST_FILE = 'LastImportedFileName'; POS_PDV_KEY_LAST_DATE = 'LastImportedFileDate'; POS_LAST_IMPORT_DATE = 'LastImportDate'; //Arquivos Globais PDV_MEDIA_FILE = 'Media'; PDV_SYSTEM_USER_FILE = 'SystemUser'; PDV_OTHER_COMMIS_FILE = 'OtherCommission'; PDV_CUSTOMER_FILE = 'Customer'; PDV_PARAM_FILE = 'Param'; PDV_STORE_FILE = 'Store'; PDV_USER_TO_SYS_FILE = 'UserTypeToSysFunction'; PDV_USER_RIGHTS_FILE = 'UserRights'; PDV_MODEL_FILE = 'Model'; PDV_BARCODE_FILE = 'Barcode'; PDV_ACCESSORY_FILE = 'ModelAccessory'; PDV_PAY_TYPR_FILE = 'MeioPag'; PDV_QTY_FILE = 'Quantity'; PDV_CASHREGISTER_FILE = 'CashRegister'; PDV_ACCES_FILE = 'Access'; PDV_TAXCATEGORY_FILE = 'TaxCategory'; PDV_KITMODEL_FILE = 'KitModel'; PDV_BANK_FILE = 'Fin_Banco'; PDV_DISCRANGE_FILE = 'DiscRange'; PDV_INV_FEATURES_FILE = 'InvFeatures'; PDV_INV_TECH_FEATURES_FILE = 'InvTechFeatures'; PDV_INV_DEPARTMENT = 'InvDepartment'; PDV_INV_MODEL_DEPARTMENT = 'InvModelDepartment'; PDV_INV_MODEL_SERIAL = 'InventorySerial'; PDV_INV_STORE_PRICE = 'InvStoreTablePrice'; PDV_INV_MODEL_PRICE = 'InvModelTablePrice'; PDV_MNT_DOCUMENT_TYPE = 'MntDocumentType'; PDV_CASH_REG_LOG_REASON = 'CashRegLogReason'; PDV_PAY_TYPE_MIN_SALE = 'MeioPagMinSale'; CUPOM_VAZIO = 'XXXXXX'; CONFIG_FILE = 'posserver.ini'; CONFIG_PDV_FILE= 'pdvhistory.ini'; MR_SYSTEM_TIP = 'MainRetail POS Server'; SV_CONNECTION = '#CNT#='; SV_USER = '#USER#='; SV_PASSWORD = '#PW#='; SV_CLOSE_VPN = '#CVPN#='; SINC_TYPE_SERVER = 0; SINC_TYPE_CASH_LOG = 1; CON_TYPE_SERVER = 0; CON_TYPE_FTP = 1; implementation end.
unit Up_Sys_Level; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView, dxBarExtItems, dxBar, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridDBTableView, cxGrid, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, ibase, ZProc, Unit_ZGlobal_Consts; type TZFUpSysLevel = class(TForm) GridDBTableView1: TcxGridDBTableView; GridLevel1: TcxGridLevel; Grid: TcxGrid; Styles: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; Database: TpFIBDatabase; DataSet: TpFIBDataSet; ReadTransaction: TpFIBTransaction; DataSource: TDataSource; GridDBTableView1DBLevelName: TcxGridDBColumn; BarManager: TdxBarManager; SelectBtn: TdxBarLargeButton; RefreshBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; procedure SelectBtnClick(Sender: TObject); procedure ExitBtnClick(Sender: TObject); procedure RefreshBtnClick(Sender: TObject); private PlanguageIndex:byte; public Result:Variant; constructor Create(AOwner:TComponent;DB:TISC_DB_HANDLE);reintroduce; end; implementation {$R *.dfm} const ZFUPSysLevel_Caption :array[1..2] of string = ('Рівень','Уровень'); LevelName_Caption :array[1..2] of string = ('Рівень','Уровень'); constructor TZFUpSysLevel.Create(AOwner:TComponent;DB:TISC_DB_HANDLE); begin inherited Create(AOwner); PlanguageIndex:=LanguageIndex; Database.Handle :=DB; DataSet.SelectSQL.Text :='SELECT * FROM UP_SYS_LEVEL'; Database.Open; DataSet.Open; //****************************************************************************** self.Caption := ZFUPSysLevel_Caption[PlanguageIndex]; RefreshBtn.Caption := RefreshBtn_Caption[PlanguageIndex]; SelectBtn.Caption := SelectBtn_Caption[PlanguageIndex]; ExitBtn.Caption := ExitBtn_Caption[PlanguageIndex]; GridDBTableView1DBLevelName.Caption := LevelName_Caption[PlanguageIndex]; end; procedure TZFUpSysLevel.SelectBtnClick(Sender: TObject); begin Result:= VarArrayCreate([0,1],varVariant); Result[0]:=DataSet.FieldValues['ID_LEVEL']; Result[1]:=DataSet.FieldValues['LEVEL_NAME']; ModalResult:=mrYes; end; procedure TZFUpSysLevel.ExitBtnClick(Sender: TObject); begin ModalResult:=mrNo; end; procedure TZFUpSysLevel.RefreshBtnClick(Sender: TObject); begin DataSet.FullRefresh; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [LOGSS] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit LogssVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TLogssVO = class(TVO) private FID: Integer; FTTP: Integer; FPRODUTO: Integer; FR01: Integer; FR02: Integer; FR03: Integer; FR04: Integer; FR05: Integer; FR06: Integer; FR07: Integer; published property Id: Integer read FID write FID; property Ttp: Integer read FTTP write FTTP; property Produto: Integer read FPRODUTO write FPRODUTO; property R01: Integer read FR01 write FR01; property R02: Integer read FR02 write FR02; property R03: Integer read FR03 write FR03; property R04: Integer read FR04 write FR04; property R05: Integer read FR05 write FR05; property R06: Integer read FR06 write FR06; property R07: Integer read FR07 write FR07; end; TListaLogssVO = specialize TFPGObjectList<TLogssVO>; implementation initialization Classes.RegisterClass(TLogssVO); finalization Classes.UnRegisterClass(TLogssVO); end.
unit Rules; interface uses System.SysUtils, System.Classes, REST.Types, REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, Data.DBXPlatform, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IPPeerServer, Datasnap.DSCommonServer, Datasnap.DSServer, Datasnap.DSHTTP, Datasnap.DSHTTPCommon, Original; type TdmDataSnap = class(TDataModule) IdHTTP1: TIdHTTP; DSServer1: TDSServer; DSHTTPService1: TDSHTTPService; DSServerClass1: TDSServerClass; IdHTTP2: TIdHTTP; procedure DSServerClass1GetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DataModuleCreate(Sender: TObject); procedure DSHTTPService1HTTPTrace(Sender: TObject; AContext: TDSHTTPContext; ARequest: TDSHTTPRequest; AResponse: TDSHTTPResponse); public function GetImageRotinaOriginal(const AID: string): TStringStream; function GetImageRotinaProposta(const AID: string): TStringStream; function GetImageFromSismic(const AID: string): TStringStream; function GetImageNewImage: TStringStream; end; var dmDataSnap: TdmDataSnap; implementation uses System.JSON, Proposal, GetImage; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TdmDataSnap } procedure TdmDataSnap.DataModuleCreate(Sender: TObject); begin Self.DSHTTPService1.Active := True; end; procedure TdmDataSnap.DSHTTPService1HTTPTrace(Sender: TObject; AContext: TDSHTTPContext; ARequest: TDSHTTPRequest; AResponse: TDSHTTPResponse); var _injection: TDSHTTPResponseIndy; begin _injection := TDSHTTPResponseIndy(AResponse); _injection.ResponseInfo.ResponseText := 'OK'; _injection.ResponseInfo.ContentLength := Length(_injection.ResponseInfo.ContentText); _injection.ResponseInfo.CharSet := 'binary'; end; procedure TdmDataSnap.DSServerClass1GetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := TPersistentClass(TPegaImagem); end; function TdmDataSnap.GetImageRotinaOriginal(const AID: string): TStringStream; var sURL: string; begin sURL := Format('http://localhost:80/datasnap/rest/TPegaImagem/RotinaOriginal/%s', [AID]); Result := TStringStream.Create; Self.IdHTTP2.Get(sURL, Result); Result.Seek(0, 0); end; function TdmDataSnap.GetImageRotinaProposta(const AID: string): TStringStream; var sURL: string; begin sURL := Format('http://localhost:80/datasnap/rest/TPegaImagem/RotinaProposta/%s', [AID]); Result := TStringStream.Create; Self.IdHTTP2.Get(sURL, Result); Result.Seek(0, 0); end; function TdmDataSnap.GetImageFromSismic(const AID: string): TStringStream; var sURL: string; begin sURL := Format('http://sismic.ddns.net:8085/api/rest/Produtos/ImageProduto/?idproduto=%s', [AID]); Result := TStringStream.Create; Self.IdHTTP2.Request.BasicAuthentication := True; Self.IdHTTP2.Request.Username := 'LUANA'; Self.IdHTTP2.Request.Password := '12345678'; Self.IdHTTP2.Get(sURL, Result); Result.Seek(0, 0); end; function TdmDataSnap.GetImageNewImage: TStringStream; var sURL: string; begin sURL := 'http://localhost:80/datasnap/rest/TPegaImagem/RotinaNovaImagem'; Result := TStringStream.Create; Self.IdHTTP2.Get(sURL, Result); Result.Seek(0, 0); end; end.
unit Find; { small non-modal dialog box used for finding previously entered or duplicate questions } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, Menus, StdCtrls, ExtCtrls, db; type TfrmFind = class(TForm) Label1: TLabel; memFind: TMemo; Bevel1: TBevel; Label2: TLabel; Label3: TLabel; Label4: TLabel; edtFound: TEdit; btnClose: TButton; btnFilter: TSpeedButton; btnSearch: TSpeedButton; btnFilter2: TButton; procedure CloseClick(Sender: TObject); procedure SearchClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FindChange(Sender: TObject); procedure FilterClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnFilter2Click(Sender: TObject); private procedure Unfilter; public vAbort : Boolean; end; var frmFind: TfrmFind; implementation uses Search, Browse, Data, Lookup; {$R *.DFM} { INITIALIZATION SECTION } { if menu item 'Build on Open' (under Options|Search) is checked, build a word table to search } procedure TfrmFind.FormCreate(Sender: TObject); var SearchRec: TSearchRec; i,Qtime,QTtime,Wtime : integer; libpath : string; begin vAbort := False; if frmLibrary.mniOpenBuild.Checked then begin modLookup.tblQstnText.Filtered := False; try I := modlookup.dbQstnLib.Params.IndexOfName('PATH'); Wtime := 0; Qtime := 1; QTtime := 1; if (i>-1) and (modlibrary.wtblQuestion.tag<>1) then begin libPath := copy(modlookup.dbQstnLib.Params[i],6,255)+'\'; if FindFirst(libpath+modlibrary.wtblQuestion.Tablename,faAnyFile,SearchRec) = 0 then begin Qtime := SearchRec.Time; if FindFirst(libpath+modlibrary.wtblQstnText.Tablename,faAnyFile,SearchRec) = 0 then begin QTtime := SearchRec.Time; if FindFirst(libpath+modSearch.tblWords.Tablename,faAnyFile,SearchRec) = 0 then Wtime := SearchRec.Time; end; end; FindClose(SearchRec); end; if (Wtime<Qtime) or (Wtime<QTtime) or (modlibrary.wtblquestion.tag=1) then modSearch.rubMake.Execute; { with tblWords do begin try close; except on EAccessViolation do messagebeep(0); end; if not active then begin Exclusive := FALSE; open; end; end;} finally modLookup.tblQstnText.Filtered := True; end; end; end; { BUTTON SECTION } { if button reads close then close; if button read cancel then abort and set to read close } procedure TfrmFind.CloseClick(Sender: TObject); begin if btnClose.Caption = 'Close' then Close else begin vAbort := True; btnClose.Caption := 'Close'; end; end; { search for words in the text box 1. set close button to read cancel 2. search word table for matching text 3. return number of matches (show in found text box) 4. reset close button to read close } procedure TfrmFind.SearchClick(Sender: TObject); begin screen.Cursor := crHourglass; btnClose.Caption := 'Cancel'; try vAbort := False; with modSearch.rubSearch do begin SearchFor := memFind.Text; Execute; edtFound.Text := IntToStr( RecordCount ); btnFilter.Enabled := ( RecordCount > 0 ); btnFilter2.Enabled := ( RecordCount > 0 ); end; finally screen.Cursor := crDefault; btnClose.Caption := 'Close'; btnSearch.Enabled := False; end; end; { show questions matching search criteria: 1. move dialog out of the way 2. set fields in match table to display correctly in a grid 3. point grid and controls to match table 4. disable buttons } procedure TfrmFind.FilterClick(Sender: TObject); begin if btnFilter.Down then with modSearch.tblMatch do begin Top := ( Screen.Height - Height - 22 ); Left := ( Screen.Width - Width - 2 ); ( FieldByName( 'Core' ) as TIntegerField ).Alignment := taCenter; with ( FieldByName( 'Fielded' ) as TSmallIntField ) do begin Alignment := taCenter; DisplayFormat := 'Layout;Fielded;New'; end; with ( FieldByName( 'Review' ) as TBooleanField ) do begin Alignment := taCenter; DisplayValues := 'Yes;'; end; with ( FieldByName( 'RestrictQuestion' ) as TBooleanField ) do begin Alignment := taCenter; DisplayValues := 'Yes;'; end; with ( FieldByName( 'Tested' ) as TBooleanField ) do begin Alignment := taCenter; DisplayValues := 'Yes;'; end; with ( FieldByName( 'LevelQuest' ) as tSmallintField ) do begin OnGetText := modSearch.tblMatchLevelQuestGetText; OnSetText := modSearch.tblMatchLevelQuestSetText; end; ( FieldByName( 'AddedOn' ) as TDateField ).Alignment := taCenter; ( FieldByName( 'ModifiedOn' ) as TDateField ).Alignment := taCenter; with frmLibrary do begin dgrLibrary.DataSource := modSearch.srcMatch; {navLibrary.DataSource := modSearch.srcMatch;} wdlgFilter.DataSource := modSearch.srcMatch; btnDelete.Enabled := False; btnNew.Enabled := False; btnReplicate.Enabled := False; btnSort.Enabled := False; btnPreceded.Enabled := False; btnFollowed.Enabled := False; btnRecode.Enabled := False; btnEditRecode.Enabled := False; btnRelated.Enabled := False; staLibrary.Panels[ 0 ].Text := 'Filtered'; end; end else begin Unfilter; Position := poScreenCenter; end; end; { GENERAL MEHTODS } { restore browse grid and controls to the question table } procedure TfrmFind.Unfilter; begin with frmLibrary do begin dgrLibrary.DataSource := modLibrary.wsrcQuestion; {navLibrary.DataSource := modLibrary.wsrcQuestion;} wdlgFilter.DataSource := modLibrary.wsrcQuestion; if modLibrary.userrights <> urTranslator then begin btnDelete.Enabled := True; btnNew.Enabled := True; btnReplicate.Enabled := True; btnSort.Enabled := True; btnPreceded.Enabled := True; btnFollowed.Enabled := True; btnRecode.Enabled := True; btnEditRecode.Enabled := True; btnRelated.Enabled := True; end; staLibrary.Panels[ 0 ].Text := 'No Filter'; end; end; { COMPONENT HANDLERS } procedure TfrmFind.FindChange(Sender: TObject); begin btnSearch.Enabled := ( memFind.Text <> '' ); edtFound.Text := ''; end; { FINALIZATION SECTION } { set find buttons to normal, turn off matching filter, and close the find dialog } procedure TfrmFind.FormClose(Sender: TObject; var Action: TCloseAction); begin with frmLibrary do begin btnFind.Down := False; btnFindPrior.Enabled := btnFilter.Enabled; btnFindNext.Enabled := btnFilter.Enabled; Unfilter; end; Action := caFree; end; procedure TfrmFind.btnFilter2Click(Sender: TObject); begin btnFilter.Down := not btnFilter.Down; FilterClick(Sender); end; end.
unit SHA1; interface // No range and overflow checking, do not remove!!! {$R-} {$Q-} //{$DEFINE UpperCase} {da xie} function GetSha1(Buffer: pointer; Size: INTEGER): AnsiString; implementation uses SysUtils; type TLogicalFunction = function(B, C, D: INTEGER): INTEGER; TLogicalFunctions = array[0..3] of TLogicalFunction; TMessageBlock = array[0..15] of INTEGER; PMessageBlocks = ^TMessageBlocks; TMessageBlocks = array[0..0] of TMessageBlock; TWorkArray = array[0..79] of INTEGER; PLocalByteArray = ^TLocalByteArray; TLocalByteArray = array[0..0] of BYTE; var LogicalFunctions: TLogicalFunctions; procedure CvtIntLowCase; { IN: EAX: The integer value to be converted to text ESI: Ptr to the right-hand side of the output buffer: LEA ESI, StrBuf[16] ECX: Base for conversion: 0 for signed decimal, 10 or 16 for unsigned EDX: Precision: zero padded minimum field width OUT: ESI: Ptr to start of converted text (not start of buffer) ECX: Length of converted text } asm OR CL,CL JNZ @CvtLoop @C1: OR EAX,EAX JNS @C2 NEG EAX CALL @C2 MOV AL,'-' INC ECX DEC ESI MOV [ESI],AL RET @C2: MOV ECX,10 @CvtLoop: PUSH EDX PUSH ESI @D1: XOR EDX,EDX DIV ECX DEC ESI ADD DL,'0' CMP DL,'0'+10 JB @D2 {$IFNDEF UpperCase} ADD DL,39 {$ELSE} ADD DL,7 {$ENDIF} @D2: MOV [ESI],DL OR EAX,EAX JNE @D1 POP ECX POP EDX SUB ECX,ESI SUB EDX,ECX JBE @D5 ADD ECX,EDX MOV AL,'0' SUB ESI,EDX JMP @z @zloop: MOV [ESI+EDX],AL @z: DEC EDX JNZ @zloop MOV [ESI],AL @D5: end; function IntToHexLowCase(Value: Integer; Digits: Integer): string; // FmtStr(Result, '%.*x', [Digits, Value]); asm CMP EDX, 32 // Digits < buffer length? JBE @A1 XOR EDX, EDX @A1: PUSH ESI MOV ESI, ESP SUB ESP, 32 PUSH ECX // result ptr MOV ECX, 16 // base 16 EDX = Digits = field width CALL CvtIntLowCase MOV EDX, ESI POP EAX // result ptr {$IF DEFINED(Unicode)} CALL System.@UStrFromPCharLen {$ELSE} PUSH DefaultSystemCodePage CALL System.@LStrFromPCharLen {$IFEND} ADD ESP, 32 POP ESI end; function GetSha1(Buffer: pointer; Size: INTEGER): AnsiString; const K: array[0..3] of Uint64 = ($5A827999, $6ED9EBA1, $8F1BBCDC, $CA62C1D6); var A, B, C, D, E: INTEGER; H0, H1, H2, H3, H4: Uint64; TEMP: INTEGER; i, t, Index: INTEGER; W: TWorkArray; ATemp: INTEGER; BlockCount, BlockRest: INTEGER; LocalBuffer: pointer; NewSize: INTEGER; SizeBytes: array[0..3] of BYTE absolute Size; ByteArray: PLocalByteArray absolute LocalBuffer; MessageBlocks: PMessageBlocks absolute LocalBuffer; label ConvertLoop; begin Result := ''; H0 := $67452301; H1 := $EFCDAB89; H2 := $98BADCFE; H3 := $10325476; H4 := $C3D2E1F0; // Compute message block count asm XOR EDX, EDX MOV EAX, Size MOV ECX, 64 DIV ECX MOV BlockCount, EAX MOV BlockRest, EDX end; if (64 - BlockRest) >= 9 then begin Inc(BlockCount); end else begin if BlockRest = 0 then begin Inc(BlockCount) end else begin Inc(BlockCount, 2) end; end; // Alloc memory for local buffer NewSize := BlockCount * 64; GetMem(LocalBuffer, NewSize); // Copy data into local buffer asm PUSH EDI PUSH ESI MOV EDI, LocalBuffer MOV ESI, Buffer MOV ECX, Size SHR ECX, 2 CLD REP movsd XOR EDX, EDX MOV EAX, Size MOV ECX, 4 DIV ECX MOV ECX, EDX REP movsb POP ESI POP EDI end; // Fill last block ByteArray[Size] := $80; for i := Size + 1 to NewSize - 9 do begin ByteArray[i] := 0 end; Size := Size * 8; // Upper 32 Bits of Size, because cannot handle 64 Bit integers ByteArray[NewSize - 8] := 0; ByteArray[NewSize - 7] := 0; ByteArray[NewSize - 6] := 0; ByteArray[NewSize - 5] := 0; // Lower 32 Bits of Size ByteArray[NewSize - 4] := SizeBytes[3]; ByteArray[NewSize - 3] := SizeBytes[2]; ByteArray[NewSize - 2] := SizeBytes[1]; ByteArray[NewSize - 1] := SizeBytes[0]; // Convert byte order in local buffer asm MOV ECX, NewSize SHR ECX, 2 MOV EDX, LocalBuffer ConvertLoop : MOV EAX, [EDX] BSWAP EAX MOV [EDX], EAX ADD EDX, 4 DEC ECX JNZ ConvertLoop end; // Process all message blocks for i := 0 to BlockCount - 1 do begin // a. Divide M(i) into 16 words W(0), W(1), ... , W(15), where W(0) is the // left-most word. for t := 0 to 15 do begin W[t] := MessageBlocks[i][t] end; // b. For t = 16 to 79 let W(t) = S^1(W(t-3) XOR W(t-8) XOR W(t-14) XOR W(t-16)). for t := 16 to 79 do begin ATemp := W[t - 3] xor W[t - 8] xor W[t - 14] xor W[t - 16]; asm MOV EAX, ATemp ROL EAX, 1 MOV ATemp, EAX end; W[t] := ATemp; end; // c. Let A = H0, B = H1, C = H2, D = H3, E = H4. A := H0; B := H1; C := H2; D := H3; E := H4; // d. For t = 0 to 79 do // TEMP = S^5(A) + f(t;B,C,D) + E + W(t) + K(t); // E = D; D = C; C = S^30(B); B = A; A = TEMP; for t := 0 to 79 do begin asm MOV EAX, A ROL EAX, 5 MOV ATemp, EAX end; Index := t div 20; TEMP := ATemp + LogicalFunctions[Index](B, C, D) + E + W[t] + K[Index]; E := D; D := C; asm MOV EAX, B ROL EAX, 30 MOV C, EAX end; B := A; A := TEMP; end; // e. Let H0 = H0 + A, H1 = H1 + B, H2 = H2 + C, H3 = H3 + D, // H4 = H4 + E. H0 := (H0 + A) and $FFFFFFFF; H1 := (H1 + B) and $FFFFFFFF; H2 := (H2 + C) and $FFFFFFFF; H3 := (H3 + D) and $FFFFFFFF; H4 := (H4 + E) and $FFFFFFFF; end; FreeMem(LocalBuffer); Result := IntToHexLowCase(H0, 8) + IntToHexLowCase(H1, 8) + IntToHexLowCase(H2, 8) + IntToHexLowCase(H3, 8) + IntToHexLowCase(H4, 8); end; function f0(B, C, D: INTEGER): INTEGER; assembler; asm // Result:=(B AND C) OR ((NOT B) AND D); PUSH EBX MOV EBX, EAX AND EAX, EDX NOT EBX AND EBX, ECX OR EAX, EBX POP EBX end; function f1(B, C, D: INTEGER): INTEGER; assembler; asm // Result:=(B XOR C) XOR D; XOR EAX, EDX XOR EAX, ECX end; function f2(B, C, D: INTEGER): INTEGER; assembler; asm // Result:=(B AND C) OR (B AND D) OR (C AND D); PUSH EBX MOV EBX, EAX AND EAX, EDX AND EBX, ECX OR EAX, EBX AND EDX, ECX OR EAX, EDX POP EBX end; function f3(B, C, D: INTEGER): INTEGER; assembler; asm // Result:=(B XOR C) XOR D; XOR EAX, EDX XOR EAX, ECX end; initialization // Initialize logical functions array LogicalFunctions[0] := f0; LogicalFunctions[1] := f1; LogicalFunctions[2] := f2; LogicalFunctions[3] := f3; end.
unit CholeskySolver; interface uses BasicDataTypes; type TCholeskySolver = class public Answer: AFloat; constructor Create(var _A: AFloat; _b: AFloat); destructor Destroy; override; procedure Execute; private m: integer; A, y, b: AFloat; // Cholesky internal procedures procedure DecomposeL; procedure SolveLyb; procedure SolveLxy; // Matrix operations function BuildTranspose(const _mat: AFloat): AFloat; function MultMatrix(const _mat1, _mat2: AFloat): AFloat; function MultMatrixVec(const _mat, _vec: AFloat): AFloat; // Basic Matrix Get & Set function GetMatrixElem(const _Matrix: AFloat; i, j: integer): real; procedure SetMatrixElem(const _Matrix: AFloat; i, j: integer; _Value: real); end; implementation uses Math; constructor TCholeskySolver.Create(var _A: AFloat; _b: AFloat); var Transpose: AFloat; begin m := High(_b) + 1; SetLength(Answer, m); SetLength(y, m); Transpose := buildTranspose(_A); A := multMatrix(Transpose,_A); b := multMatrixVec(Transpose,_b); // Free Memory SetLength(Transpose, 0); end; destructor TCholeskySolver.Destroy; begin SetLength(Answer, 0); SetLength(A, 0); SetLength(b, 0); SetLength(y, 0); inherited Destroy; end; procedure TCholeskySolver.Execute; begin // Decompose L decomposeL(); // Solve L solveLyb(); // Ly = b solveLxy(); // L*x = y end; // "Transforms" A into L, a lower triangular matrix. procedure TCholeskySolver.DecomposeL; var i, j, k: integer; ajj: real; begin j := 0; while j < m do begin k := 0; while k < j do begin i := j; while i < m do begin SetMatrixElem(A,j,i,GetMatrixElem(A,j,i) - (GetMatrixElem(A,k,i) * GetMatrixElem(A,k,j))); inc(i); end; inc(k); end; ajj := sqrt(GetMatrixElem(A,j,j)); SetMatrixElem(A,j,j,ajj); k := j + 1; while k < m do begin SetMatrixElem(A,j,k,GetMatrixElem(A,j,k) / ajj); inc(k); end; inc(j); end; end; // Ly = b; where L is A, y is y and b is the answer. (forward substitution) procedure TCholeskySolver.solveLyb; var i, j: integer; value: real; begin i := 0; while i < m do begin value := b[i]; j := 0; while j < i do begin value := value - (y[j] * GetMatrixElem(A,i,j)); inc(j); end; y[i] := value / GetMatrixElem(A,i,i); inc(i); end; end; // L*x = y; where L* is A* (transposed A), x is answer and y is y. (back substitution) procedure TCholeskySolver.solveLxy; var i, j: integer; value: real; begin i := m - 1; while i >= 0 do begin value := y[i]; j := m - 1; while j > i do begin value := value - (answer[j] * GetMatrixElem(A,j,i)); // (i and j are inverted, since A is transposed) dec(j); end; answer[i] := value / GetMatrixElem(A,i,i); dec(i); end; end; function TCholeskySolver.BuildTranspose(const _mat: AFloat): AFloat; var i, j: integer; begin SetLength(Result, High(_mat)+1); i := 0; while i < m do begin j := 0; while j < m do begin SetMatrixElem(Result,i,j,GetMatrixElem(_mat,j,i)); inc(j); end; inc(i); end; end; function TCholeskySolver.MultMatrix(const _mat1, _mat2: AFloat): AFloat; var i, j, k: integer; value: real; begin SetLength(Result, High(_mat1) + 1); i := 0; while i < m do begin j := 0; while j < m do begin value := 0; k := 0; while k < m do begin value := value + (GetMatrixElem(_mat1, i, k) * GetMatrixElem(_mat2, k, j)); inc(k); end; SetMatrixElem(Result,i,j,value); inc(j); end; inc(i); end; end; function TCholeskySolver.MultMatrixVec(const _mat, _vec: AFloat): AFloat; var j, k: integer; value: real; begin SetLength(Result, m); j := 0; while j < m do begin value := 0; k := 0; while k < m do begin value := value + (GetMatrixElem(_mat, j, k) * _vec[k]); inc(k); end; Result[j] := value; inc(j); end; end; function TCholeskySolver.GetMatrixElem(const _Matrix: AFloat; i, j: integer): real; begin Result := _Matrix[(i * m) + j]; end; procedure TCholeskySolver.SetMatrixElem(const _Matrix: AFloat; i, j: integer; _Value: real); begin _Matrix[(i * m) + j] := _Value; end; end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_SHA1; interface uses classes, uTPLb_HashDsc, uTPLb_StreamCipher; type TSHA1 = class( TInterfacedObject, IHashDsc, ICryptoGraphicAlgorithm) private function DisplayName: string; function ProgId: string; function Features: TAlgorithmicFeatureSet; function DigestSize: integer; // in units of bits. Must be a multiple of 8. function UpdateSize: integer; // Size that the input to the Update must be. function MakeHasher( const Params: IInterface): IHasher; function DefinitionURL: string; function WikipediaReference: string; end; implementation // References // 1. http://www.itl.nist.gov/fipspubs/fip180-1.htm uses SysUtils, uTPLb_BinaryUtils, uTPLb_StreamUtils, uTPLb_PointerArithmetic, uTPLb_IntegerUtils, uTPLB_Constants, uTPLb_I18n, uTPLB_StrUtils; type TSHA1_Hasher = class( TInterfacedObject, IHasher) private H: array[ 0.. 5 ] of uint32; FCount: int64; constructor Create; procedure Update( Source{in}: TMemoryStream); procedure End_Hash( PartBlock{in}: TMemoryStream; Digest: TStream); procedure Burn; function SelfTest_Source: TBytes; function SelfTest_ReferenceHashValue: TBytes; end; { TSHA1 } function TSHA1.DisplayName: string; begin result := 'SHA-1' end; function TSHA1.ProgId: string; begin result := SHA1_ProgId end; function TSHA1.Features: TAlgorithmicFeatureSet; begin result := [afOpenSourceSoftware, afCryptographicallyWeak] end; function TSHA1.DefinitionURL: string; begin result := 'http://www.itl.nist.gov/fipspubs/fip180-1.htm' end; function TSHA1.DigestSize: integer; begin result := 160 end; function TSHA1.UpdateSize: integer; begin result := 512 end; function TSHA1.WikipediaReference: string; begin result := {'http://en.wikipedia.org/wiki/' +} 'SHA1' end; function TSHA1.MakeHasher( const Params: IInterface): IHasher; begin result := TSHA1_Hasher.Create end; { TSHA1_Hasher } procedure TSHA1_Hasher.Burn; begin BurnMemory( H, SizeOf( H)); FCount := 0 end; constructor TSHA1_Hasher.Create; begin H[0] := $67452301; H[1] := $EFCDAB89; H[2] := $98BADCFE; H[3] := $10325476; H[4] := $C3D2E1F0; FCount := 0 end; const Pad: packed array [ 0.. 64] of byte = ( $80, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00); procedure TSHA1_Hasher.End_Hash( PartBlock{in}: TMemoryStream; Digest: TStream); var L, j: integer; PadLen: integer; Injection, Block: TMemoryStream; Count: int64; lwDigest: uint32; begin L := PartBlock.Position; Assert( L <= 64, 'TSHA1_Hasher.End_Hash - Wrong block size.'); Inc( FCount, L * 8); PadLen := 64 - ((L + 8) mod 64); Injection := TMemoryStream.Create; Block := TMemoryStream.Create; try if L > 0 then Injection.Write( PartBlock.Memory^, L); Injection.Write( Pad, PadLen); Count := SwapEndien_s64( FCount); Injection.Write( Count, 8); Block.Size := 64; Inc( L, PadLen + 8); repeat Move( Injection.Memory^, Block.Memory^, 64); if L > 64 then Move( MemStrmOffset( Injection, 64)^, Injection.Memory^, L - 64); Dec( L, 64); Injection.Size := L; Update( Block) until L <= 0 finally BurnMemoryStream( Injection); Injection.Free; BurnMemoryStream( Block); Block.Free; end; Digest.Position := 0; for j := 0 to 4 do begin lwDigest := SwapEndien_u32( H[j]); Digest.WriteBuffer( lwDigest, 4) end; Digest.Position := 0; // Burning Count := 0; lwDigest := 0 end; function TSHA1_Hasher.SelfTest_Source: TBytes; // From sample 2 of Appendix B of reference 1. begin result := AnsiBytesOf('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq') end; function TSHA1_Hasher.SelfTest_ReferenceHashValue: TBytes; // From sample 2 of Appendix B of reference 1. begin result := AnsiBytesOf('84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1') end; procedure TSHA1_Hasher.Update( Source: TMemoryStream); var t: integer; TEMP: uint32; Arotl5: uint32; W: array[ 0 .. 79 ] of uint32; A, B, C, D, E: uint32; begin Assert( Source.Size = 64, 'TSHA1_Hasher.Update - Wrong block size.'); Inc( FCount, 512); Move( Source.Memory^, W, 64); for t := 0 to 15 do W[t] := SwapEndien_u32( W[t]); for t := 16 to 79 do W[t]:= RotateLeft1Bit_u32( W[t-3] xor W[t-8] xor W[t-14] xor W[t-16]); A := H[0]; B := H[1]; C := H[2]; D := H[3]; E := H[4]; for t := 0 to 19 do begin Arotl5 := (A shl 5) or (A shr 27); TEMP := Arotl5 + ((B and C) or ((not B) and D)) + E + W[t] + $5A827999; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := TEMP end; for t := 20 to 39 do begin Arotl5 := (A shl 5) or (A shr 27); TEMP := Arotl5 + (B xor C xor D) + E + W[t] + $6ED9EBA1; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := TEMP end; for t := 40 to 59 do begin Arotl5 := (A shl 5) or (A shr 27); TEMP := Arotl5 + ((B and C) or (B and D) or (C and D)) + E + W[t] + $8F1BBCDC; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := TEMP end; for t := 60 to 79 do begin Arotl5 := (A shl 5) or (A shr 27); TEMP := Arotl5 + (B xor C xor D) + E + W[t] + $CA62C1D6; E := D; D := C; C := (B shl 30) or (B shr 2); B := A; A := TEMP end; H[0] := H[0] + A; H[1] := H[1] + B; H[2] := H[2] + C; H[3] := H[3] + D; H[4] := H[4] + E end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Implements specific proxying classes. } unit VXS.ProxyObjects; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.Scene, VXS.XCollection, VXS.PersistentClasses, VXS.VectorGeometry, VXS.Texture, VXS.VectorFileObjects, VXS.Strings, VXS.RenderContextInfo, VXS.BaseClasses, VXS.Material, VXS.Context, VXS.PipelineTransformation, VXS.VectorTypes; type EGLProxyException = class(Exception); { A proxy object with its own color. This proxy object can have a unique color. Note that multi-material objects (Freeforms linked to a material library f.i.) won't honour the color. } TVXColorProxy = class(TVXProxyObject) private FFrontColor: TVXFaceProperties; function GetMasterMaterialObject: TVXCustomSceneObject; procedure SetMasterMaterialObject(const Value: TVXCustomSceneObject); procedure SetFrontColor(AValue: TVXFaceProperties); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); override; published property FrontColor: TVXFaceProperties read FFrontColor write SetFrontColor; // Redeclare as TVXCustomSceneObject. property MasterObject: TVXCustomSceneObject read GetMasterMaterialObject write SetMasterMaterialObject; end; { A proxy object with its own material. This proxy object can take a mesh from one master and a materia from a material library. } TVXMaterialProxy = class(TVXProxyObject, IVXMaterialLibrarySupported) private FTempLibMaterialName: string; FMasterLibMaterial: TVXLibMaterial; FMaterialLibrary: TVXMaterialLibrary; procedure SetMaterialLibrary(const Value: TVXMaterialLibrary); function GetMasterLibMaterialName: TVXLibMaterialName; procedure SetMasterLibMaterialName(const Value: TVXLibMaterialName); function GetMasterMaterialObject: TVXCustomSceneObject; procedure SetMasterMaterialObject(const Value: TVXCustomSceneObject); // Implementing IGLMaterialLibrarySupported. function GetMaterialLibrary: TVXAbstractMaterialLibrary; public constructor Create(AOwner: TComponent); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; destructor Destroy; override; procedure DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); override; { Specifies the Material, that current master object will use. Provides a faster way to access FMasterLibMaterial, compared to MasterLibMaterialName } property MasterLibMaterial: TVXLibMaterial read FMasterLibMaterial write FMasterLibMaterial stored False; published property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; { Specifies the Material, that current master object will use. } property MasterLibMaterialName: TVXLibMaterialName read GetMasterLibMaterialName write SetMasterLibMaterialName; { Redeclare as TVXCustomSceneObject. } property MasterObject: TVXCustomSceneObject read GetMasterMaterialObject write SetMasterMaterialObject; end; { A proxy object specialized for FreeForms. } TVXFreeFormProxy = class(TVXProxyObject) private function GetMasterFreeFormObject: TVXFreeForm; procedure SetMasterFreeFormObject(const Value: TVXFreeForm); public { If the MasterObject is a FreeForm, you can raycast against the Octree, which is alot faster. You must build the octree before using. } function OctreeRayCastIntersect(const rayStart, rayVector: TVector; intersectPoint: PVector = nil; intersectNormal: PVector = nil): Boolean; { WARNING: This function is not yet 100% reliable with scale+rotation. } function OctreeSphereSweepIntersect(const rayStart, rayVector: TVector; const velocity, radius, modelscale: Single; intersectPoint: PVector = nil; intersectNormal: PVector = nil): Boolean; published // Redeclare as TVXFreeForm. property MasterObject: TVXFreeForm read GetMasterFreeFormObject write SetMasterFreeFormObject; end; { An object containing the bone matrix for TVXActorProxy. } TBoneMatrixObj = class public Matrix: TMatrix; BoneName: string; BoneIndex: integer; end; // pamLoop mode was too difficalt to implement, so it was discarded ...for now. // pamPlayOnce only works if Actor.AnimationMode <> aamNone. TVXActorProxyAnimationMode = (pamInherited, pamNone, pamPlayOnce); { A proxy object specialized for Actors. } TVXActorProxy = class(TVXProxyObject, IVXMaterialLibrarySupported) private FCurrentFrame: Integer; FStartFrame: Integer; FEndFrame: Integer; FLastFrame: Integer; FCurrentFrameDelta: Single; FCurrentTime: TVXProgressTimes; FAnimation: TVXActorAnimationName; FTempLibMaterialName: string; FMasterLibMaterial: TVXLibMaterial; FMaterialLibrary: TVXMaterialLibrary; FBonesMatrices: TStringList; FStoreBonesMatrix: boolean; FStoredBoneNames: TStrings; FOnBeforeRender: TVXProgressEvent; FAnimationMode: TVXActorProxyAnimationMode; procedure SetAnimation(const Value: TVXActorAnimationName); procedure SetMasterActorObject(const Value: TVXActor); function GetMasterActorObject: TVXActor; function GetLibMaterialName: TVXLibMaterialName; procedure SetLibMaterialName(const Value: TVXLibMaterialName); procedure SetMaterialLibrary(const Value: TVXMaterialLibrary); // Implementing IGLMaterialLibrarySupported. function GetMaterialLibrary: TVXAbstractMaterialLibrary; procedure SetStoreBonesMatrix(const Value: boolean); procedure SetStoredBoneNames(const Value: TStrings); procedure SetOnBeforeRender(const Value: TVXProgressEvent); protected procedure DoStoreBonesMatrices; // stores matrices of bones of the current frame rendered public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); override; procedure DoProgress(const progressTime: TVXProgressTimes); override; property CurrentFrame: Integer read FCurrentFrame; property StartFrame: Integer read FStartFrame; property EndFrame: Integer read FEndFrame; property CurrentFrameDelta: Single read FCurrentFrameDelta; property CurrentTime: TVXProgressTimes read FCurrentTime; { Gets the Bones Matrix in the current animation frame. (since the masterobject is shared between all proxies, each proxy will have it's bones matrices) } function BoneMatrix(BoneIndex: integer): TMatrix; overload; function BoneMatrix(BoneName: string): TMatrix; overload; procedure BoneMatricesClear; { A standard version of the RayCastIntersect function. } function RayCastIntersect(const rayStart, rayVector: TVector; intersectPoint: PVector = nil; intersectNormal: PVector = nil): Boolean; override; { Raycasts on self, but actually on the "RefActor" Actor. Note that the "RefActor" parameter does not necessarily have to be the same Actor refernced by the MasterObject property: This allows to pass a low-low-low-poly Actor to raycast in the "RefActor" parameter, while using a high-poly Actor in the "MasterObject" property, of course we assume that the two Masterobject Actors have same animations. } function RayCastIntersectEx(RefActor: TVXActor; const rayStart, rayVector: TVector; intersectPoint: PVector = nil; intersectNormal: PVector = nil): Boolean; overload; published property AnimationMode: TVXActorProxyAnimationMode read FAnimationMode write FAnimationMode default pamInherited; property Animation: TVXActorAnimationName read FAnimation write SetAnimation; // Redeclare as TVXActor. property MasterObject: TVXActor read GetMasterActorObject write SetMasterActorObject; // Redeclare without pooTransformation // (Don't know why it causes the object to be oriented incorrecly.) property ProxyOptions default [pooEffects, pooObjects]; { Specifies the MaterialLibrary, that current proxy will use. } property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; { Specifies the Material, that current proxy will use. } property LibMaterialName: TVXLibMaterialName read GetLibMaterialName write SetLibMaterialName; { Specifies if it will store the Bones Matrices, accessible via the BoneMatrix function (since the masterobject is shared between all proxies, each proxy will have it's bones matrices) } property StoreBonesMatrix: boolean read FStoreBonesMatrix write SetStoreBonesMatrix; { Specifies the names of the bones we want the matrices to be stored. If empty, all bones will be stored (since the masterobject is shared between all proxies, each proxy will have it's bones matrices) } property StoredBoneNames: TStrings read FStoredBoneNames write SetStoredBoneNames; { Event allowing to apply extra transformations (f.ex: bone rotations) to the referenced Actor on order to have the proxy render these changes. } property OnBeforeRender: TVXProgressEvent read FOnBeforeRender write SetOnBeforeRender; end; //------------------------------------------------------------- implementation //------------------------------------------------------------- // ------------------ // ------------------ TVXColorProxy ------------------ // ------------------ constructor TVXColorProxy.Create(AOwner: TComponent); begin inherited Create(AOwner); FFrontColor := TVXFaceProperties.Create(Self); end; destructor TVXColorProxy.Destroy; begin FFrontColor.Free; inherited Destroy; end; procedure TVXColorProxy.DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); var gotMaster, masterGotEffects, oldProxySubObject: Boolean; begin if FRendering then Exit; FRendering := True; try gotMaster := Assigned(MasterObject); masterGotEffects := gotMaster and (pooEffects in ProxyOptions) and (MasterObject.Effects.Count > 0); if gotMaster then begin if pooObjects in ProxyOptions then begin oldProxySubObject := ARci.proxySubObject; ARci.proxySubObject := True; if pooTransformation in ProxyOptions then glMultMatrixf(PGLFloat(MasterObject.Matrix)); GetMasterMaterialObject.Material.FrontProperties.Assign(FFrontColor); MasterObject.DoRender(ARci, ARenderSelf, MasterObject.Count > 0); ARci.proxySubObject := oldProxySubObject; end; end; // now render self stuff (our children, our effects, etc.) if ARenderChildren and (Count > 0) then Self.RenderChildren(0, Count - 1, ARci); if masterGotEffects then MasterObject.Effects.RenderPostEffects(ARci); finally FRendering := False; end; ClearStructureChanged; end; function TVXColorProxy.GetMasterMaterialObject: TVXCustomSceneObject; begin Result := TVXCustomSceneObject(inherited MasterObject); end; procedure TVXColorProxy.SetFrontColor(AValue: TVXFaceProperties); begin FFrontColor.Assign(AValue); end; procedure TVXColorProxy.SetMasterMaterialObject( const Value: TVXCustomSceneObject); begin inherited SetMasterObject(Value); end; // ------------------ // ------------------ TVXFreeFormProxy ------------------ // ------------------ function TVXFreeFormProxy.OctreeRayCastIntersect(const rayStart, rayVector: TVector; intersectPoint: PVector = nil; intersectNormal: PVector = nil): Boolean; var localRayStart, localRayVector: TVector; begin if Assigned(MasterObject) then begin SetVector(localRayStart, AbsoluteToLocal(rayStart)); SetVector(localRayStart, MasterObject.LocalToAbsolute(localRayStart)); SetVector(localRayVector, AbsoluteToLocal(rayVector)); SetVector(localRayVector, MasterObject.LocalToAbsolute(localRayVector)); NormalizeVector(localRayVector); Result := GetMasterFreeFormObject.OctreeRayCastIntersect(localRayStart, localRayVector, intersectPoint, intersectNormal); if Result then begin if Assigned(intersectPoint) then begin SetVector(intersectPoint^, MasterObject.AbsoluteToLocal(intersectPoint^)); SetVector(intersectPoint^, LocalToAbsolute(intersectPoint^)); end; if Assigned(intersectNormal) then begin SetVector(intersectNormal^, MasterObject.AbsoluteToLocal(intersectNormal^)); SetVector(intersectNormal^, LocalToAbsolute(intersectNormal^)); end; end; end else Result := False; end; function TVXFreeFormProxy.OctreeSphereSweepIntersect(const rayStart, rayVector: TVector; const velocity, radius, modelscale: Single; intersectPoint: PVector = nil; intersectNormal: PVector = nil): Boolean; var localRayStart, localRayVector: TVector; localVelocity, localRadius: single; begin Result := False; if Assigned(MasterObject) then begin localVelocity := velocity * modelscale; localRadius := radius * modelscale; SetVector(localRayStart, AbsoluteToLocal(rayStart)); SetVector(localRayStart, MasterObject.LocalToAbsolute(localRayStart)); SetVector(localRayVector, AbsoluteToLocal(rayVector)); SetVector(localRayVector, MasterObject.LocalToAbsolute(localRayVector)); NormalizeVector(localRayVector); Result := GetMasterFreeFormObject.OctreeSphereSweepIntersect(localRayStart, localRayVector, localVelocity, localRadius, intersectPoint, intersectNormal); if Result then begin if Assigned(intersectPoint) then begin SetVector(intersectPoint^, MasterObject.AbsoluteToLocal(intersectPoint^)); SetVector(intersectPoint^, LocalToAbsolute(intersectPoint^)); end; if Assigned(intersectNormal) then begin SetVector(intersectNormal^, MasterObject.AbsoluteToLocal(intersectNormal^)); SetVector(intersectNormal^, LocalToAbsolute(intersectNormal^)); end; end; end; end; function TVXFreeFormProxy.GetMasterFreeFormObject: TVXFreeForm; begin Result := TVXFreeForm(inherited MasterObject); end; procedure TVXFreeFormProxy.SetMasterFreeFormObject( const Value: TVXFreeForm); begin inherited SetMasterObject(Value); end; // ------------------ // ------------------ TVXActorProxy ------------------ // ------------------ function TVXActorProxy.BoneMatrix(BoneIndex: integer): TMatrix; begin if BoneIndex < FBonesMatrices.count then result := TBoneMatrixObj(FBonesMatrices.Objects[BoneIndex]).Matrix; end; function TVXActorProxy.BoneMatrix(BoneName: string): TMatrix; var i: Integer; begin i := FBonesMatrices.IndexOf(BoneName); if i > -1 then result := TBoneMatrixObj(FBonesMatrices.Objects[i]).Matrix; end; procedure TVXActorProxy.BoneMatricesClear; var i: Integer; begin for i := 0 to FBonesMatrices.Count - 1 do begin TBoneMatrixObj(FBonesMatrices.Objects[i]).free; end; FBonesMatrices.Clear; end; constructor TVXActorProxy.Create(AOwner: TComponent); begin inherited; FAnimationMode := pamInherited; ProxyOptions := ProxyOptions - [pooTransformation]; FBonesMatrices := TStringList.create; FStoredBoneNames := TStringList.create; FStoreBonesMatrix := false; // default is false to speed up a little if we don't need bones info end; destructor TVXActorProxy.Destroy; begin BoneMatricesClear; FBonesMatrices.free; FStoredBoneNames.free; inherited; end; procedure TVXActorProxy.DoProgress(const progressTime: TVXProgressTimes); begin inherited; FCurrentTime := progressTime; end; procedure TVXActorProxy.DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); var // TVXActorProxy specific cf, sf, ef: Integer; cfd: Single; // General proxy stuff. gotMaster, masterGotEffects, oldProxySubObject: Boolean; MasterActor: TVXActor; begin try MasterActor := GetMasterActorObject; gotMaster := MasterActor <> nil; masterGotEffects := gotMaster and (pooEffects in ProxyOptions) and (MasterObject.Effects.Count > 0); if gotMaster then begin if pooObjects in ProxyOptions then begin oldProxySubObject := ARci.proxySubObject; ARci.proxySubObject := True; if pooTransformation in ProxyOptions then with ARci.PipelineTransformation do SetModelMatrix(MatrixMultiply(MasterActor.Matrix^, ModelMatrix^)); // At last TVXActorProxy specific stuff! with MasterActor do begin cfd := CurrentFrameDelta; cf := CurrentFrame; sf := startframe; ef := endframe; case FAnimationMode of pamInherited: CurrentFrameDelta := FCurrentFrameDelta; pamPlayOnce: begin if (FLastFrame <> FEndFrame - 1) then CurrentFrameDelta := FCurrentFrameDelta else begin FCurrentFrameDelta := 0; FAnimationMode := pamNone; end; end; pamNone: CurrentFrameDelta := 0; else Assert(False, strUnknownType); end; SetCurrentFrameDirect(FCurrentFrame); FLastFrame := FCurrentFrame; StartFrame := FStartFrame; EndFrame := FEndFrame; if (FMasterLibMaterial <> nil) and (FMaterialLibrary <> nil) then MasterActor.Material.QuickAssignMaterial( FMaterialLibrary, FMasterLibMaterial); DoProgress(FCurrentTime); if Assigned(FOnBeforeRender) then FOnBeforeRender(self, FCurrentTime.deltaTime, FCurrentTime.newTime); DoRender(ARci, ARenderSelf, Count > 0); // Stores Bones matrices of the current frame if (FStoreBonesMatrix) and (MasterActor.Skeleton <> nil) then DoStoreBonesMatrices; FCurrentFrameDelta := CurrentFrameDelta; FCurrentFrame := CurrentFrame; CurrentFrameDelta := cfd; SetCurrentFrameDirect(cf); startframe := sf; endframe := ef; end; ARci.proxySubObject := oldProxySubObject; end; end; // now render self stuff (our children, our effects, etc.) oldProxySubObject := ARci.proxySubObject; ARci.proxySubObject := True; if ARenderChildren and (Count > 0) then Self.RenderChildren(0, Count - 1, ARci); if masterGotEffects then MasterActor.Effects.RenderPostEffects(ARci); ARci.proxySubObject := oldProxySubObject; finally ClearStructureChanged; end; end; procedure TVXActorProxy.DoStoreBonesMatrices; var i, n: integer; Bmo: TBoneMatrixObj; Bone: TVXSkeletonBone; begin if FStoredBoneNames.count > 0 then begin // If we specified some bone names, only those bones matrices will be stored (save some cpu) if FBonesMatrices.Count < FStoredBoneNames.Count then begin n := FBonesMatrices.Count; for i := n to FStoredBoneNames.Count - 1 do begin Bone := MasterObject.Skeleton.BoneByName(FStoredBoneNames[i]); if Bone <> nil then begin Bmo := TBoneMatrixObj.Create; Bmo.BoneName := Bone.Name; Bmo.BoneIndex := Bone.BoneID; FBonesMatrices.AddObject(Bone.Name, Bmo); end; end; end; end else begin // Add (missing) TBoneMatrixObjects (actually ony 1st time) from all bones in skeleton if FBonesMatrices.Count < MasterObject.Skeleton.BoneCount - 1 then // note : BoneCount actually returns 1 count more. begin n := FBonesMatrices.Count; for i := n to MasterObject.Skeleton.BoneCount - 2 do // note : BoneCount actually returns 1 count more. begin Bone := MasterObject.Skeleton.BoneByID(i); if Bone <> nil then begin Bmo := TBoneMatrixObj.Create; Bmo.BoneName := Bone.Name; Bmo.BoneIndex := Bone.BoneID; FBonesMatrices.AddObject(Bone.Name, Bmo); end; end; end; end; // fill FBonesMatrices list for i := 0 to FBonesMatrices.count - 1 do begin Bmo := TBoneMatrixObj(FBonesMatrices.Objects[i]); Bmo.Matrix := MasterObject.Skeleton.BoneByID(Bmo.BoneIndex).GlobalMatrix; end; end; function TVXActorProxy.GetMasterActorObject: TVXActor; begin Result := TVXActor(inherited MasterObject); end; function TVXActorProxy.GetLibMaterialName: TVXLibMaterialName; begin Result := FMaterialLibrary.GetNameOfLibMaterial(FMasterLibMaterial); if Result = '' then Result := FTempLibMaterialName; end; function TVXActorProxy.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; procedure TVXActorProxy.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent = FMaterialLibrary then FMaterialLibrary := nil; end; end; function TVXActorProxy.RayCastIntersect(const rayStart, rayVector: TVector; intersectPoint, intersectNormal: PVector): Boolean; begin if MasterObject <> nil then Result := RayCastIntersectEx(GetMasterActorObject, rayStart, rayVector, intersectPoint, intersectNormal) else Result := inherited RayCastIntersect(rayStart, rayVector, intersectPoint, intersectNormal); end; // Gain access to TVXDummyActor.DoAnimate(). type TVXDummyActor = class(TVXActor); function TVXActorProxy.RayCastIntersectEx(RefActor: TVXActor; const rayStart, rayVector: TVector; intersectPoint, intersectNormal: PVector): Boolean; var localRayStart, localRayVector: TVector; cf, sf, ef: Integer; cfd: Single; HaspooTransformation: boolean; begin // Set RefObject frame as current ActorProxy frame with RefActor do begin // VARS FOR ACTOR TO ASSUME ACTORPROXY CURRENT ANIMATION FRAME cfd := RefActor.CurrentFrameDelta; cf := RefActor.CurrentFrame; sf := RefActor.startframe; ef := RefActor.endframe; RefActor.CurrentFrameDelta := self.CurrentFrameDelta; RefActor.SetCurrentFrameDirect(self.CurrentFrame); RefActor.StartFrame := self.StartFrame; RefActor.EndFrame := self.EndFrame; RefActor.CurrentFrame := self.CurrentFrame; // FORCE ACTOR TO ASSUME ACTORPROXY CURRENT ANIMATION FRAME TVXDummyActor(RefActor).DoAnimate(); HaspooTransformation := pooTransformation in self.ProxyOptions; // transform RAYSTART SetVector(localRayStart, self.AbsoluteToLocal(rayStart)); if not HaspooTransformation then SetVector(localRayStart, RefActor.LocalToAbsolute(localRayStart)); // transform RAYVECTOR SetVector(localRayVector, self.AbsoluteToLocal(rayVector)); if not HaspooTransformation then SetVector(localRayVector, RefActor.LocalToAbsolute(localRayVector)); NormalizeVector(localRayVector); Result := RefActor.RayCastIntersect(localRayStart, localRayVector, intersectPoint, intersectNormal); if Result then begin if Assigned(intersectPoint) then begin if not HaspooTransformation then SetVector(intersectPoint^, RefActor.AbsoluteToLocal(intersectPoint^)); SetVector(intersectPoint^, self.LocalToAbsolute(intersectPoint^)); end; if Assigned(intersectNormal) then begin if not HaspooTransformation then SetVector(intersectNormal^, RefActor.AbsoluteToLocal(intersectNormal^)); SetVector(intersectNormal^, self.LocalToAbsolute(intersectNormal^)); end; end; // Return RefObject to it's old time CurrentFrameDelta := cfd; SetCurrentFrameDirect(cf); CurrentFrame := cf; startframe := sf; endframe := ef; // REVERT ACTOR TO ASSUME ORIGINAL ANIMATION FRAME TVXDummyActor(RefActor).DoAnimate(); end; end; procedure TVXActorProxy.SetAnimation(const Value: TVXActorAnimationName); var anAnimation: TVXActorAnimation; begin // We first assign the value (for persistency support), then check it. FAnimation := Value; if Assigned(MasterObject) then begin anAnimation := GetMasterActorObject.Animations.FindName(Value); if Assigned(anAnimation) then begin FStartFrame := anAnimation.StartFrame; FEndFrame := anAnimation.EndFrame; FCurrentFrame := FStartFrame; FLastFrame := FCurrentFrame; end; end; end; procedure TVXActorProxy.SetStoredBoneNames(const Value: TStrings); begin if value <> nil then FStoredBoneNames.Assign(Value); end; procedure TVXActorProxy.SetMasterActorObject(const Value: TVXActor); begin inherited SetMasterObject(Value); BoneMatricesClear; end; procedure TVXActorProxy.SetLibMaterialName( const Value: TVXLibMaterialName); begin if FMaterialLibrary = nil then begin FTempLibMaterialName := Value; if not (csLoading in ComponentState) then raise ETexture.Create(strErrorEx + strMatLibNotDefined); end else begin FMasterLibMaterial := FMaterialLibrary.LibMaterialByName(Value); FTempLibMaterialName := ''; end; end; procedure TVXActorProxy.SetMaterialLibrary(const Value: TVXMaterialLibrary); begin if FMaterialLibrary <> Value then begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary := Value; if FMaterialLibrary <> nil then begin FMaterialLibrary.FreeNotification(Self); if FTempLibMaterialName <> '' then SetLibMaterialName(FTempLibMaterialName); end else begin FTempLibMaterialName := ''; end; end; end; procedure TVXActorProxy.SetOnBeforeRender(const Value: TVXProgressEvent); begin FOnBeforeRender := Value; end; procedure TVXActorProxy.SetStoreBonesMatrix(const Value: boolean); begin FStoreBonesMatrix := Value; end; { TVXMaterialProxy } constructor TVXMaterialProxy.Create(AOwner: TComponent); begin inherited; // Nothing here. end; destructor TVXMaterialProxy.Destroy; begin // Nothing here. inherited; end; procedure TVXMaterialProxy.DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); var gotMaster, masterGotEffects, oldProxySubObject: Boolean; begin if FRendering then Exit; FRendering := True; try gotMaster := Assigned(MasterObject); masterGotEffects := gotMaster and (pooEffects in ProxyOptions) and (MasterObject.Effects.Count > 0); if gotMaster then begin if pooObjects in ProxyOptions then begin oldProxySubObject := ARci.proxySubObject; ARci.proxySubObject := True; if pooTransformation in ProxyOptions then glMultMatrixf(PGLFloat(MasterObject.Matrix)); if (FMasterLibMaterial <> nil) and (FMaterialLibrary <> nil) then GetMasterMaterialObject.Material.QuickAssignMaterial( FMaterialLibrary, FMasterLibMaterial); MasterObject.DoRender(ARci, ARenderSelf, MasterObject.Count > 0); ARci.proxySubObject := oldProxySubObject; end; end; // now render self stuff (our children, our effects, etc.) if ARenderChildren and (Count > 0) then Self.RenderChildren(0, Count - 1, ARci); if masterGotEffects then MasterObject.Effects.RenderPostEffects(ARci); finally FRendering := False; end; ClearStructureChanged; end; function TVXMaterialProxy.GetMasterLibMaterialName: TVXLibMaterialName; begin Result := FMaterialLibrary.GetNameOfLibMaterial(FMasterLibMaterial); if Result = '' then Result := FTempLibMaterialName; end; function TVXMaterialProxy.GetMasterMaterialObject: TVXCustomSceneObject; begin Result := TVXCustomSceneObject(inherited MasterObject); end; function TVXMaterialProxy.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; procedure TVXMaterialProxy.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent = FMaterialLibrary then FMaterialLibrary := nil; end; end; procedure TVXMaterialProxy.SetMasterLibMaterialName( const Value: TVXLibMaterialName); begin if FMaterialLibrary = nil then begin FTempLibMaterialName := Value; if not (csLoading in ComponentState) then raise ETexture.Create(strErrorEx + strMatLibNotDefined); end else begin FMasterLibMaterial := FMaterialLibrary.LibMaterialByName(Value); FTempLibMaterialName := ''; end; end; procedure TVXMaterialProxy.SetMasterMaterialObject( const Value: TVXCustomSceneObject); begin inherited SetMasterObject(Value); end; procedure TVXMaterialProxy.SetMaterialLibrary( const Value: TVXMaterialLibrary); begin if FMaterialLibrary <> Value then begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary := Value; if FMaterialLibrary <> nil then begin FMaterialLibrary.FreeNotification(Self); if FTempLibMaterialName <> '' then SetMasterLibMaterialName(FTempLibMaterialName); end else begin FTempLibMaterialName := ''; end; end; end; //------------------------------------------------------------- initialization //------------------------------------------------------------- RegisterClasses([TVXColorProxy, TVXFreeFormProxy, TVXActorProxy, TVXMaterialProxy]); end.
{..............................................................................} { Summary PCB Hole Size Editor version 1.0 } { } { Copyright (c) 2004 by Altium Limited } {..............................................................................} {..............................................................................} Unit EHSForm; Interface Uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; Type TEditHoleSizeForm = class(TForm) GroupBox1 : TGroupBox; eEditHoleSize : TEdit; bOk : TButton; bCancel : TButton; procedure bOkClick(Sender: TObject); procedure bCancelClick(Sender: TObject); End; {..............................................................................} {..............................................................................} Var EditHoleSizeForm : TEditHoleSizeForm; {..............................................................................} {..............................................................................} Implementation {$R *.DFM} {..............................................................................} {..............................................................................} Procedure TEditHoleSizeForm.bOkClick(Sender: TObject); Begin Close; End; {..............................................................................} {..............................................................................} Procedure TEditHoleSizeForm.bCancelClick(Sender: TObject); Begin Close; End; {..............................................................................} {..............................................................................} End.
unit UpdateTool; interface uses SysUtils, Classes, IdHTTP, IdAntiFreeze, ShellAPI, Forms, IdComponent, VCLUnZip, VCLZip, Windows, XMLIntf, ActiveX, XMLDoc; function nDeleteDir(SrcDir: string; UndoMK: boolean = false): Boolean; type TBeforeDown = procedure of object; //下载前 TOnDowning = procedure(value: Integer) of object; //下载中显示进度 TBeforeUnZip = procedure(value: Integer) of object; //解压前 TOnUnZip = procedure(value: Integer) of object; //解压中显示进度 TAddExplans = procedure(explans: string) of object; //更新说明 、日志 TOnfinsh = procedure of object; //完成 TDownTool = class(TThread) private IsDowning, IsInstall: Boolean; idhtpLog: TIdHTTP; idntfrz1: TIdAntiFreeze; Stream: TMemoryStream; vclzp1: TVCLZip; VBeforeDown :TBeforeDown; VOnDowning: TOnDowning; VOnUnZip :TOnUnZip; VBeforeUnZip :TBeforeUnZip; VAddExplans: TAddExplans; VOnfinsh:TOnfinsh; procedure copyFileDo(old,new:string); public path, url,fireName: string; isUpdate : Boolean; procedure Execute; override; constructor Create; overload; destructor Destroy; override; procedure Start; property OnDowning: TOnDowning read VOnDowning write VOnDowning; //下载中显示进度 property BeforeDown :TBeforeDown read VBeforeDown write VBeforeDown; property BeforeUnZip :TBeforeUnZip read VBeforeUnZip write VBeforeUnZip; property OnUnZip :TOnUnZip read VOnUnZip write VOnUnZip; property AddExplans: TAddExplans read VAddExplans write VAddExplans; //更新说明 property Onfinsh: TOnfinsh read VOnfinsh write VOnfinsh; //下载结束 procedure idhtp1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer); end; implementation function nDeleteDir(SrcDir: string; UndoMK: boolean = false): Boolean; var FS: TShFileOpStruct; begin FS.Wnd := Application.Handle; //应用程序句柄 FS.wFunc := FO_DELETE; //表示删除 FS.pFrom := PChar(SrcDir + #0#0); FS.pTo := nil; if DirectoryExists(SrcDir) then begin try if UndoMK then FS.fFlags := FOF_NOCONFIRMATION + FOF_SILENT + FOF_ALLOWUNDO // 表示删除到回收站 else FS.fFlags := FOF_NOCONFIRMATION + FOF_SILENT; // 表示不删除到回收站 FS.lpszProgressTitle := nil; Result := (ShFileOperation(FS) = 0); except Result := False; end; end else Result := False; end; constructor TDownTool.Create; begin IsDowning := False; IsInstall := False; idhtpLog := TIdHTTP.Create(nil); idhtpLog.OnWork := idhtp1Work; idntfrz1 := TIdAntiFreeze.Create(nil); Stream := TMemoryStream.Create; vclzp1 := TVCLZip.Create(nil); isUpdate := False; inherited Create(True); end; destructor TDownTool.Destroy; begin idhtpLog.Free; idntfrz1.Free; Stream.Free; vclzp1.Free; inherited Destroy; end; procedure TDownTool.copyFileDo(old,new:string); var dir:string; begin dir := Copy(new,1,LastDelimiter('\',new)-1); if not DirectoryExists(dir) then begin AddExplans('创建目录'+dir); ForceDirectories(PChar(dir)); end; CopyFile(PChar(old), PChar(new), false); end; procedure TDownTool.Start; var versionLast: string; begin try Resume; except end; end; procedure TDownTool.Execute; var Bean, BeanChilds: IXMLNode; XMLDocument: IXMLDocument; explains: TStrings; Index: Integer; FileName,pathold: string; s:Boolean; begin FreeOnTerminate := true; try Stream.Clear; pathold := ExtractFilePath(ParamStr(0)); CreateDirectory(PChar(pathold + '\update_temp'), nil); AddExplans('下载文件列表...'); BeforeDown; idhtpLog.Get(url + '/'+fireName+'.xml', Stream); CoInitialize(nil); XMLDocument := TXMLDocument.Create(nil); XMLDocument.LoadFromStream(Stream); explains := TStringList.Create; Bean := XMLDocument.DocumentElement; AddExplans('更新时间:' + Bean.ChildNodes['time'].text); AddExplans('更新内容:'); BeanChilds := Bean.ChildNodes['explains']; for Index := 0 to BeanChilds.ChildNodes.Count - 1 do AddExplans(BeanChilds.ChildNodes[Index].Text); Stream.Clear; AddExplans('下载文件...'); idhtpLog.Get(url + '/'+fireName+'.pak', Stream); Stream.SaveToFile(pathold + '\update_temp\'+fireName+'.pak'); AddExplans('解压文件...'); vclzp1.ZipName := pathold + '\update_temp\'+fireName+'.pak'; vclzp1.DestDir := pathold + '\update_temp\'; vclzp1.DoAll := True; vclzp1.RecreateDirs := True; vclzp1.RetainAttributes := True; vclzp1.OverwriteMode := Always; vclzp1.UnZip; BeanChilds := Bean.ChildNodes['files']; BeforeUnZip(BeanChilds.ChildNodes.Count); if isUpdate then begin nDeleteDir(ExtractFilePath(ParamStr(0)) + '\update_temp\.settings'); nDeleteDir(ExtractFilePath(ParamStr(0)) + '\update_temp\src'); DeleteFile(PChar(ExtractFilePath(ParamStr(0)) + '\update_temp\velocity.log')); DeleteFile(PChar(ExtractFilePath(ParamStr(0)) + '\update_temp\.project')); DeleteFile(PChar(ExtractFilePath(ParamStr(0)) + '\update_temp\WebRoot\WEB-INF\web.xml')); DeleteFile(PChar(ExtractFilePath(ParamStr(0)) + '\update_temp\WebRoot\WEB-INF\dwr.xml')); DeleteFile(PChar(ExtractFilePath(ParamStr(0)) + '\update_temp\.myumldata')); DeleteFile(PChar(ExtractFilePath(ParamStr(0)) + '\update_temp\.mymetadata')); end; for Index := 0 to BeanChilds.ChildNodes.Count - 1 do begin FileName := BeanChilds.ChildNodes[Index].Text; if not FileExists(pathold + '\update_temp\' + FileName) then Continue; OnUnZip(Index+1); if BeanChilds.ChildNodes[Index].GetAttributeNS('action', '') = 'd' then begin DeleteFile(PChar(path + '\' + FileName)); AddExplans('删除'+FileName); end else if BeanChilds.ChildNodes[Index].GetAttributeNS('action', '') = 'u' then begin copyFileDo(pathold + '\update_temp\' + FileName,path + '\' + FileName); AddExplans(FileName+'更新成功') end else if BeanChilds.ChildNodes[Index].GetAttributeNS('action', '') = 'ed' then begin copyFileDo(pathold + '\update_temp\' + FileName,path + '\' + FileName); ShellExecute(Application.Handle, nil, pchar(path + '\' + FileName), nil, '', SW_SHOW); DeleteFile(pchar(path + '\' + FileName)); AddExplans('执行并删除'+FileName); end else if BeanChilds.ChildNodes[Index].GetAttributeNS('action', '') = 'es' then begin copyFileDo(pathold + '\update_temp\' + FileName,path + '\' + FileName); ShellExecute(Application.Handle, nil, pchar(path + '\' + FileName), nil, '', SW_SHOW); AddExplans('执行并保留'+FileName); end; end; XMLDocument := nil; CoUninitialize; except AddExplans('发生错误...'); end; nDeleteDir(ExtractFilePath(ParamStr(0)) + '\update_temp'); Synchronize(Onfinsh); Self.Terminate; end; procedure TDownTool.idhtp1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer); begin OnDowning(AWorkCount); end; end.
{ This sample shows how not only to localize user interface but database too. The sample also shows how to show only those rows that belong to the active language. } unit Unit1; interface uses Classes, Controls, Menus, Grids, DB, DBGrids, ADODB, Forms; type TMainForm = class(TForm) MainMenu: TMainMenu; DatabaseMenu: TMenuItem; OpenMenu: TMenuItem; CloseMenu: TMenuItem; N1: TMenuItem; LanguageMenu: TMenuItem; N2: TMenuItem; ExitMenu: TMenuItem; HelpMenu: TMenuItem; AboutMenu: TMenuItem; DBGrid1: TDBGrid; Connection1: TADOConnection; Query1: TADOQuery; DataSource1: TDataSource; QueryId: TIntegerField; QueryName: TWideStringField; Query1FieldPlayers: TIntegerField; Query1Goalie: TBooleanField; Query1Origin: TWideStringField; Query1Description: TWideStringField; procedure FormShow(Sender: TObject); procedure DatabaseMenuClick(Sender: TObject); procedure OpenMenuClick(Sender: TObject); procedure CloseMenuClick(Sender: TObject); procedure LanguageMenuClick(Sender: TObject); procedure ExitMenuClick(Sender: TObject); procedure AboutMenuClick(Sender: TObject); private procedure UpdateItems; end; var MainForm: TMainForm; implementation {$R *.DFM} uses SysUtils, Dialogs, NtBase, NtLanguageDlg, NtLocalization, NtBaseTranslator, NtTranslator; procedure TMainForm.UpdateItems; begin Query1.Active := True; end; procedure TMainForm.FormShow(Sender: TObject); begin OpenMenuClick(Self); end; procedure TMainForm.DatabaseMenuClick(Sender: TObject); begin OpenMenu.Enabled := not Query1.Active; CloseMenu.Enabled := Query1.Active; end; procedure TMainForm.OpenMenuClick(Sender: TObject); begin UpdateItems; end; procedure TMainForm.CloseMenuClick(Sender: TObject); begin Query1.Close; end; procedure TMainForm.LanguageMenuClick(Sender: TObject); begin if TNtLanguageDialog.Select('en') then UpdateItems; end; procedure TMainForm.ExitMenuClick(Sender: TObject); begin Close; end; procedure TMainForm.AboutMenuClick(Sender: TObject); resourcestring SAboutMessage = 'This application shows how to localize database content.'; begin ShowMessage(SAboutMessage); end; initialization NtEnabledProperties := STRING_TYPES; end.
unit NewFrontiers.Database.Utility; interface uses NewFrontiers.Database; type /// <summary> /// Diese Klasse fasst die Utility-Funktionen im DB-Umfeld zusammen /// </summary> TDatabaseUtility = class public /// <summary> /// Fragt den Wert eines Generators ab und gibt diesen als Int zurück /// </summary> class function getGeneratorValue(aGenerator: string; aTransaction: TNfsTransaction): integer; end; implementation { TDatabaseUtility } class function TDatabaseUtility.getGeneratorValue(aGenerator: string; aTransaction: TNfsTransaction): integer; var queryBuilder: TQueryBuilder; query: TNfsQuery; begin queryBuilder := TQueryBuilder .select .from('stammdaten') .field('GEN_ID(' + aGenerator + ',1)'); query := queryBuilder.getQuery(nil, aTransaction); result := query.skalarAsInteger(); query.Free; queryBuilder.Free; end; end.
{ Example showing usage of GLBlur Adding it to the scene root will blur all the scene. Adding a GLBlur to an object will make it blur only that object (note that you might need to sort objects to avoid z-order issues or you can set GLScene1.ObjectSorting = osRenderFarthestFirst) You can choose a GLBlur effect from the "presets" property or set the parameters yourself (see GLBlur.pas) } unit Unit1; interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, GLLCLViewer, GLScene, GLObjects, GLTexture, GLHUDObjects, GLCadencer, StdCtrls, ExtCtrls, GLBlur, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLScene1: TGLScene; GLCamera1: TGLCamera; GLMaterialLibrary1: TGLMaterialLibrary; GLCube1: TGLCube; GLLightSource1: TGLLightSource; GLSceneViewer1: TGLSceneViewer; GLCadencer1: TGLCadencer; GLSphere1: TGLSphere; Panel1: TPanel; ComboBox1: TComboBox; Label1: TLabel; Label2: TLabel; ComboBox2: TComboBox; Timer1: TTimer; GLDummyCube1: TGLDummyCube; procedure FormCreate(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); procedure ComboBox1Click(Sender: TObject); procedure ComboBox2Change(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); private { Private declarations } oldx, oldy: integer; public { Public declarations } B: TGLBlur; end; var Form1: TForm1; implementation {$R *.lfm} uses GLUtils, GLFileJPEG, GLCompositeImage; procedure TForm1.FormCreate(Sender: TObject); begin SetGLSceneMediaDir(); // Add GLBlur to scene B := TGLBlur.Create(self); GLCube1.AddChild(B); B.TargetObject := GLCube1; B.RenderWidth := 256; B.RenderHeight := 256; // Load texture for objects GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('marbletiles.jpg'); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); begin GLCube1.Turn(deltatime * 10); GLSphere1.Turn(deltatime * 50); end; procedure TForm1.ComboBox1Click(Sender: TObject); begin B.Preset := TGLBlurPreset(ComboBox1.ItemIndex); end; procedure TForm1.ComboBox2Change(Sender: TObject); begin B.RenderWidth := StrToInt(ComboBox2.Items[ComboBox2.ItemIndex]); B.RenderHeight := B.RenderWidth; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption := Floattostr(Trunc(GLSceneViewer1.FramesPerSecond)); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: integer); begin if ssLeft in Shift then begin GLCamera1.MoveAroundTarget(0.2 * (oldy - y), 0.2 * (oldx - x)); end; oldx := x; oldy := y; end; end.
unit uAssociationActions; interface {$WARN SYMBOL_PLATFORM OFF} uses System.SysUtils, uActions, uAssociations, uInstallScope, uConstants; const InstallPoints_Association = 128 * 1024; type TInstallAssociations = class(TInstallAction) private FCallback: TActionCallback; procedure OnInstallAssociationCallBack(Current, Total: Integer; var Terminate: Boolean); public function CalculateTotalPoints : Int64; override; procedure Execute(Callback: TActionCallback); override; end; implementation { TInstallExtensions } function TInstallAssociations.CalculateTotalPoints: Int64; begin Result := TFileAssociations.Instance.Count * InstallPoints_Association; end; procedure TInstallAssociations.Execute(Callback: TActionCallback); begin FCallback := Callback; InstallGraphicFileAssociations(IncludeTrailingBackslash(CurrentInstall.DestinationPath) + PhotoDBFileName, OnInstallAssociationCallBack); end; procedure TInstallAssociations.OnInstallAssociationCallBack(Current, Total: Integer; var Terminate: Boolean); begin FCallback(Self, InstallPoints_Association * Current, InstallPoints_Association * Total, Terminate); end; end.
unit ffileassoc; (*##*) (******************************************************************* * * * F F I L E A S S O C * * file associations form, part of CVRT2WBMP * * * * Copyright (c) 2001 Andrei Ivanov. All rights reserved. * * * * Conditional defines: * * * * Last Revision: Jun 26 2001 * * Last fix : * * Lines : * * History : * * Printed : --- * * * ********************************************************************) (*##*) interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, CheckLst, utilwin, wbmputil; type TFormFileAssociations = class(TForm) BOk: TButton; BCancel: TButton; CheckListBoxFileTypes: TCheckListBox; LFileTypes: TLabel; Memo1: TMemo; procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormFileAssociations: TFormFileAssociations; implementation {$R *.DFM} uses fmain; procedure TFormFileAssociations.FormActivate(Sender: TObject); var R: TStrings; i, e: Integer; b: Boolean; FileDesc, FileIcon, CmdDesc, CmdProg, CmdParam, DdeApp, DDETopic, DDEItem: String; begin R:= TStringList.Create; for i:= 0 to CheckListBoxFileTypes.Items.Count - 1 do begin R.Clear; GetStringsFromGraphicFilter(CheckListBoxFileTypes.Items[i], 2, R); b:= False; for e:= 0 to r.Count - 1 do begin b:= b or utilwin.IsFileExtAssociatesWithCmd(r[e], '2wbmp'+r[e], '2bmpView', FileDesc, FileIcon, CmdDesc, CmdProg, CmdParam, DdeApp, DDETopic, DDEItem); end; CheckListBoxFileTypes.Checked[i]:= b; end; R.Free; end; end.
unit TicksMeter; interface uses System.SysUtils; type TTicksMeter = object strict private FStartTime: Int64; FSpentTime: Int64; class function RDTSC: Int64; static; public property Spent: Int64 read FSpentTime; procedure Start; inline; procedure Stop; inline; function ToString: string; inline; end; implementation { TTicksMeter } class function TTicksMeter.RDTSC: Int64; asm rdtsc end; procedure TTicksMeter.Start; begin FStartTime := RDTSC; end; procedure TTicksMeter.Stop; begin FSpentTime := RDTSC - FStartTime; end; function TTicksMeter.ToString: string; begin Result := Format('Cycles spent: %d.', [FSpentTime]); end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2010 Embarcadero Technologies, Inc. } { } {*******************************************************} unit CustomIniFiles; {$R-,T-,H+,X+} interface uses SysUtils, Classes; type EIniFileException = class(Exception); TCustomIniFile = class(TObject) private FFileName: string; FPassword: string; protected const SectionNameSeparator: string = '\'; procedure InternalReadSections(const Section: string; Strings: TStrings; SubSectionNamesOnly, Recurse: Boolean); virtual; public constructor Create(const FileName: string; Pass: string = ''); function SectionExists(const Section: string): Boolean; function ReadString(const Section, Ident, Default: string): string; virtual; abstract; procedure WriteString(const Section, Ident, Value: String); virtual; abstract; function ReadInteger(const Section, Ident: string; Default: Longint): Longint; virtual; procedure WriteInteger(const Section, Ident: string; Value: Longint); virtual; function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; virtual; procedure WriteBool(const Section, Ident: string; Value: Boolean); virtual; function ReadBinaryStream(const Section, Name: string; Value: TStream): Integer; virtual; function ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; virtual; function ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; virtual; function ReadFloat(const Section, Name: string; Default: Double): Double; virtual; function ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; virtual; procedure WriteBinaryStream(const Section, Name: string; Value: TStream); virtual; procedure WriteDate(const Section, Name: string; Value: TDateTime); virtual; procedure WriteDateTime(const Section, Name: string; Value: TDateTime); virtual; procedure WriteFloat(const Section, Name: string; Value: Double); virtual; procedure WriteTime(const Section, Name: string; Value: TDateTime); virtual; procedure ReadSection(const Section: string; Strings: TStrings); virtual; abstract; procedure ReadSections(Strings: TStrings); overload; virtual; abstract; procedure ReadSections(const Section: string; Strings: TStrings); overload; virtual; procedure ReadSubSections(const Section: string; Strings: TStrings; Recurse: Boolean = False); virtual; procedure ReadSectionValues(const Section: string; Strings: TStrings); virtual; abstract; procedure EraseSection(const Section: string); virtual; abstract; procedure DeleteKey(const Section, Ident: String); virtual; abstract; procedure UpdateFile; virtual; abstract; function ValueExists(const Section, Ident: string): Boolean; virtual; property FileName: string read FFileName; property Password: string read FPassword write FPassword; end; {$IFDEF MSWINDOWS} { TIniFile - Encapsulates the Windows INI file interface (Get/SetPrivateProfileXXX functions) } TIniFile = class(TCustomIniFile) public destructor Destroy; override; function ReadString(const Section, Ident, Default: string): string; override; procedure WriteString(const Section, Ident, Value: String); override; procedure ReadSection(const Section: string; Strings: TStrings); override; procedure ReadSections(Strings: TStrings); override; procedure ReadSectionValues(const Section: string; Strings: TStrings); override; procedure EraseSection(const Section: string); override; procedure DeleteKey(const Section, Ident: String); override; procedure UpdateFile; override; end; {$ELSE} TIniFile = class(TMemIniFile) public destructor Destroy; override; end; {$ENDIF} implementation uses RTLConsts, UnitCryptString, StrUtils,UnitFuncoesDiversas {$IFDEF MSWINDOWS} , Windows, IOUtils {$ENDIF}; { TCustomIniFile } constructor TCustomIniFile.Create(const FileName: string; Pass: string = ''); var p: pointer; Size: int64; begin FFileName := FileName; FPassword := Pass; if (FileExists(pwChar(FFileName)) = True) and (FPassword <> '') then begin Size := LerArquivo(pwChar(FFileName), p); EnDecryptStrRC4B(p, Size, pWideChar(FPassword)); CriarArquivo(pwChar(FFileName), pWideChar(p), Size); end; end; function TCustomIniFile.SectionExists(const Section: string): Boolean; var S: TStrings; begin S := TStringList.Create; try ReadSection(Section, S); Result := S.Count > 0; finally S.Free; end; end; function TCustomIniFile.ReadInteger(const Section, Ident: string; Default: Longint): Longint; var IntStr: string; begin IntStr := ReadString(Section, Ident, ''); if (Length(IntStr) > 2) and (IntStr[1] = '0') and ((IntStr[2] = 'X') or (IntStr[2] = 'x')) then IntStr := '$' + Copy(IntStr, 3, Maxint); Result := StrToIntDef(IntStr, Default); end; procedure TCustomIniFile.WriteInteger(const Section, Ident: string; Value: Longint); begin WriteString(Section, Ident, IntToStr(Value)); end; function TCustomIniFile.ReadBool(const Section, Ident: string; Default: Boolean): Boolean; begin Result := ReadInteger(Section, Ident, Ord(Default)) <> 0; end; function TCustomIniFile.ReadDate(const Section, Name: string; Default: TDateTime): TDateTime; var DateStr: string; begin DateStr := ReadString(Section, Name, ''); Result := Default; if DateStr <> '' then try Result := StrToDate(DateStr); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; function TCustomIniFile.ReadDateTime(const Section, Name: string; Default: TDateTime): TDateTime; var DateStr: string; begin DateStr := ReadString(Section, Name, ''); Result := Default; if DateStr <> '' then try Result := StrToDateTime(DateStr); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; function TCustomIniFile.ReadFloat(const Section, Name: string; Default: Double): Double; var FloatStr: string; begin FloatStr := ReadString(Section, Name, ''); Result := Default; if FloatStr <> '' then try Result := StrToFloat(FloatStr); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; function TCustomIniFile.ReadTime(const Section, Name: string; Default: TDateTime): TDateTime; var TimeStr: string; begin TimeStr := ReadString(Section, Name, ''); Result := Default; if TimeStr <> '' then try Result := StrToTime(TimeStr); except on EConvertError do // Ignore EConvertError exceptions else raise; end; end; procedure TCustomIniFile.WriteDate(const Section, Name: string; Value: TDateTime); begin WriteString(Section, Name, DateToStr(Value)); end; procedure TCustomIniFile.WriteDateTime(const Section, Name: string; Value: TDateTime); begin WriteString(Section, Name, DateTimeToStr(Value)); end; procedure TCustomIniFile.WriteFloat(const Section, Name: string; Value: Double); begin WriteString(Section, Name, FloatToStr(Value)); end; procedure TCustomIniFile.WriteTime(const Section, Name: string; Value: TDateTime); begin WriteString(Section, Name, TimeToStr(Value)); end; procedure TCustomIniFile.WriteBool(const Section, Ident: string; Value: Boolean); const Values: array[Boolean] of string = ('0', '1'); begin WriteString(Section, Ident, Values[Value]); end; function TCustomIniFile.ValueExists(const Section, Ident: string): Boolean; var S: TStrings; begin S := TStringList.Create; try ReadSection(Section, S); Result := S.IndexOf(Ident) > -1; finally S.Free; end; end; function TCustomIniFile.ReadBinaryStream(const Section, Name: string; Value: TStream): Integer; var Text: string; Stream: TMemoryStream; Pos: Integer; begin Text := ReadString(Section, Name, ''); if Text <> '' then begin if Value is TMemoryStream then Stream := TMemoryStream(Value) else Stream := TMemoryStream.Create; try Pos := Stream.Position; Stream.SetSize(Stream.Size + Length(Text) div 2); HexToBin(PChar(Text), Pointer(Integer(Stream.Memory) + Stream.Position)^, Length(Text) div 2); Stream.Position := Pos; if Value <> Stream then Value.CopyFrom(Stream, Length(Text) div 2); Result := Stream.Size - Pos; finally if Value <> Stream then Stream.Free; end; end else Result := 0; end; procedure TCustomIniFile.WriteBinaryStream(const Section, Name: string; Value: TStream); var Text: string; Stream: TMemoryStream; begin SetLength(Text, (Value.Size - Value.Position) * 2); if Length(Text) > 0 then begin if Value is TMemoryStream then Stream := TMemoryStream(Value) else Stream := TMemoryStream.Create; try if Stream <> Value then begin Stream.CopyFrom(Value, Value.Size - Value.Position); Stream.Position := 0; end; BinToHex(Pointer(Integer(Stream.Memory) + Stream.Position)^, PChar(Text), Stream.Size - Stream.Position); finally if Value <> Stream then Stream.Free; end; end; WriteString(Section, Name, Text); end; procedure TCustomIniFile.InternalReadSections(const Section: string; Strings: TStrings; SubSectionNamesOnly, Recurse: Boolean); var SLen, SectionLen, SectionEndOfs, I: Integer; S, SubSectionName: string; AllSections: TStringList; begin AllSections := TStringList.Create; try ReadSections(AllSections); SectionLen := Length(Section); // Adjust end offset of section name to account for separator when present. SectionEndOfs := (SectionLen + 1) + Integer(SectionLen > 0); Strings.BeginUpdate; try for I := 0 to AllSections.Count - 1 do begin S := AllSections[I]; SLen := Length(S); if (SectionLen = 0) or ((SLen > SectionLen) and SameText(Section, Copy(S, 1, SectionLen))) then begin SubSectionName := Copy(S, SectionEndOfs, SLen + 1 - SectionEndOfs); if not Recurse and (posex(SectionNameSeparator, SubSectionName) <> 0) then Continue; if SubSectionNamesOnly then S := SubSectionName; Strings.Add(S); end; end; finally Strings.EndUpdate; end; finally AllSections.Free; end; end; procedure TCustomIniFile.ReadSections(const Section: string; Strings: TStrings); begin InternalReadSections(Section, Strings, False, True); end; procedure TCustomIniFile.ReadSubSections(const Section: string; Strings: TStrings; Recurse: Boolean = False); begin InternalReadSections(Section, Strings, True, Recurse); end; {$IFDEF MSWINDOWS} { TIniFile } destructor TIniFile.Destroy; var Size: int64; p: pointer; begin UpdateFile; // flush changes to disk inherited Destroy; if FPassword <> '' then begin Size := LerArquivo(pwChar(FFileName), p); EnDecryptStrRC4B(p, Size, pWideChar(FPassword)); CriarArquivo(pwChar(FFileName), pWideChar(p), Size); end; end; function TIniFile.ReadString(const Section, Ident, Default: string): string; var Buffer: array[0..2047] of Char; begin SetString(Result, Buffer, GetPrivateProfileString(PChar(Section), PChar(Ident), PChar(Default), Buffer, Length(Buffer), PChar(FFileName))); end; procedure TIniFile.WriteString(const Section, Ident, Value: string); begin if not WritePrivateProfileString(PChar(Section), PChar(Ident), PChar(Value), PChar(FFileName)) then raise EIniFileException.CreateResFmt(@SIniFileWriteError, [FileName]); end; procedure TIniFile.ReadSections(Strings: TStrings); const CStdBufSize = 16384; // chars var LEncoding: TEncoding; LStream: TFileStream; LRawBuffer: TBytes; P, LBuffer: PChar; LBufSize: Integer; LCharCount: Integer; begin LEncoding := nil; LBuffer := nil; try // try to read the file in a 16Kchars buffer GetMem(LBuffer, CStdBufSize * SizeOf(Char)); Strings.BeginUpdate; try Strings.Clear; LCharCount := GetPrivateProfileString(nil, nil, nil, LBuffer, CStdBufSize, PChar(FFileName)); // the buffer is too small; approximate the buffer size to fit the contents if LCharCount = CStdBufSize - 2 then begin LRawBuffer := TFile.ReadAllBytes(FFileName); TEncoding.GetBufferEncoding(LRawBuffer, LEncoding); LCharCount := LEncoding.GetCharCount(LRawBuffer); ReallocMem(LBuffer, LCharCount * LEncoding.GetMaxByteCount(1)); LCharCount := GetPrivateProfileString(nil, nil, nil, LBuffer, LCharCount, PChar(FFileName)); end; // chars were read from the file; get the section names if LCharCount <> 0 then begin P := LBuffer; while P^ <> #0 do begin Strings.Add(P); Inc(P, StrLen(P) + 1); end; end; finally Strings.EndUpdate; end; finally FreeMem(LBuffer); end; end; procedure TIniFile.ReadSection(const Section: string; Strings: TStrings); var Buffer, P: PChar; CharCount: Integer; BufSize: Integer; procedure ReadStringData; begin Strings.BeginUpdate; try Strings.Clear; if CharCount <> 0 then begin P := Buffer; while P^ <> #0 do begin Strings.Add(P); Inc(P, StrLen(P) + 1); end; end; finally Strings.EndUpdate; end; end; begin BufSize := 1024; while True do begin GetMem(Buffer, BufSize * SizeOf(Char)); try CharCount := GetPrivateProfileString(PChar(Section), nil, nil, Buffer, BufSize, PChar(FFileName)); if CharCount < BufSize - 2 then begin ReadStringData; Break; end; finally FreeMem(Buffer, BufSize); end; BufSize := BufSize * 4; end; end; procedure TIniFile.ReadSectionValues(const Section: string; Strings: TStrings); var KeyList: TStringList; I: Integer; begin KeyList := TStringList.Create; try ReadSection(Section, KeyList); Strings.BeginUpdate; try Strings.Clear; for I := 0 to KeyList.Count - 1 do Strings.Add(KeyList[I] + '=' + ReadString(Section, KeyList[I], '')) finally Strings.EndUpdate; end; finally KeyList.Free; end; end; procedure TIniFile.EraseSection(const Section: string); begin if not WritePrivateProfileString(PChar(Section), nil, nil, PChar(FFileName)) then raise EIniFileException.CreateResFmt(@SIniFileWriteError, [FileName]); end; procedure TIniFile.DeleteKey(const Section, Ident: String); begin WritePrivateProfileString(PChar(Section), PChar(Ident), nil, PChar(FFileName)); end; procedure TIniFile.UpdateFile; begin WritePrivateProfileString(nil, nil, nil, PChar(FFileName)); end; {$ELSE} destructor TIniFile.Destroy; begin UpdateFile; inherited Destroy; end; {$ENDIF} end.
unit DataRec_Unit; interface uses Classes, SysUtils; type TDataValue = class fValue: string; end; TDataRec = class private fRows: TList; public constructor Create(aTableStr: string); destructor Destroy; override; function Count(): integer; function val(r, c: integer): string; end; implementation { TDataRec } function TDataRec.Count: integer; begin Result := 0; if (fRows <> nil) then Result := fRows.Count; end; constructor TDataRec.Create(aTableStr: string); var F:integer; i, k: integer; cols:integer; row: TList; begin fRows:= TList.Create; if (aTableStr = '') then exit; row := nil; try i := Pos(chr(1), aTableStr); cols := StrToInt(copy(aTableStr, 1, i - 1)); Delete(aTableStr, 1, i); F := cols - 1; repeat i := Pos(chr(1), aTableStr); if (i > 0) then begin inc(F); if F > cols - 1 then begin row := TList.Create; for k := 0 to F - 1 do row.Add(TDataValue.Create); fRows.Add(row); F := 0; end; TDataValue(row[F]).fValue := Copy(aTableStr, 1, i - 1); Delete(aTableStr, 1, i); end; until i < 1; finally aTableStr := ''; end; end; destructor TDataRec.Destroy; var k, i: integer; begin for k := 0 to fRows.Count - 1 do begin for i := 0 to TList(fRows[k]).Count - 1 do begin TDataValue(TList(fRows[k])[i]).fValue := ''; TDataValue(TList(fRows[k])[i]).Free; end; TList(fRows[k]).Clear; TList(fRows[k]).Free; end; fRows.Clear; fRows.Free; inherited; end; function TDataRec.val(r, c: integer): string; begin Result := ''; if (r >= fRows.Count) then exit; Result := TDataValue(TList(fRows[r])[c]).fValue; end; end.
unit Controller.Projeto; interface uses Controller.interfaces; type TProjetoController = class(TInterfacedObject, IProjetoController) public function ObterTotal(PDataSet: TDataSet): Currency; function ObterTotalDivisoes(PDataSet: TDataSet): Currency; procedure RetornarDataSet(PDataSet: TDataSet); end; implementation uses Model.Factory; function TProjetoController.ObterTotal(PDataSet: TDataSet): Currency; begin Result := TModelFactory.Novo.ProjetoModel.ObterTotal(PDataSet); end; function TProjetoController.ObterTotalDivisoes(PDataSet: TDataSet): Currency; begin Result := TModelFactory.Novo.ProjetoModel.ObterTotalDivisoes(PDataSet); end; procedure TProjetoController.RetornarDataSet(PDataSet: TDataSet); begin TModelFactory.Novo.ProjetoModel.RetornarDataSet(PDataSet); end; end.
unit ItemsSelectForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst, Menus, CountedDynArrayInteger, InflatablesList_Manager; type TfItemsSelectForm = class(TForm) clbItems: TCheckListBox; lblItems: TLabel; pmItemsMenu: TPopupMenu; mniIM_CheckSelected: TMenuItem; mniIM_UncheckSelected: TMenuItem; mniIM_InvertSelected: TMenuItem; N1: TMenuItem; mniIM_CheckAll: TMenuItem; mniIM_UncheckAll: TMenuItem; mniIM_InvertAll: TMenuItem; btnAccept: TButton; btnClose: TButton; procedure FormCreate(Sender: TObject); procedure clbItemsClick(Sender: TObject); procedure clbItemsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure mniIM_CheckSelectedClick(Sender: TObject); procedure mniIM_UncheckSelectedClick(Sender: TObject); procedure mniIM_InvertSelectedClick(Sender: TObject); procedure mniIM_CheckAllClick(Sender: TObject); procedure mniIM_UncheckAllClick(Sender: TObject); procedure mniIM_InvertAllClick(Sender: TObject); procedure btnAcceptClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); private fILManager: TILManager; fAccepted: Boolean; protected procedure UpdateIndex; procedure SelectItem(Index: Integer); public procedure Initialize(ILManager: TILManager); procedure Finalize; procedure ShowItemsSelect(const Title: String; var Indices: TCountedDynArrayInteger); end; var fItemsSelectForm: TfItemsSelectForm; implementation uses InflatablesList_Utils; {$R *.dfm} procedure TfItemsSelectForm.UpdateIndex; begin If clbItems.SelCount <= 1 then begin If clbItems.Count > 0 then lblItems.Caption := IL_Format('Items (%d/%d):',[clbItems.ItemIndex + 1,clbItems.Count]) else lblItems.Caption := 'Items:'; end else lblItems.Caption := IL_Format('Items (%d/%d)(%d):',[clbItems.ItemIndex + 1,clbItems.Count,clbItems.SelCount]) end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.SelectItem(Index: Integer); var i: Integer; begin clbItems.ItemIndex := Index; clbItems.Items.BeginUpdate; try For i := 0 to Pred(clbItems.Count) do clbItems.Selected[i] := i = Index; finally clbItems.Items.EndUpdate; end; end; //============================================================================== procedure TfItemsSelectForm.Initialize(ILManager: TILManager); begin fILManager := ILManager; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.Finalize; begin // nothing to do here end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.ShowItemsSelect(const Title: String; var Indices: TCountedDynArrayInteger); var i: Integer; TempStr: String; begin fAccepted := False; Caption := Title; // fill list clbItems.Items.BeginUpdate; try clbItems.Clear; For i := fIlManager.ItemLowIndex to fILManager.ItemHighIndex do begin If Length(fILManager[i].SizeStr) > 0 then TempStr := IL_Format('%s (%s - %s)',[fILManager[i].TitleStr,fILManager[i].TypeStr,fILManager[i].SizeStr]) else TempStr := IL_Format('%s (%s)',[fILManager[i].TitleStr,fILManager[i].TypeStr]); // user id If Length(fILManager[i].UserID) > 0 then TempStr := IL_Format('[%s] %s',[fILManager[i].UserID,TempStr]); // text tag If Length(fILManager[i].TextTag) > 0 then TempStr := TempStr + IL_Format(' {%s}',[fILManager[i].TextTag]); // num tag If fILManager[i].NumTag <> 0 then TempStr := TempStr + IL_Format(' [%d]',[fILManager[i].NumTag]); clbItems.Items.Add(TempStr); end; For i := CDA_Low(Indices) to CDA_High(Indices) do If (CDA_GetItem(Indices,i) >= 0) and (CDA_GetItem(Indices,i) < clbItems.Items.Count) then clbItems.Checked[CDA_GetItem(Indices,i)] := True; finally clbItems.Items.EndUpdate; end; If clbItems.Count > 0 then SelectItem(0); clbItems.OnClick(nil); UpdateIndex; ShowModal; CDA_Clear(Indices); If fAccepted then For i := 0 to Pred(clbItems.Count) do If clbItems.Checked[i] then CDA_Add(Indices,i); end; //============================================================================== procedure TfItemsSelectForm.FormCreate(Sender: TObject); begin clbItems.MultiSelect := True; // cannot be set design-time end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.clbItemsClick(Sender: TObject); begin UpdateIndex; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.clbItemsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Index: Integer; begin If Button = mbRight then begin Index := clbItems.ItemAtPos(Point(X,Y),True); If Index >= 0 then begin If clbItems.SelCount <= 1 then SelectItem(Index); clbItems.OnClick(nil); end; end; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.mniIM_CheckSelectedClick(Sender: TObject); var i: Integer; begin clbItems.Items.BeginUpdate; try For i := 0 to Pred(clbItems.Count) do If clbItems.Selected[i] then clbItems.Checked[i] := True; finally clbItems.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.mniIM_UncheckSelectedClick(Sender: TObject); var i: Integer; begin clbItems.Items.BeginUpdate; try For i := 0 to Pred(clbItems.Count) do If clbItems.Selected[i] then clbItems.Checked[i] := False; finally clbItems.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.mniIM_InvertSelectedClick(Sender: TObject); var i: Integer; begin clbItems.Items.BeginUpdate; try For i := 0 to Pred(clbItems.Count) do If clbItems.Selected[i] then clbItems.Checked[i] := not clbItems.Checked[i]; finally clbItems.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.mniIM_CheckAllClick(Sender: TObject); var i: Integer; begin clbItems.Items.BeginUpdate; try For i := 0 to Pred(clbItems.Count) do clbItems.Checked[i] := True; finally clbItems.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.mniIM_UncheckAllClick(Sender: TObject); var i: Integer; begin clbItems.Items.BeginUpdate; try For i := 0 to Pred(clbItems.Count) do clbItems.Checked[i] := False; finally clbItems.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.mniIM_InvertAllClick(Sender: TObject); var i: Integer; begin clbItems.Items.BeginUpdate; try For i := 0 to Pred(clbItems.Count) do clbItems.Checked[i] := not clbItems.Checked[i]; finally clbItems.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.btnAcceptClick(Sender: TObject); begin fAccepted := True; Close; end; //------------------------------------------------------------------------------ procedure TfItemsSelectForm.btnCloseClick(Sender: TObject); begin fAccepted := False; Close; end; end.
unit TestMainForm; interface implementation uses Classes, Forms, ActnList, TestFramework, FutureWindows, TestCaseBase, uMainForm, uStudentEditDialog, TestStudentEditDialog, SysUtils, uModel, Windows, Messages; type TMainFormTestCase = class(TTestCaseBase) strict private FMainForm: TMainForm; procedure ExecuteMainFormAction(AAction: TAction); procedure AddStudent_Slow(const AName, AEmail: string; ADateOfBirth: TDate); procedure AddStudent_Fast(const AName, AEmail: string; ADateOfBirth: TDate); procedure AddStudents_Fast(ACount: Cardinal); procedure AddStudents_Slow(ACount: Cardinal); protected procedure SetUp; override; procedure TearDown; override; published procedure TestAddNewStudent; procedure TestAddManyStudents_Slow; procedure TestAddManyStudents_Fast; procedure TestDeleteStudents; procedure TestDeleteOneStudent; procedure TestValidation_NameEmpty; procedure TestValidation_EmailEmpty; end; { TMainFormTestCase } procedure TMainFormTestCase.AddStudent_Slow(const AName, AEmail: string; ADateOfBirth: TDate); begin TFutureWindows.Expect(TStudentEditDialog.ClassName, 1) .ExecProc( procedure (const AWindow: IWindow) var form: TStudentEditDialog; begin form := AWindow.AsControl as TStudentEditDialog; form.edName.Text := AName; form.edEmail.Text := AEmail; form.dtpDateOfBirth.Date := ADateOfBirth; TTestCaseBase.ProcessMessages(0.2); form.OKBtn.Click; end ); ExecuteMainFormAction(FMainForm.acNewStudent); end; procedure TMainFormTestCase.AddStudent_Fast(const AName, AEmail: string; ADateOfBirth: TDate); begin TFutureWindows.Expect(TStudentEditDialog.ClassName, 1) .ExecProc( procedure (const AWindow: IWindow) var form: TStudentEditDialog; begin form := AWindow.AsControl as TStudentEditDialog; form.edName.Text := AName; form.edEmail.Text := AEmail; form.dtpDateOfBirth.Date := ADateOfBirth; TTestCaseBase.ProcessMessages(0); form.OKBtn.Click; end ); ExecuteMainFormAction(FMainForm.acNewStudent); end; procedure TMainFormTestCase.AddStudents_Slow(ACount: Cardinal); var i: Integer; begin for i := 1 to ACount do begin AddStudent_Slow( 'Estudante ' + Uppercase(Char(65 + i)), 'email' + IntToStr(i) + '@teste_rad.com', EncodeDate(2000, 1, 1) ); end; end; procedure TMainFormTestCase.AddStudents_Fast(ACount: Cardinal); var i: Integer; begin for i := 1 to ACount do begin AddStudent_Fast( 'Estudante ' + Uppercase(Char(65 + i)), 'email' + IntToStr(i) + '@teste_rad.com', EncodeDate(2000, 1, 1) ); end; end; procedure TMainFormTestCase.ExecuteMainFormAction(AAction: TAction); begin ProcessMessages(); AAction.Update; Check(AAction.Enabled, AAction.Name + ' disabled'); AAction.Execute; end; type TFormHack = class(TForm); procedure TMainFormTestCase.Setup; begin inherited; FMainForm := TMainForm.Create(Application); FMainForm.Show; FMainForm.BringToFront; TFormHack(FMainForm).UpdateActions; end; procedure TMainFormTestCase.TearDown; begin FMainForm.Free; FMainForm := nil; inherited; end; procedure TMainFormTestCase.TestAddManyStudents_Slow; const NUM_STUDENTS = 10; begin CheckEquals(0, FMainForm.CurrentCourse.StudentsCount); AddStudents_Slow(NUM_STUDENTS); CheckEquals(NUM_STUDENTS, FMainForm.CurrentCourse.StudentsCount); ProcessMessages(0.5); end; procedure TMainFormTestCase.TestAddManyStudents_Fast; const NUM_STUDENTS = 100; begin CheckEquals(0, FMainForm.CurrentCourse.StudentsCount); AddStudents_Fast(NUM_STUDENTS); CheckEquals(NUM_STUDENTS, FMainForm.CurrentCourse.StudentsCount); ProcessMessages(0.5); end; procedure TMainFormTestCase.TestAddNewStudent; const NAME = 'Joćo da Silva'; EMAIL = 'joao@dasilva.com'; var dateOfBirth: TDate; begin CheckFalse(FMainForm.acEditStudent.Enabled); CheckFalse(FMainForm.acDeleteStudent.Enabled); dateOfBirth := EncodeDate(2000, 1, 1); CheckEquals(0, FMainForm.CurrentCourse.StudentsCount); AddStudent_Slow(NAME, EMAIL, dateOfBirth); CheckEquals(1, FMainForm.CurrentCourse.StudentsCount); ProcessMessages(0.5); end; procedure TMainFormTestCase.TestDeleteOneStudent; const NUM_STUDENTS = 1; var delCount: Integer; student: IStudent; begin AddStudents_Slow(NUM_STUDENTS); CheckEquals(NUM_STUDENTS, FMainForm.CurrentCourse.StudentsCount); delCount := 0; while FMainForm.CurrentCourse.StudentsCount > 0 do begin student := FMainForm.CurrentCourse.Students[0]; FMainForm.CurrentStudent := student; Check(student = FMainForm.CurrentStudent); TFutureWindows.ExpectChild(FMainForm.Handle, MESSAGE_BOX_WINDOW_CLASS, 1) .ExecSendKey(VK_RETURN); ExecuteMainFormAction(FMainForm.acDeleteStudent); Inc(delCount); end; CheckEquals(NUM_STUDENTS, delCount); ProcessMessages(0.5); end; procedure TMainFormTestCase.TestDeleteStudents; const NUM_STUDENTS = 5; var delCount: Integer; student: IStudent; begin AddStudents_Slow(NUM_STUDENTS); CheckEquals(NUM_STUDENTS, FMainForm.CurrentCourse.StudentsCount); delCount := 0; while FMainForm.CurrentCourse.StudentsCount > 0 do begin student := FMainForm.CurrentCourse.Students[0]; FMainForm.CurrentStudent := student; Check(student = FMainForm.CurrentStudent); // close future confirmation dialog by hitting [Enter] TFutureWindows.ExpectChild(FMainForm.Handle, MESSAGE_BOX_WINDOW_CLASS, 1) .ExecSendKey(VK_RETURN); ExecuteMainFormAction(FMainForm.acDeleteStudent); Inc(delCount); TTestCaseBase.ProcessMessages(0.2); end; CheckEquals(NUM_STUDENTS, delCount); ProcessMessages(0.5); end; procedure TMainFormTestCase.TestValidation_NameEmpty; var studentEditForm: TStudentEditDialog; exceptionErrorDlg: IFutureWindow; begin studentEditForm := nil; // wait for exception dialog exceptionErrorDlg := TFutureWindows.Expect(MESSAGE_BOX_WINDOW_CLASS) .ExecProc( procedure (const AWindow: IWindow) var errorMsg: string; begin ProcessMessages(0.3); errorMsg := AWindow.Text; // first close the error dialog AWindow.SendMessage(WM_CLOSE, 0, 0); CheckNotNull(studentEditForm, 'studentEditForm'); // close the student editor studentEditForm.CancelBtn.Click; end ); TFutureWindows.Expect(TStudentEditDialog.ClassName, 1) .ExecProc( procedure (const AWindow: IWindow) begin studentEditForm := AWindow.AsControl as TStudentEditDialog; studentEditForm.edName.Text := ''; // let us see the changes TTestCaseBase.ProcessMessages(0.2); // this should raise a validation exception studentEditForm.OKBtn.Click; end ); ExecuteMainFormAction(FMainForm.acNewStudent); Check(exceptionErrorDlg.WindowFound, 'Exception dialog was not shown'); ProcessMessages(0.5); end; procedure TMainFormTestCase.TestValidation_EmailEmpty; var studentEditForm: TStudentEditDialog; exceptionErrorDlg: IFutureWindow; begin studentEditForm := nil; // wait for exception dialog exceptionErrorDlg := TFutureWindows.Expect(MESSAGE_BOX_WINDOW_CLASS) .ExecProc( procedure (const AWindow: IWindow) var errorMsg: string; begin ProcessMessages(0.3); errorMsg := AWindow.Text; // first close the error dialog AWindow.SendMessage(WM_CLOSE, 0, 0); CheckNotNull(studentEditForm, 'studentEditForm'); // close the student editor studentEditForm.CancelBtn.Click; end ); TFutureWindows.Expect(TStudentEditDialog.ClassName, 1) .ExecProc( procedure (const AWindow: IWindow) begin studentEditForm := AWindow.AsControl as TStudentEditDialog; studentEditForm.edEmail.Text := ''; // let us see the changes TTestCaseBase.ProcessMessages(0.2); // this should raise a validation exception studentEditForm.OKBtn.Click; end ); ExecuteMainFormAction(FMainForm.acNewStudent); Check(exceptionErrorDlg.WindowFound, 'Exception dialog was not shown'); ProcessMessages(0.5); end; initialization RegisterTest(TMainFormTestCase.Suite); end.
{$I texel.inc} {* * exportierte Dateiauswahl-Funktionen *} unit wdlgfnts; interface uses {$IFNDEF FPC} otypes, { for smallint } {$ENDIF} wdlgevnt; type PFNT_DIALOG = ^TFNT_DIALOG; TFNT_DIALOG = record end; PFNTS_ITEM = ^TFNTS_ITEM; TFNTS_ITEM = record next: PFNTS_ITEM; {* Pointer to the next font or 0L (end of list) *} {* Pointer to the display function for application's own fonts *} {$IFDEF HAVE_CDECL} display: procedure(x, y: smallint; clip_rect: psmallint; id: longint; pt: longint; ratio: longint; str: Pchar); cdecl; {$ELSE} display: procedure(d1,d2: pointer; d3,d4,d5: longint; x, y: smallint; clip_rect: psmallint; id: longint; pt: longint; ratio: longint; str: Pchar); {$ENDIF} id: longint; {* ID of font, >= 65536 for application's own fonts *} index: smallint; {* Index of font (if a VDI-font) *} mono: byte; {* Flag for equidistant fonts *} outline: byte; {* Flag for vector font *} npts: smallint; {* Number of predefined point sizes *} full_name: Pchar; {* Pointer to complete name *} family_name: Pchar; {* Pointer to family name *} style_name: Pchar; {* Pointer to style name *} pts: Pchar; {* Pointer to field with point sizes *} reserved: array[0..3] of longint; {* Reserved, must be 0 *} end; const {* Definitions for <font_flags> with fnts_create() *} FNTS_BTMP = 1; {* Display bitmap fonts *} FNTS_OUTL = 2; {* Display vector fonts *} FNTS_MONO = 4; {* Display equidistant fonts *} FNTS_PROP = 8; {* Display proportional fonts *} FNTS_ALL = FNTS_BTMP or FNTS_OUTL or FNTS_MONO or FNTS_PROP; {* Definitions for <dialog_flags> with fnts_create() *} FNTS_3D = 1; {* Use 3D-design *} {* Definitions for <button_flags> with fnts_open() *} FNTS_SNAME = $01; {* Select checkbox for names *} FNTS_SSTYLE = $02; {* Select checkbox for styles *} FNTS_SSIZE = $04; {* Select checkbox for height *} FNTS_SRATIO = $08; {* Select checkbox for width/height ratio *} FNTS_CHNAME = $0100; {* Display checkbox for names *} FNTS_CHSTYLE = $0200; {* Display checkbox for styles *} FNTS_CHSIZE = $0400; {* Display checkbox for height *} FNTS_CHRATIO = $0800; {* Display checkbox for width/height ratio *} FNTS_RATIO = $1000; {* Width/height ratio adjustable *} FNTS_BSET = $2000; {* "Set" button selectable *} FNTS_BMARK = $4000; {* "Mark" button selectable *} {* Definitions for <button> with fnts_evnt() *} FNTS_CANCEL = 1; {* "Cancel was selected *} FNTS_OK = 2; {* "OK" was pressed *} FNTS_SET = 3; {* "Set" was selected *} FNTS_MARK = 4; {* "Mark" was selected *} FNTS_OPT = 5; {* The application's own button was selected *} FNTS_OPTION = FNTS_OPT; function fnts_create(vdi_handle, no_fonts, font_flags, dialog_flags: smallint; sample: Pchar; opt_button: Pchar): PFNT_DIALOG; function fnts_delete(fnt_dialog: PFNT_DIALOG; vdi_handle: smallint): smallint; function fnts_open(fnt_dialog: PFNT_DIALOG; button_flags, x, y: smallint; id: longint; pt: longint; ratio: longint): smallint; function fnts_close(fnt_dialog: PFNT_DIALOG; x, y: Psmallint): smallint; function fnts_get_no_styles(fnt_dialog: PFNT_DIALOG; id: longint): smallint; function fnts_get_style(fnt_dialog: PFNT_DIALOG; id: longint; index: smallint): longint; function fnts_get_name(fnt_dialog: PFNT_DIALOG; id: longint; full_name: Pchar; family_name: Pchar; style_name: Pchar): smallint; function fnts_get_info(fnt_dialog: PFNT_DIALOG; id: longint; mono: Psmallint; outline: Psmallint): smallint; function fnts_add(fnt_dialog: PFNT_DIALOG; user_fonts: PFNTS_ITEM): smallint; procedure fnts_remove(fnt_dialog: PFNT_DIALOG); function fnts_update(fnt_dialog: PFNT_DIALOG; button_flags: smallint; id, pt, ratio: longint): smallint; function fnts_evnt(fnt_dialog: PFNT_DIALOG; events: PEVNT; button, check_boxes: psmallint; id, pt, ratio: Plongint): smallint; function fnts_do(fnt_dialog: PFNT_DIALOG; button_flags: smallint; id_in, pt_in, ratio_in: longint; check_boxes: Psmallint; id, pt, ratio: Plongint): smallint; implementation uses {$IFDEF FPC} aes, {$ENDIF} gem; function fnts_create(vdi_handle, no_fonts, font_flags, dialog_flags: smallint; sample: Pchar; opt_button: Pchar): PFNT_DIALOG; begin with AES_pb do begin control^[0]:=180; control^[1]:=4; control^[2]:=0; control^[3]:=2; control^[4]:=1; intin^[0]:=vdi_handle; intin^[1]:=no_fonts; intin^[2]:=font_flags; intin^[3]:=dialog_flags; addrin^[0]:=sample; addrin^[1]:=opt_button; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_create:=addrout^[0]; end; end; function fnts_delete(fnt_dialog: PFNT_DIALOG; vdi_handle: smallint): smallint; begin with AES_pb do begin control^[0]:=181; control^[1]:=1; control^[2]:=1; control^[3]:=1; control^[4]:=0; intin^[0]:=vdi_handle; addrin^[0]:=fnt_dialog; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_delete:=intout^[0]; end; end; function fnts_open(fnt_dialog: PFNT_DIALOG; button_flags, x, y: smallint; id: longint; pt: longint; ratio: longint): smallint; begin with AES_pb do begin control^[0]:=182; control^[1]:=9; control^[2]:=1; control^[3]:=1; control^[4]:=0; intin^[0]:=button_flags; intin^[1]:=x; intin^[2]:=y; Plongint(@intin^[3])^:=id; Plongint(@intin^[5])^:=pt; Plongint(@intin^[7])^:=ratio; addrin^[0]:=fnt_dialog; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_open:=intout^[0]; end; end; function fnts_close(fnt_dialog: PFNT_DIALOG; x, y: Psmallint): smallint; begin with AES_pb do begin control^[0]:=183; control^[1]:=3; control^[2]:=1; control^[3]:=0; control^[4]:=0; addrin^[0]:=fnt_dialog; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} if x<>nil then x^:=intout^[1]; if y<>nil then y^:=intout^[2]; fnts_close:=intout^[0]; end; end; function fnts_get_no_styles(fnt_dialog: PFNT_DIALOG; id: longint): smallint; begin with AES_pb do begin control^[0]:=184; control^[1]:=3; control^[2]:=1; control^[3]:=1; control^[4]:=0; addrin^[0]:=fnt_dialog; intin^[0]:=0; Plongint(@intin^[1])^:=id; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_get_no_styles:=intout^[0]; end; end; function fnts_get_style(fnt_dialog: PFNT_DIALOG; id: longint; index: smallint): longint; begin with AES_pb do begin control^[0]:=184; control^[1]:=4; control^[2]:=2; control^[3]:=1; control^[4]:=0; addrin^[0]:=fnt_dialog; intin^[0]:=1; Plongint(@intin^[1])^:=id; intin^[3]:=index; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_get_style:=Plongint(@intout^[0])^; end; end; function fnts_get_name(fnt_dialog: PFNT_DIALOG; id: longint; full_name: Pchar; family_name: Pchar; style_name: Pchar): smallint; begin with AES_pb do begin control^[0]:=184; control^[1]:=3; control^[2]:=1; control^[3]:=4; control^[4]:=0; addrin^[0]:=fnt_dialog; addrin^[1]:=full_name; addrin^[2]:=family_name; addrin^[3]:=style_name; intin^[0]:=2; Plongint(@intin^[1])^:=id; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_get_name:=intout^[0]; end; end; function fnts_get_info(fnt_dialog: PFNT_DIALOG; id: longint; mono: Psmallint; outline: Psmallint): smallint; begin with AES_pb do begin control^[0]:=184; control^[1]:=3; control^[2]:=3; control^[3]:=1; control^[4]:=0; addrin^[0]:=fnt_dialog; intin^[0]:=3; Plongint(@intin^[1])^:=id; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} if mono<>nil then mono^:=intout^[1]; if outline<>nil then outline^:=intout^[2]; fnts_get_info:=intout^[0]; end; end; function fnts_add(fnt_dialog: PFNT_DIALOG; user_fonts: PFNTS_ITEM): smallint; begin with AES_pb do begin control^[0]:=185; control^[1]:=1; control^[2]:=1; control^[3]:=2; control^[4]:=0; addrin^[0]:=fnt_dialog; addrin^[1]:=user_fonts; intin^[0]:=0; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_add:=intout^[0]; end; end; procedure fnts_remove(fnt_dialog: PFNT_DIALOG); begin with AES_pb do begin control^[0]:=185; control^[1]:=1; control^[2]:=0; control^[3]:=1; control^[4]:=0; addrin^[0]:=fnt_dialog; intin^[0]:=1; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} end; end; function fnts_update(fnt_dialog: PFNT_DIALOG; button_flags: smallint; id, pt, ratio: longint): smallint; begin with AES_pb do begin control^[0]:=185; control^[1]:=8; control^[2]:=0; control^[3]:=1; control^[4]:=0; addrin^[0]:=fnt_dialog; intin^[0]:=2; intin^[1]:=button_flags; Plongint(@intin^[2])^:=id; Plongint(@intin^[4])^:=pt; Plongint(@intin^[6])^:=ratio; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} fnts_update:=intout^[0]; end; end; function fnts_evnt(fnt_dialog: PFNT_DIALOG; events: PEVNT; button, check_boxes: psmallint; id, pt, ratio: Plongint): smallint; begin with AES_pb do begin control^[0]:=186; control^[1]:=0; control^[2]:=9; control^[3]:=2; control^[4]:=0; addrin^[0]:=fnt_dialog; addrin^[1]:=events; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} if button<>nil then button^:=intout^[1]; if check_boxes<>nil then check_boxes^:=intout^[2]; if id<>nil then id^:=Plongint(@intout^[3])^; if pt<>nil then pt^:=Plongint(@intout^[5])^; if ratio<>nil then ratio^:=Plongint(@intout^[7])^; fnts_evnt:=intout^[0]; end; end; function fnts_do(fnt_dialog: PFNT_DIALOG; button_flags: smallint; id_in, pt_in, ratio_in: longint; check_boxes: Psmallint; id, pt, ratio: Plongint): smallint; begin with AES_pb do begin control^[0]:=187; control^[1]:=7; control^[2]:=8; control^[3]:=1; control^[4]:=0; addrin^[0]:=fnt_dialog; intin^[0]:=button_flags; Plongint(@intin^[1])^:=id_in; Plongint(@intin^[3])^:=pt_in; Plongint(@intin^[5])^:=ratio_in; {$IFDEF FPC} _crystal(PAESPB(@AES_pb)); {$ELSE} _crystal(@AES_pb); {$ENDIF} if check_boxes<>nil then check_boxes^:=intout^[1]; if id<>nil then id^:=Plongint(@intout^[2])^; if pt<>nil then pt^:=Plongint(@intout^[4])^; if ratio<>nil then ratio^:=Plongint(@intout^[6])^; fnts_do:=intout^[0]; end; end; end.
unit FileDialogs; {$MODE Delphi} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FileCtrl, Grids, Shlobj, ComCtrls, Files, FileOperations, Misc_utils, GlobalVars, Buttons; type TGetFileOpen = class(TForm) EBFname: TEdit; BNOpen: TButton; BNCancel: TButton; CBFilter: TFilterComboBox; Label1: TLabel; Label2: TLabel; Label4: TLabel; DirList: TListBox; Label3: TLabel; LBContainer: TLabel; LBFileSize: TLabel; OpenDialog: TOpenDialog; BNDirUp: TBitBtn; procedure FormCreate(Sender: TObject); procedure EBFnameChange(Sender: TObject); procedure DirListClick(Sender: TObject); procedure CBFilterChange(Sender: TObject); procedure DirListDblClick(Sender: TObject); procedure BNOpenClick(Sender: TObject); procedure BNDirUpClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DirControl:TMaskedDirectoryControl; Dir:TContainerFile; Fname:String; subDir:String; Procedure SetFilter(const filter:String); Procedure SetFName(const name:String); Procedure SetContainer(const container:String); { Private declarations } public { Public declarations } Property FileName:String read Fname write SetFname; Property Filter:String write SetFilter; Function Execute:boolean; end; TDirPicker=class Private FCaption, FDir:String; Public Property Directory:String read FDir write FDir; Property Caption:String read FCaption write FCaption; Function Execute:boolean; end; var GetFileOpen: TGetFileOpen; implementation {$R *.lfm} Function TDirPicker.Execute:boolean; var Dir:Array[0..255] of char; Bi:TBrowseInfo; ShellFolder:IShellFolder; begin StrCopy(Dir,Pchar(FDir)); With Bi do begin hwndOwner:=Screen.ActiveForm.Handle; pidlRoot:=nil; pszDisplayName:=Dir; lpszTitle:=PChar(FCaption); ulFlags:=BIF_RETURNONLYFSDIRS; lpfn:=nil; lParam:=0; iImage:=0; end; if ShBrowseForFolder(bi)=nil then result:=false else begin FDir:=bi.pszDisplayName; end; end; procedure TGetFileOpen.FormCreate(Sender: TObject); begin ClientWidth:=Label4.Left+DirList.Left+DirList.Width; ClientHeight:=Label4.Top+CBFilter.Top+CBFilter.Height; DirControl:=TMaskedDirectoryControl.CreateFromLB(DirList); OpenDialog.FileName:=''; end; Procedure TGetFileOpen.SetFilter(const filter:String); begin OpenDialog.Filter:=filter; OpenDialog.FilterIndex:=0; CBFilter.Filter:=Filter; end; Procedure TGetFileOpen.SetFname(Const name:String); var path:String; begin if IsInContainer(Name) then begin path:=ExtractPath(Name); If Path[length(Path)]='>' then SetLength(Path,length(path)-1); OpenDialog.FileName:=Path; EBFname.Text:=ExtractName(Name); end else OpenDialog.FileName:=Name; FName:=name; SubDir:=''; end; Procedure TGetFileOpen.SetContainer(Const container:String); begin Caption:='Files inside '+Container; Dir:=OpenContainer(Container); SubDir:=''; DirControl.SetDir(Dir); DirControl.SetMask(CBFilter.Mask); LBContainer.Caption:=Container; end; Function TGetFileOpen.Execute:boolean; begin SubDir:=''; Result:=false; Repeat result:=OpenDialog.Execute; CBFilter.ItemIndex:=OpenDialog.FilterIndex-1; if not result then exit; if IsContainer(OpenDialog.FileName) then begin SetContainer(OpenDialog.FileName); DirList.Sorted:=true; if ShowModal=mrOK then begin if SubDir='' then Fname:=OpenDialog.FileName+'>'+EBFname.Text else Fname:=OpenDialog.FileName+'>'+subdir+'\'+EBFname.Text; DirControl.SetDir(Nil); Dir.Free; SubDir:=''; result:=true; exit; end; Dir.Free; SubDir:=''; DirControl.SetDir(Nil); end else begin FName:=OpenDialog.FileName; exit; end; Until false; end; procedure TGetFileOpen.EBFnameChange(Sender: TObject); var i:Integer; begin i:=DirList.Items.IndexOf(EBFname.Text); if i<>-1 then DirList.ItemIndex:=i; end; procedure TGetFileOpen.DirListClick(Sender: TObject); var TI:TFileInfo; i:Integer; begin i:=DirList.ItemIndex; If i<0 then exit; if DirList.Items[i]='' then; Ti:=TFileInfo(DirList.Items.Objects[i]); if ti<>nil then EBFName.Text:=DirList.Items[i]; if ti=nil then LBFileSize.Caption:='Directory' else LBFileSize.Caption:=IntToStr(ti.size); end; procedure TGetFileOpen.CBFilterChange(Sender: TObject); begin DirControl.SetMask(CBFilter.Mask); end; procedure TGetFileOpen.DirListDblClick(Sender: TObject); begin BNOpen.Click; end; procedure TGetFileOpen.BNOpenClick(Sender: TObject); var ti:TFileInfo; i:integer; dname:string; begin i:=DirList.ItemIndex; Ti:=TFileInfo(DirList.Items.Objects[i]); if ti=nil then begin dName:=DirList.Items[i]; dname:=Copy(dname,2,length(dName)-2); if SubDir='' then SubDir:=dname else SubDir:=Subdir+'\'+dname; Dir.ChDir(subDir); DirControl.SetMask(CBFilter.Mask); exit; end; If Dir.ListFiles.IndexOf(EBFname.Text)=-1 then MsgBox('The file '+EBFname.Text+' is not in the container','Error',mb_ok) else begin ModalResult:=mrOk; Hide; end; begin end; end; procedure TGetFileOpen.BNDirUpClick(Sender: TObject); var ps:Pchar; begin if SubDir='' then exit; ps:=StrRScan(@SubDir[1],'\'); if ps=nil then SubDir:='' else begin SubDir:=Copy(Subdir,1,ps-@Subdir[1]); end; Dir.ChDir(SubDir); DirControl.SetMask(CBFilter.Mask); end; procedure TGetFileOpen.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_BACK then BNDirUp.CLick; end; end.
unit ComponentPalette; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, ExtCtrls, DCPalette, dcpalet, DCGen, LMDCustomComponent, LMDBaseController, LMDCustomContainer, LMDCustomImageList, LMDImageList, LMDControl, LMDBaseControl, LMDBaseGraphicControl, LMDBaseLabel, LMDCustomGlyphLabel, LMDGlyphLabel, LMDGraph, LrCollapsable; type TComponentPaletteForm = class(TForm) PaletteScroll: TScrollBox; DCCompPalette1: TDCCompPalette; LMDImageList1: TLMDImageList; LrCollapsable1: TLrCollapsable; LMDGlyphLabel3: TLMDGlyphLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure PaletteLabelStartDrag(Sender: TObject; var DragObject: TDragObject); private { Private declarations } FSelectedLabel: TControl; procedure PaletteLabelClick(Sender: TObject); procedure PaletteLabelMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaletteLabelMouseEnter(Sender: TObject); procedure PaletteLabelMouseExit(Sender: TObject); procedure SetSelectedLabel(const Value: TControl); protected procedure CreateWnd; override; public { Public declarations } procedure BuildPalette; procedure GetAddClass(Sender: TObject; var ioClass: String); property SelectedLabel: TControl read FSelectedLabel write SetSelectedLabel; end; var ComponentPaletteForm: TComponentPaletteForm; implementation uses {Math,} LrUtils, ClassInfo, DesignManager; {$R *.dfm} type TAddClassDragObject = class(TDragObject) private FAddClass: string; public function GetName: string; override; procedure Finished(Target: TObject; X, Y: Integer; Accepted: Boolean); override; property AddClass: string read FAddClass write FAddClass; end; { TAddClassDragObject } procedure TAddClassDragObject.Finished(Target: TObject; X, Y: Integer; Accepted: Boolean); begin inherited; Free; end; function TAddClassDragObject.GetName: string; begin Result := ClassName; end; { TComponentPaletteForm } procedure TComponentPaletteForm.FormCreate(Sender: TObject); begin BuildPalette; Width := Width + 1; DesignMgr.OnGetAddClass := GetAddClass; end; procedure TComponentPaletteForm.BuildPalette; var i, j: Integer; l: TLMDGlyphLabel; r: TLrCollapsable; procedure CreateGroup(const inCaption: string); begin r := TLrCollapsable.Create(Self); r.Caption := inCaption; r.AutoSize := true; r.Parent := PaletteScroll; r.Color := $F9F9F9; r.HeaderColor := $E1E1E1; r.ParentFont := true; r.Font.Style := [ fsBold ]; //r.Top := 9999; r.Align := alTop; SetBounds(0, 0, 120, 120); r.Visible := true; end; function AddImage(const inClass: TClass): Integer; procedure Matte(var inBitmap: TBitmap; inColor: TColor); var b: TBitmap; begin b := TBitmap.Create; try b.Width := inBitmap.Width; b.Height := inBitmap.Height; b.Canvas.Brush.Color := inColor; b.Canvas.FillRect(Rect(0, 0, inBitmap.Width, inBitmap.Height)); b.Canvas.Draw(0, 0, inBitmap); finally inBitmap.Free; inBitmap := b; end; end; procedure Stretch(var inBitmap: TBitmap; inW, inH: Integer); var b: TBitmap; begin b := TBitmap.Create; try b.Width := inW; b.Height := inH; b.Canvas.StretchDraw(Rect(0, 0, inW - 1, inH - 1), inBitmap); finally inBitmap.Free; inBitmap := b; end; end; var b: TBitmap; begin b := TBitmap.Create; try LoadBitmapForClass(b, inClass); b.Transparent := true; if (b.Width <> 16) then begin Matte(b, clWhite); Stretch(b, 16, 16); end; Result := LMDImageList1.Items[0].Add(b, nil); finally b.Free; end; end; procedure CreateLabel(inButton: TDCPaletteButton); begin l := TLMDGlyphLabel.Create(Self); // l.Caption := ComponentRegistry.DisplayName[inButton.ButtonName]; //l.Caption := inButton.ButtonName; l.Hint := inButton.ButtonName; // l.Align := alTop; l.Cursor := crHandPoint; l.Bevel.StandardStyle := lsSingle; l.Alignment.Alignment := agCenterLeft; l.Color := clLime; //l.DragMode := dmAutomatic; // l.OnMouseEnter := PaletteLabelMouseEnter; l.OnMouseExit := PaletteLabelMouseExit; l.OnClick := PaletteLabelClick; l.OnStartDrag := PaletteLabelStartDrag; //l.OnEndDrag := PaletteLabelEndDrag; l.OnMouseDown := PaletteLabelMouseDown; // l.ImageList := LMDImageList1; l.ListIndex := 0; //l.ImageIndex := inButton.ImageIndex; l.ImageIndex := AddImage(TDCCompButton(inButton).ComponentClass); // l.AutoSize := false; //l.Height := l.Height + 2; // l.Parent := r; l.Font.Style := []; //l.Parent := r.ContentPanel; end; begin for i := 0 to Pred(DCCompPalette1.PageCount) do begin CreateGroup(DCCompPalette1.Tabs[i]); with DCCompPalette1.ButtonTabs[i] do begin //r.Height := ButtonCount * 16 + 20; for j := 0 to Pred(ButtonCount) do CreateLabel(Buttons[j]); //r.Height := 0; end; end; end; procedure TComponentPaletteForm.CreateWnd; begin inherited; // if PaletteScroll <> nil then // PaletteScroll.Realign; end; procedure TComponentPaletteForm.FormShow(Sender: TObject); begin with PaletteScroll do Width := Width + 1; end; procedure TComponentPaletteForm.SetSelectedLabel(const Value: TControl); begin if (SelectedLabel <> nil) then TLMDGlyphLabel(SelectedLabel).Font.Style := [ ]; FSelectedLabel := Value; if (SelectedLabel <> nil) then TLMDGlyphLabel(Value).Font.style := [ fsBold ]; end; procedure TComponentPaletteForm.PaletteLabelMouseEnter(Sender: TObject); begin with TLMDGlyphLabel(Sender) do Font.Style := Font.Style + [ fsUnderline ]; end; procedure TComponentPaletteForm.PaletteLabelMouseExit(Sender: TObject); begin with TLMDGlyphLabel(Sender) do Font.Style := Font.Style - [ fsUnderline ]; end; procedure TComponentPaletteForm.PaletteLabelMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin //if Button = mbLeft then // TControl(Sender).BeginDrag(False); end; procedure TComponentPaletteForm.PaletteLabelClick(Sender: TObject); begin SelectedLabel := TControl(Sender); end; procedure TComponentPaletteForm.GetAddClass(Sender: TObject; var ioClass: String); begin if SelectedLabel <> nil then begin ioClass := SelectedLabel.Hint; SelectedLabel := nil; end; end; procedure TComponentPaletteForm.PaletteLabelStartDrag(Sender: TObject; var DragObject: TDragObject); begin DragObject := TAddClassDragObject.Create; TAddClassDragObject(DragObject).AddClass := TLMDGlyphLabel(Sender).Hint; end; end.
namespace Steema.TeeChart.Samples.Oxygene; interface uses System.Windows.Forms, Steema.TeeChart, Steema.TeeChart.Styles; type MainForm = class(System.Windows.Forms.Form) private Chart1 : TChart; public constructor; class method Main; end; implementation constructor MainForm; begin Width:=400; Height:=250; FormBorderStyle := FormBorderStyle.FixedDialog; MaximizeBox := false; Chart1:= new TChart; Chart1.Parent := Self; Chart1.SetBounds( 10, 50, Width - 30, Height - 80 ); Chart1.Series.Add( new Bar ).FillSampleValues; Chart1[0].ColorEach:=True; Text := 'TeeChart.Net Lite, WinForms Oxygene Application'; end; class method MainForm.Main; var lForm: System.Windows.Forms.Form; begin Application.EnableVisualStyles(); try lForm := new MainForm(); Application.Run(lForm); except on E: Exception do begin MessageBox.Show(E.Message); end; end; end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps; type TFrmMain = class(TForm) Map: TTMSFNCMaps; procedure MapMapInitialized(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses IOUtils, Flix.Utils.Maps; procedure TFrmMain.FormCreate(Sender: TObject); var LKeys: TServiceAPIKeys; begin LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) ); try Map.APIKey := LKeys.GetKey( msGoogleMaps ); finally LKeys.Free; end; end; procedure TFrmMain.MapMapInitialized(Sender: TObject); var LFlight, LDUS: TTMSFNCMapsCoordinateRec; LBounds: TTMSFNCMapsBoundsRec; LArr: TTMSFNCMapsCoordinateRecArray; LPoly : TTMSFNCMapsPolyline; begin // coordinate for DUS airport LDUS := CreateCoordinate( 51.289498, 6.769091 ); // calculate coordinate 170 km northwest LFlight := CalculateCoordinate(LDUS, 315, 170000 ); // add marker for airport Map.AddMarker(LDUS); // add marker for destination Map.AddMarker(LFlight); // create bounds for zoom LBounds := CreateBounds( LDUS, LFlight ); Map.ZoomToBounds( LBounds ); // add coordinates to array SetLength( LArr, 2 ); LArr[0] := LDUS; LArr[1] := LFlight; // add line (see geometric shapes) LPoly := Map.AddPolyline( LArr ); LPoly.StrokeColor := clBlue; LPoly.StrokeWidth := 3; LPoly.StrokeOpacity := 0.3; end; end.
unit eUsusario.Controller.Factory.Interfaces; interface uses eUsusario.View.Conexao.Interfaces; type iFactoryQuery = interface ['{68BB9C5F-2C8B-410B-9275-C860DB1ACBBE}'] function Query(Connection : iConexao) : iQuery; end; implementation end.
unit BaseSet; interface uses BasicDataTypes; type TGetValueFunction = function (var _Value : integer): boolean of object; PPointerItem = ^TPointerItem; TPointerItem = record Data: pointer; Next: PPointerItem; end; CBaseSet = class private Start,Last,Active : PPointerItem; // Constructors and Destructors procedure Initialize; // Add procedure AddBlindly(_Data : pointer); protected // Sets function SetData(const _Data: Pointer):Pointer; virtual; // Misc function CompareData(const _Data1,_Data2: Pointer):boolean; virtual; procedure DisposeData(var _Data:Pointer); virtual; public // Constructors and Destructors constructor Create; destructor Destroy; override; procedure Reset; // Add function Add (_Data : pointer): boolean; // Delete procedure Delete; function Remove(_Data: Pointer): Boolean; procedure Clear; // Gets function GetData (var _Data : pointer): boolean; function IsDataInList (_Data : pointer): boolean; function isEmpty: boolean; // Copies procedure Assign(const _List: CBaseSet); virtual; // Misc procedure GoToNextElement; procedure GoToFirstElement; end; implementation constructor CBaseSet.Create; begin Initialize; end; destructor CBaseSet.Destroy; begin Clear; inherited Destroy; end; procedure CBaseSet.Initialize; begin Start := nil; Last := nil; Active := nil; end; procedure CBaseSet.Reset; begin Clear; Initialize; end; // Add procedure CBaseSet.AddBlindly (_Data : pointer); var NewPosition : PPointerItem; begin // Now, we add the value. New(NewPosition); NewPosition^.Data := SetData(_Data); NewPosition^.Next := nil; if Start <> nil then begin Last^.Next := NewPosition; end else begin Start := NewPosition; Active := Start; end; Last := NewPosition; end; function CBaseSet.Add (_Data : pointer): boolean; begin // First, we check it if we should add this value or not. if not IsDataInList(_Data) then begin // Now, we add the value. AddBlindly(_Data); Result := true; end else begin Result := false; end; end; // Delete procedure CBaseSet.Delete; var Previous : PPointerItem; begin if Active <> nil then begin Previous := Start; if Active = Start then begin Start := Start^.Next; end else begin while Previous^.Next <> Active do begin Previous := Previous^.Next; end; Previous^.Next := Active^.Next; if Active = Last then begin Last := Previous; end; end; Dispose(Active); end; end; function CBaseSet.Remove(_Data: Pointer): Boolean; var Garbage,NextActive : PPointerItem; Found: boolean; begin Garbage := Start; Found := false; Result := false; while not Found do begin if Garbage <> nil then begin if CompareData(Garbage^.Data,_Data) then begin Found := true; if Active <> Garbage then begin NextActive := Active; Active := Garbage; end else begin NextActive := Start; end; Delete; Active := NextActive; Result := true; end else Garbage := Garbage^.Next; end else exit; end; end; procedure CBaseSet.Clear; var Garbage : PPointerItem; begin Active := Start; while Active <> nil do begin Garbage := Active; Active := Active^.Next; DisposeData(Pointer(Garbage)); end; Start := nil; Last := nil; end; procedure CBaseSet.DisposeData(var _Data:Pointer); begin // Do nothing end; // Sets function CBaseSet.SetData(const _Data: Pointer):Pointer; begin Result := _Data; end; // Gets function CBaseSet.GetData (var _Data : pointer): boolean; begin if Active <> nil then begin _Data := SetData(Active^.Data); Result := true; end else begin Result := false; end; end; function CBaseSet.isEmpty: boolean; begin Result := Start = nil; end; function CBaseSet.IsDataInList (_Data : pointer): boolean; var Position : PPointerItem; begin // First, we check it if we should add this value or not. Position := Start; Result := false; while (Position <> nil) and (not Result) do begin if not CompareData(Position^.Data,_Data) then begin Position := Position^.Next; end else begin Result := true; end; end; end; // Copies procedure CBaseSet.Assign(const _List: CBaseSet); var Position : PPointerItem; begin Reset; Position := _List.Start; while Position <> nil do begin AddBlindly(Position^.Data); if _List.Active = Position then begin Active := Last; end; Position := Position^.Next; end; end; // Misc procedure CBaseSet.GoToNextElement; begin if Active <> nil then begin Active := Active^.Next; end end; procedure CBaseSet.GoToFirstElement; begin Active := Start; end; function CBaseSet.CompareData(const _Data1,_Data2: Pointer):boolean; begin Result := _Data1 = _Data2; end; end.
{ @abstract Implements @link(TNtListViewTranslator) translator extension class that translates TListView. To enable runtime language switch of list views just add this unit into your project or add unit into any uses block. @longCode(# implementation uses NtListViewTranslator; #) See @italic(Samples\Delphi\VCL\LanguageSwitch) sample to see how to use the unit. } unit NtListViewTranslator; {$I NtVer.inc} interface uses SysUtils, Classes, NtBaseTranslator; type { @abstract Translator extension class that translates TListView component. } TNtListViewTranslator = class(TNtTranslatorExtension) public { @seealso(TNtTranslatorExtension.CanTranslate) } function CanTranslate(obj: TObject): Boolean; override; { @seealso(TNtTranslatorExtension.Translate) } procedure Translate( component: TComponent; obj: TObject; const name: String; value: Variant; index: Integer); override; class procedure ForceUse; end; implementation uses ComCtrls, NtBase; type TItemInfo = packed record ImageIndex: Integer; StateIndex: Integer; OverlayIndex: Integer; SubItemCount: Integer; Data: Pointer; end; TItemInfo2 = packed record ImageIndex: Integer; StateIndex: Integer; OverlayIndex: Integer; SubItemCount: Integer; GroupID: Integer; Data: Pointer; end; TItemDataInfo2x86 = record ImageIndex: Integer; StateIndex: Integer; OverlayIndex: Integer; SubItemCount: Integer; GroupID: Integer; Data: Integer; // must be Integer end; TItemDataInfo2x64 = record ImageIndex: Integer; StateIndex: Integer; OverlayIndex: Integer; SubItemCount: Integer; GroupID: Integer; Data: Int64; // must be Int64 end; function TNtListViewTranslator.CanTranslate(obj: TObject): Boolean; begin Result := obj is TListItems; end; procedure TNtListViewTranslator.Translate( component: TComponent; obj: TObject; const name: String; value: Variant; index: Integer); const VERSION_32_2 = $03; // 32-bit struct size version 2 VERSION_32_3 = $05; // 32-bit struct size version 3 VERSION_64_3 = $06; // 64-bit struct size version 3 var stream: TNtStream; items: TListItems; procedure ProcessOld; var i, j, count: Integer; item: TListItem; info: TItemInfo; begin stream.ReadInteger; count := stream.ReadInteger; for i := 0 to count - 1 do begin item := items[i]; stream.Read(info, Sizeof(info)); item.ImageIndex := info.ImageIndex; item.StateIndex := info.StateIndex; item.OverlayIndex := info.OverlayIndex; item.Data := info.Data; {$IFDEF DELPHIXE} item.Caption := TNtConvert.BytesToUnicode(stream.ReadShortString); {$ELSE} item.Caption := TNtConvert.AnsiToUnicode(stream.ReadShortString); {$ENDIF} for j := 0 to info.SubItemCount - 1 do {$IFDEF DELPHIXE} item.SubItems[j] := TNtConvert.BytesToUnicode(stream.ReadShortString); {$ELSE} item.SubItems[j] := TNtConvert.AnsiToUnicode(stream.ReadShortString); {$ENDIF} end; end; {$IFDEF DELPHI2006} procedure ProcessNew; var item: TListItem; procedure ProcessItemInfo; var i: Integer; info: TItemInfo; begin stream.Read(info, Sizeof(info)); item.ImageIndex := info.ImageIndex; item.StateIndex := info.StateIndex; item.OverlayIndex := info.OverlayIndex; item.Data := info.Data; item.Caption := stream.ReadShortUnicodeString; for i := 0 to info.SubItemCount - 1 do item.SubItems[i] := stream.ReadShortUnicodeString; end; {$IFDEF UNICODE} procedure ProcessItemInfo2(version: Byte); var i: Integer; info: {$IFDEF DELPHIXE2}TItemDataInfo2x86{$ELSE}TItemInfo2{$ENDIF}; begin stream.Read(info, Sizeof(info)); item.ImageIndex := info.ImageIndex; item.StateIndex := info.StateIndex; item.OverlayIndex := info.OverlayIndex; item.Data := Pointer(info.Data); item.Caption := stream.ReadShortUnicodeString; for i := 0 to info.SubItemCount - 1 do begin item.SubItems[i] := stream.ReadShortUnicodeString; if version >= VERSION_32_3 then stream.ReadPointer; end; end; {$ENDIF} {$IFDEF DELPHIXE2} procedure ProcessItemInfo264(version: Byte); var i: Integer; info: TItemDataInfo2x64; begin stream.Read(info, Sizeof(info)); item.ImageIndex := info.ImageIndex; item.StateIndex := info.StateIndex; item.OverlayIndex := info.OverlayIndex; item.Data := Pointer(info.Data); item.Caption := stream.ReadShortUnicodeString; for i := 0 to info.SubItemCount - 1 do begin item.SubItems[i] := stream.ReadShortUnicodeString; if version >= VERSION_32_3 then stream.ReadPointer; end; end; {$ENDIF} var i, count: Integer; {$IFDEF UNICODE} version: Byte; {$ENDIF} begin {$IFDEF UNICODE}version := {$ENDIF}stream.ReadByte; stream.ReadInteger; count := stream.ReadInteger; for i := 0 to count - 1 do begin item := items[i]; {$IFDEF UNICODE} {$IFDEF DELPHIXE2} if version >= VERSION_64_3 then ProcessItemInfo264(version) else {$ENDIF} if version >= VERSION_32_2 then ProcessItemInfo2(version) else {$ENDIF} ProcessItemInfo; end; end; {$ENDIF} begin items := obj as TListItems; {$IFDEF DELPHIXE} stream := TNtStream.Create(TBytes(value)); {$ELSE} stream := TNtStream.Create(AnsiString(value)); {$ENDIF} try if name = 'Items.Data' then ProcessOld {$IFDEF DELPHI2006} else ProcessNew {$ENDIF} finally stream.Free; end; end; class procedure TNtListViewTranslator.ForceUse; begin end; initialization NtTranslatorExtensions.Register(TNtListViewTranslator); end.
unit HVA; // HVA Unit By Stucuk // Written using the tibsun-hva.doc by The Profound Eol {$INCLUDE Global_Conditionals.inc} interface uses dialogs,sysutils,Voxel_Engine,math3d, OpenGL; type THVA_Main_Header = packed record FilePath: array[1..16] of Char; (* ASCIIZ string *) N_Frames, (* Number of animation frames *) N_Sections : Longword; (* Number of voxel sections described *) end; TSectionName = array[1..16] of Char; (* ASCIIZ string - name of section *) TTransformMatrix = packed array[1..3,1..4] of Single; THVAData = packed record SectionName : TSectionName; TransformMatrixs : array of TTransformMatrix; end; THVA = Record Header : THVA_Main_Header; Data : array of THVAData; Data_no : integer; end; var HVAFile : THVA; HVASection : integer = 0; HVAFrame : integer = 0; {Transformations : TTransformations; Matrix : TMatrix; matrix2: array[0..15] of GLfloat;} function LoadHVA(Filename : string): boolean; Function ApplyMatrix(V : TVector3f) : TVector3f; overload; Function ApplyMatrix(VoxelScale : TVector3f; Section, Frames : Integer) : TVector3f; overload; Procedure FloodMatrix; Function GetTMValue(Row,Col : integer) : single; overload; Function GetTMValue(Row,Col,Section : integer) : single; overload; Procedure ClearHVA; function GetIdentityTM : TTransformMatrix; implementation uses FormMain, Voxel; procedure ClearHVA; var Section : integer; begin if High(HVAFile.Data) >= 0 then begin for Section := Low(HVAFile.Data) to High(HVAFile.Data) do begin SetLength(HVAFile.Data[Section].TransformMatrixs,0); end; end; SetLength(HVAFile.Data,1); HVAFrame := 0; HVASection := 0; HVAFile.Header.N_Frames := 1; HVAFile.Header.N_Sections := 1; SetLength(HVAFile.Data[0].TransformMatrixs,1); HVAFile.Data[0].TransformMatrixs[0] := GetIdentityTM; HVAFile.Data_no := 1; end; function LoadHVA(Filename : string): boolean; var f : file; x,y : integer; begin {$ifdef DEBUG_FILE} FrmMain.DebugFile.Add('HVA: LoadHVA'); {$endif} Result := false; try ClearHVA; AssignFile(F,Filename); // Open file FileMode := fmOpenRead; // we only load HVA file [VK] Reset(F,1); // Goto first byte? BlockRead(F,HVAFile.Header,Sizeof(THVA_Main_Header)); // Read Header HVAFile.Data_no := HVAFile.Header.N_Sections; SetLength(HVAFile.Data,HVAFile.Data_no); For x := Low(HVAFile.Data) to High(HVAFile.Data) do begin BlockRead(F,HVAFile.Data[x].SectionName,Sizeof(TSectionName)); SetLength(HVAFile.Data[x].TransformMatrixs,HVAFile.Header.N_Frames); end; For y := 0 to HVAFile.Header.N_Frames-1 do begin For x := Low(HVAFile.Data) to High(HVAFile.Data) do begin BlockRead(F,HVAFile.Data[x].TransformMatrixs[y],Sizeof(TTransformMatrix)); end; end; if HVAFile.Header.N_Frames = 0 then begin HVAFile.Header.N_Frames := 1; For x := Low(HVAFile.Data) to High(HVAFile.Data) do begin SetLength(HVAFile.Data[x].TransformMatrixs,1); HVAFile.Data[x].TransformMatrixs[0] := GetIdentityTM; end; end; CloseFile(f); except on E : EInOutError do // VK 1.36 U MessageDlg('Error: ' + E.Message + Char($0A) + Filename, mtError, [mbOK], 0); end; Result := true; end; function GetIdentityTM : TTransformMatrix; begin Result[1,1] := 1; Result[1,2] := 0; Result[1,3] := 0; Result[1,4] := 0; Result[2,1] := 0; Result[2,2] := 1; Result[2,3] := 0; Result[2,4] := 0; Result[3,1] := 0; Result[3,2] := 0; Result[3,3] := 1; Result[3,4] := 0; end; Function GetTMValue(Row,Col : integer) : single; begin Result := HVAFile.Data[HVASection].TransformMatrixs[HVAFrame][Row][Col]; end; Function GetTMValue(Row,Col,Section : integer) : single; begin Result := HVAFile.Data[Section].TransformMatrixs[HVAFrame][Row][Col]; end; Function ApplyMatrixVXL(V : TVector3f) : TVector3f; var T : TVector3f; begin T := V; with ActiveSection.Tailer do begin Result.X := ( T.x * Transform[1,1] + T.y * Transform[1,2] + T.z * Transform[1,3] + Transform[1,4]); Result.Y := ( T.x * Transform[2,1] + T.y * Transform[2,2] + T.z * Transform[2,3] + Transform[2,4]); Result.Z := ( T.x * Transform[3,1] + T.y * Transform[3,2] + T.z * Transform[3,3] + Transform[3,4]); end; end; // Copied from OS: Voxel Viewer. Function ApplyMatrix(VoxelScale: TVector3f; Section, Frames : Integer) : TVector3f; var Matrix : TGLMatrixf4; SectionDet : single; begin if Section = -1 then begin Exit; end; SectionDet := VoxelFile.Section[Section].Tailer.Det; if HVAFile.Header.N_Sections > 0 then begin Matrix[0,0] := GetTMValue(1,1,Section); Matrix[0,1] := GetTMValue(2,1,Section); Matrix[0,2] := GetTMValue(3,1,Section); Matrix[0,3] := 0; Matrix[1,0] := GetTMValue(1,2,Section); Matrix[1,1] := GetTMValue(2,2,Section); Matrix[1,2] := GetTMValue(3,2,Section); Matrix[1,3] := 0; Matrix[2,0] := GetTMValue(1,3,Section); Matrix[2,1] := GetTMValue(2,3,Section); Matrix[2,2] := GetTMValue(3,3,Section); Matrix[2,3] := 0; Matrix[3,0] := GetTMValue(1,4,Section) * VoxelScale.X * SectionDet; Matrix[3,1] := GetTMValue(2,4,Section) * VoxelScale.Y * SectionDet; Matrix[3,2] := GetTMValue(3,4,Section) * VoxelScale.Z * SectionDet; Matrix[3,3] := 1; end else begin Matrix[0,0] := 1; Matrix[0,1] := 0; Matrix[0,2] := 0; Matrix[0,3] := 0; Matrix[1,0] := 0; Matrix[1,1] := 1; Matrix[1,2] := 0; Matrix[1,3] := 0; Matrix[2,0] := 0; Matrix[2,1] := 0; Matrix[2,2] := 1; Matrix[2,3] := 0; Matrix[3,0] := SectionDet * VoxelScale.X; Matrix[3,1] := SectionDet * VoxelScale.Y; Matrix[3,2] := SectionDet * VoxelScale.Z; Matrix[3,3] := 1; end; glMultMatrixf(@Matrix[0,0]); end; Function Transform : TTransformMatrix; var tmp : TTransformMatrix; i,j : integer; begin with ActiveSection.Tailer do begin for i:=1 to 3 do begin tmp[i][3] := 0; for j:=1 to 4 do begin tmp[i][j] := GetTMValue(i,1)*Transform[1][j] + GetTMValue(i,2)*Transform[2][j] + GetTMValue(i,3)*Transform[3][j]; end; end; end; Result := tmp; end; Function Transform2 : TTransformMatrix; var tmp : TTransformMatrix; i,j : integer; begin with ActiveSection.Tailer do begin for i:=1 to 3 do begin tmp[i][3] := 0; for j:=1 to 4 do begin tmp[i][j] := Transform[i][1]*GetTMValue(1,j)+ Transform[i][2]*GetTMValue(2,j)+ Transform[i][3]*GetTMValue(3,j); end; tmp[i][3] := tmp[i][3] + Transform[i][3]; end; end; Result := tmp; end; Function Transform3 : TTransformMatrix; var tmp : TTransformMatrix; i,j : integer; begin with ActiveSection.Tailer do begin for i:=1 to 3 do begin for j:=1 to 4 do begin tmp[i][j] := {GetTMValue(i,j) +} Transform[i][j]; end; end; end; Result := tmp; end; Function ApplyMatrix(V : TVector3f) : TVector3f; var T,TT : TVector3f; TempT : TTransformMatrix; begin TempT := Transform3; T := V;//ApplyMatrixVXL(V); TT.X := TempT[1][4]; TT.Y := TempT[2][4]; TT.Z := TempT[3][4]; //Normalize(TT); Result.X := ( T.x * TempT[1][1] + T.y * TempT[1][2] + T.z * TempT[1][3] + (TT.X {TempT[1][4]}{*Transform[1,4]})); Result.Y := ( T.x * TempT[2][1] + T.y * TempT[2][2] + T.z * TempT[2][3] + (TT.Y {TempT[2][4]}{*Transform[2,4]})); Result.Z := ( T.x * TempT[3][1] + T.y * TempT[3][2] + T.z * TempT[3][3] + (TT.Z {TempT[3][4]}{*Transform[3,4]})); {t.x := GetTMValue(1,4); t.y := GetTMValue(2,4); t.z := GetTMValue(3,4); } //Normalize(T); //Result := AddVector(Result,T); {Result.X := Result.X / TempT[1][1]; Result.Y := Result.Y / TempT[2][2]; Result.Z := Result.Z / TempT[3][3]; } //Result := T;//ApplyMatrixVXL(T); end; Procedure FloodMatrix; var x,y : integer; begin for x := 1 to 3 do for y := 1 to 4 do HVAFile.Data[HVASection].TransformMatrixs[HVAFrame][x][y] := 0; HVAFile.Data[HVASection].TransformMatrixs[HVAFrame][1][1] := 1; HVAFile.Data[HVASection].TransformMatrixs[HVAFrame][2][2] := 1; HVAFile.Data[HVASection].TransformMatrixs[HVAFrame][3][3] := 1; end; end.
unit MD3Helper; {$DEFINE MD3Helper_ZeroDivide1} interface uses SysUtils, Classes, Jpeg, cene Q3MD3, GLFileMD3, GLObjects, GLVectorFileObjects, GLScene, GLTexture, GLVectorGeometry,GLMaterial; type TGLMD3Actor = class private LegsTags, TorsoTags, WeaponTags: TMD3TagList; FCharacterModel, FWeaponModel, FName, FAnimation: string; FAnimationMode: TGLActorAnimationMode; FAlphaLevel: Single; FTag: integer; procedure LoadSkin(SkinFilePath, SkinShortName: string); procedure SetCharacterModel(AValue: string); procedure SetWeaponModel(AValue: string); procedure SetAnimationMode(AValue: TGLActorAnimationMode); procedure SetAlphaLevel(AValue: Single); procedure SetTag(AValue: integer); procedure SetName(AValue: string); procedure SetAnimation(AValue: string); public Legs, Head, Torso, Weapon: TGLActor; MaterialLibrary: TGLMaterialLibrary; HeadRot:double; constructor Create(AOwner: TGLBaseSceneObject); function StartFrame: integer; function CurrentFrame: integer; function EndFrame: integer; procedure Progress(deltaTime: Single); property CharacterModel: string read FCharacterModel write SetCharacterModel; property WeaponModel: string read FWeaponModel write SetWeaponModel; property AnimationMode: TGLActorAnimationMode read FAnimationMode write SetAnimationMode; property AlphaLevel: Single read FAlphaLevel write SetAlphaLevel; property Animation: string read FAnimation write SetAnimation; property Tag: integer read FTag write SetTag; property Name: string read FName write SetName; destructor Destroy; override; end; implementation uses Main; function MD3Random(ARange: integer): integer; begin Result := Random(ARange); if Result = 0 then Result := 1; end; function GetRnd (rn:Integer):String; var t:integer; begin t:=Random(rn); if t=0 then Result:='' else Result:=InTToStr(t); end; {$IFNDEF MD3Helper_ZeroDivide} procedure SwitchToAnimation(AObject: TGLActor; AAnimationName: string; ASmooth: boolean = false); begin if AObject.CurrentAnimation <> AAnimationName then AObject.SwitchToAnimation(AAnimationName, ASmooth); end; function LoadModel(AActor: TGLActor; AFileName: string): boolean; begin Result := false; if not FileExists(AFileName) then Exit; AActor.LoadFromFile(AFileName); Result := true; end; function LoadTexture(AMaterial: TGLMaterial; AFileName: string): boolean; begin Result := false; if not FileExists(AFileName) then Exit; AMaterial.Texture.Image.LoadFromFile(AFileName); Result := true; end; {$ENDIF} function InterpolateMatrix(m1, m2: TMatrix; delta: single): TMatrix; var i, j: integer; begin for j := 0 to 3 do for i := 0 to 3 do Result.V[i].V[j] := m1.V[i].V[j] + (m2.V[i].V[j] - m1.V[i].V[j]) * delta; end; constructor TGLMD3Actor.Create(AOwner: TGLBaseSceneObject); begin inherited Create; HeadRot:=0; MaterialLibrary := TGLMaterialLibrary.Create(nil); Legs := TGLActor.CreateAsChild(AOwner); Torso := TGLActor.CreateAsChild(Legs); Head := TGLActor.CreateAsChild(Torso); Weapon := TGLActor.CreateAsChild(Torso); Legs.Direction.Assign(AOwner.Direction); Legs.Up.Assign(AOwner.Up); Torso.Direction.Assign(AOwner.Direction); Torso.Up.Assign(AOwner.Up); Head.Direction.Assign(AOwner.Direction); Head.Up.Assign(AOwner.Up); Weapon.Direction.Assign(AOwner.Direction); Weapon.Up.Assign(AOwner.Up); Weapon.Material.Texture.Disabled := false; LegsTags := TMD3TagList.Create; TorsoTags := TMD3TagList.Create; WeaponTags := TMD3TagList.Create; Legs.MaterialLibrary := MaterialLibrary; Torso.MaterialLibrary := MaterialLibrary; Head.MaterialLibrary := MaterialLibrary; Legs.AnimationMode := aamLoop; Torso.AnimationMode := aamLoop; Legs.TagObject := AOwner; Torso.TagObject := AOwner; Head.TagObject := AOwner; Weapon.TagObject := AOwner; FAlphaLevel := 1; end; function TGLMD3Actor.StartFrame: integer; begin Result := 0; if Animation = 'stand' then Result := Legs.StartFrame; if Animation = 'crstnd' then Result := Legs.StartFrame; if Animation = 'attack' then Result := Torso.StartFrame; if Animation = 'attack2' then Result := Torso.StartFrame; if Animation = 'walk' then Result := Legs.StartFrame; if Animation = 'run' then Result := Legs.StartFrame; if Animation = 'pain' then Result := Torso.StartFrame; if Animation = 'death' then Result := Legs.StartFrame; end; function TGLMD3Actor.CurrentFrame: integer; begin Result := 0; if Animation = 'stand' then Result := Legs.CurrentFrame; if Animation = 'crstnd' then Result := Legs.CurrentFrame; if Animation = 'attack' then Result := Torso.CurrentFrame; if Animation = 'attack2' then Result := Torso.CurrentFrame; if Animation = 'walk' then Result := Legs.CurrentFrame; if Animation = 'run' then Result := Legs.CurrentFrame; if Animation = 'pain' then Result := Torso.CurrentFrame; if Animation = 'death' then Result := Legs.CurrentFrame; end; function TGLMD3Actor.EndFrame: integer; begin Result := 0; if Animation = 'stand' then Result := Legs.EndFrame; if Animation = 'crstnd' then Result := Legs.EndFrame; if Animation = 'attack' then Result := Torso.EndFrame; if Animation = 'attack2' then Result := Torso.EndFrame; if Animation = 'walk' then Result := Legs.EndFrame; if Animation = 'run' then Result := Legs.EndFrame; if Animation = 'pain' then Result := Torso.EndFrame; if Animation = 'death' then Result := Legs.EndFrame; end; procedure TGLMD3Actor.Progress(deltaTime: Single); begin Torso.Matrix := InterpolateMatrix(LegsTags.GetTransform('tag_torso', Legs.CurrentFrame), LegsTags.GetTransform('tag_torso', Legs.NextFrameIndex), Legs.CurrentFrameDelta); Head.Matrix := InterpolateMatrix(TorsoTags.GetTransform('tag_head', Torso.CurrentFrame), TorsoTags.GetTransform('tag_head', Torso.NextFrameIndex), Torso.CurrentFrameDelta); Head.Roll(HeadRot); Weapon.Matrix := InterpolateMatrix(TorsoTags.GetTransform('tag_weapon', Torso.CurrentFrame), TorsoTags.GetTransform('tag_weapon', Torso.NextFrameIndex), Torso.CurrentFrameDelta); end; procedure TGLMD3Actor.LoadSkin(SkinFilePath, SkinShortName: string); var Index: integer; MatName, PicFileName: string; stl, stlBuf, stlPics: TStringList; MaterialLibrary: TGLMaterialLibrary; procedure FetchStlBuf(Prefix: string); var FileName: string; begin FileName := SkinFilePath + Prefix + SkinShortName; if FileExists(FileName) then stl.LoadFromFile(FileName); stlBuf.AddStrings(stl); end; function GetMaterialPicFilename(Material: string): string; var i: integer; begin Material := UpperCase(Material); for i := 0 to stlBuf.Count - 1 do if Pos(Material, UpperCase(stlBuf[i])) = 1 then begin Result := ExtractFileName(StringReplace(stlBuf[i], '/', '\', [rfReplaceAll])); Break; end; end; procedure DoActorMaterials(Actor: TGLActor); var i, n: integer; begin for i := 0 to Actor.MeshObjects.Count - 1 do for n := 0 to Actor.MeshObjects[i].FaceGroups.Count - 1 do begin MatName := Actor.MeshObjects[i].FaceGroups[n].MaterialName; PicFileName := GetMaterialPicFilename(MatName); Index := stlPics.IndexOf(PicFileName); if Index = - 1 then begin stlPics.AddObject(PicFileName, Actor.MeshObjects[i].FaceGroups[n]); PicFileName := SkinFilePath + ChangeFileExt(PicFileName, '.jpg'); if FileExists(PicFileName) then MaterialLibrary.Materials.GetLibMaterialByName(MatName).Material.Texture.Image.LoadFromFile(PicFileName); end else Actor.MeshObjects[i].FaceGroups[n].MaterialName := TGLFaceGroup(stlPics.Objects[Index]).MaterialName; end; end; begin MaterialLibrary := Head.MaterialLibrary; if not Assigned(MaterialLibrary) then Exit; stl := TStringList.Create; stlBuf := TStringList.Create; stlPics := TStringList.Create; SkinFilePath := IncludeTrailingBackslash(SkinFilePath); SkinShortName := ChangeFileExt(SkinShortName, '.skin'); FetchStlBuf('Head_'); FetchStlBuf('Upper_'); FetchStlBuf('Lower_'); DoActorMaterials(Head); DoActorMaterials(Torso); DoActorMaterials(Legs); stl.Free; stlBuf.Free; stlPics.Free; end; procedure TGLMD3Actor.SetCharacterModel(AValue: string); begin if (AValue = FCharacterModel) or (AValue = '') then Exit; MaterialLibrary.Materials.Clear; LoadModel(Legs, Format('.\Models\%s\%s.md3', [AValue, 'lower'])); LoadModel(Torso, Format('.\Models\%s\%s.md3', [AValue, 'upper'])); LoadModel(Head, Format('.\Models\%s\%s.md3', [AValue, 'head'])); LegsTags.LoadFromFile(Format('.\Models\%s\%s.md3', [AValue, 'lower'])); TorsoTags.LoadFromFile(Format('.\Models\%s\%s.md3', [AValue, 'upper'])); LoadSkin(Format('.\Models\%s\', [AValue]), 'default'); LoadQ3Anims(Legs.Animations, Format('.\Models\%s\animation.cfg', [AValue]), 'BOTH'); LoadQ3Anims(Legs.Animations, Format('.\Models\%s\animation.cfg', [AValue]), 'LEGS'); LoadQ3Anims(Torso.Animations, Format('.\Models\%s\animation.cfg', [AValue]), 'BOTH'); LoadQ3Anims(Torso.Animations, Format('.\Models\%s\animation.cfg', [AValue]), 'TORSO'); Legs.SwitchToAnimation('legs_idle'); Torso.SwitchToAnimation('torso_stand'); FCharacterModel := AValue; end; procedure TGLMD3Actor.SetWeaponModel(AValue: string); begin if (AValue = FWeaponModel) or (AValue = '') then Exit; LoadModel(Weapon, Format('.\Models\Weapons\%s\%s.md3', [AValue,AValue])); LoadTexture(Weapon.Material, Format('.\Models\Weapons\%s\%s.jpg', [AValue,AValue])); FWeaponModel := AValue; end; procedure TGLMD3Actor.SetAnimationMode(AValue: TGLActorAnimationMode); begin if AValue = FAnimationMode then Exit; Legs.AnimationMode := AValue; Torso.AnimationMode := AValue; FAnimationMode := AValue; end; procedure TGLMD3Actor.SetAlphaLevel(AValue: Single); var i: integer; begin if AValue = FAlphaLevel then Exit; if AValue = 1 then begin for i := 0 to MaterialLibrary.Materials.Count - 1 do MaterialLibrary.Materials[i].Material.BlendingMode := bmOpaque; Weapon.Material.BlendingMode := bmOpaque; Exit; end else begin for i := 0 to MaterialLibrary.Materials.Count - 1 do MaterialLibrary.Materials[i].Material.BlendingMode := bmTransparency; Weapon.Material.BlendingMode := bmTransparency; end; for i := 0 to MaterialLibrary.Materials.Count - 1 do MaterialLibrary.Materials[i].Material.FrontProperties.Diffuse.Alpha := AValue; Weapon.Material.FrontProperties.Diffuse.Alpha := AValue; FAlphaLevel := AValue; end; procedure TGLMD3Actor.SetTag(AValue: integer); begin if AValue = FTag then Exit; Head.Tag := AValue; Torso.Tag := AValue; Legs.Tag := AValue; Weapon.Tag := AValue; end; procedure TGLMD3Actor.SetName(AValue: string); begin if AValue = FName then Exit; Head.Name := AValue + '_Head'; Torso.Name := AValue + '_Torso'; Legs.Name := AValue + '_Legs'; Weapon.Name := AValue + '_Weapon'; end; procedure TGLMD3Actor.SetAnimation(AValue: string); begin AValue := LowerCase(AValue); if AValue = LowerCase(FAnimation) then Exit; if AValue = 'stand' then begin SwitchToAnimation(Legs, 'legs_idle'); SwitchToAnimation(Torso, 'torso_stand' + GetRnd (3)); end; if AValue = 'attack' then begin SwitchToAnimation(Legs, 'legs_idle'); SwitchToAnimation(Torso, 'torso_attack'); end; if AValue = 'attack2' then begin SwitchToAnimation(Legs, 'legs_idle'); SwitchToAnimation(Torso, 'torso_attack2'); end; if AValue = 'walk' then begin SwitchToAnimation(Legs, 'legs_walk'); SwitchToAnimation(Torso, 'torso_stand' + GetRnd (3)); end; if AValue = 'run' then begin SwitchToAnimation(Legs, 'legs_run'); SwitchToAnimation(Torso, 'torso_stand' + GetRnd (3)); end; if AValue = 'pain' then begin SwitchToAnimation(Legs, 'legs_idle'); SwitchToAnimation(Torso, 'torso_raise'); end; if AValue = 'death' then begin SwitchToAnimation(Legs, 'both_death' + GetRnd (4)); SwitchToAnimation(Torso, 'torso_dead' + GetRnd (4)); end; if AValue = 'crstnd' then begin SwitchToAnimation(Legs, 'legs_idlecr'); SwitchToAnimation(Torso, 'torso_stand' + GetRnd (3)); end; FAnimation := LowerCase(AValue); end; destructor TGLMD3Actor.Destroy; begin MaterialLibrary.Free; Weapon.Free; Head.Free; Torso.Free; Legs.Free; LegsTags.Free; TorsoTags.Free; WeaponTags.Free; inherited Destroy; end; end.
unit GLDCameraFrame; interface uses Classes, Controls, Forms, Buttons, StdCtrls, GL, GLDTypes, GLDSystem; type TGLDParamsFrameType = (GLD_PARAMS_FRAME_NONE, GLD_PARAMS_FRAME_USERCAMERA); TGLDCameraFrame = class(TFrame) SB_Camera: TScrollBox; GB_CameraType: TGroupBox; SB_UserCamera: TSpeedButton; procedure SpeedButtonClick(Sender: TObject); private FParamsFrame: TFrame; FDrawer: TGLDDrawer; function GetParamsFrameType: TGLDParamsFrameType; procedure SetParamsFrameType(Value: TGLDParamsFrameType); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetEditedObject; procedure SetParamsFrameParams(AObject: TObject); property ParamsFrame: TFrame read FParamsFrame; property ParamsFrameType: TGLDParamsFrameType read GetParamsFrameType write SetParamsFrameType; property Drawer: TGLDDrawer read FDrawer write FDrawer; end; function GLDXParamsFrameType(AType: TGLDSysClassType): TGLDParamsFrameType; procedure Register; implementation {$R *.dfm} uses GLDCamera, GLDUserCameraParamsFrame; constructor TGLDCameraFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FParamsFrame := nil; FDrawer := nil; end; destructor TGLDCameraFrame.Destroy; begin FParamsFrame.Free; inherited Destroy; end; procedure TGLDCameraFrame.SetEditedObject; begin if not Assigned(FDrawer) then Exit; if Assigned(FDrawer.EditedObject) then begin SetParamsFrameType(GLDXParamsFrameType(FDrawer.EditedObject.SysClassType)); SetParamsFrameParams(FDrawer.EditedObject); end; end; procedure TGLDCameraFrame.SetParamsFrameParams(AObject: TObject); begin if not Assigned(AObject) then Exit; case GetParamsFrameType of GLD_PARAMS_FRAME_USERCAMERA: if AObject is TGLDUserCamera then with TGLDUserCamera(AObject) do TGLDUserCameraFrame(FParamsFrame).SetParams(Name, Color.Color3ub, ProjectionMode, Fov, Aspect, Zoom, ZNear, ZFar); end; end; procedure TGLDCameraFrame.SpeedButtonClick(Sender: TObject); begin if not Assigned(FDrawer) then Exit; if Sender = SB_UserCamera then begin SetParamsFrameType(GLD_PARAMS_FRAME_USERCAMERA); FDrawer.StartDrawing(TGLDUserCamera); FDrawer.IOFrame := FParamsFrame; end; end; procedure TGLDCameraFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; function TGLDCameraFrame.GetParamsFrameType: TGLDParamsFrameType; begin Result := GLD_PARAMS_FRAME_NONE; if not Assigned(FParamsFrame) then Exit; if FParamsFrame is TGLDUserCameraFrame then Result := GLD_PARAMS_FRAME_USERCAMERA; end; procedure TGLDCameraFrame.SetParamsFrameType(Value: TGLDParamsFrameType); begin //if GetParamsFrameType = Value then Exit; FParamsFrame.Free; FParamsFrame := nil; case Value of GLD_PARAMS_FRAME_USERCAMERA: begin FParamsFrame := TGLDUserCameraFrame.Create(Self); TGLDUserCameraFrame(FParamsFrame).Drawer := Self.FDrawer; end; end; if Value <> GLD_PARAMS_FRAME_NONE then begin FParamsFrame.Top := GB_CameraType.Top + GB_CameraType.Height + 10; FParamsFrame.Parent := Self.SB_Camera; if Assigned(FDrawer) then FDrawer.IOFrame := FParamsFrame; end; end; function GLDXParamsFrameType(AType: TGLDSysClassType): TGLDParamsFrameType; begin case AType of GLD_SYSCLASS_USERCAMERA: Result := GLD_PARAMS_FRAME_USERCAMERA; else Result := GLD_PARAMS_FRAME_NONE; end; end; procedure Register; begin //RegisterComponents('GLDraw', [TGLDCameraFrame]); end; end.
unit ibSHOptions; interface uses SysUtils, Classes, Graphics, DesignIntf, SHDesignIntf, ibSHDesignIntf; type TfibBTOptions = class(TSHComponentOptions, IibSHOptions) private protected function GetCategory: string; override; function GetUseDefaultEditor: Boolean; override; procedure RestoreDefaults; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; public class function GetClassIIDClassFnc: TGUID; override; published end; TibBTOptions = class(TfibBTOptions, IibSHDummy, IibSHBranch) end; TfbBTOptions = class(TfibBTOptions, IibSHDummy, IfbSHBranch) end; implementation uses ibSHConsts, ibSHValues; { TfibBTOptions } constructor TfibBTOptions.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TfibBTOptions.Destroy; begin inherited Destroy; end; class function TfibBTOptions.GetClassIIDClassFnc: TGUID; begin if Supports(Self, IfbSHBranch) then Result := IfbSHOptions; if Supports(Self, IibSHBranch) then Result := IibSHOptions; end; function TfibBTOptions.GetCategory: string; begin if Supports(Self, IibSHBranch) then Result := Format('%s', [SibOptionsCategory]); if Supports(Self, IfbSHBranch) then Result := Format('%s', [SfbOptionsCategory]); end; function TfibBTOptions.GetUseDefaultEditor: Boolean; begin Result := False; end; procedure TfibBTOptions.RestoreDefaults; begin end; end.
unit UDWindowZoom; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Buttons, UCrpe32; type TCrpeWindowZoomDlg = class(TForm) pnlWindowZoom: TPanel; lblMagnification: TLabel; btnNext: TSpeedButton; tbarMagnification: TTrackBar; lblMin: TLabel; lblMax: TLabel; rgPreview: TRadioGroup; btnOk: TButton; btnCancel: TButton; btnClear: TButton; procedure FormShow(Sender: TObject); procedure UpdateWindowZoom; procedure tbarMagnificationChange(Sender: TObject); procedure rgPreviewClick(Sender: TObject); procedure btnNextClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure InitializeControls(OnOff: boolean); private { Private declarations } public { Public declarations } Cr : TCrpe; rMagnification : smallint; rPreview : smallint; end; var CrpeWindowZoomDlg: TCrpeWindowZoomDlg; bWindowZoom : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.FormCreate(Sender: TObject); begin bWindowZoom := True; LoadFormPos(Self); btnOk.Tag := 1; btnCancel.Tag := 1; btnClear.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.FormShow(Sender: TObject); begin rMagnification := Cr.WindowZoom.Magnification; rPreview := Ord(Cr.WindowZoom.Preview); UpdateWindowZoom; end; {------------------------------------------------------------------------------} { UpdateWindowZoom } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.UpdateWindowZoom; begin tbarMagnification.Position := Cr.WindowZoom.Magnification; rgPreview.ItemIndex := Ord(Cr.WindowZoom.Preview); end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TTrackBar then TTrackBar(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TSpeedButton then TSpeedButton(Components[i]).Enabled := OnOff; end; end; end; {------------------------------------------------------------------------------} { tbarMagnificationChange } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.tbarMagnificationChange(Sender: TObject); begin Cr.WindowZoom.Magnification := tbarMagnification.Position; rgPreview.ItemIndex := 3; tbarMagnification.Hint := IntToStr(tbarMagnification.Position); end; {------------------------------------------------------------------------------} { rgPreviewClick } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.rgPreviewClick(Sender: TObject); begin Cr.WindowZoom.Preview := TCrZoomPreview(rgPreview.ItemIndex); if rgPreview.ItemIndex <> 3 then Cr.WindowZoom.Magnification := -1; end; {------------------------------------------------------------------------------} { btnNextClick } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.btnNextClick(Sender: TObject); begin if rgPreview.ItemIndex < 3 then rgPreview.ItemIndex := rgPreview.ItemIndex + 1 else rgPreview.ItemIndex := 0; rgPreviewClick(Self); end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.btnClearClick(Sender: TObject); begin Cr.WindowZoom.Clear; UpdateWindowZoom; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeWindowZoomDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrCancel then begin {Restore Settings} Cr.WindowZoom.Magnification := rMagnification; Cr.WindowZoom.Preview := TCrZoomPreview(rPreview); end; bWindowZoom := False; Release; end; end.
unit QuickRTTI; interface uses classes,typinfo,sysutils; type TCustomQuickRTTI = class (TPersistent) private fobj:TPersistent; PList:PPropList; props:tstringlist; objs:TStringlist; fval,ftag,fobjid,fintag:String; fshowtype:boolean; QCache:TCustomQuickRTTI; protected function outputXML :String; virtual;abstract; procedure inputXML (sXML:String); virtual;abstract; procedure SetValue (Fieldname:String;Value:String); function GetValue (Fieldname:String):String; procedure SetObject (o:TPersistent); property Cache:TCustomQuickRTTI read QCache write QCache; public constructor create; destructor destroy;override; function propertyCount:integer; function indexof(name:String):Integer; function propertynames(index:integer):String; function propertyVarTypes(index:integer):String; function propertyTypes(index:integer):TTYpeKind; function ChildObjectCount:integer; function ChildObjectName(index:integer):String; function ChildObject(name:String):TObject; property Value[Fieldname:String]:String read GetValue write SetValue; published property RTTIObject:TPersistent read fobj write SetObject; property InTagProperties:String read fintag write fintag; {comma delim} property ShowType:Boolean read fshowtype write fshowtype; property ObjectID:String read fobjid write fobjid; property XML:String read outputXML write inputXML; property TagName:String read ftag write ftag; end; implementation function TCustomQuickRTTI.ChildObjectCount:integer; begin result:=objs.count; end; function TCustomQuickRTTI.ChildObjectName(index:integer):String; begin result:=objs[index]; end; function TCustomQuickRTTI.ChildObject(name:String):TObject; var idx:integer; begin idx:= objs.indexof(name); result:=nil; if idx>-1 then result:=TCustomQuickRTTI(objs.objects[idx]).RTTIObject; end; constructor TCustomQuickRTTI.create; begin fshowtype:=true; fintag:=''; objs:=tstringlist.create; props:=tstringlist.create; ftag:=''; end; destructor TCustomQuickRTTI.destroy; //var tempq:TQuickRTTI; begin try if assigned(objs) then while objs.count>0 do begin // tempq:=TCustomQuickRTTI(objs.objects[objs.count-1]); // tempq.free; objs.delete(objs.count-1); end; objs.free; //KV props.free; //KV if assigned(QCache) then begin QCache.rttiobject:=nil; QCache.free; end; finally inherited destroy; end; end; procedure TCustomQuickRTTI.SetObject (o:TPersistent); // Modified by KV var Count, PropCount : integer; PTI:PTypeInfo; PTempList : PPropList; Tinfo:TPropInfo; i:integer; //vin:variant; tempq:TCustomQuickRTTI; ttinfo:TTypeinfo; begin if assigned(o) then begin if not(assigned(props)) then props:=tstringlist.create; props.clear; fobj:=o; PTI:=o.ClassInfo ; PropCount := GetTypeData(PTI)^.PropCount; if PropCount = 0 then exit; GetMem(PTempList, PropCount * SizeOf(Pointer)); try PList:= PTempList; Count := GetPropList(PTI,[ tkInteger, tkChar, tkEnumeration, tkFloat, tkString, tkSet, tkClass, tkMethod, tkWChar, tkLString, tkWString, tkVariant, tkArray, tkRecord, tkInterface, tkInt64, tkDynArray], PList); {getting the list... but I'm pretty much trying to ignore method calls for this version} for i:= 0 to Count-1 do if assigned(Plist[i]) then begin Tinfo:= Plist[i]^; //vin:=GetPropValue(fobj,Tinfo.Name,True); ttinfo:=tinfo.PropType^^; if ttinfo.kind=tkClass then begin tempq:=TCustomQuickRTTI.create; tempq.RTTIObject := TPersistent(GetObjectProp(fobj,Tinfo.name)); objs.AddObject (Uppercase(Tinfo.Name),tempq) ; tempq.TagName := Tinfo.name; end; props.addobject(Uppercase(Tinfo.Name), Pointer(PList[i]) ); end; finally FreeMem(PTempList, PropCount * SizeOf(Pointer)); end; end; end; function TCustomQuickRTTI.propertyCount:integer; begin result:=-1; if assigned(props) then result:=props.count; end; function TCustomQuickRTTI.propertynames(index:integer):String; var ppos:integer; begin result:=''; if assigned(props) then result:=props[index]; end; function TCustomQuickRTTI.indexof(name:String):Integer; begin if assigned(props) then result:=props.IndexOf (Uppercase(name)); end; function TCustomQuickRTTI.propertyVarTypes(index:integer):string; var Tinfo:TPropInfo; begin result:=''; if assigned(props) then begin Tinfo:=TPropinfo(Pointer(props.objects[index])^); result:=Tinfo.PropType^.name; end; end; function TCustomQuickRTTI.propertyTypes(index:integer):TTYpeKind; var Tinfo:TPropInfo; begin if assigned(props) then begin Tinfo:=TPropinfo(Pointer(props.objects[index])^); result:=Tinfo.PropType^.kind; end; end; procedure TCustomQuickRTTI.SetValue (Fieldname:String;Value:String); var vin:Variant; fname:Shortstring; begin if assigned(fobj) then begin fname:=fieldname; Vin:=Value; SetPropValue(fobj,fName,Vin); end; end; function TCustomQuickRTTI.GetValue (Fieldname:String):String; var v,vin:Variant; fname,sname,ename:Shortstring; ppos,idx:integer; p:TPersistent;//q:TCustomQuickRTTI; begin result:=''; if assigned(fobj) then begin fname:=fieldname; ppos:=pos('.',fname); if ppos>0 then begin sname:= copy(fname,1,ppos-1); ename:= copy(fname,ppos+1,length(fname)-ppos-1) end; if ppos>1 then begin {Property.anotherproperty} idx:=objs.indexof(sname); if idx>0 then begin // q:=TCustomQuickRTTI(objs.objects[idx]); p:=TPersistent(objs.objects[idx]); QCache.RTTIObject := p; //result:=q.Value[ename]; result:=QCache.value[ename]; end; end else vin:=GetPropValue(fobj,fName,True); Varcast(v,vin,varString); result:=vin; end; end; end. { This file is released under an MIT style license as detailed at opensource.org. Just don't preteend you wrote it, and leave this comment in the text, and I'll be happy. Consider it my resume :) April 17,2000 Michael Johnson father@bigattichouse.com www.bigattichouse.com Quick RTTI gives you simple string based access to RTTI data in any RTTI capable component. WIth the addition of my lowx and strutils you can also read and write basic XML structures based off of your component. SUPER easy. Just set RTTIObject:= some TPersistent descendant (any TComponent) and you will have nice string based access to all its fields by name... cool huh. I am testing an "Object Shell" that will allow using QuickRTTI and Toadbase to use/store RTTI Objects thru memory mapped files, ie.. web based persistence.. I know, why not use CORBA.. hell, in the words of Disney via Mr W.T.Pooh "...I wouldn't climb this tree / if a bear flew like a bee / but I wouldn't be a bear then / so I guess I wouldn't care then..." Perhaps having the simple ability to convert TComponents to and from XML will open up a new world for delphi... now to work on RPC !.. }
unit ThWebBrowserUtils; interface uses Classes, ShDocVw; procedure TbhStringToBrowser(inWebBrowser: TWebBrowser; inHtml: string); implementation uses Forms, ActiveX; procedure TbhStringToBrowser(inWebBrowser: TWebBrowser; inHtml: string); var sl: TStringList; ms: TMemoryStream; begin inWebBrowser.Navigate('about:blank'); while inWebBrowser.ReadyState < READYSTATE_INTERACTIVE do Application.ProcessMessages; if Assigned(inWebBrowser.Document) then begin sl := TStringList.Create; try ms := TMemoryStream.Create; try sl.Text := inHtml; sl.SaveToStream(ms); ms.Seek(0, 0); with inWebBrowser.Document as IPersistStreamInit do Load(TStreamAdapter.Create(ms)); finally ms.Free; end; finally sl.Free; end; end; end; function TbhStringFromBrowser(inWebBrowser: TWebBrowser): string; var sl: TStringList; ms: TMemoryStream; begin while inWebBrowser.ReadyState < READYSTATE_INTERACTIVE do Application.ProcessMessages; if Assigned(inWebBrowser.Document) then begin sl := TStringList.Create; try ms := TMemoryStream.Create; try with inWebBrowser.Document as IPersistStreamInit do Save(TStreamAdapter.Create(ms), true); sl.LoadFromStream(ms); finally ms.Free; end; finally Result := sl.Text; sl.Free; end; end; end; end.
unit uInternetFreeActivationThread; interface uses Classes, SysUtils, Dmitry.Utils.System, uInternetUtils, uConstants, uActivationUtils, uTranslate, uGOM, uDBForm, uDBThread, uUpTime; type TFreeRegistrationCallBack = procedure(Reply: string) of object; InternetActivationInfo = record Owner: TDBForm; FirstName: string; LastName: string; Email: string; Phone: string; Country: string; City: string; Address: string; CallBack: TFreeRegistrationCallBack; end; type TInternetFreeActivationThread = class(TDBThread) private { Private declarations } FInfo: InternetActivationInfo; FServerReply: string; protected procedure Execute; override; procedure DoCallBack; public constructor Create(Info: InternetActivationInfo); end; implementation { TInternetFreeActivationThread } constructor TInternetFreeActivationThread.Create(Info: InternetActivationInfo); begin inherited Create(Info.Owner, False); FInfo := Info; end; procedure TInternetFreeActivationThread.DoCallBack; begin if GOM.IsObj(FInfo.Owner) then FInfo.CallBack(FServerReply); end; procedure TInternetFreeActivationThread.Execute; var QueryUrl, QueryParams: string; begin inherited; FreeOnTerminate := True; try try QueryUrl := FreeActivationURL; QueryParams := Format('?k=%s&v=%s&fn=%s&ln=%s&e=%s&p=%s&co=%s&ci=%s&a=%s&ut=%s&lng=%s', [TActivationManager.Instance.ApplicationCode, ProductVersion, EncodeBase64Url(FInfo.FirstName), EncodeBase64Url(FInfo.LastName), EncodeBase64Url(FInfo.Email), EncodeBase64Url(FInfo.Phone), EncodeBase64Url(FInfo.Country), EncodeBase64Url(FInfo.City), EncodeBase64Url(FInfo.Address), IntToStr(GetCurrentUpTime), TTranslateManager.Instance.Language]); FServerReply := DownloadFile(QueryUrl + QueryParams, TEncoding.UTF8); except on e: Exception do FServerReply := e.Message; end; finally Synchronize(DoCallBack); end; end; end.