text
stringlengths
14
6.51M
unit ufrmMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, diocp.task, diocp.tcp.blockClient, uStreamCoderSocket, uRawTcpClientCoderImpl, Grids, DBGrids, uIRemoteServer, uRemoteServerDIOCPImpl, DB, DBClient; type // 异步执行任务对象 TASyncTaskObject = class private FData: OleVariant; FErrMessage: String; FHost: String; FPort: Integer; FSQL: String; FuseTime: Cardinal; public property Data: OleVariant read FData write FData; property ErrMessage: String read FErrMessage write FErrMessage; property Host: String read FHost write FHost; property Port: Integer read FPort write FPort; property SQL: String read FSQL write FSQL; property useTime: Cardinal read FuseTime write FuseTime; end; TfrmMain = class(TForm) mmoSQL: TMemo; btnConnect: TButton; edtHost: TEdit; edtPort: TEdit; DBGrid1: TDBGrid; btnOpen: TButton; cdsMain: TClientDataSet; dsMain: TDataSource; btnOpenASync: TButton; procedure btnConnectClick(Sender: TObject); procedure btnOpenASyncClick(Sender: TObject); procedure btnOpenClick(Sender: TObject); private { Private declarations } FRemoteSvrObj:TRemoteServerDIOCPImpl; FRemoteSvr:IRemoteServer; procedure OnASyncTask(pvTaskRequest: TIocpTaskRequest); /// <summary> /// 异步任务执行完成的回调, 主要用来处理数据的显示,因为子线程不能直接调用访问UI /// </summary> procedure OnASyncTaskCompleted(pvTaskRequest:TIocpTaskRequest); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmMain: TfrmMain; implementation {$R *.dfm} { TfrmMain } constructor TfrmMain.Create(AOwner: TComponent); begin inherited; FRemoteSvrObj := TRemoteServerDIOCPImpl.Create; FRemoteSvr := FRemoteSvrObj; end; destructor TfrmMain.Destroy; begin FRemoteSvr := nil; inherited Destroy; end; procedure TfrmMain.btnConnectClick(Sender: TObject); begin FRemoteSvrObj.setHost(edtHost.Text); FRemoteSvrObj.setPort(StrToInt(edtPort.Text)); FRemoteSvrObj.Open(); ShowMessage('open succ!'); end; procedure TfrmMain.btnOpenASyncClick(Sender: TObject); var lvTaskObject : TASyncTaskObject; begin // 设置按钮状态 btnOpenASync.Enabled := false; btnOpenASync.Caption := '正在执行...'; lvTaskObject := TASyncTaskObject.Create(); lvTaskObject.SQL := mmoSQL.Lines.Text; // 要执行的SQL语句 lvTaskObject.Host := edtHost.Text; // 异步执行, 内部创建连接 lvTaskObject.Port := StrToInt(edtPort.Text); // 异步执行, 内部创建连接 iocpTaskManager.PostATask(OnASyncTask, lvTaskObject); // 投递到iocpTask线程,由其他线程执行, 执行时回调OnASyncTask函数 end; procedure TfrmMain.btnOpenClick(Sender: TObject); var vData:OleVariant; l : Cardinal; begin vData := mmoSQL.Lines.Text; l := GetTickCount; if FRemoteSvr.Execute(1, vData) then begin self.cdsMain.Data := vData; Self.Caption := Format('query: count:%d, time:%d', [self.cdsMain.RecordCount, GetTickCount - l]); end; end; procedure TfrmMain.OnASyncTask(pvTaskRequest: TIocpTaskRequest); var vData:OleVariant; l : Cardinal; lvTaskObject : TASyncTaskObject; lvRemoteSvrObj:TRemoteServerDIOCPImpl; lvRemoteSvr:IRemoteServer; begin lvTaskObject :=TASyncTaskObject(pvTaskRequest.TaskData); try lvRemoteSvrObj := TRemoteServerDIOCPImpl.Create; lvRemoteSvr := lvRemoteSvrObj; lvRemoteSvrObj.setHost(lvTaskObject.Host); lvRemoteSvrObj.setPort(lvTaskObject.Port); lvRemoteSvrObj.Open(); l := GetTickCount; vData := lvTaskObject.SQL; if lvRemoteSvr.Execute(1, vData) then begin lvTaskObject.Data := vData; lvTaskObject.useTime := GetTickCount - l; end; except on E:Exception do begin // 执行时出现了异常, 记录错误信息 lvTaskObject.ErrMessage := e.Message; end; end; // 投递到iocpTask线程,由主线程执行, 执行时回调OnASyncTask函数 // 第三个参数为true,代表主线程去执行 iocpTaskManager.PostATask(OnASyncTaskCompleted, lvTaskObject, true); end; procedure TfrmMain.OnASyncTaskCompleted(pvTaskRequest:TIocpTaskRequest); var lvTaskObject : TASyncTaskObject; begin lvTaskObject :=TASyncTaskObject(pvTaskRequest.TaskData); try // 设置按钮状态 btnOpenASync.Enabled := true; btnOpenASync.Caption := '异步执行'; if lvTaskObject.ErrMessage <> '' then begin // 异常 ShowMessage(lvTaskObject.ErrMessage); Exit; end else begin self.cdsMain.Data := lvTaskObject.Data; Self.Caption := Format('query: count:%d, time:%d', [self.cdsMain.RecordCount, lvTaskObject.useTime]); end; finally // 不在需要 lvTaskObject.Free; end; end; end.
unit caMathEval; {$INCLUDE ca.inc} interface uses // Standard Delphi units Classes, SysUtils, Math, // ca units caClasses, caTypes, caVector, caUtils; const cComma = ','; cDoubleComma = ',,'; type EcaMathEvalException = class(Exception); TcaOperandVariableEvent = procedure(Sender: TObject; const AOperand: String; var AValue: Extended) of object; //--------------------------------------------------------------------------- // IcaMathTokens //--------------------------------------------------------------------------- IcaMathTokens = interface ['{474F2872-F6BE-4BF6-84E2-94129C1111D5}'] // Property methods function GetExpression: String; function GetTokens: TStrings; procedure SetExpression(const Value: String); // Properties property Expression: String read GetExpression write SetExpression; property Tokens: TStrings read GetTokens; end; //--------------------------------------------------------------------------- // TcaMathTokens //--------------------------------------------------------------------------- TcaMathTokens = class(TInterfacedObject, IcaMathTokens) private FExpression: String; FTokens: TStrings; // Property methods function GetExpression: String; function GetTokens: TStrings; procedure SetExpression(const Value: String); // Private methods procedure UpdateTokens; public constructor Create; destructor Destroy; override; // Properties property Expression: String read GetExpression write SetExpression; property Tokens: TStrings read GetTokens; end; //--------------------------------------------------------------------------- // IcaInFixToPostfix //--------------------------------------------------------------------------- IcaInFixToPostfix = interface ['{F84D2A15-9F76-415F-AE91-EAF176F80A95}'] // Property methods function GetPostfixTokens: TStrings; function GetInfixTokens: TStrings; procedure SetInfixTokens(const Value: TStrings); // Properties property PostfixTokens: TStrings read GetPostfixTokens; property InfixTokens: TStrings read GetInfixTokens write SetInfixTokens; end; //--------------------------------------------------------------------------- // TcaInfixToPostfix //--------------------------------------------------------------------------- TcaInfixToPostfix = class(TInterfacedObject, IcaInFixToPostfix) private FPostfixTokens: TStrings; FInfixTokens: TStrings; // Property methods function GetPostfixTokens: TStrings; function GetInfixTokens: TStrings; procedure SetInfixTokens(const Value: TStrings); // Private methods procedure UpdatePostfixTokens; public constructor Create; destructor Destroy; override; // Properties property PostfixTokens: TStrings read GetPostfixTokens; property InfixTokens: TStrings read GetInfixTokens write SetInfixTokens; end; //--------------------------------------------------------------------------- // IcaPostfixEvaluator //--------------------------------------------------------------------------- IcaPostfixEvaluator = interface ['{44D75E82-81D5-457F-A82A-A46C9FCC0173}'] // Property methods function GetPostfixTokens: TStrings; function GetTrigUnits: TcaTrigUnits; function GetValue: Extended; procedure SetPostfixTokens(const Value: TStrings); procedure SetTrigUnits(const Value: TcaTrigUnits); // Event property methods function GetOnGetOperandVariable: TcaOperandVariableEvent; procedure SetOnGetOperandVariable(const Value: TcaOperandVariableEvent); // Properties property PostfixTokens: TStrings read GetPostfixTokens write SetPostfixTokens; property TrigUnits: TcaTrigUnits read GetTrigUnits write SetTrigUnits; property Value: Extended read GetValue; // Event properties property OnGetOperandVariable: TcaOperandVariableEvent read GetOnGetOperandVariable write SetOnGetOperandVariable; end; //--------------------------------------------------------------------------- // TcaPostfixEvaluator //--------------------------------------------------------------------------- TcaPostfixEvaluator = class(TInterfacedObject, IcaPostfixEvaluator) private FPostfixTokens: TStrings; FTrigUnits: TcaTrigUnits; FValue: Extended; FOnGetOperandVariable: TcaOperandVariableEvent; // Property methods function GetPostfixTokens: TStrings; function GetTrigUnits: TcaTrigUnits; function GetValue: Extended; procedure SetPostfixTokens(const Value: TStrings); procedure SetTrigUnits(const Value: TcaTrigUnits); // Event property methods function GetOnGetOperandVariable: TcaOperandVariableEvent; procedure SetOnGetOperandVariable(const Value: TcaOperandVariableEvent); // Private methods function GetOperandValue(const AOperand: String): Extended; function GetTrigOperand(AOperand: Extended): Extended; procedure Evaluate; protected // Protected methods procedure DoGetOperandVariable(const AOperand: String; var AValue: Extended); virtual; public constructor Create; destructor Destroy; override; // Properties property PostfixTokens: TStrings read GetPostfixTokens write SetPostfixTokens; property TrigUnits: TcaTrigUnits read GetTrigUnits write SetTrigUnits; property Value: Extended read GetValue; // Event properties property OnGetOperandVariable: TcaOperandVariableEvent read GetOnGetOperandVariable write SetOnGetOperandVariable; end; //--------------------------------------------------------------------------- // IcaMathEvaluator //--------------------------------------------------------------------------- IcaMathEvaluator = interface ['{BD670DED-CBF3-448C-81B6-C10568F7BA00}'] // Property methods function GetExpression: String; function GetTrigUnits: TcaTrigUnits; function GetValue: Extended; function GetValueAsString: String; procedure SetExpression(const Value: String); procedure SetTrigUnits(const Value: TcaTrigUnits); // Event property methods function GetOnGetOperandVariable: TcaOperandVariableEvent; procedure SetOnGetOperandVariable(const Value: TcaOperandVariableEvent); // Properties property Expression: String read GetExpression write SetExpression; property TrigUnits: TcaTrigUnits read GetTrigUnits write SetTrigUnits; property Value: Extended read GetValue; property ValueAsString: String read GetValueAsString; // Event properties property OnGetOperandVariable: TcaOperandVariableEvent read GetOnGetOperandVariable write SetOnGetOperandVariable; end; //--------------------------------------------------------------------------- // TcaMathEvaluator //--------------------------------------------------------------------------- TcaMathEvaluator = class(TInterfacedObject, IcaMathEvaluator) private FExpression: String; FInfixToPostfix: IcaInFixToPostfix; FMathTokens: IcaMathTokens; FOnGetOperandVariable: TcaOperandVariableEvent; FPostfixEvaluator: IcaPostfixEvaluator; FValue: Extended; // Property methods function GetExpression: String; function GetTrigUnits: TcaTrigUnits; function GetValue: Extended; function GetValueAsString: String; procedure SetExpression(const Value: String); procedure SetTrigUnits(const Value: TcaTrigUnits); // Event property methods function GetOnGetOperandVariable: TcaOperandVariableEvent; procedure SetOnGetOperandVariable(const Value: TcaOperandVariableEvent); // Private methods procedure UpdateValue; // Event handler procedure OperandVariableEvent(Sender: TObject; const AOperand: String; var AValue: Extended); protected // Protected methods procedure DoGetOperandVariable(const AOperand: String; var AValue: Extended); virtual; public constructor Create; property Expression: String read GetExpression write SetExpression; property TrigUnits: TcaTrigUnits read GetTrigUnits write SetTrigUnits; property Value: Extended read GetValue; property ValueAsString: String read GetValueAsString; // Event properties property OnGetOperandVariable: TcaOperandVariableEvent read GetOnGetOperandVariable write SetOnGetOperandVariable; end; implementation //--------------------------------------------------------------------------- // TcaMathTokens //--------------------------------------------------------------------------- constructor TcaMathTokens.Create; begin inherited; FTokens := TStringList.Create; end; destructor TcaMathTokens.Destroy; begin FTokens.Free; inherited; end; function TcaMathTokens.GetExpression: String; begin Result := FExpression; end; function TcaMathTokens.GetTokens: TStrings; begin Result := FTokens; end; procedure TcaMathTokens.SetExpression(const Value: String); begin FExpression := Value; UpdateTokens; end; procedure TcaMathTokens.UpdateTokens; var Index: Integer; Ch: Char; ChPrev: Char; TokensStr: String; AExpression: String; PreDelim: String; PostDelim: String; ZeroInserts: IcaIntegerVector; begin AExpression := LowerCase(FExpression); Utils.StripChar(#32, AExpression); // Check for any '-' operators used for negation or '+' used as a prefix ZeroInserts := TcaIntegerVector.Create; for Index := 1 to Length(AExpression) do begin Ch := AExpression[Index]; if (Ch = '-') or (Ch = '+') then begin // If the '-' is the first token or if it is not preceeded // by an operand, then insert a '0' operand before the '-' if Index = 1 then ZeroInserts.Add(Index) else begin ChPrev := AExpression[Index - 1]; if Utils.IsOperator(ChPrev) or Utils.IsBracket(ChPrev) then ZeroInserts.Add(Index); end; end; end; for Index := ZeroInserts.Count - 1 downto 0 do Insert('0', AExpression, ZeroInserts[Index]); // Break expression into comma separated tokens TokensStr := ''; for Index := 1 to Length(AExpression) do begin PreDelim := ''; PostDelim := ''; Ch := AExpression[Index]; if Utils.IsOperator(Ch) or Utils.IsBracket(Ch) then begin PreDelim := cComma; PostDelim := cComma; end; TokensStr := TokensStr + PreDelim + Ch + PostDelim; end; if TokensStr[1] = cComma then Utils.DeleteFromStart(TokensStr, 1); Utils.Replace(TokensStr, cDoubleComma, cComma); FTokens.CommaText := TokensStr; end; //--------------------------------------------------------------------------- // TcaInfixToPostfix //--------------------------------------------------------------------------- constructor TcaInfixToPostfix.Create; begin inherited; FPostfixTokens := TStringList.Create; FInfixTokens := TStringList.Create; end; destructor TcaInfixToPostfix.Destroy; begin FPostfixTokens.Free; FInfixTokens.Free; inherited; end; function TcaInfixToPostfix.GetPostfixTokens: TStrings; begin Result := FPostfixTokens; end; function TcaInfixToPostfix.GetInfixTokens: TStrings; begin Result := FInfixTokens; end; procedure TcaInfixToPostfix.SetInfixTokens(const Value: TStrings); begin FInfixTokens.Assign(Value); UpdatePostfixTokens; end; procedure TcaInfixToPostfix.UpdatePostfixTokens; var Index: Integer; OperatorStack: IcaStringStack; Token: String; begin FPostfixTokens.Clear; OperatorStack := TcaStringList.Create; for Index := 0 to FInfixTokens.Count - 1 do begin Token := FInfixTokens[Index]; // Add operand to output if Utils.IsOperand(Token) then begin // Check for special constants if Token = 'pi' then Token := FloatToStr(Pi); if Token = 'e' then Token := FloatToStr(Exp(1)); FPostfixTokens.Add(Token); Continue; end; // Push open bracket on to stack if Token = '(' then begin OperatorStack.Push(Token); Continue; end; // Add pending operators to output if Token = ')' then begin // Pop operators from stack until an open bracket is found while OperatorStack.Peek <> '(' do begin if OperatorStack.IsEmpty then raise EcaMathEvalException.Create('Mismatched bracket error'); FPostfixTokens.Add(OperatorStack.Pop); end; // Discard the open bracket OperatorStack.Pop; Continue; end; // Push function onto the stack if Utils.IsFunction(Token) then begin OperatorStack.Push(Token); Continue; end; // Add pending operators to output if Utils.IsOperator(Token) then begin while (not OperatorStack.IsEmpty) and (not (Utils.GetOperatorPrecedence(OperatorStack.Peek, Token) = opLower)) and (not (Utils.GetOperatorPrecedence(OperatorStack.Peek, Token) = opSameRightAssoc)) do FPostfixTokens.Add(OperatorStack.Pop); OperatorStack.Push(Token); Continue; end; end; // Add remaining operators to output while not OperatorStack.IsEmpty do begin if OperatorStack.Peek = '(' then raise EcaMathEvalException.Create('Mismatched bracket error'); FPostfixTokens.Add(OperatorStack.Pop); end; OperatorStack := nil; end; //--------------------------------------------------------------------------- // TcaPostfixEvaluator //--------------------------------------------------------------------------- constructor TcaPostfixEvaluator.Create; begin inherited; FPostfixTokens := TStringList.Create; end; destructor TcaPostfixEvaluator.Destroy; begin FPostfixTokens.Free; inherited; end; // Protected methods procedure TcaPostfixEvaluator.DoGetOperandVariable(const AOperand: String; var AValue: Extended); begin if Assigned(FOnGetOperandVariable) then FOnGetOperandVariable(Self, AOperand, AValue); end; // Private methods procedure TcaPostfixEvaluator.Evaluate; var EvalResult: Extended; Index: Integer; LeftOperand: Extended; Operand: Extended; OperandStack: IcaStringStack; RightOperand: Extended; Token: String; MathUtils: IcaMathUtils; begin MathUtils := Utils as IcaMathUtils; OperandStack := TcaStringList.Create; for Index := 0 to FPostfixTokens.Count - 1 do begin Token := FPostfixTokens[Index]; if Utils.IsOperand(Token) then OperandStack.Push(Token) else begin EvalResult := 0; if Utils.IsOperator(Token) then begin RightOperand := GetOperandValue(OperandStack.Pop); LeftOperand := GetOperandValue(OperandStack.Pop); if Token = '+' then EvalResult := LeftOperand + RightOperand else if Token = '-' then EvalResult := LeftOperand - RightOperand else if Token = '*' then EvalResult := LeftOperand * RightOperand else if Token = '/' then EvalResult := LeftOperand / RightOperand else if Token = '^' then EvalResult := Power(LeftOperand, RightOperand); end; if Utils.IsFunction(Token) then begin Operand := GetOperandValue(OperandStack.Pop); if Token = 'cos' then EvalResult := Cos(GetTrigOperand(Operand)) else if Token = 'exp' then EvalResult := Exp(Operand) else if Token = 'int' then EvalResult := Int(Operand) else if Token = 'sin' then EvalResult := Sin(GetTrigOperand(Operand)) else if Token = 'frac' then EvalResult := Frac(Operand) else if Token = 'round' then EvalResult := Round(Operand) else if Token = 'trunc' then EvalResult := MathUtils.Trunc(Operand) else if Token = 'tan' then EvalResult := Tan(GetTrigOperand(Operand)) else if Token = 'ln' then EvalResult := Ln(Operand) else if Token = 'log10' then EvalResult := Log10(Operand) else if Token = 'sqrt' then EvalResult := Sqrt(Operand); end; OperandStack.Push(FloatToStr(EvalResult)); end; end; if (OperandStack as IcaStringList).Count <> 1 then raise EcaMathEvalException.Create('Postfix evaluator stack count <> 1'); // FValue := StrToFloat(OperandStack.Pop); FValue := GetOperandValue(OperandStack.Pop); end; function TcaPostfixEvaluator.GetTrigOperand(AOperand: Extended): Extended; begin if FTrigUnits = tuDegrees then Result := DegToRad(AOperand) else Result := AOperand; end; function TcaPostfixEvaluator.GetOperandValue(const AOperand: String): Extended; var Handled: Boolean; OperandChar: Char; begin Result := 0; Handled := False; if AOperand <> '' then begin OperandChar := AOperand[1]; if OperandChar in ['a'..'z', 'A'..'Z'] then begin DoGetOperandVariable(AOperand, Result); Handled := True; end; end; if not Handled then Result := Utils.Str2Float(AOperand, 0); end; function TcaPostfixEvaluator.GetPostfixTokens: TStrings; begin Result := FPostfixTokens; end; function TcaPostfixEvaluator.GetTrigUnits: TcaTrigUnits; begin Result := FTrigUnits; end; function TcaPostfixEvaluator.GetValue: Extended; begin Result := FValue; end; procedure TcaPostfixEvaluator.SetPostfixTokens(const Value: TStrings); begin FPostfixTokens.Assign(Value); Evaluate; end; procedure TcaPostfixEvaluator.SetTrigUnits(const Value: TcaTrigUnits); begin FTrigUnits := Value; end; // Event property methods function TcaPostfixEvaluator.GetOnGetOperandVariable: TcaOperandVariableEvent; begin Result := FOnGetOperandVariable; end; procedure TcaPostfixEvaluator.SetOnGetOperandVariable(const Value: TcaOperandVariableEvent); begin FOnGetOperandVariable := Value; end; //--------------------------------------------------------------------------- // TcaMathEvaluator //--------------------------------------------------------------------------- constructor TcaMathEvaluator.Create; begin inherited; FMathTokens := TcaMathTokens.Create; FInfixToPostfix := TcaInFixToPostfix.Create; FPostfixEvaluator := TcaPostfixEvaluator.Create; FPostfixEvaluator.OnGetOperandVariable := OperandVariableEvent; SetTrigUnits(tuDegrees); end; // Protected methods procedure TcaMathEvaluator.DoGetOperandVariable(const AOperand: String; var AValue: Extended); begin if Assigned(FOnGetOperandVariable) then FOnGetOperandVariable(Self, AOperand, AValue); end; // Event handler procedure TcaMathEvaluator.OperandVariableEvent(Sender: TObject; const AOperand: String; var AValue: Extended); begin DoGetOperandVariable(AOperand, AValue); end; // Property methods function TcaMathEvaluator.GetExpression: String; begin Result := FExpression; end; function TcaMathEvaluator.GetTrigUnits: TcaTrigUnits; begin Result := FPostfixEvaluator.TrigUnits; end; procedure TcaMathEvaluator.SetExpression(const Value: String); begin FExpression := Value; UpdateValue; end; function TcaMathEvaluator.GetValue: Extended; begin Result := FValue; end; function TcaMathEvaluator.GetValueAsString: String; begin Result := FloatToStr(FValue); end; procedure TcaMathEvaluator.SetTrigUnits(const Value: TcaTrigUnits); begin FPostfixEvaluator.TrigUnits := Value; end; procedure TcaMathEvaluator.UpdateValue; begin if FExpression <> '' then begin FMathTokens.Expression := FExpression; FInfixToPostfix.InfixTokens := FMathTokens.Tokens; FPostfixEvaluator.PostfixTokens := FInfixToPostfix.PostfixTokens; FValue := FPostfixEvaluator.Value; end else FValue := 0; end; // Event property methods function TcaMathEvaluator.GetOnGetOperandVariable: TcaOperandVariableEvent; begin Result := FOnGetOperandVariable; end; procedure TcaMathEvaluator.SetOnGetOperandVariable(const Value: TcaOperandVariableEvent); begin FOnGetOperandVariable := Value; end; end.
unit UTipoDetalhamento; interface uses Contnrs, uRegistro, uNumeroCampo; type TTipoDetalhamento = class(TRegistro) private fID : Integer; fCodigo : String; fDescricao : String; fNumeroCampo : TNumeroCampo; procedure SetCodigo(const Value: String); procedure SetDescricao(const Value: String); procedure SetID(const Value: Integer); procedure SetNumeroCampo(const Value: TNumeroCampo); public property ID : Integer read fID write SetID; property NumeroCampo : TNumeroCampo read fNumeroCampo write SetNumeroCampo; property Descricao : String read fDescricao write SetDescricao; property Codigo : String read fCodigo write SetCodigo; function Todos : TObjectList; function TodosDoNumeroCampo : TObjectList; function Procurar () : TRegistro; constructor create(); end; implementation uses UTipoDetalhamentoBD; { TTipoDetalhamento } constructor TTipoDetalhamento.create; begin fNumeroCampo := TNumeroCampo.create; end; function TTipoDetalhamento.Procurar: TRegistro; var lTipoDetalhamentoBD : TTipoDetalhamentoBD; begin lTipoDetalhamentoBD := TTipoDetalhamentoBD.Create; result := lTipoDetalhamentoBD.Procurar(self); fDescricao := TTipoDetalhamento(result).fDescricao; fCodigo := TTipoDetalhamento(result).fCodigo; end; procedure TTipoDetalhamento.SetCodigo(const Value: String); begin fCodigo := Value; end; procedure TTipoDetalhamento.SetDescricao(const Value: String); begin fDescricao := Value; end; procedure TTipoDetalhamento.SetID(const Value: Integer); begin fID := Value; end; procedure TTipoDetalhamento.SetNumeroCampo(const Value: TNumeroCampo); begin fNumeroCampo := Value; end; function TTipoDetalhamento.Todos: TObjectList; var lTipoDetalhamentoBD : TTipoDetalhamentoBD; begin lTipoDetalhamentoBD := TTipoDetalhamentoBD.Create; result := lTipoDetalhamentoBD.Todos(); end; function TTipoDetalhamento.TodosDoNumeroCampo: TObjectList; var lTipoDetalhamentoBD : TTipoDetalhamentoBD; begin lTipoDetalhamentoBD := TTipoDetalhamentoBD.Create; result := lTipoDetalhamentoBD.TodosDoNumeroCampo(self); end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} {$HPPEMIT '#pragma link "Data.Bind.DBLinks"'} {Do not Localize} unit Data.Bind.DBLinks; interface uses System.SysUtils, System.Classes, Data.Bind.Components, Data.Bind.DBScope, System.Bindings.Outputs, Data.DB; type TBaseBindDBControlLink = class(TContainedBindComponent) private function GetOnAssigningValue: TBindCompAssigningValueEvent; function GetOnEvalError: TBindCompEvalErrorEvent; procedure SetOnAssigningValue(const Value: TBindCompAssigningValueEvent); procedure SetOnEvalError(const Value: TBindCompEvalErrorEvent); function GetOnActivated: TNotifyEvent; function GetOnActivating: TNotifyEvent; procedure SetOnActivated(const Value: TNotifyEvent); procedure SetOnActivating(const Value: TNotifyEvent); function GetOnAssignedValue: TBindCompAssignedValueEvent; procedure SetOnAssignedValue(const Value: TBindCompAssignedValueEvent); protected procedure SetSourceControl(const Value: TCustomBindScopeDB); function GetSourceControl: TCustomBindScopeDB; procedure SetSourceMember(const Value: string); function GetSourceMember: string; function GetControlComponent: TComponent; override; procedure SetControlComponent(const Value: TComponent); override; public procedure GenerateExpressions; virtual; abstract; procedure UpdateColumns; virtual; abstract; procedure ClearGeneratedExpressions; virtual; abstract; function CanActivate: Boolean; virtual; abstract; function RequiresControlHandler: Boolean; virtual; abstract; function GetDelegate: TCommonBindComponent; virtual; abstract; property DataSource: TCustomBindScopeDB read GetSourceControl write SetSourceControl; property OnAssigningValue: TBindCompAssigningValueEvent read GetOnAssigningValue write SetOnAssigningValue; property OnAssignedValue: TBindCompAssignedValueEvent read GetOnAssignedValue write SetOnAssignedValue; property OnEvalError: TBindCompEvalErrorEvent read GetOnEvalError write SetOnEvalError; property OnActivating: TNotifyEvent read GetOnActivating write SetOnActivating; property OnActivated: TNotifyEvent read GetOnActivated write SetOnActivated; end; TBaseBindDBFieldLink = class(TBaseBindDBControlLink) private FBindLink: TCustomBindLink; function GetAutoActivate: Boolean; procedure SetAutoActivate(const Value: Boolean); function GetActive: Boolean; procedure SetActive(const Value: Boolean); protected public function GetDelegate: TCommonBindComponent; override; function CanActivate: Boolean; override; procedure ClearGeneratedExpressions; override; function RequiresControlHandler: Boolean; override; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property BindLink: TCustomBindLink read FBindLink; property FieldName: string read GetSourceMember write SetSourceMember; property AutoActivate: Boolean read GetAutoActivate write SetAutoActivate default True; property Active: Boolean read GetActive write SetActive; end; TBaseDBGridLinkColumn = class; TBaseDBGridLinkColumns = class; ICustomDBGrid = interface ['{E14CC39A-D660-4801-9FFB-7CA7F2B6A99F}'] function GetReadOnly: Boolean; function GetDataSet: TDataSet; function GetActive: Boolean; function GetDefaultFields: Boolean; function GetComponentState: TComponentState; function CreateColumns: TBaseDBGridLinkColumns; //function FindField(const AName: string): TField; procedure BeginUpdate; procedure CancelLayout; procedure EndUpdate; procedure BeginLayout; procedure EndLayout; procedure LayoutChanged; procedure InvalidateColumn(AColumn: TBaseDBGridLinkColumn); procedure InvalidateField(AField: TField); function AcquireLayoutLock: Boolean; property ReadOnly: Boolean read GetReadOnly; property DataSet: TDataSet read GetDataSet; property Active: Boolean read GetActive; property DefaultFields: Boolean read GetDefaultFields; property ComponentState: TComponentState read GetComponentState; end; IBindDBGridLinkControlManager = interface; TBaseBindDBGridLink = class(TBaseBindDBControlLink, ICustomDBGrid) private FBindGridLink: TCustomBindGridLink; FUpdateLock: Byte; FLayoutLock: Byte; function GetAutoActivate: Boolean; procedure SetAutoActivate(const Value: Boolean); procedure SetActive(const Value: Boolean); procedure InternalLayout; function GetBufferCount: Integer; procedure SetBufferCount(const Value: Integer); protected function GetColumns: TBaseDBGridLinkColumns; virtual; abstract; function GetBindDBColumnFactory(AGuid: TGuid): IInterface; virtual; function GetBindDBColumnManager: IBindDBGridLinkControlManager; virtual; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure ClearColumns(AManager: IBindDBGridLinkControlManager); virtual; { ICustomDBGrid } procedure BeginUpdate; procedure CancelLayout; procedure EndUpdate; function GetReadOnly: Boolean; function GetDataSet: TDataSet; function GetActive: Boolean; function GetDefaultFields: Boolean; function GetComponentState: TComponentState; function CreateColumns: TBaseDBGridLinkColumns; procedure BeginLayout; procedure EndLayout; function AcquireLayoutLock: Boolean; procedure LayoutChanged; procedure InvalidateColumn(AColumn: TBaseDBGridLinkColumn); virtual; procedure InvalidateField(AField: TField); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CanActivate: Boolean; override; function GetDelegate: TCommonBindComponent; override; procedure ClearGeneratedExpressions; override; property BindGridLink: TCustomBindGridLink read FBindGridLink; property Active: Boolean read GetActive write SetActive; property BufferCount: Integer read GetBufferCount write SetBufferCount default -1; property AutoActivate: Boolean read GetAutoActivate write SetAutoActivate default True; end; TBaseDBGridLinkColumn = class(TCollectionItem) private FField: TField; FFieldName: string; FStored: Boolean; function GetField: TField; function GetParentColumn: TBaseDBGridLinkColumn; procedure SetField(Value: TField); virtual; procedure SetFieldName(const Value: string); protected procedure Initialize; virtual; function GetGridIntf: ICustomDBGrid; function GetGrid: TComponent; function GetDisplayName: string; override; procedure SetIndex(Value: Integer); override; property IsStored: Boolean read FStored write FStored default True; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function DefaultAlignment: TAlignment; procedure RestoreDefaults; virtual; property Field: TField read GetField write SetField; property ParentColumn: TBaseDBGridLinkColumn read GetParentColumn; published property FieldName: string read FFieldName write SetFieldName; end; TDBGridLinkColumnsState = (csDefault, csCustomized); TBaseDBGridLinkColumnClass = class of TBaseDBGridLinkColumn; TBaseDBGridLinkColumns = class(TCollection) private FGrid: TComponent; function GetColumn(Index: Integer): TBaseDBGridLinkColumn; procedure SetColumn(Index: Integer; Value: TBaseDBGridLinkColumn); procedure SetState(NewState: TDBGridLinkColumnsState); function GetState: TDBGridLinkColumnsState; function GetDataSet: TDataSet; protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; function GetGridIntf: ICustomDBGrid; public constructor Create(Grid: TComponent; ColumnClass: TBaseDBGridLinkColumnClass); virtual; function Add: TBaseDBGridLinkColumn; function Updating: Boolean; procedure LoadFromFile(const Filename: string); procedure LoadFromStream(S: TStream); procedure RestoreDefaults; procedure RebuildColumns; procedure SaveToFile(const Filename: string); procedure SaveToStream(S: TStream); property State: TDBGridLinkColumnsState read GetState write SetState; property Grid: TComponent read FGrid; property BaseItems[Index: Integer]: TBaseDBGridLinkColumn read GetColumn write SetColumn; end; TDBGridLinkColumnExpressionPair = record private FControlExpression: string; FSourceExpression: string; public constructor Create(const AControlExpression, ASourceExpression: string); property ControlExpression: string read FControlExpression; property SourceExpression: string read FSourceExpression; end; TDBGridLinkColumnDescription = record private FColumnControl: TComponent; FColumnName: string; FColumnIndex: Integer; FSourceMemberName: string; FControlMemberName: string; FFormatCellExpressions: TArray<TDBGridLinkColumnExpressionPair>; FFormatColumnExpressions: TArray<TDBGridLinkColumnExpressionPair>; FParseCellExpressions: TArray<TDBGridLinkColumnExpressionPair>; public constructor Create(AColumnControl: TComponent; const AColumnName: string; AColumnIndex: Integer; const AControlMemberName, ASourceMemberName: string; AFormatColumnExpressions, AFormatCellExpressions, AParseCellExpression: TArray<TDBGridLinkColumnExpressionPair>); property ColumnControl: TComponent read FColumnControl; property ColumnName: string read FColumnName; property ColumnIndex: Integer read FColumnIndex; property SourceMemberName: string read FSourceMemberName; property ControlMemberName: string read FControlMemberName; property ParseCellExpression: TArray<TDBGridLinkColumnExpressionPair> read FParseCellExpressions; property FormatCellExpressions: TArray<TDBGridLinkColumnExpressionPair> read FFormatCellExpressions; property FormatColumnExpressions: TArray<TDBGridLinkColumnExpressionPair> read FFormatColumnExpressions; function IsEqual(const ADescription: TDBGridLinkColumnDescription): Boolean; end; IBindDBGridLinkControlManager = interface ['{F631C178-78F7-4164-A532-6F335760A26A}'] procedure BeginUpdate; procedure EndUpdate; procedure ClearColumns; function CanAddColumn(AColumn: TBaseDBGridLinkColumn): Boolean; overload; function CanAddColumn(AField: TField): Boolean; overload; function AddColumn(AColumn: TBaseDBGridLinkColumn): Integer; overload; function AddColumn(AField: TField): Integer; overload; procedure UpdateColumn(AColumn: TBaseDBGridLinkColumn; const ADescription: TDBGridLinkColumnDescription); overload; procedure UpdateColumn(AField: TField; const ADescription: TDBGridLinkColumnDescription); overload; function DescribeColumn(AIndex: Integer; AColumn: TBaseDBGridLinkColumn): TDBGridLinkColumnDescription; overload; function DescribeColumn(AIndex: Integer; AField: TField): TDBGridLinkColumnDescription; overload; end; TBindDBColumnFactory = class public constructor Create; virtual; function Supports(AIntf: TGuid; AGrid: TComponent): Boolean; virtual; abstract; function CreateFactory(AIntf: TGuid; AGrid: TComponent): IInterface; virtual; abstract; end; TBindDBColumnFactoryClass = class of TBindDBColumnFactory; procedure RegisterBindDBColumnFactory(AFactories: array of TBindDBColumnFactoryClass); procedure UnregisterBindDBColumnFactory(AFactories: array of TBindDBColumnFactoryClass); implementation uses Data.Bind.Consts, Generics.Collections, System.Bindings.Methods, System.Bindings.EvalProtocol, System.RTTI; type TInternalBindLink = class(TCustomBindLink) private FBindDBControlLink: TBaseBindDBControlLink; protected procedure ApplyComponents; override; function GetBindingsList: TCustomBindingsList; override; function CanActivate: Boolean; override; function RequiresControlHandler: Boolean; override; function DisplayName: string; override; function Designing: Boolean; override; function Loading: Boolean; override; function CanDesignActivate: Boolean; override; procedure DoOnActivating; override; procedure DoOnDeactivated; override; public constructor Create(ABindDBControlLink: TBaseBindDBControlLink); reintroduce; end; TInternalBindGridLink = class(TCustomBindGridLink, IBindLayoutChanged, IBindListRefresh, IBindListRefreshing) private FBindDBControlLink: TBaseBindDBControlLink; FListRefreshing: TNotifyEvent; protected procedure ApplyComponents; override; function GetBindingsList: TCustomBindingsList; override; function CanActivate: Boolean; override; function DisplayName: string; override; function Designing: Boolean; override; function Loading: Boolean; override; function CanDesignActivate: Boolean; override; procedure DoOnActivating; override; procedure DoOnDeactivated; override; { IBindLayoutChanged } procedure BindLayoutChanged; procedure IBindLayoutChanged.LayoutChanged = BindLayoutChanged; { IBindListRefresh } procedure RefreshList; function RefreshNeeded: Boolean; { IBindListRefreshing } function GetListRefreshing: TNotifyEvent; procedure SetListRefreshing(AEvent: TNotifyEvent); public constructor Create(ABindDBControlLink: TBaseBindDBControlLink); reintroduce; end; var FBindDBColumnFactories: TList<TBindDBColumnFactoryClass>; procedure RegisterBindDBColumnFactory(AFactories: array of TBindDBColumnFactoryClass); var LClass: TBindDBColumnFactoryClass; begin for LClass in AFactories do FBindDBColumnFactories.Add(LClass); end; procedure UnregisterBindDBColumnFactory(AFactories: array of TBindDBColumnFactoryClass); var LClass: TBindDBColumnFactoryClass; begin for LClass in AFactories do FBindDBColumnFactories.Remove(LClass); end; function GetBindDBColumnFactory(AGuid: TGuid; AGrid: TComponent): IInterface; var LClass: TBindDBColumnFactoryClass; LFactory: TBindDBColumnFactory; I: Integer; begin for I := FBindDBColumnFactories.Count - 1 downto 0 do begin LClass := FBindDBColumnFactories[I]; LFactory := LClass.Create; try if LFactory.Supports(AGuid, AGrid) then begin Result := LFactory.CreateFactory(AGuid, AGrid); Exit; end; finally LFactory.Free; end; end; Result := nil; end; { TInternalBindLink } function TInternalBindLink.CanActivate: Boolean; begin Result := FBindDBControlLink.CanActivate; end; function TInternalBindLink.CanDesignActivate: Boolean; begin Result := True; // Can show data at design time end; function TInternalBindLink.GetBindingsList: TCustomBindingsList; begin Result := FBindDBControlLink.BindingsList; end; function TInternalBindLink.Loading: Boolean; begin Result := csLoading in FBindDBControlLink.ComponentState; end; function TInternalBindLink.RequiresControlHandler: Boolean; begin Result := FBindDBControlLink.RequiresControlHandler; end; constructor TInternalBindLink.Create(ABindDBControlLink: TBaseBindDBControlLink); begin inherited Create(nil); FBindDBControlLink := ABindDBControlLink; end; function TInternalBindLink.Designing: Boolean; begin Result := csDesigning in FBindDBControlLink.ComponentState; end; function TInternalBindLink.DisplayName: string; begin Result := FBindDBControlLink.Name; end; procedure TInternalBindLink.DoOnActivating; begin // Must generate expression when dataset is active in // order to retrieve fields FBindDBControlLink.ClearGeneratedExpressions; FBindDBControlLink.GenerateExpressions; inherited; end; procedure TInternalBindLink.DoOnDeactivated; begin FBindDBControlLink.ClearGeneratedExpressions; inherited; end; procedure TInternalBindLink.ApplyComponents; begin inherited; end; { TInternalBindGridLink } function TInternalBindGridLink.CanActivate: Boolean; begin Result := FBindDBControlLink.CanActivate; end; function TInternalBindGridLink.CanDesignActivate: Boolean; begin Result := True; end; function TInternalBindGridLink.GetBindingsList: TCustomBindingsList; begin Result := FBindDBControlLink.BindingsList; end; function TInternalBindGridLink.GetListRefreshing: TNotifyEvent; begin Result := FListRefreshing; end; procedure TInternalBindGridLink.BindLayoutChanged; var LGrid: ICustomDBGrid; begin if Supports(FBindDBControlLink, ICustomDBGrid, LGrid) then begin if (csLoading in LGrid.ComponentState) then Exit; LGrid.LayoutChanged; end; end; function TInternalBindGridLink.Loading: Boolean; begin Result := csLoading in FBindDBControlLink.ComponentState; end; procedure TInternalBindGridLink.RefreshList; begin if Assigned(FListRefreshing) then FListRefreshing(Self); ResetGrid; end; function TInternalBindGridLink.RefreshNeeded: Boolean; var LEditor: IBindListEditor; LIntf: IScopeRecordEnumerable; LEnumerator: IScopeRecordEnumerator; begin Result := False; if (ControlComponent <> nil) then Supports(GetBindEditor(ControlComponent, IBindListEditor), IBindListEditor, LEditor) else LEditor := nil; if LEditor <> nil then if Supports(SourceComponent, IScopeRecordEnumerable, LIntf) then LEnumerator := LIntf.GetEnumerator('', BufferCount) else LEnumerator := nil; if (LEditor <> nil) and (LEnumerator <> nil) then Result := LEditor.UpdateNeeded(LEnumerator); end; procedure TInternalBindGridLink.SetListRefreshing(AEvent: TNotifyEvent); begin FListRefreshing := AEvent; end; constructor TInternalBindGridLink.Create(ABindDBControlLink: TBaseBindDBControlLink); begin inherited Create(nil); FBindDBControlLink := ABindDBControlLink; end; function TInternalBindGridLink.Designing: Boolean; begin Result := csDesigning in FBindDBControlLink.ComponentState; end; function TInternalBindGridLink.DisplayName: string; begin Result := FBindDBControlLink.Name; end; procedure TInternalBindGridLink.DoOnActivating; begin // Must generate expression when dataset is active in // order to retrieve fields FBindDBControlLink.ClearGeneratedExpressions; FBindDBControlLink.GenerateExpressions; inherited; end; procedure TInternalBindGridLink.DoOnDeactivated; begin FBindDBControlLink.ClearGeneratedExpressions; inherited; end; procedure TInternalBindGridLink.ApplyComponents; begin FBindDBControlLink.UpdateColumns; inherited; end; { TBindDBFieldLink } function TBaseBindDBFieldLink.CanActivate: Boolean; begin Result := (GetControlComponent <> nil) and (DataSource <> nil) and (FieldName <> ''); end; constructor TBaseBindDBFieldLink.Create(AOwner: TComponent); begin inherited; FBindLink := TInternalBindLink.Create(Self); end; destructor TBaseBindDBFieldLink.Destroy; begin FBindLink.Free; inherited; end; procedure TBaseBindDBFieldLink.ClearGeneratedExpressions; begin inherited; FBindLink.ParseExpressions.Clear; FBindLink.FormatExpressions.Clear; FBindLink.ClearExpressions.Clear; end; function TBaseBindDBFieldLink.GetActive: Boolean; begin Result := BindLink.Active; end; function TBaseBindDBFieldLink.GetDelegate: TCommonBindComponent; begin Result := FBindLink; end; function TBaseBindDBFieldLink.GetAutoActivate: Boolean; begin Result := FBindLink.AutoActivate; end; procedure TBaseBindDBFieldLink.Loaded; begin inherited; FBindLink.Loaded; end; function TBaseBindDBFieldLink.RequiresControlHandler: Boolean; begin Result := True; end; procedure TBaseBindDBFieldLink.SetActive(const Value: Boolean); begin BindLink.Active := Value; end; procedure TBaseBindDBFieldLink.SetAutoActivate(const Value: Boolean); begin FBindLink.AutoActivate := Value; end; { TBaseBindDBGridLink } function TBaseBindDBGridLink.AcquireLayoutLock: Boolean; begin Result := (FUpdateLock = 0) and (FLayoutLock = 0); if Result then BeginLayout; end; procedure TBaseBindDBGridLink.BeginLayout; begin BeginUpdate; if FLayoutLock = 0 then GetColumns.BeginUpdate; Inc(FLayoutLock); end; procedure TBaseBindDBGridLink.BeginUpdate; begin Inc(FUpdateLock); end; procedure TBaseBindDBGridLink.EndLayout; begin if FLayoutLock > 0 then begin try try if FLayoutLock = 1 then InternalLayout; finally if FLayoutLock = 1 then GetColumns.EndUpdate; end; finally Dec(FLayoutLock); EndUpdate; end; end; end; procedure TBaseBindDBGridLink.EndUpdate; begin if FUpdateLock > 0 then Dec(FUpdateLock); end; procedure TBaseBindDBGridLink.CancelLayout; begin if FLayoutLock > 0 then begin if FLayoutLock = 1 then GetColumns.EndUpdate; Dec(FLayoutLock); EndUpdate; end; end; function TBaseBindDBGridLink.CanActivate: Boolean; begin Result := (GetControlComponent <> nil) and (DataSource <> nil); end; constructor TBaseBindDBGridLink.Create(AOwner: TComponent); begin inherited; FBindGridLink := TInternalBindGridLink.Create(Self); end; function TBaseBindDBGridLink.CreateColumns: TBaseDBGridLinkColumns; begin Result := TBaseDBGridLinkColumns.Create(Self, TBaseDBGridLinkColumn); end; destructor TBaseBindDBGridLink.Destroy; begin FBindGridLink.Free; inherited; end; procedure TBaseBindDBGridLink.ClearColumns( AManager: IBindDBGridLinkControlManager); begin AManager.ClearColumns; end; procedure TBaseBindDBGridLink.ClearGeneratedExpressions; begin inherited; FBindGridLink.ColumnExpressions.Clear; FBindGridLink.FormatControlExpressions.Clear; FBindGridLink.ClearControlExpressions.Clear; FBindGridLink.PosSourceExpressions.Clear; FBindGridLink.PosControlExpressions.Clear; end; function TBaseBindDBGridLink.GetActive: Boolean; begin Result := FBindGridLink.Active; end; function TBaseBindDBGridLink.GetBindDBColumnFactory(AGuid: TGuid): IInterface; begin if ControlComponent <> nil then Result := Data.Bind.DBLinks.GetBindDBColumnFactory(AGuid, ControlComponent); end; function TBaseBindDBGridLink.GetBindDBColumnManager: IBindDBGridLinkControlManager; begin Supports(GetBindDBColumnFactory(IBindDBGridLinkControlManager), IBindDBGridLinkControlManager, Result); end; function TBaseBindDBGridLink.GetBufferCount: Integer; begin Result := FBindGridLink.BufferCount; end; function TBaseBindDBGridLink.GetComponentState: TComponentState; begin Result := Self.ComponentState; end; function TBaseBindDBGridLink.GetDataSet: TDataSet; begin Result := nil; if DataSource <> nil then if DataSource.DataSource <> nil then Result := DataSource.DataSource.DataSet; end; function TBaseBindDBGridLink.GetDefaultFields: Boolean; begin Result := True; if GetDataSet <> nil then Result := GetDataSet.DefaultFields; end; function TBaseBindDBGridLink.GetDelegate: TCommonBindComponent; begin Result := FBindGridLink; end; function TBaseBindDBGridLink.GetAutoActivate: Boolean; begin Result := FBindGridLink.AutoActivate; end; function TBaseBindDBGridLink.GetReadOnly: Boolean; begin Result := False; end; procedure TBaseBindDBGridLink.InvalidateColumn(AColumn: TBaseDBGridLinkColumn); begin LayoutChanged; end; procedure TBaseBindDBGridLink.InvalidateField(AField: TField); begin LayoutChanged; end; { InternalLayout is called with layout locks and column locks in effect } procedure TBaseBindDBGridLink.InternalLayout; begin if ([csLoading, csDestroying] * ComponentState) <> [] then Exit; UpdateColumns; FBindGridLink.ResetColumns; end; procedure TBaseBindDBGridLink.LayoutChanged; begin if AcquireLayoutLock then EndLayout; end; procedure TBaseBindDBGridLink.Loaded; begin inherited; FBindGridLink.Loaded; end; procedure TBaseBindDBGridLink.Notification(AComponent: TComponent; Operation: TOperation); var NeedLayout: Boolean; I: Integer; LDataSet: TDataSet; begin inherited; if (Operation = opRemove) then begin if (AComponent is TField) then begin LDataSet := GetDataSet; NeedLayout := (LDataSet <> nil) and (not (csDestroying in LDataSet.ComponentState)); if NeedLayout then BeginLayout; try for I := 0 to GetColumns.Count-1 do with GetColumns.BaseItems[I] do if Field = AComponent then begin Field := nil; end; finally if NeedLayout then EndLayout end; end; end; end; procedure TBaseBindDBGridLink.SetActive(const Value: Boolean); begin BindGridLink.Active := Value; end; procedure TBaseBindDBGridLink.SetAutoActivate(const Value: Boolean); begin FBindGridLink.AutoActivate := Value; end; procedure TBaseBindDBGridLink.SetBufferCount(const Value: Integer); begin FBindGridLink.BufferCount := Value; end; { TDBGridLinkColumnCollection } constructor TBaseDBGridLinkColumns.Create(Grid: TComponent; ColumnClass: TBaseDBGridLinkColumnClass); begin inherited Create(ColumnClass); FGrid := Grid; end; function TBaseDBGridLinkColumns.Add: TBaseDBGridLinkColumn; begin Result := TBaseDBGridLinkColumn(inherited Add); end; function TBaseDBGridLinkColumns.GetColumn(Index: Integer): TBaseDBGridLinkColumn; begin Result := TBaseDBGridLinkColumn(inherited Items[Index]); end; function TBaseDBGridLinkColumns.GetOwner: TPersistent; begin Result := FGrid; end; procedure TBaseDBGridLinkColumns.LoadFromFile(const Filename: string); var S: TFileStream; begin S := TFileStream.Create(Filename, fmOpenRead); try LoadFromStream(S); finally S.Free; end; end; type TColumnsWrapper = class(TComponent) private FColumns: TBaseDBGridLinkColumns; published property Columns: TBaseDBGridLinkColumns read FColumns write FColumns; end; procedure TBaseDBGridLinkColumns.LoadFromStream(S: TStream); var Wrapper: TColumnsWrapper; begin Wrapper := TColumnsWrapper.Create(nil); try Wrapper.Columns := (FGrid as ICustomDBGrid).CreateColumns; S.ReadComponent(Wrapper); Assign(Wrapper.Columns); finally Wrapper.Columns.Free; Wrapper.Free; end; end; procedure TBaseDBGridLinkColumns.RestoreDefaults; var I: Integer; begin BeginUpdate; try for I := 0 to Count-1 do BaseItems[I].RestoreDefaults; finally EndUpdate; end; end; function TBaseDBGridLinkColumns.GetDataSet: TDataSet; begin Result := (FGrid as ICustomDBGrid).DataSet; end; function TBaseDBGridLinkColumns.GetGridIntf: ICustomDBGrid; begin Supports(Grid, ICustomDBGrid, Result) end; procedure TBaseDBGridLinkColumns.RebuildColumns; procedure AddFields(Fields: TFields; Depth: Integer); var I: Integer; begin Inc(Depth); for I := 0 to Fields.Count-1 do begin Add.FieldName := Fields[I].FullName; if Fields[I].DataType in [ftADT, ftArray] then AddFields((Fields[I] as TObjectField).Fields, Depth); end; end; begin if GetDataSet <> nil then begin //FGrid.BeginLayout; try Clear; AddFields(GetDataSet.Fields, 0); finally //FGrid.EndLayout; end end else Clear; end; procedure TBaseDBGridLinkColumns.SaveToFile(const Filename: string); var S: TStream; begin S := TFileStream.Create(Filename, fmCreate); try SaveToStream(S); finally S.Free; end; end; procedure TBaseDBGridLinkColumns.SaveToStream(S: TStream); var Wrapper: TColumnsWrapper; begin Wrapper := TColumnsWrapper.Create(nil); try Wrapper.Columns := Self; S.WriteComponent(Wrapper); finally Wrapper.Free; end; end; procedure TBaseDBGridLinkColumns.SetColumn(Index: Integer; Value: TBaseDBGridLinkColumn); begin Items[Index].Assign(Value); end; procedure TBaseDBGridLinkColumns.SetState(NewState: TDBGridLinkColumnsState); begin if NewState = State then Exit; if NewState = csDefault then Clear else RebuildColumns; end; procedure TBaseDBGridLinkColumns.Update(Item: TCollectionItem); var Grid: ICustomDBGrid; begin Grid := GetGridIntf; if (FGrid = nil) or (csLoading in FGrid.ComponentState) then Exit; if Item = nil then begin Grid.LayoutChanged; end else begin Grid.InvalidateColumn(TBaseDBGridLinkColumn(Item)); end; end; function TBaseDBGridLinkColumns.Updating: Boolean; begin Result := Self.UpdateCount > 0; end; function TBaseDBGridLinkColumns.GetState: TDBGridLinkColumnsState; begin Result := TDBGridLinkColumnsState((Count > 0) and BaseItems[0].IsStored); end; { TDBGridLinkColumn } constructor TBaseDBGridLinkColumn.Create(Collection: TCollection); var Grid: ICustomDBGrid; begin if Assigned(Collection) and (Collection is TBaseDBGridLinkColumns) then Grid := TBaseDBGridLinkColumns(Collection).GetGridIntf; if Assigned(Grid) then Grid.BeginLayout; try inherited Create(Collection); Initialize; finally if Assigned(Grid) then Grid.EndLayout; end; end; destructor TBaseDBGridLinkColumn.Destroy; begin inherited Destroy; end; procedure TBaseDBGridLinkColumn.Initialize; begin FStored := True; end; procedure TBaseDBGridLinkColumn.Assign(Source: TPersistent); begin if Source is TBaseDBGridLinkColumn then begin if Assigned(Collection) then Collection.BeginUpdate; try RestoreDefaults; FieldName := TBaseDBGridLinkColumn(Source).FieldName; finally if Assigned(Collection) then Collection.EndUpdate; end; end else inherited Assign(Source); end; function TBaseDBGridLinkColumn.DefaultAlignment: TAlignment; begin if Assigned(Field) then Result := FField.Alignment else Result := taLeftJustify; end; function TBaseDBGridLinkColumn.GetField: TField; var Grid: ICustomDBGrid; begin { Returns Nil if FieldName can't be found in dataset } Grid := GetGridIntf; if (FField = nil) and (Length(FFieldName) > 0) and Assigned(Grid) and Assigned(Grid.DataSet) then with Grid.Dataset do if Active or (not DefaultFields) then SetField(FindField(FieldName)); Result := FField; end; function TBaseDBGridLinkColumn.GetGrid: TComponent; begin if Assigned(Collection) and (Collection is TBaseDBGridLinkColumns) then Result := TBaseDBGridLinkColumns(Collection).Grid else Result := nil; end; function TBaseDBGridLinkColumn.GetGridIntf: ICustomDBGrid; begin if Assigned(Collection) and (Collection is TBaseDBGridLinkColumns) then Result := TBaseDBGridLinkColumns(Collection).GetGridIntf else Result := nil; end; function TBaseDBGridLinkColumn.GetDisplayName: string; begin Result := FFieldName; if Result = '' then Result := inherited GetDisplayName; end; function TBaseDBGridLinkColumn.GetParentColumn: TBaseDBGridLinkColumn; var Col: TBaseDBGridLinkColumn; Fld: TField; I: Integer; begin Result := nil; Fld := Field; if (Fld <> nil) and (Fld.ParentField <> nil) and (Collection <> nil) then for I := Index - 1 downto 0 do begin Col := TBaseDBGridLinkColumn(Collection.Items[I]); if Fld.ParentField = Col.Field then begin Result := Col; Exit; end; end; end; procedure TBaseDBGridLinkColumn.RestoreDefaults; begin end; procedure TBaseDBGridLinkColumn.SetField(Value: TField); begin if FField = Value then Exit; if Assigned(FField) and (GetGrid <> nil) then FField.RemoveFreeNotification(GetGrid); if Assigned(Value) and (csDestroying in Value.ComponentState) then Value := nil; // don't acquire references to fields being destroyed FField := Value; if Assigned(Value) then begin if GetGrid <> nil then FField.FreeNotification(GetGrid); FFieldName := Value.FullName; end; if not IsStored then begin if Value = nil then FFieldName := ''; RestoreDefaults; end; Changed(False); end; procedure TBaseDBGridLinkColumn.SetFieldName(const Value: string); var AField: TField; Grid: ICustomDBGrid; begin AField := nil; Grid := GetGridIntf; if Assigned(Grid) and Assigned(Grid.DataSet) and not (csLoading in Grid.ComponentState) and (Length(Value) > 0) then AField := Grid.DataSet.FindField(Value); { no exceptions } FFieldName := Value; SetField(AField); Changed(False); end; procedure TBaseDBGridLinkColumn.SetIndex(Value: Integer); var LLayout: Boolean; Grid: ICustomDBGrid; // Fld: TField; I, OldIndex: Integer; // Col: TDBGridLinkColumn; begin OldIndex := Index; Grid := GetGridIntf; if IsStored then begin LLayout := False; if Assigned(Collection) and (Collection is TBaseDBGridLinkColumns) then if not TBaseDBGridLinkColumns(Collection).Updating then begin Grid.BeginLayout; LLayout := True; end; try I := OldIndex + 1; // move child columns along with parent while (I < Collection.Count) and (TBaseDBGridLinkColumn(Collection.Items[I]).ParentColumn = Self) do Inc(I); Dec(I); if OldIndex > Value then // column moving left begin while I > OldIndex do begin Collection.Items[I].Index := Value; Inc(OldIndex); end; inherited SetIndex(Value); end else begin inherited SetIndex(Value); while I > OldIndex do begin Collection.Items[OldIndex].Index := Value; Dec(I); end; end; finally if LLayout then Grid.EndLayout; end; end else Assert(False); // begin // if (Grid <> nil) and Grid.Active then // begin // if Grid.AcquireLayoutLock then // try // Col := Grid.ColumnAtDepth(Grid.Columns[Value], Depth); // if (Col <> nil) then // begin // Fld := Col.Field; // if Assigned(Fld) then // Field.Index := Fld.Index; // end; // finally // Grid.EndLayout; // end; // end; // inherited SetIndex(Value); // end; end; { TBindDBColumnFactory } constructor TBindDBColumnFactory.Create; begin // end; { TDBGridLinkColumnExpressionPair } constructor TDBGridLinkColumnExpressionPair.Create(const AControlExpression, ASourceExpression: string); begin FControlExpression := AControlExpression; FSourceExpression := ASourceExpression; end; { TDBGridLinkColumnDescription } constructor TDBGridLinkColumnDescription.Create(AColumnControl: TComponent; const AColumnName: string; AColumnIndex: Integer; const AControlMemberName, ASourceMemberName: string; AFormatColumnExpressions, AFormatCellExpressions, AParseCellExpression: TArray<TDBGridLinkColumnExpressionPair>); begin FColumnControl := AColumnControl; FColumnName := AColumnName; FColumnIndex := AColumnIndex; FControlMemberName := AControlMemberName; FSourceMemberName := ASourceMemberName; FFormatColumnExpressions := AFormatColumnExpressions; FFormatCellExpressions := AFormatCellExpressions; FParseCellExpressions := AParseCellExpression; end; function TDBGridLinkColumnDescription.IsEqual( const ADescription: TDBGridLinkColumnDescription): Boolean; function SameExpressions(AExpr1, AExpr2: TArray<TDBGridLinkColumnExpressionPair>): Boolean; var I:Integer; begin Result := Length(AExpr1) = Length(AExpr2); if Result then begin for I := 0 to Length(AExpr1)-1 do if (AExpr1[I].FControlExpression = AExpr2[I].FControlExpression) and (AExpr1[I].FSourceExpression = AExpr2[I].FSourceExpression) then begin end else Exit(False); end; end; begin Result := (Self.FColumnName = ADescription.FColumnName) and (Self.FColumnIndex = ADescription.FColumnIndex) and (Self.FSourceMemberName = ADescription.FSourceMemberName) and (Self.FControlMemberName = ADescription.FControlMemberName) and SameExpressions(Self.FFormatCellExpressions, ADescription.FFormatCellExpressions) and SameExpressions(Self.FFormatColumnExpressions, ADescription.FFormatColumnExpressions) and SameExpressions(Self.FParseCellExpressions, ADescription.FParseCellExpressions); end; { TBaseBindDBControlLink } function TBaseBindDBControlLink.GetControlComponent: TComponent; begin Result := GetDelegate.ControlComponent; end; function TBaseBindDBControlLink.GetOnActivated: TNotifyEvent; begin Result := GetDelegate.OnActivated; end; function TBaseBindDBControlLink.GetOnActivating: TNotifyEvent; begin Result := GetDelegate.OnActivating; end; function TBaseBindDBControlLink.GetOnAssigningValue: TBindCompAssigningValueEvent; begin Result := GetDelegate.OnAssigningValue; end; function TBaseBindDBControlLink.GetOnEvalError: TBindCompEvalErrorEvent; begin Result := GetDelegate.OnEvalError; end; function TBaseBindDBControlLink.GetOnAssignedValue: TBindCompAssignedValueEvent; begin Result := GetDelegate.OnAssignedValue; end; function TBaseBindDBControlLink.GetSourceControl: TCustomBindScopeDB; begin if GetDelegate.SourceComponent <> nil then Result := GetDelegate.SourceComponent as TCustomBindScopeDB else Result := nil; end; function TBaseBindDBControlLink.GetSourceMember: string; begin Result := GetDelegate.SourceMemberName; end; procedure TBaseBindDBControlLink.SetControlComponent(const Value: TComponent); begin GetDelegate.ControlComponent := Value; end; procedure TBaseBindDBControlLink.SetOnActivated(const Value: TNotifyEvent); begin GetDelegate.OnActivated := Value; end; procedure TBaseBindDBControlLink.SetOnActivating(const Value: TNotifyEvent); begin GetDelegate.OnActivating := Value; end; procedure TBaseBindDBControlLink.SetOnAssigningValue( const Value: TBindCompAssigningValueEvent); begin GetDelegate.OnAssigningValue := Value; end; procedure TBaseBindDBControlLink.SetOnEvalError( const Value: TBindCompEvalErrorEvent); begin GetDelegate.OnEvalError := Value; end; procedure TBaseBindDBControlLink.SetOnAssignedValue( const Value: TBindCompAssignedValueEvent); begin GetDelegate.OnAssignedValue := Value; end; procedure TBaseBindDBControlLink.SetSourceControl( const Value: TCustomBindScopeDB); begin GetDelegate.SourceComponent := Value; end; procedure TBaseBindDBControlLink.SetSourceMember(const Value: string); begin GetDelegate.SourceMemberName := Value; end; initialization FBindDBColumnFactories := TList<TBindDBColumnFactoryClass>.Create; finalization FBindDBColumnFactories.Free; end.
unit update; {$mode ObjFPC}{$H+} interface uses Classes, StrUtils, SysUtils, Windows, http; function GetLatestVersion: string; function GetVersionInfo(const FileName, Query: string): string; function CheckUpdate: Boolean; procedure ShowUpdate; function QueryUpdate: Boolean; implementation function GetLatestVersion: string; var Reader: TStrings; sLine: string; iPos: Int32; begin Reader := TStringList.Create; try Reader.Text := HTTPGet('https://github.com/tinydew4/NoadTalk/releases'); for sLine in Reader do begin iPos := Pos('/tag/', sLine); if iPos > 0 then begin Result := MidStr(sLine, iPos + 6, Length(sLine)); Result := LeftStr(Result, Pos('"', Result) - 1); Break; end; end; finally Reader.Free; end; end; function GetVersionInfo(const FileName, Query: string): string; var dwHandle: DWORD; dwVerInfoLength: DWORD; VerInfo: TBytes; dwValueLength: DWORD; Value: Pointer; sQuery: string; begin Result := ''; dwVerInfoLength := GetFileVersionInfoSize(PChar(FileName), dwHandle); SetLength(VerInfo, dwVerInfoLength); if not GetFileVersionInfo(PChar(FileName), 0, dwVerInfoLength, @VerInfo[0]) then Exit; if not VerQueryValue(@VerInfo[0], '\VarFileInfo\Translation', Value, dwValueLength) then Exit; sQuery := '\StringFileInfo\' + IntToHex(MakeLong(HiWord(Longint(Value^)), LoWord(Longint(Value^))), 8) + '\' + Query; if not VerQueryValue(@VerInfo[0], PChar(sQuery), Value, dwValueLength) then Exit; Result := StrPas(Value); end; function CheckUpdate: Boolean; begin Result := GetLatestVersion <> GetVersionInfo(ParamStr(0), 'FileVersion'); end; procedure ShowUpdate; begin ShellExecute(0, 'open', 'https://github.com/tinydew4/NoadTalk/releases', nil, nil, SW_SHOW); end; function QueryUpdate: Boolean; begin Result := False; if not CheckUpdate then Exit; if MessageBox(0, 'Update found. Want to check?', 'Update', MB_YESNO) <> IDYES then Exit; ShowUpdate; Result := True; end; end.
unit MendPrn; interface uses SysUtils, Windows, (*Buffer,*) MemMap, Classes; type //////////////////////////////////////////////// EFileOpen = class(Exception); /////////////////////////////////////////////// TPMCFG = packed record PinStatus: DWORD; end; TBuffer = class(TMemoryStream); TPM = class; TMPU = class; TOPU = class; TROM = class; /////////////////////////////////////////////////////////// TPM = class public constructor Create(FileName: string; Config: TPMCFG); destructor Destroy; override; private FConfig: TPMCFG; FMpu: TMPU; FOpu: TOPU; FRom: TROM; private function GetConfig: TPMCFG; procedure FreeMembers; public property Config: TPMCFG read GetConfig; end; ///////////////////////////////////////////////////// TMPU = class public constructor Create(var PM: TPM); destructor Destroy; override; private FPm: TPM; end; ///////////////////////////////////////////////////// TOPU = class public constructor Create(var PM: TPM); destructor Destroy; override; private FPm: TPM; end; ///////////////////////////////////////////////////// TROM = class(TObject) public constructor Create(FileName: string); destructor Destroy; override; function GetData(var Buf: TBuffer): LongInt; private FFileName: string; FMap: TMemMapFile; FPosition: Cardinal; function GetFileName: string; public property FileName: string read GetFileName; end; implementation { TPM } constructor TPM.Create(FileName: string; Config: TPMCFG); begin try FMpu := TMPU.Create(Self); FOpu := TOPU.Create(Self); FRom := TROM.Create(FileName); except on E: EFileOpen do raise; end; FConfig := Config; end; destructor TPM.Destroy; begin FreeMembers; inherited; end; procedure TPM.FreeMembers; begin if FMpu <> nil then begin FMpu.Free; FMpu := nil; end; if FOpu <> nil then begin FOpu.Free; FOpu := nil; end; if FRom <> nil then begin FRom.Free; FRom := nil; end; end; function TPM.GetConfig: TPMCFG; begin Result := FConfig; end; { TMPU } constructor TMPU.Create(var PM: TPM); begin FPm := PM; end; destructor TMPU.Destroy; begin inherited; end; { TOPU } constructor TOPU.Create(var PM: TPM); begin FPm := PM; end; destructor TOPU.Destroy; begin inherited; end; { TROM } constructor TROM.Create(FileName: string); begin try FMap := TMemMapFile.Create(FileName, fmOpenRead, 0, True); except raise EFileOpen.Create(FileName); end; end; destructor TROM.Destroy; begin if FMap <> nil then FMap.Free; inherited; end; function TROM.GetData(var Buf: TBuffer): LongInt; begin if not Assigned(Buf) then Buf := TBuffer.Create; end; function TROM.GetFileName: string; begin Result := FFileName; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Data.DBXMetaDataUtil; interface type TDBXMetaDataUtil = class public class function QuoteIdentifier(const UnquotedIdentifier: UnicodeString; const QuoteChar: UnicodeString; const QuotePrefix: UnicodeString; const QuoteSuffix: UnicodeString): UnicodeString; static; class function UnquotedIdentifier(const QuotedIdentifier: UnicodeString; const QuoteChar: UnicodeString; const QuotePrefix: UnicodeString; const QuoteSuffix: UnicodeString): UnicodeString; static; end; implementation uses Data.DBXPlatform, System.StrUtils, System.SysUtils; class function TDBXMetaDataUtil.QuoteIdentifier(const UnquotedIdentifier: UnicodeString; const QuoteChar: UnicodeString; const QuotePrefix: UnicodeString; const QuoteSuffix: UnicodeString): UnicodeString; var Buffer: TDBXStringBuffer; Index: Integer; From: Integer; QuotedIdentifier: UnicodeString; begin Buffer := TDBXStringBuffer.Create; Index := StringIndexOf(UnquotedIdentifier,QuoteSuffix); if (Index < 0) or (Length(QuoteSuffix) = 0) then begin Buffer.Append(QuotePrefix); Buffer.Append(UnquotedIdentifier); Buffer.Append(QuoteSuffix); end else begin Buffer.Append(QuoteChar); From := 0; Index := StringIndexOf(UnquotedIdentifier,QuoteChar); if Length(QuoteChar) > 0 then while Index >= 0 do begin IncrAfter(Index); Buffer.Append(Copy(UnquotedIdentifier,From+1,Index-(From))); Buffer.Append(QuoteChar); From := Index; Index := StringIndexOf(UnquotedIdentifier,QuoteChar,From); end; Buffer.Append(Copy(UnquotedIdentifier,From+1,Length(UnquotedIdentifier)-(From))); Buffer.Append(QuoteChar); end; QuotedIdentifier := Buffer.ToString; FreeAndNil(Buffer); Result := QuotedIdentifier; end; class function TDBXMetaDataUtil.UnquotedIdentifier(const QuotedIdentifier: UnicodeString; const QuoteChar: UnicodeString; const QuotePrefix: UnicodeString; const QuoteSuffix: UnicodeString): UnicodeString; var Identifier: UnicodeString; DoubleEndQuote: UnicodeString; Index: Integer; Buffer: TDBXStringBuffer; From: Integer; begin Identifier := QuotedIdentifier; if StringStartsWith(Identifier,QuotePrefix) and StringEndsWith(Identifier,QuoteSuffix) then Identifier := Copy(Identifier,Length(QuotePrefix)+1,Length(Identifier) - Length(QuoteSuffix)-(Length(QuotePrefix))) else if StringStartsWith(Identifier,QuoteChar) and StringEndsWith(Identifier,QuoteChar) then begin Identifier := Copy(Identifier,Length(QuotePrefix)+1,Length(Identifier) - Length(QuoteSuffix)-(Length(QuotePrefix))); DoubleEndQuote := QuoteChar + QuoteChar; Index := StringIndexOf(Identifier,DoubleEndQuote); if Index >= 0 then begin Buffer := TDBXStringBuffer.Create; From := 0; while Index >= 0 do begin Buffer.Append(Copy(Identifier,From+1,Index-(From))); Buffer.Append(QuoteChar); From := Index + Length(DoubleEndQuote); Index := StringIndexOf(Identifier,DoubleEndQuote,From); end; Buffer.Append(Copy(Identifier,From+1,Length(Identifier)-(From))); Identifier := Buffer.ToString; FreeAndNil(Buffer); end; end; Result := Identifier; end; end.
unit Getter.TrimBasics.FAT; interface uses SysUtils, Windows, Partition, Getter.TrimBasics, Getter.VolumeBitmap; type TFATTrimBasicsGetter = class(TTrimBasicsGetter) public function IsPartitionMyResponsibility: Boolean; override; function GetTrimBasicsToInitialize: TTrimBasicsToInitialize; override; private function GetLBAPerCluster: Cardinal; function GetPartitionSizeCoveredByBitmapInCluster: UInt64; function GetPartitionSizeInByte: UInt64; function GetPaddingLBA(LBAPerCluster: Integer): Integer; end; implementation { TFATTrimBasicsGetter } function TFATTrimBasicsGetter.IsPartitionMyResponsibility: Boolean; const FromFirst = 1; NotFound = 0; begin result := Pos('FAT', GetFileSystemName, FromFirst) > NotFound; end; function TFATTrimBasicsGetter.GetTrimBasicsToInitialize: TTrimBasicsToInitialize; begin result := inherited; result.LBAPerCluster := GetLBAPerCluster; result.PaddingLBA := GetPaddingLBA(result.LBAPerCluster); end; function TFATTrimBasicsGetter.GetPartitionSizeCoveredByBitmapInCluster: UInt64; var VolumeBitmapGetter: TVolumeBitmapGetter; FirstPointLCN: LARGE_INTEGER; begin VolumeBitmapGetter := TVolumeBitmapGetter.Create(GetPathOfFileAccessing); FirstPointLCN.QuadPart := 0; result := VolumeBitmapGetter.GetVolumeBitmap(FirstPointLCN).PositionSize. BitmapSize.QuadPart; FreeAndNil(VolumeBitmapGetter); end; function TFATTrimBasicsGetter.GetPartitionSizeInByte: UInt64; var Partition: TPartition; begin Partition := TPartition.Create(GetPathOfFileAccessing); result := Partition.PartitionLengthInByte; FreeAndNil(Partition); end; function TFATTrimBasicsGetter.GetLBAPerCluster: Cardinal; var NotUsed: Array[0..2] of Cardinal; begin GetDiskFreeSpace(PChar(GetPathOfFileAccessing + '\'), result, NotUsed[0], NotUsed[1], NotUsed[2]); end; function TFATTrimBasicsGetter.GetPaddingLBA(LBAPerCluster: Integer): Integer; var PartitionSizeInLBA: UInt64; PartitionSizeCoveredByBitmapInLBA: UInt64; begin PartitionSizeInLBA := GetPartitionSizeInByte div BytePerLBA; PartitionSizeCoveredByBitmapInLBA := GetPartitionSizeCoveredByBitmapInCluster * LBAPerCluster; result := PartitionSizeInLBA - PartitionSizeCoveredByBitmapInLBA; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1997,98 Inprise Corporation } { } {*******************************************************} unit VCLCom; interface uses ActiveX, ComObj, Classes; type { Component object factory } TComponentFactory = class(TAutoObjectFactory) public constructor Create(ComServer: TComServerObject; ComponentClass: TComponentClass; const ClassID: TGUID; Instancing: TClassInstancing; ThreadingModel: TThreadingModel = tmSingle); function CreateComObject(const Controller: IUnknown): TComObject; override; procedure UpdateRegistry(Register: Boolean); override; end; implementation type { VCL OLE Automation object } TVCLAutoObject = class(TAutoObject, IVCLComObject) private FComponent: TComponent; FOwnsComponent: Boolean; protected procedure FreeOnRelease; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; override; public constructor Create(Factory: TComObjectFactory; Component: TComponent); destructor Destroy; override; procedure Initialize; override; function ObjQueryInterface(const IID: TGUID; out Obj): HResult; override; end; { TVCLAutoObject } constructor TVCLAutoObject.Create(Factory: TComObjectFactory; Component: TComponent); begin FComponent := Component; CreateFromFactory(Factory, nil); end; destructor TVCLAutoObject.Destroy; begin if FComponent <> nil then begin FComponent.VCLComObject := nil; if FOwnsComponent then FComponent.Free; end; inherited Destroy; end; procedure TVCLAutoObject.FreeOnRelease; begin FOwnsComponent := True; end; procedure TVCLAutoObject.Initialize; begin inherited Initialize; if FComponent = nil then begin FComponent := TComponentClass(Factory.ComClass).Create(nil); FOwnsComponent := True; end; FComponent.VCLComObject := Pointer(IVCLComObject(Self)); end; function TVCLAutoObject.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; begin Result := DispInvoke(Pointer(Integer(FComponent) + TComponentFactory(Factory).DispIntfEntry^.IOffset), TComponentFactory(Factory).DispTypeInfo, DispID, Flags, TDispParams(Params), VarResult, ExcepInfo, ArgErr); end; function TVCLAutoObject.ObjQueryInterface(const IID: TGUID; out Obj): HResult; begin Result := inherited ObjQueryInterface(IID, Obj); if (Result <> 0) and (FComponent <> nil) then if FComponent.GetInterface(IID, Obj) then Result := 0; end; { TComponentFactory } constructor TComponentFactory.Create(ComServer: TComServerObject; ComponentClass: TComponentClass; const ClassID: TGUID; Instancing: TClassInstancing; ThreadingModel: TThreadingModel); begin inherited Create(ComServer, TAutoClass(ComponentClass), ClassID, Instancing, ThreadingModel); end; type TComponentProtectedAccess = class(TComponent); TComponentProtectedAccessClass = class of TComponentProtectedAccess; procedure TComponentFactory.UpdateRegistry(Register: Boolean); begin if Register then inherited UpdateRegistry(Register); TComponentProtectedAccessClass(ComClass).UpdateRegistry(Register, GUIDToString(ClassID), ProgID); if not Register then inherited UpdateRegistry(Register); end; function TComponentFactory.CreateComObject(const Controller: IUnknown): TComObject; begin Result := TVCLAutoObject.CreateFromFactory(Self, Controller); end; { Global routines } procedure CreateVCLComObject(Component: TComponent); begin TVCLAutoObject.Create(ComClassManager.GetFactoryFromClass( Component.ClassType), Component); end; initialization begin CreateVCLComObjectProc := CreateVCLComObject; end; finalization begin CreateVCLComObjectProc := nil; end; end.
unit BaseTests; interface uses SysUtils, Classes, Generics.Collections; type ETestError = class(EAbort) end; TLoggingObj = class(TObject) strict private FOnBeforeDestroy: TThreadProcedure; public constructor Create(const OnBeforeDestroy: TThreadProcedure); destructor Destroy; override; end; TLoggingObjDescendant = class(TLoggingObj) end; // Use class instance wrapper for detectong memory leaks TInteger = class private FValue: Integer; public constructor Create(Value: Integer); property Value: Integer read FValue write FValue; end; function IsEqual(L: TList<string>; const Collection: array of string): Boolean; implementation { TLoggingObj } constructor TLoggingObj.Create(const OnBeforeDestroy: TThreadProcedure); begin FOnBeforeDestroy := OnBeforeDestroy end; destructor TLoggingObj.Destroy; begin FOnBeforeDestroy(); inherited; end; { TInteger } constructor TInteger.Create(Value: Integer); begin FValue := Value end; function IsEqual(L: TList<string>; const Collection: array of string): Boolean; var I: Integer; begin Result := L.Count = Length(Collection); if Result then for I := 0 to L.Count-1 do if L[I] <> Collection[I] then Exit(False) end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.FlipView.Sliding; interface uses FMX.Presentation.Style, FMX.Controls.Presentation, FMX.Ani, FMX.Graphics, FMX.Objects, FMX.Controls, FMX.Types, FMX.Presentation.Messages, FGX.FlipView, FGX.FlipView.Presentation, FGX.FlipView.Types; type { TfgFlipViewSlidingPresentation } TfgFlipViewSlidingPresentation = class(TfgStyledFlipViewBasePresentation) private [Weak] FNextImageContainer: TImage; FNextImageAnimator: TRectAnimation; FImageAnimator: TRectAnimation; procedure HandlerFinishAnimation(Sender: TObject); protected { Messages From Model} procedure MMSlideOptionsChanged(var AMessage: TDispatchMessage); message TfgFlipViewMessages.MM_SLIDE_OPTIONS_CHANGED; protected procedure InitAnimatorParams(const ADirection: TfgDirection); { Styles } procedure ApplyStyle; override; procedure FreeStyle; override; public procedure ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection; const AAnimate: Boolean); override; end; implementation uses System.Classes, System.Types, FMX.Presentation.Factory, FGX.Asserts; { TfgFlipViewSlidingPresentation } procedure TfgFlipViewSlidingPresentation.ApplyStyle; var StyleObject: TFmxObject; NewImage: TBitmap; begin inherited ApplyStyle; { Image container for last slide } if ImageContainer <> nil then begin ImageContainer.Visible := True; NewImage := Model.CurrentImage; if NewImage <> nil then ImageContainer.Bitmap.Assign(Model.CurrentImage); end; { Image container for new slide } StyleObject := FindStyleResource('image-next'); if (StyleObject <> nil) and (StyleObject is TImage) then begin FNextImageContainer := TImage(StyleObject); FNextImageContainer.Visible := False; end; if (ImageContainer <> nil) and (FNextImageContainer <> nil) then begin FImageAnimator := TRectAnimation.Create(nil); FImageAnimator.Parent := ImageContainer; FImageAnimator.Enabled := False; FImageAnimator.Stored := False; FImageAnimator.PropertyName := 'Margins'; FImageAnimator.Duration := Model.SlideOptions.Duration; FImageAnimator.OnFinish := HandlerFinishAnimation; FNextImageAnimator := TRectAnimation.Create(nil); FNextImageAnimator.Parent := FNextImageContainer; FNextImageAnimator.Enabled := False; FNextImageAnimator.Stored := False; FNextImageAnimator.PropertyName := 'Margins'; FNextImageAnimator.Duration := Model.SlideOptions.Duration; end; end; procedure TfgFlipViewSlidingPresentation.FreeStyle; begin FImageAnimator := nil; FNextImageAnimator := nil; inherited FreeStyle; end; procedure TfgFlipViewSlidingPresentation.HandlerFinishAnimation(Sender: TObject); begin try if (FNextImageContainer <> nil) and (ImageContainer <> nil) then begin ImageContainer.Bitmap.Assign(FNextImageContainer.Bitmap); ImageContainer.Margins.Rect := TRectF.Empty; end; if FNextImageAnimator <> nil then FNextImageContainer.Visible := False; finally Model.FinishChanging; end; end; procedure TfgFlipViewSlidingPresentation.InitAnimatorParams(const ADirection: TfgDirection); procedure InitHorizontalShifting(out AFirstContainerMarginsRect, ANextContainerMarginsRect: TRectF); var Offset: Extended; begin case ADirection of TfgDirection.Forward: Offset := ImageContainer.Width; TfgDirection.Backward: Offset := -ImageContainer.Width; else Offset := ImageContainer.Width; end; AFirstContainerMarginsRect := TRectF.Create(-Offset, 0, Offset, 0); ANextContainerMarginsRect := TRectF.Create(Offset, 0, -Offset, 0); end; procedure InitVerticalShifting(out AFirstContainerMarginsRect, ANextContainerMarginsRect: TRectF); var Offset: Extended; begin case ADirection of TfgDirection.Forward: Offset := ImageContainer.Height; TfgDirection.Backward: Offset := -ImageContainer.Height; else Offset := ImageContainer.Height; end; AFirstContainerMarginsRect := TRectF.Create(0, -Offset, 0, Offset); ANextContainerMarginsRect := TRectF.Create(0, Offset, 0, -Offset); end; var FirstContainerMarginsRect: TRectF; NextContainerMarginsRect: TRectF; begin AssertIsNotNil(Model); AssertIsNotNil(FImageAnimator); AssertIsNotNil(FNextImageAnimator); AssertIsNotNil(ImageContainer); case Model.SlideOptions.Direction of TfgSlideDirection.Horizontal: InitHorizontalShifting(FirstContainerMarginsRect, NextContainerMarginsRect); TfgSlideDirection.Vertical: InitVerticalShifting(FirstContainerMarginsRect, NextContainerMarginsRect); end; FImageAnimator.StartValue.Rect := TRectF.Empty; FImageAnimator.StopValue.Rect := FirstContainerMarginsRect; FNextImageAnimator.StartValue.Rect := NextContainerMarginsRect; FNextImageAnimator.StopValue.Rect := TRectF.Empty; end; procedure TfgFlipViewSlidingPresentation.MMSlideOptionsChanged(var AMessage: TDispatchMessage); begin AssertIsNotNil(Model); AssertIsNotNil(Model.SlideOptions); if FImageAnimator <> nil then FImageAnimator.Duration := Model.SlideOptions.Duration; if FNextImageAnimator <> nil then FNextImageAnimator.Duration := Model.SlideOptions.Duration; end; procedure TfgFlipViewSlidingPresentation.ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection; const AAnimate: Boolean); begin AssertIsNotNil(Model); inherited; if (csDesigning in ComponentState) or not AAnimate then begin if ImageContainer <> nil then ImageContainer.Bitmap.Assign(Model.CurrentImage); Model.FinishChanging; end else begin if (FNextImageContainer <> nil) and (FNextImageAnimator <> nil) and (FImageAnimator <> nil) then begin FNextImageContainer.Bitmap.Assign(Model.CurrentImage); InitAnimatorParams(ADirection); FImageAnimator.Start; FNextImageContainer.Visible := True; FNextImageAnimator.Start; end; end; end; initialization TPresentationProxyFactory.Current.Register('fgFlipView-Sliding', TStyledPresentationProxy<TfgFlipViewSlidingPresentation>); finalization TPresentationProxyFactory.Current.Unregister('fgFlipView-Sliding', TStyledPresentationProxy<TfgFlipViewSlidingPresentation>); end.
unit func_ccreg_set64; interface implementation type TEnum64 = (_a00,_a01,_a02,_a03,_a04,_a05,_a06,_a07,_a08,_a09,_a10,_a11,_a12,_a13,_a14,_a15,_a16,_a17,_a18,_a19,_a20,_a21,_a22,_a23,_a24,_a25,_a26,_a27,_a28,_a29,_a30,_a31, _a32,_a33,_a34,_a35,_a36,_a37,_a38,_a39,_a40,_a41,_a42,_a43,_a44,_a45,_a46,_a47,_a48,_a49,_a50,_a51,_a52,_a53,_a54,_a55,_a56,_a57,_a58,_a59,_a60,_a61,_a62,_a63); TSet64 = packed set of TEnum64; function F(a: TSet64): TSet64; external 'CAT' name 'func_ccreg_set64'; var a, r: TSet64; procedure Test; begin a := [_a01]; R := F(a); Assert(a = r); end; initialization Test(); finalization end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC: HDC; hrc: HGLRC; uTimerId : uint; Quadric : GLUquadricObj; LightPos : Array [0..3] of GLfloat; Delta : GLfloat; procedure Init; procedure SetDCPixelFormat; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; const Sphere = 1; var frmGL: TfrmGL; implementation uses mmSystem; {$R *.DFM} {======================================================================= Инициализация} procedure TfrmGL.Init; begin glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glColor3f (0.0, 1.0, 1.0); Quadric := gluNewQuadric; glNewList (Sphere, GL_COMPILE); gluSphere (Quadric, 1.5, 24, 24); glEndList; end; {======================================================================= Рисование картинки} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint(Handle, ps); glClear( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); glLightfv(GL_LIGHT0, GL_POSITION, @LightPos); glCallList(Sphere); SwapBuffers(DC); EndPaint(Handle, ps); end; {======================================================================= Обработка таймера} procedure FNTimeCallBack(uTimerID, uMessage: UINT;dwUser, dw1, dw2: DWORD) stdcall; begin With frmGL do begin LightPos[0] := LightPos[0] + Delta; If LightPos[0] > 15.0 then Delta := -1.0 else If (LightPos[0] < -15.0) then Delta := 1.0; InvalidateRect(Handle, nil, False); end; end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); Delta := 1.0; LightPos [0] := 10.0; LightPos [1] := 10.0; LightPos [2] := 10.0; LightPos [3] := 1.0; Init; uTimerID := timeSetEvent (15, 0, @FNTimeCallBack, 0, TIME_PERIODIC); end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight ); glMatrixMode(GL_PROJECTION); glLoadIdentity; glFrustum(-1.0, 1.0, -1.0, 1.0, 5.0, 25.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glTranslatef( 0.0, 0.0, -12.0 ); InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin timeKillEvent(uTimerID); glDeleteLists (sphere, 1); gluDeleteQuadric (Quadric); wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); end; {======================================================================= Обработка нажатия клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; end.
unit FC.StockData.StockDataSourceRegistry; interface uses Classes,SysUtils, FC.Definitions, FC.StockData.StockDataSource; type TStockLoadedDataSourceRegistry = class private FDataSources: TList; function GetDataSource(index: integer): TStockDataSource_B; public function DataSourceCount: integer; property DataSources[index: integer]: TStockDataSource_B read GetDataSource; procedure AddDataSource(aDataSource: TStockDataSource_B); procedure RemoveDataSource(aDataSource: TStockDataSource_B); function FindDataSourceObject(const ConnectionString: string; aClass:TClass; const aSymbol: string; aInterval: TStockTimeInterval; const aTag: string): TStockDataSource_B; constructor Create; destructor Destroy; override; end; function StockLoadedDataSourceRegistry: TStockLoadedDataSourceRegistry; implementation var gSLDRegistry: TStockLoadedDataSourceRegistry; function StockLoadedDataSourceRegistry: TStockLoadedDataSourceRegistry; begin if gSLDRegistry = nil then gSLDRegistry:=TStockLoadedDataSourceRegistry.Create; result:=gSLDRegistry; end; { TStockLoadedDataSourceRegistry } constructor TStockLoadedDataSourceRegistry.Create; begin FDataSources:=TList.Create; end; procedure TStockLoadedDataSourceRegistry.AddDataSource(aDataSource: TStockDataSource_B); begin FDataSources.Add(aDataSource) end; function TStockLoadedDataSourceRegistry.DataSourceCount: integer; begin result:=FDataSources.Count; end; function TStockLoadedDataSourceRegistry.GetDataSource(index: integer): TStockDataSource_B; begin result:=FDataSources[index]; end; destructor TStockLoadedDataSourceRegistry.Destroy; begin FreeAndNil(FDataSources); inherited; end; procedure TStockLoadedDataSourceRegistry.RemoveDataSource(aDataSource: TStockDataSource_B); begin FDataSources.Remove(aDataSource); end; function TStockLoadedDataSourceRegistry.FindDataSourceObject(const ConnectionString: string; aClass:TClass; const aSymbol: string; aInterval: TStockTimeInterval; const aTag: string): TStockDataSource_B; var i: integer; aDS: TStockDataSource_B; begin result:=nil; for i:=0 to DataSourceCount-1 do begin aDS:=GetDataSource(i); if (TObject(FDataSources[i]) is aClass) then if (aDS.Connection<>nil) and (aDS.Connection.ConnectionString=ConnectionString) and (aDS.Tag=aTag) then if aDS.StockSymbol.IsEqual(aSymbol,aInterval) then begin result:=FDataSources[i]; break; end; end; end; initialization finalization FreeAndNil(gSLDRegistry); end.
{*********************************************} { TeeBI Software Library } { TStringArray and helper type } { Copyright (c) 2015-2017 by Steema Software } { All Rights Reserved } {*********************************************} unit BI.Arrays.Strings; interface // TStringArray is a lightweight "array of string", // similar to BI.Arrays TTextArray type. // Main purpose of TStringArray is to implement a "Split" function syntax // compatible with all versions of both FreePascal and Delphi (VCL and FMX) type TStringArray=Array of String; TStringArrayHelper=record helper for TStringArray public procedure Add(const S:String); function Count:Integer; inline; class function Split(const S,Delimiter:String):TStringArray; overload; static; class function Split(const S:String; const Delimiter:Char):TStringArray; overload; static; class function Split(const S:String; const Delimiter,Quote:Char):TStringArray; overload; static; end; TArrayOfStrings=TStringArray; implementation
PROGRAM CLEANUSR; USES FileOps; CONST errorlogfile = 'IDERR.LOG'; TYPE UserIDString = String[10]; UserIDNodePtr = ^UserIDNode; UserIDNode = RECORD UserIDNum : UserIDString; Next : UserIDNodePtr; END; SecArray = ARRAY[0..99] OF UserIDNodePtr; VAR UserID : UserIDString; Instr : String; UserIDList : SecArray; ExitSave, heap : POINTER; IDFile, IDFile2, errlog : text; { input parameters } PriceStart, PriceLength, FactorStart, FactorLength, UserIDStart, UserIDLength : WORD; ReadFile : String; (* ---------------------------------------------- *) PROCEDURE Help; BEGIN Writeln('usage: CLEANUSR FileName'); Writeln('Error report will be in ',errorlogfile); HALT; END; (* ---------------------------------------------- *) PROCEDURE Setup; VAR err : INTEGER; BEGIN ReadFile := Paramstr(1); IF (paramcount = 0) OR (ReadFile[1] = '?') THEN Help; { prepare error log} assign(errlog,errorlogfile); rewrite(errlog); writeln(errlog,'DUPLICATE ID NUMBERS KILLED'); writeln(errlog); IF NOT exist(ReadFile) THEN BEGIN Writeln(ReadFile,' not found!'); Help; END; assign(IdFile,ReadFile); reset(IDFile); assign(IdFile2,'temp.txt'); rewrite(IDFile2); END; (* ---------------------------------------------- *) PROCEDURE InitNodes; VAR n : BYTE; BEGIN Mark(heap); FOR n := 0 TO 99 DO UserIDList[n] := NIL; END; (* ---------------------------------------------- *) FUNCTION UserIDWasDone(UserIDStr : UserIDString) : BOOLEAN; { build a linked list of UserIDs found } { scan linked list to see if UserID is present, { add if not, return FALSE. Return TRUE if it is } { also return TRUE on Error - assume error has } { already been done so no action will be taken } VAR err, nodecount, index : INTEGER; UserIDNode, Node : UserIDNodePtr; Done, FoundUserID : BOOLEAN; BEGIN FoundUserID := FALSE; Done := FALSE; nodecount := 0; err := 0; val(copy(UserIDStr,1,2),index,err); IF err > 0 THEN UserIDWasDone := TRUE ELSE BEGIN Node := UserIDList[index]; IF NOT (Node = NIL) THEN { array index points to something } REPEAT inc(NodeCount); IF (Node^.UserIDNum = UserIDStr) THEN BEGIN FoundUserID := TRUE; Done := TRUE; END ELSE IF Node^.Next = NIL THEN Done := TRUE ELSE Node := Node^.Next; UNTIL Done; IF NOT FoundUserID THEN BEGIN New(UserIDNode); UserIDNode^.UserIDNum := UserIDStr; UserIDNode^.Next := NIL; IF (Node = NIL) THEN {first item in list} UserIDList[index] := UserIDNode ELSE { somewhere down the list } Node^.Next := UserIDNode; END; UserIDWasDone := FoundUserID; END {if err <> 0}; END; (* ---------------------------------------------- *) FUNCTION ExtractIDString(instr : STRING) : UserIDString; { user id string is 5 numbers followed by ',' followed by } { 1 to 4 numbers followed by a space } CONST Id1Len = 5; VAR i, err, testnum, strstop : INTEGER; FoundID : BOOLEAN; Id1, Id2 : STRING[5]; BEGIN strstop := length(instr)-Id1Len; i := 1; FoundID := FALSE; REPEAT ID1 := copy(instr,i,Id1Len); val(ID1,testnum,err); IF (err = 0) THEN BEGIN IF (copy(instr,i+Id1Len,1) = ',') THEN BEGIN ID2 := copy(instr,i+6,5); ID2 := copy(ID2,1,pos(' ',ID2)-1); val(ID2,testnum,err); IF (err = 0) THEN FoundID := TRUE; END; END; INC(i); UNTIL FoundID or (i > strstop); IF FoundID THEN ExtractIDString := ID1 + ID2 ELSE ExtractIDString := '00'+ copy(instr,1,8); END {ExtractIDString}; (* ---------------------------------------------- *) PROCEDURE KillDupes; VAR IdStr, instr : STRING; BEGIN WHILE NOT eof(IDFile) DO BEGIN readln(IdFile,instr); IdStr := ExtractIDString(instr); IF NOT UserIDWasDone(IdStr) THEN Writeln(IDFile2,instr) ELSE Writeln('duplicate ',instr); END {DO}; END; (* ---------------------------------------------- *) (* ---------------------------------------------- *) PROCEDURE Finish; BEGIN Release(Heap); Close(errlog); Close(IDFile); END; (* ---------------------------------------------- *) BEGIN Setup; InitNodes; KillDupes; Finish; END.
unit FastDemo; interface //线程安全版本 uses Windows, SysUtils; const CONST_BYTE_SIZE = 4; CONST_PAGE_SINGLE = 1024; COSNT_PAGE_SINGLE_SIZE = CONST_PAGE_SINGLE * CONST_BYTE_SIZE; type TFastQueue = class private FCS: TRTLCriticalSection; // FMem: Pointer; FTmpMem: Pointer; // FPushIndex: Integer; //压入队列计数器 FPopIndex: Integer; //弹出队列计数器 FCapacity: Integer; //队列容量,始终大于 FPushIndex // procedure Lock(); procedure UnLock(); procedure SetCapacity(const AValue: Integer); // procedure setSynCapacity(const AValue: Integer); function getSynCapacity: Integer; function getSynCurCount: Integer; public constructor Create(AInitCapacity: Integer = CONST_PAGE_SINGLE); destructor Destroy(); override; // function Push(AItem: Pointer): Pointer; function Pop(): Pointer; function PushString(AItem: string): Pointer; function PopString(): string; procedure Clear; public property Capacity: Integer read getSynCapacity write setSynCapacity; property Count: Integer read getSynCurCount; end; implementation { TFastQueue } constructor TFastQueue.Create(AInitCapacity: Integer); begin InitializeCriticalSection(FCS); FPushIndex := 0; FPopIndex := 0; if AInitCapacity < CONST_PAGE_SINGLE then AInitCapacity := CONST_PAGE_SINGLE; SetCapacity(AInitCapacity); end; destructor TFastQueue.Destroy; begin FreeMem(FMem); if FTmpMem <> nil then FreeMem(FTmpMem); DeleteCriticalSection(FCS); inherited; end; procedure TFastQueue.Lock; begin EnterCriticalSection(FCS); end; procedure TFastQueue.UnLock; begin LeaveCriticalSection(FCS); end; procedure TFastQueue.SetCapacity(const AValue: Integer); var vPageCount, vOldSize, vNewSize: Integer; begin if AValue > FCapacity then begin if FTmpMem <> nil then FreeMem(FTmpMem); vPageCount := AValue div CONST_PAGE_SINGLE; if (AValue mod CONST_PAGE_SINGLE) > 0 then Inc(vPageCount); //保存旧的容量 vOldSize := FCapacity * CONST_BYTE_SIZE; //计算新的容量 FCapacity := vPageCount * CONST_PAGE_SINGLE; vNewSize := FCapacity * CONST_BYTE_SIZE; //扩容 GetMem(FTmpMem, vNewSize); FillChar(FTmpMem^, vNewSize, #0); //转移数据 if FMem <> nil then begin Move(FMem^, FTmpMem^, vOldSize); FreeMem(FMem); end; FMem := FTmpMem; //FTmpMem (保证弹出、插入数据时使用) 与 FMem 大小一致 GetMem(FTmpMem, vNewSize); end; end; function TFastQueue.Push(AItem: Pointer): Pointer; var vPMem: PInteger; vNextPriority, vPriority, vIndex: Integer; vNotPushed: boolean; begin Lock(); try vPMem := PInteger(FMem); Inc(vPMem, FPushIndex); vPMem^ := Integer(AItem); Inc(FPushIndex); //检测栈容量是否足够(至少保留一位空位,否则扩容 1024) if FPushIndex >= FCapacity then begin SetCapacity(FCapacity + CONST_PAGE_SINGLE); end; finally UnLock(); end; end; function TFastQueue.Pop: Pointer; procedure MoveMem(); var vvPSrc: PInteger; vvTmpMem: Pointer; begin FillChar(FTmpMem^, FCapacity * CONST_BYTE_SIZE, #0); vvPSrc := PInteger(FMem); Inc(vvPSrc, FPopIndex); Move(vvPSrc^, FTmpMem^, (FCapacity - FPopIndex) * CONST_BYTE_SIZE); //交换指针 vvTmpMem := FMem; FMem := FTmpMem; FTmpMem := vvTmpMem; end; var vPMem: PInteger; begin Lock(); try Result := nil; if (FPopIndex = FPushIndex) then Exit; // 1.获取弹出元素 vPMem := PInteger(FMem); Inc(vPMem, FPopIndex); Result := Pointer(vPMem^); // 2.弹出元素后 弹出计数器 +1 Inc(FPopIndex); // 3.队列底部空余内存达到 1024 整体迁移 if FPopIndex = CONST_PAGE_SINGLE then begin //迁移数据 MoveMem(); //重置弹出位置 FPopIndex := 0; //减少压入队列的数量 Dec(FPushIndex, CONST_PAGE_SINGLE); end; finally UnLock(); end; end; function TFastQueue.PushString(AItem: string): Pointer; var vPChar: PChar; begin vPChar := StrAlloc(256); StrCopy(vPChar, pchar(AItem + ' |' + inttostr(FPushIndex))); Push(vPChar); end; function TFastQueue.PopString: string; var vPChar: PChar; begin Result := 'nil'; vPChar := Pop; if vPChar <> '' then begin Result := vPChar; StrDispose(vPChar); end; end; procedure TFastQueue.Clear; begin Lock(); try FPushIndex := 0; FPopIndex := 0; SetCapacity(CONST_PAGE_SINGLE); finally UnLock(); end; end; procedure TFastQueue.setSynCapacity(const AValue: Integer); begin Lock(); try SetCapacity(AValue); finally UnLock(); end; end; function TFastQueue.getSynCapacity: Integer; begin Lock(); try Result := FCapacity; finally UnLock(); end; end; function TFastQueue.getSynCurCount: Integer; begin Lock(); try Result := FPushIndex - FPopIndex; finally UnLock(); end; end; end.
{ @abstract(Interfaces and support VCL classes for GMLib.) @author(Xavier Martinez (cadetill) <cadetill@gmail.com>) @created(Novembre 18, 2015) @lastmod(Novembre 18, 2015) The GMClasses.VCL unit provides access to VCL interfaces and VCL base classes used into GMLib. } unit GMClasses.VCL; {$I ..\..\gmlib.inc} interface uses {$IFDEF DELPHIXE2} Vcl.Graphics; {$ELSE} Graphics; {$ENDIF} type { -------------------------------------------------------------------------- } // @include(..\..\docs\GMClasses.VCL.TGMTransformVCL.txt) TGMTransformVCL = record public // @include(..\..\docs\GMClasses.VCL.TGMTransformVCL.TColorToStr.txt) class function TColorToStr(Color: TColor): string; static; end; implementation uses {$IFDEF DELPHIXE2} System.SysUtils, Winapi.Windows; {$ELSE} SysUtils, Windows; {$ENDIF} { TGMTransformVCL } class function TGMTransformVCL.TColorToStr(Color: TColor): string; function GetRValue(rgb: LongWord): Byte; begin Result := Byte(rgb); end; function GetGValue(rgb: LongWord): Byte; begin Result := Byte(rgb shr 8); end; function GetBValue(rgb: LongWord): Byte; begin Result := Byte(rgb shr 16); end; var tmpRGB: LongWord; begin tmpRGB := ColorToRGB(Color); Result := Format('#%.2x%.2x%.2x', [GetRValue(tmpRGB), GetGValue(tmpRGB), GetBValue(tmpRGB)]); end; end.
unit Component.ProgressSection; interface uses Classes, Component.ButtonGroup; type TProgressToApply = record ProgressValue: Integer; ProgressCaption: String; SpeedCaption: String; end; TProgressSection = class private ThreadToSynchronize: TThread; ProgressToApply: TProgressToApply; procedure SetEnabledPropertyTo(Enabled: Boolean; ButtonGroupEntry: TButtonGroupEntry); procedure SynchronizedApplyProgress; procedure SynchronizedHideProgress; procedure SynchronizedShowProgress; public constructor Create(ThreadToSynchronize: TThread); procedure HideProgress; procedure ShowProgress; procedure ChangeProgress(ProgressToApply: TProgressToApply); end; implementation uses Form.Main; procedure TProgressSection.SetEnabledPropertyTo(Enabled: Boolean; ButtonGroupEntry: TButtonGroupEntry); begin ButtonGroupEntry.ImageButton.Enabled := Enabled; ButtonGroupEntry.LabelButton.Enabled := Enabled; end; procedure TProgressSection.SynchronizedShowProgress; var CurrentButtonGroupEntry: TButtonGroupEntry; begin fMain.DisableSSDLabel; for CurrentButtonGroupEntry in fMain.GetButtonGroup do SetEnabledPropertyTo(false, CurrentButtonGroupEntry); fMain.iHelp.Enabled := false; fMain.lHelp.Enabled := false; fMain.gDownload.Visible := true; fMain.OpenButtonGroup; end; procedure TProgressSection.HideProgress; begin if ThreadToSynchronize <> nil then TThread.Synchronize(ThreadToSynchronize, SynchronizedHideProgress) else SynchronizedHideProgress; end; procedure TProgressSection.ShowProgress; begin if ThreadToSynchronize <> nil then TThread.Synchronize(ThreadToSynchronize, SynchronizedShowProgress) else SynchronizedShowProgress; end; procedure TProgressSection.ChangeProgress(ProgressToApply: TProgressToApply); begin self.ProgressToApply := ProgressToApply; if ThreadToSynchronize <> nil then TThread.Queue(ThreadToSynchronize, SynchronizedApplyProgress) else SynchronizedApplyProgress; end; constructor TProgressSection.Create(ThreadToSynchronize: TThread); begin self.ThreadToSynchronize := ThreadToSynchronize; end; procedure TProgressSection.SynchronizedApplyProgress; begin fMain.pDownload.Position := ProgressToApply.ProgressValue; fMain.lProgress.Caption := ProgressToApply.ProgressCaption; fMain.lSpeed.Caption := ProgressToApply.SpeedCaption; end; procedure TProgressSection.SynchronizedHideProgress; var CurrentButtonGroupEntry: TButtonGroupEntry; begin fMain.EnableSSDLabel; for CurrentButtonGroupEntry in fMain.GetButtonGroup do SetEnabledPropertyTo(true, CurrentButtonGroupEntry); fMain.iHelp.Enabled := true; fMain.lHelp.Enabled := true; fMain.gDownload.Visible := false; end; end.
unit Ntapi.ntdbg; {$MINENUMSIZE 4} interface uses Winapi.WinNt, Ntapi.ntdef; const DEBUG_READ_EVENT = $0001; DEBUG_PROCESS_ASSIGN = $0002; DEBUG_SET_INFORMATION = $0004; DEBUG_QUERY_INFORMATION = $0008; DEBUG_ALL_ACCESS = STANDARD_RIGHTS_ALL or $000F; DebugObjAccessMapping: array [0..3] of TFlagName = ( (Value: DEBUG_READ_EVENT; Name: 'Read event'), (Value: DEBUG_PROCESS_ASSIGN; Name: 'Assign process'), (Value: DEBUG_SET_INFORMATION; Name: 'Set information'), (Value: DEBUG_QUERY_INFORMATION; Name: 'Query information') ); DebugObjAccessType: TAccessMaskType = ( TypeName: 'debug object'; FullAccess: DEBUG_ALL_ACCESS; Count: Length(DebugObjAccessMapping); Mapping: PFlagNameRefs(@DebugObjAccessMapping); ); // Creation flag DEBUG_KILL_ON_CLOSE = $1; type TDbgKmException = record ExceptionRecord: TExceptionRecord; FirstChance: LongBool; end; PDbgKmException = ^TDbgKmException; TDbgKmCreateThread = record SubSystemKey: Cardinal; StartAddress: Pointer; end; PDbgKmCreateThread = ^TDbgKmCreateThread; TDbgKmCreateProcess = record SubSystemKey: Cardinal; FileHandle: THandle; BaseOfImage: Pointer; DebugInfoFileOffset: Cardinal; DebugInfoSize: Cardinal; InitialThread: TDbgKmCreateThread; end; PDbgKmCreateProcess = ^TDbgKmCreateProcess; TDbgKmLoadDll = record FileHandle: THandle; BaseOfDll: Pointer; DebugInfoFileOffset: Cardinal; DebugInfoSize: Cardinal; NamePointer: Pointer; end; PDbgKmLoadDll = ^TDbgKmLoadDll; TDbgState = ( DbgIdle = 0, DbgReplyPending = 1, DbgCreateThreadStateChange = 2, DbgCreateProcessStateChange = 3, DbgExitThreadStateChange = 4, DbgExitProcessStateChange = 5, DbgExceptionStateChange = 6, DbgBreakpointStateChange = 7, DbgSingleStepStateChange = 8, DbgLoadDllStateChange = 9, DbgUnloadDllStateChange = 10 ); TDbgUiCreateThread = record HandleToThread: THandle; NewThread: TDbgKmCreateThread; end; PDbgUiCreateThread = ^TDbgUiCreateThread; TDbgUiCreateProcess = record HandleToProcess: THandle; HandleToThread: THandle; NewProcess: TDbgKmCreateProcess; end; PDbgUiCreateProcess = ^TDbgUiCreateProcess; TDgbKmExitThread = record ExitStatus: NTSTATUS; end; PDgbKmExitThread = ^TDgbKmExitThread; TDgbKmExitProcess = TDgbKmExitThread; PDgbKmExitProcess = ^TDgbKmExitProcess; TDbgKmUnloadDll = record BaseAddress: Pointer; end; PDbgKmUnloadDll = ^TDbgKmUnloadDll; TDbgUiWaitStateChange = record NewState: TDbgState; AppClientId: TClientId; case Integer of 0: (Exception: TDbgKmException); 1: (CreateThread: TDbgUiCreateThread); 2: (CreateProcessInfo: TDbgUiCreateProcess); 3: (ExitThread: TDgbKmExitThread); 4: (ExitProcess: TDgbKmExitProcess); 5: (LoadDll: TDbgKmLoadDll); 6: (UnloadDll: TDbgKmUnloadDll); end; PDbgUiWaitStateChange = ^TDbgUiWaitStateChange; TDebugObjectInfoClass = ( DebugObjectUnusedInformation = 0, DebugObjectKillProcessOnExitInformation = 1 ); function NtCreateDebugObject(out DebugObjectHandle: THandle; DesiredAccess: TAccessMask; const ObjectAttributes: TObjectAttributes; Flags: Cardinal): NTSTATUS; stdcall; external ntdll; function NtDebugActiveProcess(ProcessHandle: THandle; DebugObjectHandle: THandle): NTSTATUS; stdcall; external ntdll; function NtDebugContinue(DebugObjectHandle: THandle; const ClientId: TClientId; ContinueStatus: NTSTATUS): NTSTATUS; stdcall; external ntdll; function NtRemoveProcessDebug(ProcessHandle: THandle; DebugObjectHandle: THandle): NTSTATUS; stdcall; external ntdll; function NtSetInformationDebugObject(DebugObjectHandle: THandle; DebugObjectInformationClass: TDebugObjectInfoClass; DebugInformation: Pointer; DebugInformationLength: Cardinal; ReturnLength: PCardinal): NTSTATUS; stdcall; external ntdll; // Debug UI function DbgUiConnectToDbg: NTSTATUS; stdcall; external ntdll; function NtWaitForDebugEvent(DebugObjectHandle: THandle; Alertable: Boolean; Timeout: PLargeInteger; out WaitStateChange: TDbgUiWaitStateChange): NTSTATUS; stdcall; external ntdll; function DbgUiGetThreadDebugObject: THandle; stdcall; external ntdll; procedure DbgUiSetThreadDebugObject(DebugObject: THandle); stdcall; external ntdll; function DbgUiDebugActiveProcess(Process: THandle): NTSTATUS; stdcall; external ntdll; procedure DbgUiRemoteBreakin(Context: Pointer); stdcall; external ntdll; function DbgUiIssueRemoteBreakin(Process: THandle): NTSTATUS; stdcall; external ntdll; implementation end.
unit Gs232; interface uses Windows, Messages, SysUtils, Variants, Classes, Forms, Dialogs, Vcl.ExtCtrls, ShlObj, // for debug Math, Cport, CPortX; Type TAzimuthAngle = (az360, az450); TCenterPosition = (cpNorth, cpSouth); TBoundPosition = (bpNone, bpCWBound, bpCCWBound); type TReachPresetEvent = procedure(Sender: TObject) of object; TReachBoundEvent = procedure(Sender: TObject; Bound: TBoundPosition) of object; TChangeAzElEvent = procedure(Sender: TObject) of object; TChangeRelaysEvent = procedure(Sender: TObject) of object; TChangeRelayEvent = procedure(Sender: TObject; Index: Integer; State: boolean) of object; Type TRelayArray = class(TComponent) private FRelay: array[0..15] of boolean; FEnable: boolean; FCount: Integer; FChangeRelay: TChangeRelayEvent; FChangeRelays: TChangeRelaysEvent; function GetRelay(Index: integer): boolean; procedure SetRelay(Index: integer; const Value: boolean); procedure SetCount(const Value: Integer); public property Count: Integer read FCount write SetCount; property Enable: boolean read FEnable; property Relay[Index: integer]: boolean read GetRelay write SetRelay; property ChangeRelays: TChangeRelaysEvent read FChangeRelays write FChangeRelays; property ChangeRelay: TChangeRelayEvent read FChangeRelay write FChangeRelay; constructor Create(Owner: TComponent); override; destructor Destroy; override; end; //**********************************************************************// // // // GS-23のクラス // // // //**********************************************************************// type TGs232 = class(TComponent) private { Private 宣言 } bInitialization: boolean; ComPort: TCPortX; Timer1: TTimer; iAzBefore: integer; // for Event when Azimuth Data change iElBefore: integer; // for Event when Elevation Data change iAzCwBound: integer; iAzCcwBound: Integer; // tSl: TStringList; // for debug; FActive: boolean; FAzimuthD: integer; FAzimuthR: double; FAzOffsetD: integer; FAzOffsetR: double; FAzPresetD: integer; FAzPresetR: double; FAzHomeD: integer; FAzHomeR: double; FElevationD: integer; FElevationR: double; FElOffsetD: integer; FElOffsetR: double; FElPresetD: integer; FElPresetR: double; FElHomeD: integer; FElHomeR: double; FAzimuthAngle: TAzimuthAngle; FElEnable: boolean; FCenterPosition: TCenterPosition; FReturnHome: boolean; FRotationSpeed: string; FModel: string; FCommandB: string; FCommandA: string; FOrgElevationD: integer; FOrgElevationR: double; FOrgAzimuthD: integer; FOrgAzimuthR: double; FOverlap: boolean; FReachBound: TReachBoundEvent; FReachPreset: TReachPresetEvent; FChangeAzEl: TChangeAzElEvent; FMoving: boolean; FPresetting: boolean; FRelayArray: TRelayArray; FCurrent: boolean; FTempOffsetD: integer; FTempOffsetR: double; procedure GetDirectionOnRx(Sender: TObject; Str: string); function RoundDegree(Value: integer): integer; function RoundRadian(Value: double): double; procedure Timer1Timer(Sender: TObject); function GetBaudRate: string; function GetDataBits: string; function GetFlowControl: string; function GetParity: string; function GetPort: string; function GetStopBits: string; procedure SetBaudRate(const Value: string); procedure SetDataBits(const Value: string); procedure SetFlowControl(const Value: string); procedure SetParity(const Value: string); procedure SetPort(const Value: string); procedure SetStopBits(const Value: string); procedure SetReturnHome(const Value: boolean); procedure SetCenterPosition(const Value: TCenterPosition); procedure SetModel(const Value: string); procedure SetCommandA(const Value: string); procedure SetCommandB(const Value: string); procedure SetRotationSpeed(const Value: string); procedure SetElEnable(const Value: boolean); procedure setAzimuthAngle(const Value: TAzimuthAngle); procedure ComException(Sender: TObject; ComException: TComExceptions; ComPortMessage: string; WinError: Int64; WinMessage: string); procedure ComError(Sender: TObject; Errors: TComErrors); procedure SetCurrent(const Value: boolean); procedure DoSetCenterPosition; procedure DoSetAzimuthAngle; procedure DoDoCmd(Cmd: string; recursive: boolean); procedure SetTempOffsetD(const Value: integer); procedure SetTempOffsetR(const Value: double); public { Public 宣言 } property Active: boolean read FActive; property Current: boolean read FCurrent write SetCurrent; property Model: string read FModel write SetModel; property CenterPosition: TCenterPosition read FCenterPosition write SetCenterPosition; property AzimuthAngle: TAzimuthAngle read FAzimuthAngle write setAzimuthAngle; property RotationSpeed: string read FRotationSpeed write SetRotationSpeed; property AzHomeD: integer read FAzHomeD; property AzHomeR: double read FAzHomeR; property ElHomeD: integer read FElHomeD; property ElHomeR: double read FElHomeR; property ReturnHome: boolean read FReturnHome write SetReturnHome; property AzOffsetD: integer read FAzOffsetD; property AzOffsetR: double read FAzOffsetR; property ElOffsetD: integer read FElOffsetD; property ElOffsetR: double read FElOffsetR; property CommandA: string read FCommandA write SetCommandA; property CommandB: string read FCommandB write SetCommandB; property AzimuthD: integer read FAzimuthD; property AzimuthR: double read FAzimuthR; property ElevationD: integer read FElevationD; property ElevationR: double read FElevationR; property AzPresetD: integer read FAzPresetD; property AzPresetR: double read FAzPresetR; property ElPresetD: integer read FElPresetD; property ElPresetR: double read FElPresetR; property ElEnable: boolean read FElEnable write SetElEnable; property OrgAzimuthD: integer read FOrgAzimuthD; property OrgAzimuthR: double read FOrgAzimuthR; property OrgElevationD: integer read FOrgElevationD; property OrgElevationR: double read FOrgElevationR; property Overlap: boolean Read FOverlap; property Moving: boolean read FMoving; property Presetting: boolean read FPresetting; property RelayArray: TRelayArray read FRelayArray; property ReachPreset: TReachPresetEvent read FReachPreset write FReachPreset; property ReachBound: TReachBoundEvent read FReachBound write FReachBound; property ChangeAzEl: TChangeAzElEvent read FChangeAzEl write FChangeAzEl; property TempOffsetD: integer read FTempOffsetD write SetTempOffsetD; property TempOffsetR: double read FTempOffsetR write SetTempOffsetR; // RS232関連 property BaudRate: string read GetBaudRate write SetBaudRate; property DataBits: string read GetDataBits write SetDataBits; property FlowControl: string read GetFlowControl write SetFlowControl; property Parity: string read GetParity write SetParity; property Port: string read GetPort write SetPort; property StopBits: string read GetStopBits write SetStopBits; constructor Create(Owner: TComponent); override; destructor Destroy; override; procedure Open(); procedure Close(); procedure DoCmd(Cmd: string); function GetDirection(): boolean overload; procedure GoHome(); procedure GoCCW; procedure GoCW; procedure GoDown; procedure GoLeft; procedure GoPreset(); overload; procedure GoPreset(Az: integer); overload; procedure GoPreset(Az: double); overload; procedure GoPreset(Az, El: integer); overload; procedure GoPreset(Az, El: double); overload; procedure GoRight; procedure GoUp; procedure ResetPreset; procedure SetPreset(Az: integer); overload; procedure SetPreset(Az: double); overload; procedure SetPreset(Az, El: integer); overload; procedure SetPreset(Az, El: double); overload; procedure Stop(); procedure SetOffset(Az: integer); overload; procedure SetOffset(Az: Double); overload; procedure SetOffset(Az, El: integer); overload; procedure SetOffset(Az, El: Double); overload; procedure SetHome(Az: integer); overload; procedure SetHome(Az: Double); overload; procedure SetHome(Az, El: integer); overload; procedure SetHome(Az, El: Double); overload; function DoRecv(Len: integer): string; end; procedure Wait(t: integer); function GetSpecialFolder(Folder :integer):string; const Pi2: double = 2 * pi; // 2 × PI RadDivDeg: double = 2 * pi / 360; // 1度あたりのラジアン値 cAzimuthAngle: array[0..1] of string = ('P36','P45'); cCenterPosition: array[0..1] of string = ('N','S'); implementation ///////////////////////////////////////////////////////////////////////////////////////////// // // GS-232 // ///////////////////////////////////////////////////////////////////////////////////////////// constructor TGs232.Create(Owner: TComponent); //var // i: integer; begin inherited Create(Owner); bInitialization := true;; ComPort := TCPortX.Create(self); Timer1 := TTimer.Create(Self); try Timer1.Enabled := false; Timer1.Interval := 100; // 0.1秒ごとに方位を読み取る Timer1.OnTimer := Timer1Timer; finally end; FActive := false; FAzimuthD := 0; FAzimuthR := 0; FOrgAzimuthD := 0; FOrgAzimuthR := 0; FAzOffsetD := 0; FAzOffsetR := 0; FAzPresetD := 0; FAzPresetR := 0; FAzHomeD := 0; FAzHomeR := 0; FElevationD := 0; FElevationR := 0; FOrgElevationD := 0; FOrgElevationR := 0; FElOffsetD := 0; FElOffsetR := 0; FElPresetD := 0; FElPresetR := 0; FElHomeD := 0; FElHomeR := 0; FAzimuthAngle := az360; FElEnable := false; FOverlap := false; FMoving := false; FRelayArray := TRelayArray.Create(Self); FRelayArray.FChangeRelays := nil; FRelayArray.FChangeRelay := nil; end; destructor TGs232.Destroy; begin FreeAndNil(FRelayArray); FreeAndNil(ComPort); FreeAndNil(Timer1); inherited Destroy; end; procedure TGs232.Open(); begin Comport.Delimiter := #10; // GS232用固定 Comport.TriggersOnRxChar := false; // Comport.OnRecvMsg := GetDirectionOnRx; // RTX-59,GS-232共通化するため使わない Comport.OnException := ComException; ComPort.OnError := ComError; ComPort.Open; ComPort.Clear; if bInitialization then begin bInitialization := false; ComPort.SendStr('K0' + #13); // Rom Initialize for RTC-59 立ち上げ後いちっどだけ処理する end; ComPort.SendStr('S' + #13); // 動作の停止 ComPort.SendStr('I0' + #13); // データを自動で送らない DoSetAzimuthAngle; DoSetCenterPosition; iAzBefore := 9999; iElBefore := 9999; Timer1.Enabled := true; FActive := True; SetCenterPosition(FCenterPosition); // Tsl := TStringList.Create; // for debug; end; procedure TGs232.Close(); var MyDoc: string; begin Timer1.Enabled := false; // MyDoc :=GetSpecialFolder(CSIDL_PERSONAL); // sl.SaveToFile(MyDoc + '\test.csv'); // FreeAndNil(tsl); // for debug ComPort.SendStr('' + #13); ComPort.Clear; ComPort.Close; FActive := false; end; procedure TGs232.ComException(Sender: TObject; ComException: TComExceptions; ComPortMessage: string; WinError: Int64; WinMessage: string); begin Close; showMessage('ComException ' + ComPortMessage); end; procedure TGs232.ComError(Sender: TObject; Errors: TComErrors); begin Close; showMessage('ComError ' + ComErrorsToStr(Errors)); end; procedure TGs232.DoCmd(Cmd: string); // Cmdの内容を解析しながら送る begin if FActive then DoDoCmd(Cmd, true); end; procedure TGs232.DoDoCmd(Cmd: string; recursive: boolean); // Cmdの内容を解析しながら送る var b: boolean; i,j: integer; s,s1, s2,sz: string; sl: TStringList; begin sl := TstringList.Create; try sl.CommaText := UpperCase(Cmd); for i := 0 to sl.Count - 1 do begin s := sl.Strings[i]; s1 := Copy(s,1,1); s2 := Copy(s, 1, 4); if (s2 = 'WAIT') then begin sz := Copy(s, 4, 32); if TryStrToInt(Copy(s, 4, 32), j) then begin Wait(j); end; continue; end; if (s1 = 'L') or (s1 = 'R') or (s1 = 'M') or (s1 = 'U') or (s1 = 'D') then begin if recursive then DoDoCmd(FCommandB, false); ComPort.SendStr(s + #13); continue; end; if (s1 = 'S') then begin ComPort.SendStr(s + #13); if recursive then DoDoCmd(FCommandA, false); continue; end; if (s1 = 'Y') then begin TryStrToInt(Copy(s, 2, 1), j); if Copy(s, 3, 1) = '1' then b := true else b := false; RelayArray.SetRelay(j - 1, b); ComPort.SendStr(s + #13); continue; end; ComPort.SendStr(s + #13); end; finally FreeAndNil(sl); end; end; function TGs232.DoRecv(Len: integer): string; var s: string; begin s := ''; if FActive then s := ComPort.RecvStr(Len); result := s; end; function TGs232.GetBaudRate: string; begin result := Comport.BaudRate; end; function TGs232.GetDataBits: string; begin result := ComPort.DataBits; end; procedure TGs232.GetDirectionOnRx(Sender: TObject; str: string); var s,t: string; begin s := str; if copy(s, 1,3) = 'AZ=' then t := copy(s, 4,3) else if copy(s, 1, 2) = '+0' then t := copy(s, 3, 3) else t := '0'; if not TryStrToInt(t, FAzimuthD) then FAzimuthD := 0; FAzimuthD := RoundDegree(FAzimuthD + FAzOffsetD); FAzimuthR := DegToRad(FAzimuthD); FElevationD := 0; FElevationR := 0; end; function TGs232.GetDirection(): boolean; var s,t,u: string; begin result := true; try if not FElEnable then ComPort.SendStr('C' + #13) // Azの読み取り指示 else ComPort.SendStr('C2' + #13); // Az,Elの読み取り指示 // wait(20); // 入れるとデータが読み取れないことがある s := ComPort.RecvStr(11); if copy(s, 1,3) = 'AZ='then // GS-232B,RTC-59 begin t := copy(s, 4, 3); u := copy(s, 11,3); end else if copy(s, 1, 2) = '+0'then // GS-232A begin t := copy(s, 3, 3); u := copy(s, 8, 3); end else begin t := '0'; u := '0'; end; if not TryStrToInt(t, FOrgAzimuthD) then FOrgAzimuthD := 0; if not TryStrToInt(u, FOrgElevationD) then FOrgElevationD := 0; FAzimuthD := RoundDegree(FOrgAzimuthD + FAzOffsetD); FAzimuthR := DegToRad(FAzimuthD); FElevationD := RoundDegree(FOrgElevationD + FElOffsetD); FElevationR := DegToRad(FEleVationD); finally end; end; function TGs232.GetFlowControl: string; begin result := ComPort.FlowControl; end; function TGs232.GetParity: string; begin result := ComPort.Parity; end; function TGs232.GetPort: string; begin result := ComPort.Port; end; function TGs232.GetStopBits: string; begin result := ComPort.StopBits; end; procedure TGs232.GoHome(); var s: string; begin if FActive then begin s := format('M%.3d', [RoundDegree(FAzHomeD - FAzOffsetD)]); DoCmd(s); end; end; procedure TGs232.GoDown; begin if FActive then DoCmd('D'); end; procedure TGs232.GoCCW(); begin if FActive then DoCmd('L'); end; procedure TGs232.GoCW(); begin if FActive then DoCmd('R'); end; procedure TGs232.GoLeft; begin GoCCW; end; // Preset位置へ移動 procedure TGs232.GoPreset(); var s: string; begin if FActive and FPresetting then begin if FElEnable then s := format('W%.3d %.3d', [RoundDegree(FAzPresetD - FAzOffsetD - FTempOffsetD), RoundDegree(FElPresetD - FElOffsetD)]) else s := format('M%.3d', [RoundDegree(FAzPresetD - FAzOffsetD - FTempOffsetD)]); DoCmd(s); end; end; procedure TGs232.GoPreset(Az: double); begin GoPreset(RadToDeg(Az)); end; procedure TGs232.GoPreset(Az: integer); // プリセット方向へ移動 var i: integer; s: string; begin if FActive then begin FPresetting := true; i := RoundDegree(Az); s := format('M%.3d'#13, [RoundDegree(i - FAzOffsetD - FTempOffsetD)]); DoCmd(s); FAzPresetD := i; FAzPresetR := DegToRad(i); end; end; procedure TGs232.GoPreset(Az, El: double); begin GoPreset(RadToDeg(Az), RadToDeg(El)); end; procedure TGs232.GoPreset(Az, El: integer); var i, j: integer; s: string; begin if FActive and FPresetting then begin i := RoundDegree(Az); j := RoundDegree(El); s := format('W%.3d %.3d'#13, [RoundDegree(i - FAzOffsetD - FTempOffsetD), RoundDegree(j - FElOffsetD)]); DoCmd(s); FAzPresetD := i; FAzPresetR := DegToRad(i); FElPresetD := j; FElPresetR := DegToRad(j); end; end; procedure TGs232.GoRight; begin GoCW; end; procedure TGs232.GoUp; begin if FActive then DoCmd('U'); end; procedure TGs232.ResetPreset; begin SetPreset(0,0); FPresetting := false; end; function TGs232.RoundDegree(Value: integer): integer; var i: integer; begin if FAziMuthAngle = az450 then if(Value >= 0) and (value <= 450) then begin result := Value; exit; end; i := trunc(frac(Value / 360) * 360); if i < 0 then i := i + 360; result := i; end; function TGs232.RoundRadian(Value: double): double; var d: double; begin if FAziMuthAngle = az450 then if(Value >= 0) and (value <= 3 * pi) then begin result := Value; exit; end; d := frac(Value / Pi2) * Pi2; if d < 0 then d := d + Pi2; result := d; end; // 360°、450°の設定をする procedure TGs232.setAzimuthAngle(const Value: TAzimuthAngle); begin FAzimuthAngle := Value; iAzCcwBound := 0; if FAzimuthAngle = az360 then iAzCwBound := 359 else iAzCwBound := 450; if FActive then DoSetAzimuthAngle; end; procedure TGs232.DoSetAzimuthAngle; begin if FActive then ComPort.SendStr(cAzimuthAngle[ord(FAzimuthAngle)] + #13); end; // BaudRateの設定(ComPortへ直接) procedure TGs232.SetBaudRate(const Value: string); begin ComPort.BaudRate := Value; end; // 北センタ(南起点)、南センタ(北起点)の設定 procedure TGs232.SetCenterPosition(const Value: TCenterPosition); begin FCenterPosition := Value; if FActive then DoSetCenterPosition; end; procedure TGs232.DoSetCenterPosition; var s: string; begin if FActive then if FModel = 'RTC-59' then begin ComPort.SendStr('Z' + cCenterPosition[Ord(FCenterPosition)] + #13); end else if FModel = 'GS-232B' then begin ComPort.SendStr('H3' + #13); s := ComPort.RecvStr(30); ShowMessage('GS-232Bの動作未確認'); end; end; // DataのBit長の設定(ComPortへ直接) procedure TGs232.SetDataBits(const Value: string); begin ComPort.DataBits := Value; end; // GetDirectionでAzのみか、AZ&EL両方のデータを得るかどうか判断する procedure TGs232.SetElEnable(const Value: boolean); begin FElEnable := Value; end; // FlowControlの設定(ComPortへ直接) procedure TGs232.SetFlowControl(const Value: string); begin ComPort.FlowControl := Value; end; // Home Positionの記憶 procedure TGs232.SetHome(Az: Double); begin SetHome(RadToDeg(Az)); end; procedure TGs232.SetHome(Az: integer); var i: integer; begin i := RoundDegree(Az); FAzHomeD := i; FAzHomeR := DegToRad(i); end; procedure TGs232.SetHome(Az, El: Double); begin SetHome(RadToDeg(Az), RadToDeg(El)); end; procedure TGs232.SetHome(Az, El: integer); var i: integer; begin i := RoundDegree(Az); FAzHomeD := i; FAzHomeR := DegToRad(i); FElHomeD := El; FElHomeR := DegToRad(El); end; // Model名の記憶 procedure TGs232.SetModel(const Value: string); begin FModel := Value; end; // Offset Angleの記憶 procedure TGs232.SetOffset(Az: Double); begin SetOffset(RadToDeg(Az)); end; procedure TGs232.SetOffset(Az: integer); begin FAzOffsetD := Az; FAzOffSetR := DegToRad(Az); end; procedure TGs232.SetOffset(Az, El: Double); begin SetOffset(RadToDeg(Az), RadToDeg(El)); end; procedure TGs232.SetOffset(Az, El: integer); begin FAzOffsetD := Az; FAzOffSetR := DegToRad(Az); FElOffsetD := El; FElOffSetR := DegToRad(EL); end; // Parityの設定(ComPortへ直接) procedure TGs232.SetParity(const Value: string); begin ComPort.Parity := Value; end; // Preset Angleの記憶 procedure TGs232.SetPreset(Az: double); begin SetPreset(Integer(Trunc(RadToDeg(RoundRadian(Az))))); end; procedure TGs232.SetPreset(Az: integer); begin FAzPresetD := Az; FAzPresetR := DegToRad(Az); FPresetting := true; end; procedure TGs232.SetPreset(Az, El: double); begin SetPreset(Trunc(RadToDeg(Az)), Trunc(RadToDeg(El))); end; procedure TGs232.SetPreset(Az, El: integer); begin FAzPresetD := Az; FAzPresetR := DegToRad(Az); FElPresetD := El; FElPresetR := DegToRad(El); FPresetting := true; end; // Port番号の設定(ComPortへ直接) procedure TGs232.SetPort(const Value: string); begin ComPort.Port := Value; end; // 終了時にHome position へ戻るかどうかの記憶 procedure TGs232.SetReturnHome(const Value: boolean); begin FReturnHome := Value; end; // 回転スピードの設定 procedure TGs232.SetRotationSpeed(const Value: string); begin FRotationSpeed := Value; if FActive then ComPort.SendStr('X' + Copy(Value, 1, 1) + #13); end; // 回転終了後に実行するコマンドを記憶 procedure TGs232.SetCommandA(const Value: string); begin FCommandA := Value; end; // 回転開始前に実行するコマンドを記憶 procedure TGs232.SetCommandB(const Value: string); begin FCommandB := Value; end; procedure TGs232.SetCurrent(const Value: boolean); begin FCurrent := Value; if Fcurrent then // Timer1.Enabled := false else // Timer1.Enabled := false; end; // Port番号の設定(ComPortへ直接) procedure TGs232.SetStopBits(const Value: string); begin ComPort.StopBits := value; end; procedure TGs232.SetTempOffsetD(const Value: integer); begin FTempOffsetD := Value; FTempOffsetR := DegToRad(Value); end; procedure TGs232.SetTempOffsetR(const Value: double); begin FTempOffsetR := Value; FTempOffsetD := trunc(RadToDeg(Value)); end; // 回転を止める procedure TGs232.Stop(); begin if FActive then begin FMoving := false; DoCmd('S'); end; end; // タイマーでローテタからデータを得て、前回と異なるときEventを実行する procedure TGs232.Timer1Timer(Sender: TObject); var deg: integer; begin if FActive then begin FOrgAzimuthD := 0; GetDirection(); if FOrgAzimuthD > 360 then FOverlap := true else FOverlap := false; if FPresetting then begin if abs(FAzimuthD - FAzPresetD + FTempOffsetD) <= 2 then begin // Stop; if Assigned(FReachPreset) then begin if FPresetting then FReachPreset(self); FPresetting := False; end; end; end; if FMoving then begin Deg := FOrgAzimuthD; if FCenterPosition = cpNorth then begin if (Deg >=180) and (Deg <= 359) then Deg := deg - 360 + 180 else Deg := Deg + 180; end; if Deg >= iAzCwBound then begin Stop; if Assigned(FReachBound) then FReachBound(self, bpCWBound); end else if Deg <= iAzCcwBound then begin Stop; if Assigned(FReachBound) then FReachBound(self, bpCCWBound); end; end; if (abs(iAzBefore - FAzimuthD) > 1) or (abs(iElBefore - FElevationD) > 1) then begin FMoving := true; if Assigned(FChangeAzEl) then begin iAzBefore := FAzimuthD; iElBefore := FElevationD; FChangeAzEl(self); end; end; end; end; { TRelayArray } constructor TRelayArray.Create(Owner: TComponent); var i: integer; begin inherited; for i := Low(FRelay) to High(FRelay) do FRelay[i] := false; end; destructor TRelayArray.Destroy; begin inherited; end; function TRelayArray.GetRelay(Index: integer): boolean; begin if FEnable and (Index <= FCount) then result := FRelay[Index] else result := false; end; procedure TRelayArray.SetCount(const Value: Integer); begin FCount := Value; FEnable := false; if Value <> 0 then FEnable := true; if Assigned(FChangeRelays) then FChangeRelays(self); end; procedure TRelayArray.setRelay(Index: integer; const Value: boolean); begin if not FEnable then exit; if (Index < 0) or (Index > FCount - 1) then exit; FRelay[Index] := value; if Assigned(FChangeRelay) then FChangeRelay(self, Index, Value); if Assigned(FChangeRelays) then FChangeRelays(self); end; /////////////////////////////////////////////////////////////////////////////////////////////// //// //// AppnにWaitをかける //// /////////////////////////////////////////////////////////////////////////////////////////////// procedure Wait(t: integer); // t/1000秒のWaitをかける var endtime : TDateTime; //終了時間 begin endtime := Now + t / 86400 / 1000; while (Now < endtime) do Application.ProcessMessages; end; function GetSpecialFolder(Folder :integer):string; var Path: array[0..MAX_PATH] of Char; pidl: PItemIDList; begin SHGetSpecialFolderLocation(Application.Handle,Folder,pidl); SHGetPathFromIDList(pidl, Path); Result :=Path; end; end.
unit f07_laporhilang; interface uses buku_handler, kehilangan_handler, peminjaman_handler, utilitas; { DEKLARASI FUNGSI DAN PROSEDUR } procedure lapor(var data_kehilangan: tabel_kehilangan; data_peminjaman : tabel_peminjaman; var data_buku: tabel_buku; username: String); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure lapor(var data_kehilangan: tabel_kehilangan; data_peminjaman : tabel_peminjaman; var data_buku: tabel_buku; username: String); { DESKRIPSI : prosedur untuk melaporkan kehilangan buku } { PARAMETER : data kehilangan, data buku, dan username pelapor } { KAMUS LOKAL } var judul: string; temp: kehilangan; i : integer; { ALGORITMA } begin write('Masukkan id buku: '); readln(temp.id_buku); i := findID(data_buku, temp.ID_Buku); if(findID(data_buku, temp.ID_Buku)=-1) then writeln('Buku tersebut tidak ada di perpustakaan kami.') else begin temp.username := username; write('Masukkan judul buku: '); readln(judul); write('Masukkan tanggal pelaporan: '); readln(temp.tanggal_laporan); writeln(''); if (data_buku.t[i].Jumlah_Buku = '0') then writeln('Stok buku sudah habis sejak awal') else begin data_kehilangan.sz := data_kehilangan.sz+1; data_kehilangan.t[data_kehilangan.sz-1] := temp; if ((findID2(data_peminjaman, temp.ID_Buku) = -1) or (data_peminjaman.t[findID2(data_peminjaman, temp.ID_Buku)].Status_Pengembalian = 'False')) then begin data_buku.t[i].Jumlah_Buku := IntToString(StringToInt(data_buku.t[i].Jumlah_Buku) - 1) end; writeln('Laporan berhasil diterima.'); end; end; end; end.
unit ucadTransStd; interface uses SysUtils, classes, ufmTranslator, StdCtrls, uLogs, menus; type TFormTranslator = class ( TcadCompTranslator ) function Translate(const aObj: TObject; var Translated:boolean):boolean; override; class function Supports(const aObj: TObject): Boolean; override; end; TControlTranslator = class ( TcadCompTranslator ) function Translate(const aObj: TObject; var Translated:boolean):boolean; override; class function Supports(const aObj: TObject): Boolean; override; end; TLabelTranslator = class ( TcadCompTranslator ) function Translate(const aObj: TObject; var Translated:boolean):boolean; override; class function Supports(const aObj: TObject): Boolean; override; end; TPanelTranslator = class ( TcadCompTranslator ) function Translate(const aObj: TObject; var Translated:boolean):boolean; override; class function Supports(const aObj: TObject): Boolean; override; end; TComboBoxTranslator = class ( TcadCompTranslator ) function Translate(const aObj: TObject; var Translated:boolean):boolean; override; class function Supports(const aObj: TObject): Boolean; override; end; TMenuItemTranslator = class ( TcadCompTranslator ) function Translate(const aObj: TObject; var Translated:boolean):boolean; override; class function Supports(const aObj: TObject): Boolean; override; end; implementation uses forms, controls, ExtCtrls; // ----------------------------------------------------------------------------- class function TFormTranslator.Supports(const aObj: TObject): Boolean; begin Result := aObj.InheritsFrom(TForm); end; function TFormTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean; begin result := true; Translated := false; if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then with TForm(aObj) do begin Caption := TranslateProp(aObj, ClassName, '', 'Caption', Caption, Translated); Hint := TranslateProp(aObj, ClassName, '', 'Hint', Hint, Translated); end; with TForm(aObj) do ChangeCharsetProp(aObj); end; // ----------------------------------------------------------------------------- class function TControlTranslator.Supports(const aObj: TObject): Boolean; begin Result := aObj.InheritsFrom(TControl); end; function TControlTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean; var OwnerClassName : string; begin result := true; Translated := false; if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit; OwnerClassName := GetOwnerClassName(aObj); if (TComponent(aObj).Owner<>nil) and (TComponent(aObj).Owner.ClassType = tapplication) then exit; with TControl(aObj) do Hint := TranslateProp(aObj, OwnerClassName, Name, 'Hint', Hint, Translated); end; // ----------------------------------------------------------------------------- class function TLabelTranslator.Supports(const aObj: TObject): Boolean; begin Result := aObj.InheritsFrom(TLabel); end; function TLabelTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean; begin result := true; Translated := false; if sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then exit; with TLabel(aObj) do Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated); with TForm(aObj) do ChangeCharsetProp(aObj); end; // ----------------------------------------------------------------------------- class function TPanelTranslator.Supports(const aObj: TObject): Boolean; begin Result := (aObj is TPanel); end; function TPanelTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean; begin result := true; Translated := false; if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then with TPanel(aObj) do Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated); with TPanel(aObj) do ChangeCharsetProp(aObj); end; // ----------------------------------------------------------------------------- class function TComboBoxTranslator.Supports(const aObj: TObject): Boolean; begin Result := (aObj is TComboBox); end; function TComboBoxTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean; var i : integer; begin result := true; Translated := false; if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then with TComboBox(aObj) do for i:=0 to Items.count-1 do Items[i] := TranslateProp(aObj, GetOwnerClassName(aObj), TComponent(aObj).Name, 'Items['+inttostr(i)+']', Items[i], Translated); end; // ----------------------------------------------------------------------------- class function TMenuItemTranslator.Supports(const aObj: TObject): Boolean; begin Result := (aObj is TMenuItem); end; function TMenuItemTranslator.Translate(const aObj: TObject; var Translated:boolean):boolean; begin result := true; Translated := false; if not sametext(copy(TComponent(aObj).name, 1, 7),'NoXlate') then with TMenuItem(aObj) do Caption := TranslateProp(aObj, GetOwnerClassName(aObj), Name, 'Caption', Caption, Translated); end; initialization RegisterTranslators([ TFormTranslator, TControlTranslator, TLabelTranslator, TPanelTranslator, TComboBoxTranslator, TMenuItemTranslator]); end.
unit UCL.TUTooltip; interface uses UCL.Classes, UCL.Utils, System.Classes, Winapi.Windows, Winapi.Messages, VCL.Controls, VCL.Graphics; type TUCustomTooltip = class(THintWindow) const DEF_HEIGHT = 26; private var BorderColor: TColor; var BackColor: TColor; protected procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; procedure NCPaint(DC: HDC); override; public function CalcHintRect(MaxWidth: Integer; const AHint: string; AData: Pointer): TRect; override; end; TULightTooltip = class(TUCustomTooltip) public constructor Create(aOwner: TComponent); override; end; TUDarkTooltip = class(TUCustomTooltip) public constructor Create(aOwner: TComponent); override; end; implementation { TULightTooltip } constructor TULightTooltip.Create(aOwner: TComponent); begin inherited; BorderColor := $CCCCCC; BackColor := $F2F2F2; end; { TUDarkTooltip } constructor TUDarkTooltip.Create(aOwner: TComponent); begin inherited; BorderColor := $767676; BackColor := $2B2B2B; end; { TUCustomTooltip } // MAIN CLASS procedure TUCustomTooltip.CreateParams(var Params: TCreateParams); begin inherited; Params.Style := Params.Style and not WS_BORDER; Params.WindowClass.style := Params.WindowClass.style and not CS_DROPSHADOW; end; // CUSTOM METHODS function TUCustomTooltip.CalcHintRect(MaxWidth: Integer; const AHint: string; AData: Pointer): TRect; var TextW, TextH: Integer; begin TextW := Canvas.TextWidth(AHint); TextH := Canvas.TextHeight(AHint); TextW := TextW + (DEF_HEIGHT - TextH); // Spacing Result := Rect(0, 0, TextW, DEF_HEIGHT); end; procedure TUCustomTooltip.Paint; var TextW, TextH, TextX, TextY: Integer; begin //inherited; // Paint background Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := BackColor; Canvas.FillRect(Rect(0, 0, Width, Height)); // Draw border Canvas.Brush.Style := bsClear; Canvas.Pen.Color := BorderColor; Canvas.Rectangle(0, 0, Width, Height); // Draw text Canvas.Font.Name := 'Segoe UI'; Canvas.Font.Size := 8; Canvas.Font.Color := GetTextColorFromBackground(BackColor); TextW := Canvas.TextWidth(Caption); TextH := Canvas.TextHeight(Caption); TextX := (Width - TextW) div 2; TextY := (Height - TextH) div 2 - 1; Canvas.TextOut(TextX, TextY, Caption); end; procedure TUCustomTooltip.NCPaint(DC: HDC); begin // Do nothing end; end.
unit PushConsumerMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CORBA, CosEvent, PushConsumer_Impl; type TForm1 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); private { Private declarations } PushConsumer_Skeleton : PushConsumer; Event_Channel : EventChannel; Consumer_Admin : ConsumerAdmin; Push_Supplier : ProxyPushSupplier; procedure CorbaInit; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.CorbaInit; begin CorbaInitialize; // Create the skeleton and register it with the boa PushConsumer_Skeleton := TPushConsumerSkeleton.Create('Jack B Quick', TPushConsumer.Create); BOA.SetScope( RegistrationScope(1) ); BOA.ObjIsReady(PushConsumer_Skeleton as _Object); //bind to the event channel and get a Supplier Admin object Event_Channel := TEventChannelHelper.bind; Consumer_Admin := Event_Channel.for_consumers; //get a push consumer and register the supplier object Push_Supplier := Consumer_Admin.obtain_push_supplier; Push_Supplier.connect_push_consumer(PushConsumer_Skeleton); end; procedure TForm1.FormCreate(Sender: TObject); begin CorbaInit; end; end.
unit UniqueParameterValuesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap; type TUniqueParameterValuesW = class(TDSWrap) private FValue: TFieldWrap; FParamSubParamId: TFieldWrap; FProductCategoryId: TParamWrap; public constructor Create(AOwner: TComponent); override; property Value: TFieldWrap read FValue; property ParamSubParamId: TFieldWrap read FParamSubParamId; property ProductCategoryId: TParamWrap read FProductCategoryId; end; TQueryUniqueParameterValues = class(TQueryBase) private FW: TUniqueParameterValuesW; { Private declarations } public constructor Create(AOwner: TComponent); override; function SearchEx(AProductCategoryID, AParamSubParamID: Integer): Integer; reintroduce; property W: TUniqueParameterValuesW read FW; { Public declarations } end; implementation {$R *.dfm} constructor TQueryUniqueParameterValues.Create(AOwner: TComponent); begin inherited; FW := TUniqueParameterValuesW.Create(FDQuery); end; function TQueryUniqueParameterValues.SearchEx(AProductCategoryID, AParamSubParamID: Integer): Integer; begin Assert(AProductCategoryID > 0); Assert(AParamSubParamID > 0); Result := Search([W.ProductCategoryId.FieldName, W.ParamSubParamId.FieldName], [AProductCategoryID, AParamSubParamID]); end; constructor TUniqueParameterValuesW.Create(AOwner: TComponent); begin inherited; FParamSubParamId := TFieldWrap.Create(Self, 'pv.ParamSubParamId', '', True); FValue := TFieldWrap.Create(Self, 'pv.Value'); FProductCategoryId := TParamWrap.Create(Self, 'ppc.ProductCategoryId'); end; end.
/// <summary> /// TRawBytesHelper based on PascalCoin Core by Alfred Molina /// </summary> unit PascalCoin.Helpers; interface uses PascalCoin.Utils.Interfaces; type TRawBytesHelper = record helper for TRawBytes function ToString: String; // Returns a String type function ToPrintable: String; // Returns a printable string with chars from #32..#126, other chars will be printed as #126 "~" function ToHexaString: String; // Returns an Hexastring, so each byte will be printed as an hexadecimal (double size) procedure FromString(const AValue: String); // Will store a RAW bytes assuming each char of the string is a byte -> ALERT: Do not use when the String contains chars encoded with multibyte character set! function Add(const ARawValue: TRawBytes): TRawBytes; // Will concat a new RawBytes value to current value function IsEmpty: Boolean; // Will return TRUE when Length = 0 end; implementation uses System.SysUtils; { TRawBytesHelper } function TRawBytesHelper.ToPrintable: String; var i, inc_i: Integer; rbs: RawByteString; // begin SetLength(rbs, Length(Self)); inc_i := Low(rbs) - Low(Self); for i := Low(Self) to High(Self) do begin if (Self[i] in [32 .. 126]) then move(Self[i], rbs[i + inc_i], 1) else rbs[i + inc_i] := Chr(126); end; Result := rbs; end; function TRawBytesHelper.ToString: String; begin if Length(Self) > 0 then begin Result := TEncoding.ANSI.GetString(Self); end else Result := ''; end; procedure TRawBytesHelper.FromString(const AValue: String); var i: Integer; begin SetLength(Self, Length(AValue)); for i := 0 to Length(AValue) - 1 do begin Self[i] := Byte(AValue.Chars[i]); end; end; function TRawBytesHelper.Add(const ARawValue: TRawBytes): TRawBytes; var iNext: Integer; begin iNext := Length(Self); SetLength(Self, Length(Self) + Length(ARawValue)); move(ARawValue[0], Self[iNext], Length(ARawValue)); Result := Self; end; function TRawBytesHelper.IsEmpty: Boolean; begin Result := Length(Self) = 0; end; function TRawBytesHelper.ToHexaString: String; Var i: Integer; rbs: RawByteString; raw_as_hex: TRawBytes; begin SetLength(raw_as_hex, Length(Self) * 2); for i := Low(Self) to High(Self) do begin rbs := IntToHex(Self[i], 2); move(rbs[Low(rbs)], raw_as_hex[i * 2], 1); move(rbs[Low(rbs) + 1], raw_as_hex[(i * 2) + 1], 1); end; Result := raw_as_hex.ToString; end; end.
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+} unit DateTime; interface uses Global; function dtAge(Date : String) : Word; { Years old } function dtDateFullString(S : String) : String; { Verbal date string } function dtDatePackedString(L : LongInt) : String; { Date unpacked (string) } function dtDateString : String; { Current date (string) } function dtDateTimePacked : LongInt; { Current date+time packed } function dtDaysBetween(d1, d2 : String) : LongInt; { # of days between dates } function dtTimePackedString(L : LongInt) : String; { Time unpacked (string) } function dtTimePackedStr24(L : LongInt) : String; function dtTimeRecLen(var d : tDateTimeRec) : String; function dtTimeRecStr(dt : tDateTimeRec) : String; function dtTimeStr12 : String; { Current time 12 hr (string) } function dtTimeStr24 : String; { Current time 24 hr (string) } function dtValidDate(Dat : String) : Boolean; { Is date in proper format ? } function dtDateFactor(MonthNum, DayNum, YearNum : Real) : Real; function dtDatetoJulian(DateLine : String) : Integer; function dtJuliantoDate(DateInt : Integer) : String; function dtDatetoReal(dt : tDateTimeRec) : Real; procedure dtGetDateTime(var dt : tDateTimeRec); procedure dtTimeDiff(var dt : tDateTimeRec; dt1, dt2 : tDateTimeRec); function dtInTime(t1, t2 : String) : Boolean; function dtSecDiff(before, after : LongInt) : LongInt; function dtRealDiff(before, after : Real) : Real; function dtDayCount(mo, yr : Integer) : Integer; { # of days in mo months } function dtDayNum(Dt : String) : Integer; { # of Days ago ? } function dtDays(mo, yr : Integer) : Integer; { # of days in month } function dtLeapYear(yr : Integer) : Boolean; { Checks for leap year } function dtTimer : Real; { Seconds since midnight } implementation uses Dos, Strings; Var Hour,Minute,Second,S100, Year,Month,Day,Dow : Word; Syear,Smonth,Sday,Sdow : String; JulianDate : Integer; function dtTimer : Real; var hour, minute, second, sec100 : Word; begin GetTime(hour, minute, second, sec100); dtTimer := ((hour*60*60) + (minute*60) + (second) + (sec100 * 0.01)) end; function dtDateString : String; var S, D : String; Yr,Mn,Da,Dw : Word; Zr : String; begin D := ''; S := ''; Zr := '0'; GetDate(Yr,Mn,Da,Dw); D := St(Mn); if Length(D) = 1 then Insert(Zr,D,1); S := D; D := St(Da); if Length(D) = 1 then Insert(Zr,D,1); S := S + '/' + D; D := St(Yr); Delete(D,1,2); S := S + '/' + D; dtDateString := S; end; function dtLeapYear(yr : Integer) : Boolean; begin dtLeapYear := (yr mod 4 = 0) and ((yr mod 100 <> 0) or (yr mod 400 = 0)); end; function dtDayCount(mo, yr : Integer) : Integer; var m, t : Integer; begin t := 0; for m := 1 to (mo-1) do t := t+dtDays(m,yr); dtDayCount := t; end; function dtDays(mo, yr : Integer) : Integer; var D : Integer; begin d := strToInt(Copy('312831303130313130313031',1+(mo-1)*2,2)); if ((mo=2) and (dtLeapYear(yr))) then Inc(d); dtDays := d; end; function dtDayNum(Dt : String) : Integer; var d,m,y,t,c : Integer; begin t := 0; m := strToInt(Copy(dt,1,2)); d := strToInt(Copy(dt,4,2)); y := strToInt(Copy(dt,7,2))+1900; for c := 1985 to y-1 do if (dtLeapYear(c)) then Inc(t,366) else Inc(t,365); t := t+dtDayCount(m,y)+(d-1); dtDayNum := t; if y < 1985 then dtDayNum :=0; end; function dtAge(Date : String) : Word; var D : String; I : Integer; begin I := strToInt(Copy(dtDateString,7,2))-strToInt(Copy(Date,7,2)); if (dtDayNum(Copy(Date,1,6)+Copy(dtDateString,7,2)) > dtDayNum(dtDateString)) then Dec(I); dtAge := I; end; function dtValidDate(Dat : String) : Boolean; var M, D : Byte; begin M := StrToInt(Copy(Dat,1,2)); D := StrToInt(Copy(Dat,4,2)); dtValidDate := (M > 0) and (D > 0) and (M <= 12) and (D <= 31); end; { function mMachineDate : String; begin GetDate(Year,Month,Day,Dow); Str(Year,Syear); Str(Month,Smonth); if Month < 10 then Smonth := '0' + Smonth; Str(Day,Sday); if Day < 10 then Sday := '0' + Sday; mMachineDate := smonth + sday + syear; end; } Function dtDateFactor(MonthNum, DayNum, YearNum : Real) : Real; Var Factor : Real; begin Factor := (365 * YearNum) + DayNum + (31 * (MonthNum-1)); if MonthNum < 3 then Factor := Factor + Int((YearNum-1) / 4) - Int(0.75 * (Int((YearNum-1) / 100) + 1)) else Factor := Factor - Int(0.4 * MonthNum + 2.3) + Int(YearNum / 4) - Int(0.75 * (Int(YearNum / 100) + 1)); dtDateFactor := Factor; end; function dtDatetoJulian(DateLine : String) : Integer; Var Factor, MonthNum, DayNum, YearNum : Real; Ti : Integer; begin Delete(DateLine,3,1); Delete(DateLine,5,1); Insert('19',DateLine,5); if Length(DateLine) = 7 then DateLine := '0'+DateLine; MonthNum := 0.0; For Ti := 1 to 2 Do MonthNum := (10 * MonthNum) + (ord(DateLine[Ti])-ord('0')); DayNum := 0.0; For Ti := 3 to 4 Do DayNum := (10 * DayNum) + (ord(DateLine[Ti])-ord('0')); YearNum := 0.0; For Ti := 5 to 8 Do YearNum := (10 * YearNum) + (ord(DateLine[Ti])-ord('0')); Factor := dtDateFactor(MonthNum, DayNum, YearNum); dtDatetoJulian := Trunc((Factor - 679351.0) - 32767.0); end; function dtJuliantoDate(DateInt : Integer) : String; Var holdstr : String[2]; anystr : String[11]; StrMonth : String[3]; strDay : String[2]; stryear : String[4]; test, error, Year, Dummy, I : Integer; Save,Temp : Real; JuliantoanyString : String; begin holdstr := ''; JuliantoanyString := '00000000000'; Temp := Int(DateInt) + 32767 + 679351.0; Save := Temp; Dummy := Trunc(Temp/365.5); While Save >= dtDateFactor(1.0,1.0,Dummy+0.0) Do Dummy := Succ(Dummy); Dummy := Pred(Dummy); Year := Dummy; (* Determine number of Days into current year *) Temp := 1.0 + Save - dtDateFactor(1.0,1.0,Year+0.0); (* Put the Year into the output String *) For I := 8 downto 5 Do begin JuliantoanyString[I] := Char((Dummy mod 10)+ord('0')); Dummy := Dummy div 10; end; Dummy := 1 + Trunc(Temp/31.5); While Save >= dtDateFactor(Dummy+0.0,1.0,Year+0.0) Do Dummy := Succ(Dummy); Dummy := Pred(Dummy); Temp := 1.0 + Save - dtDateFactor(Dummy+0.0,1.0,Year+0.0); For I := 2 Downto 1 Do begin JuliantoanyString[I] := Char((Dummy mod 10)+ord('0')); Dummy := Dummy div 10; end; Dummy := Trunc(Temp); For I := 4 Downto 3 Do begin JuliantoanyString[I] := Char((Dummy mod 10)+ord('0')); Dummy := Dummy div 10; end; holdstr := copy(juliantoanyString,1,2); val(holdstr,test,error); { Case test of 1 : StrMonth := 'Jan'; 2 : StrMonth := 'Feb'; 3 : StrMonth := 'Mar'; 4 : StrMonth := 'Apr'; 5 : StrMonth := 'May'; 6 : StrMonth := 'Jun'; 7 : StrMonth := 'Jul'; 8 : StrMonth := 'Aug'; 9 : StrMonth := 'Sep'; 10 : StrMonth := 'Oct'; 11 : StrMonth := 'Nov'; 12 : StrMonth := 'Dec'; end;} StrMonth := St(Test); if Length(StrMonth) < 2 then Insert('0',StrMonth,1); stryear := copy(juliantoanyString,7,2); strDay := copy(juliantoanyString,3,2); anystr := StrMonth + '/' + StrDay + '/' +strYear; dtJuliantoDate := anystr; end; function dtInTime(t1, t2 : String) : Boolean; var ti1, ti2, tnow : Word; begin Delete(t1,3,1); Delete(t2,3,1); ti1 := strToInt(t1); ti2 := strToInt(t2); t1 := dtTimeStr24; Delete(t1,3,1); tnow := strToInt(t1); if ti1 = ti2 then dtInTime := tnow = ti1 else if ti1 < ti2 then dtInTime := (tnow >= ti1) and (tnow <= ti2) else if ti1 > ti2 then dtInTime := (tnow >= ti1) or (tnow <= ti2); end; function dtTimeStr24 : String; var S, D, Zr : String; Hr,Mn,Sc,Ms : Word; begin D := ''; S := ''; Zr := '0'; GetTime(Hr,Mn,Sc,Ms); D := St(Hr); if Length(D) = 1 then Insert(Zr,D,1); S := D; D := St(Mn); if Length(D) = 1 then Insert(Zr,D,1); S := S + ':' + D; D := St(Sc); if Length(D) = 1 then Insert(Zr,D,1); S := S + ':' + D; dtTimeStr24 := S; end; function dtTimeStr12 : String; var S, D, Zr : String; Hr,Mn,Sc,Ms : Word; Pm : Boolean; begin D := ''; S := ''; Zr := '0'; GetTime(Hr,Mn,Sc,Ms); Pm := (Hr >= 12); if Hr > 12 then Dec(Hr,12); if Hr = 0 then Hr := 12; D := St(Hr); S := D; D := St(Mn); if Length(D) = 1 then Insert(Zr,D,1); S := S + ':' + D; if Pm then S := S + 'pm' else S := S + 'am'; dtTimeStr12 := S; end; function dtDateTimePacked : LongInt; var Y,M,D,Dw, H,Mn,S,So : Word; Dt : Dos.DateTime; L : LongInt; begin GetTime(H,Mn,S,So); GetDate(Y,M,D,Dw); Dt.Year := Y; Dt.Month := M; Dt.Day := D; Dt.Hour := H; Dt.Min := Mn; Dt.Sec := S; PackTime(Dt,L); dtDateTimePacked := L; end; function dtDatePackedString(L : LongInt) : String; var S, D, Zr : String; Yr,Mn,Da : Word; Dt : Dos.DateTime; begin UnpackTime(L,Dt); Zr := '0'; Yr := Dt.Year; Mn := Dt.Month; Da := Dt.Day; D := St(Mn); if Length(D) = 1 then Insert(Zr,D,1); S := D; D := St(Da); if Length(D) = 1 then Insert(Zr,D,1); S := S + '/' + D; D := St(Yr); Delete(D,1,2); S := S + '/' + D; dtDatePackedString := S; end; function dtTimePackedString(L : LongInt) : String; var S, D, Zr : String; Hr,Mn : Word; Dt : Dos.DateTime; Pm : Boolean; begin UnpackTime(L,Dt); Hr := Dt.Hour; Zr := '0'; Mn := Dt.Min; Pm := (Hr >= 12); if Hr > 12 then Dec(Hr,12); if Hr = 0 then Hr := 12; D := St(Hr); S := D; D := St(Mn); if Length(D) = 1 then Insert(Zr,D,1); S := S + ':' + D; if Pm then S := S + 'pm' else S := S + 'am'; dtTimePackedString := S; end; function dtTimePackedStr24(L : LongInt) : String; var S, D, Zr : String; Hr,Mn : Word; Dt : Dos.DateTime; begin UnpackTime(L,Dt); Hr := Dt.Hour; Zr := '0'; Mn := Dt.Min; D := St(Hr); S := D; D := St(Mn); if Length(D) = 1 then Insert(Zr,D,1); S := S + ':' + D; dtTimePackedStr24 := S; end; function dtDaysBetween(d1, d2 : String) : LongInt; var internal1,internal2:longint; JNUM:real; cd,month,day,year: integer; out:string[25]; function Jul( mo, da, yr: integer): real; var i, j, k, j2, ju: real; begin i := yr; j := mo; k := da; j2 := int( (j - 14)/12 ); ju := k - 32075 + int(1461 * ( i + 4800 + j2 ) / 4 ); ju := ju + int( 367 * (j - 2 - j2 * 12) / 12); ju := ju - int(3 * int( (i + 4900 + j2) / 100) / 4); Jul := ju; end; begin out:=copy(d1,1,2); if copy(out,1,1)='0' then delete(out,1,1); val(out,month,cd); out:=copy(d1,4,2); if copy(out,1,1)='0' then delete(out,1,1); val(out,day,cd); out:=copy(d1,7,2); if copy(out,1,1)='0' then delete(out,1,1); val(out,year,cd); jnum:=jul(month,day,year); str(jnum:10:0,out); val(out,internal1,cd); out:=copy(d2,1,2); if copy(out,1,1)='0' then delete(out,1,1); val(out,month,cd); out:=copy(d2,4,2); if copy(out,1,1)='0' then delete(out,1,1); val(out,day,cd); out:=copy(d2,7,2); if copy(out,1,1)='0' then delete(out,1,1); val(out,year,cd); jnum:=jul(month,day,year); str(jnum:10:0,out); val(out,internal2,cd); dtDaysBetween := internal1-internal2; end; function dtDateFullString(S : String) : String; var D : String; Z : Byte; begin D := ''; Z := StrToInt(Copy(S,1,2)); case Z of 1 : D := 'January'; 2 : D := 'February'; 3 : D := 'March'; 4 : D := 'April'; 5 : D := 'May'; 6 : D := 'June'; 7 : D := 'July'; 8 : D := 'August'; 9 : D := 'September'; 10: D := 'October'; 11: D := 'November'; 12: D := 'December'; else D := 'Unknown'; end; Z := StrToInt(Copy(S,4,2)); D := D+' '+St(Z)+', 19'+Copy(S,7,2); dtDateFullString := D; end; { function mRealDate(D : String) : String; begin mRealDate := Copy(D,1,2)+'/'+Copy(D,3,2)+'/'+Copy(D,7,2); end; } procedure dtTimeDiff(var dt : tDateTimeRec; dt1, dt2 : tDateTimeRec); begin with dt do begin day := dt2.day-dt1.day; hour := dt2.hour-dt1.hour; min := dt2.min-dt1.min; sec := dt2.sec-dt1.sec; if (hour < 0) then begin Inc(hour,24); Dec(day); end; if (min < 0) then begin Inc(min, 60); Dec(hour); end; if (sec < 0) then begin Inc(sec, 60); Dec(min); end; end; end; function dtTimeRecStr(dt : tDateTimeRec) : String; var S : String; begin with dt do begin if day > 1 then S := St(day)+' days, ' else if day > 0 then S := St(day)+' day, ' else S := ''; if hour > 1 then S := S+St(hour)+' hours, ' else if hour > 0 then S := S+St(hour)+' hour, '; if min > 1 then S := S+St(min)+' minutes, ' else if min > 0 then S := S+St(min)+' minute, '; if sec > 1 then S := S+St(sec)+' seconds' else if sec > 0 then S := S+St(sec)+' second'; end; if S = '' then S := 'no time' else if S[Length(S)-1] = ',' then Delete(S,Length(S)-1,2); dtTimeRecStr := S; end; function dtDatetoReal(dt : tDateTimeRec) : Real; begin with dt do dtDatetoReal := day*86400.0+hour*3600.0+min*60.0+sec; end; procedure dtGetDateTime(var dt : tDateTimeRec); var w1,w2,w3,w4:word; begin GetTime(w1,w2,w3,w4); with dt do begin day := dtdaynum(dtDateString); hour := w1; min := w2; sec := w3; end; end; function dtSecDiff(before, after : LongInt) : LongInt; begin if after > before then dtSecDiff := after-before else if before > after then dtSecDiff := 86400-before+after else dtSecDiff := 0; end; function dtRealDiff(before, after : Real) : Real; begin if after > before then dtRealDiff := after-before else if before > after then dtRealDiff := 86400-before+after else dtRealDiff := 0; end; function dtTimeRecLen(var d : tDateTimeRec) : String; var h, m : LongInt; s : String; begin h := d.day*24+d.hour; m := d.min; if h > 99 then h := 99; s := st(h); if Ord(s[0]) = 1 then s := '0'+s; s := s+':'+st(m); if m < 10 then Insert('0',s,4); dtTimeRecLen := s; end; end.
{Unidad con frame para almacenar y configurar las propiedades de un editor SynEdit. Las propiedades que se manejan son con respecto al coloreado. El frame definido, está pensado para usarse en una ventana de configuración. También incluye una lista para almacenamiento de los archivos recientes Por Tito Hinostroza 23/11/2013 } unit FrameCfgEdit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, StdCtrls, Dialogs, Spin, SynEdit, Graphics, SynEditMarkupHighAll, SynEditMarkup ,ConfigFrame; type { TfcEdit } TfcEdit = class(TCfgFrame) cbutFonPan: TColorButton; cbutResPal: TColorButton; cbutTxtPan: TColorButton; chkResPalCur: TCheckBox; chkVerBarDesH: TCheckBox; chkVerPanVer: TCheckBox; chkMarLinAct: TCheckBox; cbutLinAct: TColorButton; chkVerBarDesV: TCheckBox; chkVerNumLin: TCheckBox; chkVerMarPle: TCheckBox; cmbTipoLetra: TComboBox; cbutFondo: TColorButton; cbutTexto: TColorButton; GroupBox1: TGroupBox; Label1: TLabel; Label10: TLabel; Label2: TLabel; Label3: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; spTam: TSpinEdit; procedure chkMarLinActChange(Sender: TObject); procedure chkResPalCurChange(Sender: TObject); procedure chkVerPanVerChange(Sender: TObject); //genera constructor y destructor constructor Create(AOwner: TComponent) ; override; destructor Destroy; override; private ed: TSynEdit; procedure ConfigEditor; public //configuración del editor TipLet : string; //tipo de letra TamLet : integer; //tamaño de letra MarLinAct : boolean; //marcar línea actual VerBarDesV : boolean; //ver barras de desplazamiento VerBarDesH : boolean; //ver barras de desplazamiento ResPalCur : boolean; //resaltar palabra bajo el cursor cTxtNor : TColor; //color de texto normal cFonEdi : TColor; //Color de fondo del control de edición cFonSel : TColor; //color del fondo de la selección cTxtSel : TColor; //color del texto de la selección cLinAct : TColor; //color de la línea actual cResPal : TColor; //color de la palabra actual //panel vertical VerPanVer : boolean; //ver pánel vertical VerNumLin : boolean; //ver número de línea VerMarPle : boolean; //ver marcas de plegado cFonPan : TColor; //color de fondo del panel vertical cTxtPan : TColor; //color de texto del panel vertical ArcRecientes: TStringList; //Lista de archivos recientes procedure PropToWindow; override; procedure Iniciar(secINI0: string; ed0: TSynEdit; colFonDef: TColor=clWhite); //Inicia el frame procedure SetLanguage(lang: string); end; implementation {$R *.lfm} //const // MAX_ARC_REC = 5; //si se cambia, actualizar ActualMenusReciente() { TfcEdit } procedure TfcEdit.Iniciar(secINI0: string; ed0: TSynEdit; colFonDef: TColor = clWhite); begin secINI := secINI0; //sección INI //asigna referencia necesarias ed := ed0; OnUpdateChanges := @ConfigEditor; //manejador de cambios //crea las relaciones variable-control Asoc_Col_TColBut(@cTxtNor, cbutTexto, 'cTxtNor',clBlack); Asoc_Col_TColBut(@cFonEdi, cbutFondo, 'cFonEdi',colFonDef); Asoc_Col_TColBut(@cLinAct, cbutLinAct, 'cLinAct',clYellow); Asoc_Col_TColBut(@cResPal, cbutResPal, 'cResPal',clSkyBlue); Asoc_Bol_TChkBox(@VerBarDesV,chkVerBarDesV,'VerBarDesV',true); Asoc_Bol_TChkBox(@VerBarDesH,chkVerBarDesH,'VerBarDesH',false); Asoc_Bol_TChkBox(@ResPalCur,chkResPalCur,'ResPalCur',true); Asoc_Bol_TChkBox(@MarLinAct,chkMarLinAct,'MarLinAct',false); Asoc_Bol_TChkBox(@VerPanVer, chkVerPanVer, 'VerPanVer',true); Asoc_Bol_TChkBox(@VerNumLin, chkVerNumLin, 'VerNumLin',false); Asoc_Bol_TChkBox(@VerMarPle, chkVerMarPle, 'VerMarPle',true); Asoc_Col_TColBut(@cFonPan, cbutFonPan, 'cFonPan',colFonDef); Asoc_Col_TColBut(@cTxtPan, cbutTxtPan, 'cTxtPan',clBlack); Asoc_Int_TSpinEdit(@TamLet, spTam, 'TamLet', 10); cmbTipoLetra.Items.Clear; cmbTipoLetra.Items.Add('Courier New'); cmbTipoLetra.Items.Add('Fixedsys'); cmbTipoLetra.Items.Add('Lucida Console'); cmbTipoLetra.Items.Add('Consolas'); cmbTipoLetra.Items.Add('Cambria'); Asoc_Str_TCmbBox(@TipLet, cmbTipoLetra, 'TipLet', 'Courier New'); Asoc_StrList(@ArcRecientes, 'recient'); end; procedure TfcEdit.chkVerPanVerChange(Sender: TObject); begin chkVerNumLin.Enabled:=chkVerPanVer.Checked; chkVerMarPle.Enabled:=chkVerPanVer.Checked; cbutFonPan.Enabled:=chkVerPanVer.Checked; cbutTxtPan.Enabled:=chkVerPanVer.Checked; label2.Enabled:=chkVerPanVer.Checked; label3.Enabled:=chkVerPanVer.Checked; end; procedure TfcEdit.chkMarLinActChange(Sender: TObject); begin label1.Enabled:=chkMarLinAct.Checked; cbutLinAct.Enabled:=chkMarLinAct.Checked; end; procedure TfcEdit.chkResPalCurChange(Sender: TObject); begin label10.Enabled:=chkResPalCur.Checked; cbutResPal.Enabled:=chkResPalCur.Checked; end; procedure TfcEdit.PropToWindow; begin inherited; chkMarLinActChange(self); //para actualizar chkVerPanVerChange(self); //para actualizar end; constructor TfcEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); ArcRecientes := TStringList.Create; //crea lista end; destructor TfcEdit.Destroy; begin FreeAndNil(ArcRecientes); inherited Destroy; end; procedure TfcEdit.ConfigEditor; {Configura el editor con las propiedades almacenadas} var marc: TSynEditMarkup; begin if ed = nil then exit; //protección //tipo de texto if TipLet <> '' then ed.Font.Name:=TipLet; if (TamLet > 6) and (TamLet < 32) then ed.Font.Size:=Round(TamLet); ed.Font.Color:=cTxtNor; //color de texto normal ed.Color:=cFonEdi; //color de fondo if MarLinAct then //resaltado de línea actual ed.LineHighlightColor.Background:=cLinAct else ed.LineHighlightColor.Background:=clNone; //configura panel vertical ed.Gutter.Visible:=VerPanVer; //muestra panel vertical ed.Gutter.Parts[1].Visible:=VerNumLin; //Número de línea if ed.Gutter.Parts.Count>4 then ed.Gutter.Parts[4].Visible:=VerMarPle; //marcas de plegado ed.Gutter.Color:=cFonPan; //color de fondo del panel ed.Gutter.Parts[1].MarkupInfo.Background:=cFonPan; //fondo del núemro de línea ed.Gutter.Parts[1].MarkupInfo.Foreground:=cTxtPan; //texto del núemro de línea if VerBarDesV and VerBarDesH then //barras de desplazamiento ed.ScrollBars:= ssBoth else if VerBarDesV and not VerBarDesH then ed.ScrollBars:= ssVertical else if not VerBarDesV and VerBarDesH then ed.ScrollBars:= ssHorizontal else ed.ScrollBars := ssNone; ////////Configura el resaltado de la palabra actual ////////// marc := ed.MarkupByClass[TSynEditMarkupHighlightAllCaret]; if marc<>nil then begin //hay marcador marc.Enabled:=ResPalCur; //configura marc.MarkupInfo.Background := cResPal; end; ///////fija color de delimitadores () {} [] /////////// ed.BracketMatchColor.Foreground := clRed; end; procedure TfcEdit.SetLanguage(lang: string); //Rutina de traducción begin case lowerCase(lang) of 'es': begin Label6.Caption:='&Letra:'; Label7.Caption:='&Tamaño:'; Label8.Caption:='Color de fondo:'; Label9.Caption:='Color texto:'; chkVerBarDesV.Caption:='Barra de desplaz &Vert.'; chkVerBarDesH.Caption:='Barra de desplaz &Horiz.'; chkResPalCur.Caption:='Resaltar palabra bajo cursor'; chkMarLinAct.Caption:='Marcar línea actual'; chkVerPanVer.Caption:='Panel Vertical'; chkVerNumLin.Caption:='Ver Núm.de línea'; label2.Caption:='Color Fondo:'; chkVerMarPle.Caption:='Ver Marc.de plegado'; label3.Caption:='Color de texto:'; end; 'en': begin Label6.Caption:='&Font:'; Label7.Caption:='&Size:'; Label8.Caption:='Back color:'; Label9.Caption:='Font Color:'; chkVerBarDesV.Caption:='&Vertical Scrollbar'; chkVerBarDesH.Caption:='&Horizontal Scrollbar'; chkResPalCur.Caption:='Highlight current word'; chkMarLinAct.Caption:='Hightlight current line'; chkVerPanVer.Caption:='Gutter'; chkVerNumLin.Caption:='Show line number'; label2.Caption:='Back color:'; chkVerMarPle.Caption:='Show folding marks'; label3.Caption:='Text color:'; end; end; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.Types; interface uses System.SysUtils, System.Generics.Defaults, System.Generics.Collections, System.Classes; type { TfgPair } /// <summary>Шаблонный класс для хранения в ресурсах двух однотипных значений (размеры, координаты точки и тд).</summary> TfgPair<T> = class(TPersistent) private FValue1: T; FValue2: T; FComparator: TEqualityComparison<T>; FOnChange: TNotifyEvent; protected procedure DoChange; virtual; procedure AssignTo(Dest: TPersistent); override; function EqualsValue(const Value1, Value2: T): Boolean; virtual; { Setter and Getters } procedure SetValue1(const Value: T); procedure SetValue2(const Value: T); function GetValue1: T; inline; function GetValue2: T; inline; public constructor Create(const AX, AY: T; AComparator: TEqualityComparison<T> = nil); virtual; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TfgSingleSize = class(TfgPair<Single>) published property Width: Single read GetValue1 write SetValue1; property Height: Single read GetValue2 write SetValue2; end; { Comparators } /// <summary>Набор компараторов для разых типов значений</summary> TfgEqualityComparators = class public /// <summary>Проверка равенства двух вещественных чисел типа Single</summary> class function SingleEquality(const Value1, Value2: Single): Boolean; static; inline; end; { TfgPersistent } TfgPersistent = class(TPersistent) private [Weak] FOwner: TComponent; FOnInternalChanged: TNotifyEvent; protected function GetOwner: TPersistent; override; procedure DoInternalChanged; virtual; property Owner: TComponent read FOwner; property OnInternalChanged: TNotifyEvent read FOnInternalChanged; public constructor Create(AOwner: TComponent); overload; virtual; constructor Create(AOwner: TComponent; const AOnInternalChanged: TNotifyEvent); overload; destructor Destroy; override; function IsDefaultValues: Boolean; virtual; end; { TfgCollection } TfgCollection = class; TfgCollectionNotification = (Added, Extracting, Deleting, Updated); TfgCollectionChanged = procedure (Collection: TfgCollection; Item: TCollectionItem; const Action: TfgCollectionNotification) of object; TfgCollection = class(TCollection) private FOwner: TPersistent; FOnInternalChanged: TfgCollectionChanged; protected procedure DoInternalChanged(Item: TCollectionItem; const Action: TfgCollectionNotification); virtual; function CanInternalChange: Boolean; { TCollection } procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override; procedure Update(Item: TCollectionItem); override; function GetOwner: TPersistent; override; public constructor Create(AOwner: TPersistent; const ItemClass: TCollectionItemClass; const AOnInternalChanged: TfgCollectionChanged); overload; constructor Create(ItemClass: TCollectionItemClass; const AOnInternalChanged: TfgCollectionChanged); overload; end; implementation uses System.Math, FGX.Consts; { TfgPair<T> } procedure TfgPair<T>.AssignTo(Dest: TPersistent); var DestSize: TfgPair<T>; begin if Dest is TfgPair<T> then begin DestSize := Dest as TfgPair<T>; DestSize.FValue1 := GetValue1; DestSize.FValue2 := GetValue2; end else inherited AssignTo(Dest); end; function TfgPair<T>.EqualsValue(const Value1, Value2: T): Boolean; begin if Assigned(FComparator) then Result := FComparator(Value1, Value2) else Result := False; end; function TfgPair<T>.GetValue1: T; begin Result := FValue1; end; function TfgPair<T>.GetValue2: T; begin Result := FValue2; end; constructor TfgPair<T>.Create(const AX, AY: T; AComparator: TEqualityComparison<T> = nil); begin FValue2 := AX; FValue1 := AY; FComparator := AComparator; end; procedure TfgPair<T>.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TfgPair<T>.SetValue1(const Value: T); begin if not EqualsValue(FValue1, Value) then begin FValue1 := Value; DoChange; end; end; procedure TfgPair<T>.SetValue2(const Value: T); begin if not EqualsValue(FValue2, Value) then begin FValue2 := Value; DoChange; end; end; { TfgEqualityComparators } class function TfgEqualityComparators.SingleEquality(const Value1, Value2: Single): Boolean; begin Result := SameValue(Value1, Value2, EPSILON_SINGLE); end; { TfgPersistent } constructor TfgPersistent.Create(AOwner: TComponent); begin inherited Create; FOwner := AOwner; end; constructor TfgPersistent.Create(AOwner: TComponent; const AOnInternalChanged: TNotifyEvent); begin FOnInternalChanged := AOnInternalChanged; Create(AOwner); end; destructor TfgPersistent.Destroy; begin FOnInternalChanged := nil; inherited Destroy; end; procedure TfgPersistent.DoInternalChanged; begin if Assigned(FOnInternalChanged) then FOnInternalChanged(Self); end; function TfgPersistent.GetOwner: TPersistent; begin Result := FOwner; end; function TfgPersistent.IsDefaultValues: Boolean; begin Result := False; end; { TfgCollection } constructor TfgCollection.Create(AOwner: TPersistent; const ItemClass: TCollectionItemClass; const AOnInternalChanged: TfgCollectionChanged); begin Create(ItemClass); FOwner := AOwner; FOnInternalChanged := AOnInternalChanged; end; function TfgCollection.CanInternalChange: Boolean; var ForbiddenStates: TComponentState; begin ForbiddenStates := [csLoading, csDestroying] * TComponent(Owner).ComponentState; Result := (Owner = nil) or (Owner is TComponent) and (ForbiddenStates = []); end; constructor TfgCollection.Create(ItemClass: TCollectionItemClass; const AOnInternalChanged: TfgCollectionChanged); begin Create(nil, ItemClass, AOnInternalChanged); end; procedure TfgCollection.DoInternalChanged(Item: TCollectionItem; const Action: TfgCollectionNotification); begin if Assigned(FOnInternalChanged) and (Owner <> nil) then FOnInternalChanged(Self, Item, Action); end; function TfgCollection.GetOwner: TPersistent; begin Result := FOwner; end; procedure TfgCollection.Notify(Item: TCollectionItem; Action: TCollectionNotification); var Notification: TfgCollectionNotification; begin case Action of cnAdded: Notification := TfgCollectionNotification.Added; cnExtracting: Notification := TfgCollectionNotification.Extracting; cnDeleting: Notification := TfgCollectionNotification.Deleting; else raise Exception.Create('Unknown value of [System.Classes.TCollectionNotification])'); end; if CanInternalChange then DoInternalChanged(Item, Notification); inherited; end; procedure TfgCollection.Update(Item: TCollectionItem); begin inherited; if (Item <> nil) and CanInternalChange then DoInternalChanged(Item, TfgCollectionNotification.Updated); end; end.
unit PersonBuilder; interface uses PersonBodyProperty; type TPersonBuilder = class private FPersonBodyProperty: TPersonBodyProperty; public constructor Create; destructor Destroy; override; procedure BuildHead; virtual; abstract; procedure BuildBody; virtual; abstract; procedure BuildArmLeft; virtual; abstract; procedure BuildArmRight; virtual; abstract; procedure BuildLegLeft; virtual; abstract; procedure BuildLegRight; virtual; abstract; function GetPersonInfo: string; end; TPersonThinBuilder = class(TPersonBuilder) public procedure BuildHead; override; procedure BuildBody; override; procedure BuildArmLeft; override; procedure BuildArmRight; override; procedure BuildLegLeft; override; procedure BuildLegRight; override; end; TPersonFatBuilder = class(TPersonBuilder) public procedure BuildHead; override; procedure BuildBody; override; procedure BuildArmLeft; override; procedure BuildArmRight; override; procedure BuildLegLeft; override; procedure BuildLegRight; override; end; implementation { TPersonBuilder } constructor TPersonBuilder.Create; begin FPersonBodyProperty := TPersonBodyProperty.Create; end; destructor TPersonBuilder.Destroy; begin FPersonBodyProperty.Free; inherited; end; function TPersonBuilder.GetPersonInfo: string; begin Result := FPersonBodyProperty.GetPersonInfo; end; { TPersonFatBuilder } procedure TPersonFatBuilder.BuildArmLeft; begin FPersonBodyProperty.Add('ÅÖ×ó±Û'); end; procedure TPersonFatBuilder.BuildArmRight; begin FPersonBodyProperty.Add('ÅÖÓÒ±Û'); end; procedure TPersonFatBuilder.BuildBody; begin FPersonBodyProperty.Add('ÅÖÉíÌå'); end; procedure TPersonFatBuilder.BuildHead; begin FPersonBodyProperty.Add('ÅÖÍ·'); end; procedure TPersonFatBuilder.BuildLegLeft; begin FPersonBodyProperty.Add('ÅÖ×óÍÈ'); end; procedure TPersonFatBuilder.BuildLegRight; begin FPersonBodyProperty.Add('ÅÖÓÒÍÈ'); end; { TPersonThinBuilder } procedure TPersonThinBuilder.BuildArmLeft; begin FPersonBodyProperty.Add('ÊÝ×ó±Û'); end; procedure TPersonThinBuilder.BuildArmRight; begin FPersonBodyProperty.Add('ÊÝÓÒ±Û'); end; procedure TPersonThinBuilder.BuildBody; begin FPersonBodyProperty.Add('ÊÝÉíÌå'); end; procedure TPersonThinBuilder.BuildHead; begin FPersonBodyProperty.Add('ÊÝÍ·'); end; procedure TPersonThinBuilder.BuildLegLeft; begin FPersonBodyProperty.Add('ÊÝ×óÍÈ'); end; procedure TPersonThinBuilder.BuildLegRight; begin FPersonBodyProperty.Add('ÊÝÓÒÍÈ'); end; end.
unit Auxiliary; interface uses Graphics, MetroVisCom; function ColorNameToColor(AString: String): TColor; // pre: True // ret: The color named AString, if AString represents a color contained in the // standard colors or the extended colors // clDefaultColor, otherwise function ColorToColorName(AColor: TColor): String; // pre: True // ret: The name of the color AColor, if AColor is contained in the // standard colors or the extended colors // DefaultColorName, otherwise function StringToTextPos(AString: String): TTextPos; // pre: True // ret: The direction of the wind named AString function TextPosToString(ATextPos: TTextPos): String; // pre: True // ret: The name of the direction of the wind ATextPos implementation type TColorPair = record N: String; C: TColor; end; TPosPair = record S: String; P: TTextPos; end; const ColorTable: array[0..19] of TColorPair = ( (N: 'clAqua' ; C: clAqua) , (N: 'clBlack' ; C: clBlack) , (N: 'clBlue' ; C: clBlue) , (N: 'clCream' ; C: clCream) , (N: 'clFuchsia' ; C: clFuchsia) , (N: 'clGreen' ; C: clGreen) , (N: 'clGray' ; C: clGray) , (N: 'clLime' ; C: clLime) , (N: 'clMaroon' ; C: clMaroon) , (N: 'clMedGray' ; C: clMedGray) , (N: 'clMoneyGreen'; C: clMoneyGreen) , (N: 'clNavy' ; C: clNavy) , (N: 'clOlive' ; C: clOlive) , (N: 'clPurple' ; C: clPurple) , (N: 'clRed' ; C: clRed) , (N: 'clSilver' ; C: clSilver) , (N: 'clSkyBlue' ; C: clSkyBlue) , (N: 'clTeal' ; C: clTeal) , (N: 'clYellow' ; C: clYellow) , (N: 'clWhite' ; C: clWhite) ); PosTable: array[0..7] of TPosPair = ( (S: 'N' ; P: tpNorth) , (S: 'NE'; P: tpNorthEast) , (S: 'E' ; P: tpEast) , (S: 'SE'; P: tpSouthEast) , (S: 'S' ; P: tpSouth) , (S: 'SW'; P: tpSouthWest) , (S: 'W' ; P: tpWest) , (S: 'NW'; P: tpNorthWest) ); clDefaultColor = clBlack; DefaultColorName = 'clBlack'; function ColorNameToColor(AString: String): TColor; var I: Integer; begin Result := clDefaultColor; for I := 0 to 19 do if ColorTable[I].N = AString then Result := ColorTable[I].C; end; function ColorToColorName(AColor: TColor): String; var I: Integer; begin Result := DefaultColorName; for I := 0 to 19 do if ColorTable[I].C = AColor then Result := ColorTable[I].N; end; function StringToTextPos(AString: String): TTextPos; var I: Integer; begin Result := tpNorth; for I := 0 to 7 do if PosTable[I].S = AString then Result := PosTable[I].P; end; function TextPosToString(ATextPos: TTextPos): String; var I: Integer; begin Result := ''; for I := 0 to 7 do if PosTable[I].P = ATextPos then Result := PosTable[I].S; end; end.
{** * @Author: Du xinming * @Contact: QQ<36511179>; Email<lndxm1979@163.com> * @Version: 0.0 * @Date: 2018.10.29 * @Brief: *} unit org.tcpip.tcp.client; interface uses Winapi.Windows, Winapi.Winsock2, System.SysUtils, System.Classes, System.Math, org.algorithms, org.algorithms.queue, org.utilities, org.utilities.buffer, org.tcpip, org.tcpip.tcp; type PTCPRequestParameters = ^TTCPRequestParameters; TTCPRequestParameters = record RemoteIP: string; RemotePort: Word; end; TTCPClientSocket = class(TTCPIOContext) protected procedure DoConnected; override; procedure TeaAndCigaretteAndMore(var Tea: Int64; var Cigarette: DWORD); override; public constructor Create(AOwner: TTCPIOManager); override; destructor Destroy; override; end; TTCPClient = class(TTCPIOManager) private FMaxPreIOContextCount: Integer; // 客户端开始工作前准备的已绑定、未连接的套接字数 FIOContextClass: TTCPIOContextClass; FFreeContexts: TFlexibleQueue<TTCPIOContext>; //\\ procedure SetMaxPreIOContextCount(const Value: Integer); public constructor Create; destructor Destroy; override; procedure RegisterIOContextClass(IOType: DWORD; AClass: TTCPIOContextClass); override; function DequeueFreeContext(IOType: DWORD): TTCPIOContext; override; procedure EnqueueFreeContext(AContext: TTCPIOContext); override; //\\ procedure DoWaitTIMEWAIT(IOContext: TTCPIOContext); override; //\\ function SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; Options: DWORD): Boolean; overload; function SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; BodyEx: PAnsiChar; LengthEx: DWORD; Options: DWORD): Boolean; overload; function SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; BodyEx: TStream; LengthEx: DWORD; Options: DWORD): Boolean; overload; function SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; FilePath: string; Options: DWORD): Boolean; overload; function SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length: DWORD; Options: DWORD): Boolean; overload; function SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length: DWORD; BodyEx: PAnsiChar; LengthEx: DWORD; Options: DWORD): Boolean; overload; function SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length: DWORD; BodyEx: TStream; LengthEx: DWORD; Options: DWORD): Boolean; overload; function SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length: DWORD; FilePath: string; Options: DWORD): Boolean; overload; //\\ procedure Start; override; procedure Stop; override; property MaxPreIOContextCount: Integer read FMaxPreIOContextCount write SetMaxPreIOContextCount; end; implementation { TTCPClientSocket } constructor TTCPClientSocket.Create(AOwner: TTCPIOManager); begin inherited; FStatus := $20000000; end; destructor TTCPClientSocket.Destroy; begin inherited; end; procedure TTCPClientSocket.DoConnected; var Status: DWORD; IOStatus: Int64; //{$IfDef DEBUG} // Msg: string; //{$Endif} begin if Assigned(FOwner.OnConnected) then FOwner.OnConnected(nil, Self); //{$IfDef DEBUG} // Msg := Format('[%d][%d]<%s.DoConnected>[INIT][FIOStatus] FIOStatus=%x', // [ FSocket, // GetCurrentThreadId(), // ClassName, // FIOStatus]); // FOwner.WriteLog(llDebug, Msg); //{$Endif} SendBuffer(); Status := FStatus; IOStatus := FSendIOStatus; TeaAndCigaretteAndMore(IOStatus, Status); if Status and $80000040 = $00000040 then begin // [正常结束] if not HasWriteIO(IOStatus) then FOwner.EnqueueFreeContext(Self); end else if HasError(IOStatus) or (Status and $80000000 = $80000000) then begin if not HasWriteOrIO(IOStatus) then begin FOwner.EnqueueFreeContext(Self); end; end else begin // nothing? end; end; procedure TTCPClientSocket.TeaAndCigaretteAndMore(var Tea: Int64; var Cigarette: DWORD); var More: Boolean; begin More := True; while (not HasErrorOrReadIO(Tea)) and (FStatus and $80000000 = $00000000) and More do begin if FStatus and $8000005F = $00000003 then begin // 1000,...,0101,1111, if FRecvBytes < FHeadSize then begin // 首次读(或继续读)Protocol Head Tea := RecvProtocol(); end else begin // 此时应用层协议头读完 FStatus := FStatus or $00000004; // 协议头接收完 ParseProtocol(); // 解析协议头 [这里可能产生独立的$8000,0000错误] Cigarette := FStatus; if FStatus and $80000000 = $00000000 then begin // 协议解析成功 GetBodyFileHandle(); Cigarette := FStatus; if FRecvBytes < FHeadSize + FHead^.Length then begin if FStatus and $80000000 = $00000000 then begin Tea := RecvBuffer(); end; end; end; end; end else if FStatus and $8000005F = 00000007 then begin // 1000,...,0101,1111 if FBodyInFile then // 将收到的Buffer写入临时文件 WriteBodyToFile(); // [这里可能产生独立的$8000,0000错误] Cigarette := FStatus; if FStatus and $80000000 = $00000000 then begin if FRecvBytes < FHeadSize + FHead^.Length then begin // 继续接收Body Tea := RecvBuffer(); end else begin FStatus := FStatus or $00000008; ParseAndProcessBody(); // [这里可能产生非独立独立的$8000,0000错误] Cigarette := FStatus; if FStatus and $80000000 = $00000000 then begin if FHead^.LengthEx = 0 then begin if FHead^.Options and IO_OPTION_ONCEMORE = $00000000 then begin Tea := SendDisconnect(); end else begin FRecvBytes := FRecvBytes - FHeadSize - FHead^.Length; FStatus := FStatus and $E0000003; // 1110,0000,...,0000,0011 end; end else begin GetBodyExFileHandle(); Cigarette := FStatus; if FRecvBytes < FHeadSize + FHead^.Length + FHead^.LengthEx then begin // 开始接收BodyEx if FStatus and $80000000 = $00000000 then begin Tea := RecvBuffer(); end; end; end; end; end; end; end else if (FStatus and $8000005F = $0000000F) and (FHead^.LengthEx > 0) then begin //1000,...,0101,1111 if FBodyExInFile then // 写入BodyExFile WriteBodyExToFile(); // [这里可能产生非独立独立的$8000,0000错误] Cigarette := FStatus; if FStatus and $80000000 = $00000000 then begin if FRecvBytes < FHeadSize + FHead^.Length + FHead^.LengthEx then begin // 继续接收BodyEx Tea := RecvBuffer(); end else begin FStatus := FStatus or $00000010; ParseAndProcessBodyEx(); // [这里可能产生非独立独立的$8000,0000错误] Cigarette := FStatus; // dxm 2018.11.13 // 1.对客户端来说,到此,收到了服务端发送的全部响应 // 2.既然收到了服务端的全部响应,也证明客户端的数据全部发送完成 // 因此,这里要投递优雅关闭重叠IO了 if FStatus and $80000000 = $00000000 then begin if FHead^.Options and IO_OPTION_ONCEMORE = $00000000 then begin Tea := SendDisconnect(); end else begin FRecvBytes := FRecvBytes - FHeadSize - FHead^.Length - FHead^.LengthEx; FStatus := FStatus and $E0000003; // 1110,0000,...,0000,0011 end; end; end; end; end // else if FStatus and $00000060 = $00000020 then begin // 1000,...,0101,1111 // // nothing // end else if ((FStatus and $8000005F = $0000005F) and (FHead^.LengthEx > 0)) or ( FStatus and $8000005F = $0000004F) then begin // 1000,...,0101,1111 Cigarette := FStatus; More := False; // [dxm 2018.11.9 no more? maybe!] end else begin // nothing or unkown error end; end; end; { TTCPClient } constructor TTCPClient.Create; begin inherited; FMaxPreIOContextCount := MAX_PRE_IOCONTEXT_COUNT; // 默认最大预连接数 FIOContextClass := nil; end; function TTCPClient.DequeueFreeContext(IOType: DWORD): TTCPIOContext; begin Result := FFreeContexts.Dequeue(); if Result = nil then begin Result := FIOContextClass.Create(Self); // Result.FSocket := INVALID_SOCKET; end; end; destructor TTCPClient.Destroy; begin FFreeContexts.Free(); inherited; end; procedure TTCPClient.DoWaitTIMEWAIT(IOContext: TTCPIOContext); {$IfDef DEBUG} var Msg: string; {$Endif} begin {$IfDef DEBUG} Msg := Format('[%d][%d]<%s.DoWaitTIMEWAIT> enqueue IOContext into FreeIOConetxt queue!', [ IOContext.Socket, GetCurrentThreadId(), ClassName]); WriteLog(llDebug, Msg); {$Endif} inherited; FFreeContexts.Enqueue(IOContext); end; procedure TTCPClient.EnqueueFreeContext(AContext: TTCPIOContext); var IOContext: TTCPClientSocket; //{$Ifdef DEBUG} // Msg: string; //{$Endif} begin inherited; IOContext := AContext as TTCPClientSocket; // 仅当上下文状态中存在$8000,0000时强制关闭套接字对象 if IOContext.FStatus and $C0000000 = $80000000 then begin if IOContext.Socket <> INVALID_SOCKET then begin IOContext.HardCloseSocket(); end; IOContext.FStatus := IOContext.FStatus and $20000000; FFreeContexts.Enqueue(AContext); end else begin //{$IfDef DEBUG} // Msg := Format('[%d][%d]<%s.EnqueueFreeContext> enqueue IOContext into TimeWheel for <TIMEWAITExpired>, ExpireTime=%ds, Status=%s', // [ IOContext.FSocket, // GetCurrentThreadId(), // ClassName, // 4 * 60, // IOContext.StatusString()]); // WriteLog(llDebug, Msg); //{$Endif} IOContext.FStatus := IOContext.FStatus and $20000000; FTimeWheel.StartTimer(IOContext, 4 * 60 * 1000, DoWaitTIMEWAIT); end; end; procedure TTCPClient.RegisterIOContextClass(IOType: DWORD; AClass: TTCPIOContextClass); begin FIOContextClass := AClass; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; ErrDesc: string; begin Result := True; IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := 0; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(Body, Length); IOContext.FSendBuffers.EnqueueEx(buf); finally IOContext.FSendBuffers.Unlock(); end; // dxm 2018.11.14 // 客户端通过该函数进行连接并准备了第一块待发送的数据 // 但是此时不能发送,只能先暂存,因为连接还没建立 // 由于暂存和发送动作时分离的,这里首先得正确地初始化控制变量, // 否则,如果有后续发送需求的话,发送函数SendBuffer将不会触发 IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; // dxm 2018.11.13 // 当ConnectEx重叠IO通知到达时: // 1. WSAECONNREFUSED 10061 通常是对端服务器未启动 [通知时][调用时][正常][可重用] // 2. WSAENETUNREACH 10051 网络不可达,通常是路由无法探知远端 [通知时][调用时][正常][可重用] // 3. WSAETIMEDOUT 10060 连接超时 [通知时][------][正常][可重用] iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); FreeMem(Body, Length); EnqueueFreeContext(IOContext); end; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length, Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; ByteBuf: TByteBuffer; StreamBuf: TStreamBuffer; ErrDesc: string; begin Result := True; IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := 0; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try ByteBuf := TByteBuffer.Create(); ByteBuf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(ByteBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(Body); IOContext.FSendBuffers.EnqueueEx(StreamBuf); finally IOContext.FSendBuffers.Unlock(); end; IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); Body.Free(); EnqueueFreeContext(IOContext); end; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; FilePath: string; Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; FileHandle: THandle; FileLength: Int64; FileBuf: TFileBuffer; ErrDesc: string; begin Result := True; FileHandle := FileOpen(FilePath, fmOpenRead or fmShareDenyWrite); if FileHandle <> INVALID_HANDLE_VALUE then begin FileLength := FileSeek(FileHandle, 0, 2); IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := FileLength; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(Body, Length); IOContext.FSendBuffers.EnqueueEx(buf); FileBuf := TFileBuffer.Create(); FileBuf.SetBuffer(FileHandle, FileLength); IOContext.FSendBuffers.EnqueueEx(FileBuf); finally IOContext.FSendBuffers.Unlock(); end; IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length + FileLength; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); FreeMem(Body, Length); FileClose(FileHandle); EnqueueFreeContext(IOContext); end; end else begin Result := False; FreeMem(Body, Length); end; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; BodyEx: TStream; LengthEx, Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; StreamBuf: TStreamBuffer; ErrDesc: string; begin Result := True; IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(Body, Length); IOContext.FSendBuffers.EnqueueEx(buf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(BodyEx); IOContext.FSendBuffers.EnqueueEx(StreamBuf); finally IOContext.FSendBuffers.Unlock(); end; IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length + LengthEx; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); FreeMem(Body, Length); BodyEx.Free(); EnqueueFreeContext(IOContext); end; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: PAnsiChar; Length: DWORD; BodyEx: PAnsiChar; LengthEx, Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; ErrDesc: string; begin Result := True; IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(Body, Length); IOContext.FSendBuffers.EnqueueEx(buf); buf := TByteBuffer.Create(); buf.SetBuffer(BodyEx, LengthEx); IOContext.FSendBuffers.EnqueueEx(buf); finally IOContext.FSendBuffers.Unlock(); end; IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length + LengthEx; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); FreeMem(Body, Length); FreeMem(BodyEx, LengthEx); EnqueueFreeContext(IOContext); end; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length: DWORD; FilePath: string; Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; StreamBuf: TStreamBuffer; FileHandle: THandle; FileLength: Int64; FileBuf: TFileBuffer; ErrDesc: string; begin Result := True; FileHandle := FileOpen(FilePath, fmOpenRead or fmShareDenyWrite); if FileHandle <> INVALID_HANDLE_VALUE then begin FileLength := FileSeek(FileHandle, 0, 2); IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := FileLength; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(buf); Streambuf := TStreamBuffer.Create(); Streambuf.SetBuffer(Body); IOContext.FSendBuffers.EnqueueEx(Streambuf); FileBuf := TFileBuffer.Create(); FileBuf.SetBuffer(FileHandle, FileLength); IOContext.FSendBuffers.EnqueueEx(FileBuf); finally IOContext.FSendBuffers.Unlock(); end; IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length + FileLength; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); Body.Free(); FileClose(FileHandle); EnqueueFreeContext(IOContext); end; end else begin Result := False; Body.Free(); end; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length: DWORD; BodyEx: TStream; LengthEx, Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; StreamBuf: TStreamBuffer; ErrDesc: string; begin Result := True; IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(buf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(Body); IOContext.FSendBuffers.EnqueueEx(StreamBuf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(BodyEx); IOContext.FSendBuffers.EnqueueEx(StreamBuf); finally IOContext.FSendBuffers.Unlock(); end; IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length + LengthEx; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); Body.Free(); BodyEx.Free(); EnqueueFreeContext(IOContext); end; end; function TTCPClient.SendRequest(Parameters: PTCPRequestParameters; Body: TStream; Length: DWORD; BodyEx: PAnsiChar; LengthEx, Options: DWORD): Boolean; var iRet: Integer; IOContext: TTCPClientSocket; IOBuffer: PTCPIOBuffer; AHead: TTCPSocketProtocolHead; pHead: PAnsiChar; buf: TByteBuffer; StreamBuf: TStreamBuffer; ErrDesc: string; begin Result := True; IOContext := TTCPClientSocket(DequeueFreeContext($20000000)); if PrepareSingleIOContext(IOContext) then begin IOContext.FRemoteIP := Parameters^.RemoteIP; IOContext.FRemotePort := Parameters^.RemotePort; AHead.Version := VERSION; AHead.Options := Options; AHead.Length := Length; AHead.LengthEx := LengthEx; IOContext.FillProtocol(@AHead); pHead := AllocMem(FHeadSize); Move((@AHead)^, pHead^, FHeadSize); IOContext.FSendBuffers.Lock(); try buf := TByteBuffer.Create(); buf.SetBuffer(pHead, FHeadSize); IOContext.FSendBuffers.EnqueueEx(buf); StreamBuf := TStreamBuffer.Create(); StreamBuf.SetBuffer(Body); IOContext.FSendBuffers.EnqueueEx(StreamBuf); buf := TByteBuffer.Create(); buf.SetBuffer(BodyEx, LengthEx); IOContext.FSendBuffers.EnqueueEx(buf); finally IOContext.FSendBuffers.Unlock(); end; IOContext.FSendBusy := IOContext.FSendBusy + FHeadSize + Length + LengthEx; IOBuffer := DequeueIOBuffer(); IOBuffer^.OpType := otConnect; IOBuffer^.Context := IOContext; iRet := FIOHandle.PostConnect(IOContext.FSocket, IOBuffer); if (iRet <> 0) and (iRet <> WSA_IO_PENDING) then begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PostConnect> LastErrorCode=%d, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, iRet, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); if (iRet <> WSAECONNREFUSED) or (iRet <> WSAENETUNREACH) or (iRet <> WSAETIMEDOUT) then IOContext.Set80000000Error(); EnqueueIOBuffer(IOBuffer); EnqueueFreeContext(IOContext); end; end else begin Result := False; ErrDesc := Format('[%d][%d]<%s.SendRequest.PrepareSingleIOContext> failed, Status=%s', [ IOContext.FSocket, GetCurrentThreadId(), ClassName, IOContext.StatusString()]); WriteLog(llNormal, ErrDesc); Body.Free(); FreeMem(BodyEx, LengthEx); EnqueueFreeContext(IOContext); end; end; procedure TTCPClient.SetMaxPreIOContextCount(const Value: Integer); begin if FMaxPreIOContextCount <> Value then FMaxPreIOContextCount := Value; end; procedure TTCPClient.Start; var iRet: Integer; begin inherited; if FIOContextClass = nil then raise Exception.Create('业务处理类尚未注册,启动前请调用 RegisterIOContextClass'); // 创建并初始化内存池 FBufferPool := TBufferPool.Create(); FBufferPool.Initialize(1000 * 64, 100 * 64, FBufferSize); // 创建并初始化IOBuffer池 FIOBuffers := TFlexibleQueue<PTCPIOBuffer>.Create(64); FIOBuffers.OnItemNotify := DoIOBufferNotify; // 创建并初始化IOContext池 FFreeContexts := TFlexibleQueue<TTCPIOContext>.Create(64); FFreeContexts.OnItemNotify := DoIOContextNotify; // 准备套接字上下文 iRet := PrepareMultiIOContext(FIOContextClass, FMaxPreIOContextCount); if iRet = 0 then raise Exception.Create('准备套接字上下文失败'); end; procedure TTCPClient.Stop; begin inherited; end; end.
program t_kecc7; {Monte Carlo known answer test for Keccak f[1600], WE Nov.2012} {Test vectors from MonteCarlo_xx.txt, j=99, xx=0,224,256,384,512} {$i std.inc} {$ifdef APPCONS} {$apptype console} {$endif} uses {$ifdef WINCRT} WinCRT, {$endif} BTypes, Mem_Util, keccak_n; const seed: array[0..127] of byte = ($6c,$d4,$c0,$c5,$cb,$2c,$a2,$a0, $f1,$d1,$ae,$ce,$ba,$c0,$3b,$52, $e6,$4e,$a0,$3d,$1a,$16,$54,$37, $29,$36,$54,$5b,$92,$bb,$c5,$48, $4a,$59,$db,$74,$bb,$60,$f9,$c4, $0c,$eb,$1a,$5a,$a3,$5a,$6f,$af, $e8,$03,$49,$e1,$4c,$25,$3a,$4e, $8b,$1d,$77,$61,$2d,$dd,$81,$ac, $e9,$26,$ae,$8b,$0a,$f6,$e5,$31, $76,$db,$ff,$cc,$2a,$6b,$88,$c6, $bd,$76,$5f,$93,$9d,$3d,$17,$8a, $9b,$de,$9e,$f3,$aa,$13,$1c,$61, $e3,$1c,$1e,$42,$cd,$fa,$f4,$b4, $dc,$de,$57,$9a,$37,$e1,$50,$ef, $be,$f5,$55,$5b,$4c,$1c,$b4,$04, $39,$d8,$35,$a7,$24,$e2,$fa,$e7); t224: array[0.. 27] of byte = ($11,$d9,$78,$de,$9f,$5c,$13,$4b, $43,$4e,$98,$e6,$31,$27,$20,$66, $e8,$6b,$b0,$f5,$b0,$77,$11,$f2, $a4,$1e,$f0,$89); t256: array[0.. 31] of byte = ($5e,$c1,$4b,$3d,$56,$83,$3e,$a0, $70,$f4,$df,$d6,$b0,$c3,$19,$f5, $d2,$f4,$cb,$77,$5f,$84,$8b,$8c, $2d,$59,$8e,$07,$c0,$63,$a1,$5a); t384: array[0.. 47] of byte = ($df,$da,$2f,$f7,$83,$b6,$ff,$79, $7d,$96,$f2,$7a,$78,$c0,$25,$bb, $5f,$7e,$9a,$24,$c3,$06,$17,$1d, $80,$91,$aa,$a0,$b7,$97,$87,$be, $ec,$1d,$48,$89,$72,$f7,$0b,$58, $c7,$4f,$f0,$8d,$5b,$ca,$91,$1e); t512: array[0.. 63] of byte = ($d1,$f5,$17,$57,$7f,$4b,$50,$33, $44,$93,$5c,$b7,$25,$a6,$ef,$fa, $f5,$23,$a5,$43,$ea,$fe,$ee,$12, $7f,$cb,$85,$2d,$6b,$ef,$33,$e0, $48,$76,$af,$d5,$50,$49,$99,$ed, $63,$ca,$7f,$02,$6f,$60,$f1,$a3, $0d,$f2,$ed,$a3,$6c,$5c,$62,$82, $95,$7e,$15,$0f,$03,$e6,$06,$71); t000: array[0.. 63] of byte = ($59,$41,$5a,$96,$e0,$2f,$cd,$16, $95,$24,$7d,$3b,$4b,$39,$0f,$f6, $83,$3b,$a9,$3a,$b4,$ee,$4e,$da, $c6,$aa,$52,$5c,$12,$70,$8c,$52, $14,$45,$1c,$58,$b4,$79,$d6,$64, $d1,$e2,$2e,$01,$c3,$96,$27,$3e, $17,$42,$66,$b3,$ac,$96,$83,$79, $ea,$dc,$e9,$df,$24,$c7,$a3,$41); {---------------------------------------------------------------------------} procedure mct_0; {-MCT with iterative squeezing of 64 bytes} var state: thashState; md: array[0..127] of byte; i,j,err: integer; begin write(' Squeeze 512 bits: '); err := Init(state,0); if err<>0 then begin writeln(' Init error ',err); exit; end; err := Update(state, @seed, sizeof(seed)*8); if err<>0 then begin writeln(' Update error ',err); exit; end; Err := Final(state, @md); if err<>0 then begin writeln(' Final error ',err); exit; end; for j:=0 to 99 do begin if odd(j) then write('.'); for i:=1 to 1000 do begin err := Squeeze(state, @md, 512); if err<>0 then begin writeln(' Squeeze error ',err); exit; end; end; end; writeln(compmem(@md, @t000, sizeof(t000)):6); end; {---------------------------------------------------------------------------} procedure monte_carlo(HashBitlen: integer; digp: pointer; digbytes: integer); var msg,md: array[0..127] of byte; i,j,k,err,bl: integer; begin if HashBitlen=0 then mct_0 else begin write(' Keccak ',HashBitlen,' bits: '); move(seed, msg, sizeof(msg)); bl := HashBitlen div 8; for j:=0 to 99 do begin if odd(j) then write('.'); for i:=1 to 1000 do begin err := KeccakFullBytes(HashBitlen, @msg, sizeof(msg), @md); if err<>0 then begin writeln(' KeccakFull error ',err); exit; end; for k:=127 downto bl do msg[k] := msg[k-bl]; for k:=0 to bl-1 do msg[k] := md[k]; end; end; writeln(compmem(@md, digp, digbytes):6); end; end; begin writeln('Keccak SHA-3 Monte Carlo Known Answer Test'); monte_carlo(224, @t224, sizeof(t224)); monte_carlo(256, @t256, sizeof(t256)); monte_carlo(384, @t384, sizeof(t384)); monte_carlo(512, @t512, sizeof(t512)); monte_carlo( 0, @t000, sizeof(t000)); end.
unit SIP_Event; interface uses Classes, SyncObjs; type TSIPEventScript=class(TCollectionItem) private FRingGroup: Integer; FCount: Integer; FScriptID: Integer; procedure SetCount(const Value: Integer); procedure SetRingGroup(const Value: Integer); procedure SetScriptID(const Value: Integer); published property ScriptID:Integer read FScriptID write SetScriptID; property RingGroup:Integer read FRingGroup write SetRingGroup; property Count:Integer read FCount write SetCount; end; TSIPEvent=class(TCollection) private FParameters: TStrings; FName: String; FMode: Integer; FEventKind: Integer; FID: Integer; FCrisisKind: Integer; FReport:String; FReportFile:TFileStream; FQueueStatus:String; FTime:TDateTime; FDatabase: Integer; FQueueItems:Integer; FWait:Int64; FLog: Boolean; FLock: TCriticalSection; function GetText: String; procedure SetText(const Value: String); procedure SetParameters(const Value: TStrings); procedure SetName(const Value: String); function GetEventScript(Index: Integer): TSIPEventScript; procedure SetEventKind(const Value: Integer); procedure SetMode(const Value: Integer); procedure SetID(const Value: Integer); procedure SetCrisisKind(const Value: Integer); procedure SetDatabase(const Value: Integer); procedure SetLog(const Value: Boolean); public constructor Create; destructor Destroy;override; function Add: TSIPEventScript;overload; property Text:String read GetText write SetText; property Name:String read FName write SetName; property EventScript[Index: Integer]: TSIPEventScript read GetEventScript; property DatabaseID:Integer read FID write SetID; property Log:Boolean read FLog write SetLog; function DateTime:TDateTime; procedure AddReport(const Info,Kind:String); property Database:Integer read FDatabase write SetDatabase; function Finished:Boolean; procedure UpdateWait(W:Int64); procedure BeginItem; procedure EndItem; published property Parameters:TStrings read FParameters write SetParameters; property EventKind:Integer read FEventKind write SetEventKind; property Mode:Integer read FMode write SetMode; property CrisisKind:Integer read FCrisisKind write SetCrisisKind default 0; end; TSIPEventLibrary=class(TStringList) private function GetEvent(ID:Integer): TSipEvent; function GetEventText(ID:Integer): String; procedure SetEventText(ID:Integer; const Value: String); function GetEventName(ID: Integer): String; procedure SetEventName(ID: Integer; const Value: String); procedure AddEvent(Event:TSipEvent); function GetEventDatabase(ID: Integer): Integer; procedure SetEventDatabase(ID: Integer; const Value: Integer); public Name:String; function AsJSON:String; procedure Clear;override; destructor Destroy;override; property Event[ID:Integer]:TSipEvent read GetEvent; property EventText[ID:Integer]:String read GetEventText write SetEventText; property EventName[ID:Integer]:String read GetEventName write SetEventName; property EventDatabase[ID:Integer]:Integer read GetEventDatabase write SetEventDatabase; end; TSIPEventComponent=class(TComponent) private FScript: TSIPEvent; published property Event:TSIPEvent read FScript write FScript; end; const MaxRing=70*1000; MaxAnnounce=5*60*1000; MaxMonitor=30*1000; implementation uses Util, SysUtils, dm_Alarm, SIP_Monitor; { TSIPEvent } function TSIPEvent.Add: TSIPEventScript; begin Result := inherited Add as TSIPEventScript; end; var ReportDir:String; procedure TSIPEvent.AddReport(const Info, Kind: String); begin if not Log then Exit; FLock.Enter; try if Kind='queue' then begin if FQueueStatus<>'' then FQueueStatus:=FQueueStatus+','; FQueueStatus:=FQueueStatus+Info; end else begin FReport:=FReport+Info; if FReportFile=nil then begin FTime:=Now; FReportFile:=TFileStream.Create(ReportDir+ FormatDateTime('yyyy-mm-dd hh-nn-ss',FTime)+ '('+IntToStr(FID)+').log', fmCreate or fmShareDenyWrite); end; if (FReportFile<>nil) and (FReport<>'') then begin FReportFile.Write(FReport[1],Length(FReport)); FReport:=''; end; end; finally FLock.Leave; end; end; procedure TSIPEvent.BeginItem; begin Inc(FQueueItems); end; constructor TSIPEvent.Create; begin inherited Create(TSIPEventScript); FLock:=TCriticalSection.Create; FParameters:=TStringList.Create; end; function TSIPEvent.DateTime: TDateTime; begin Result:=FTime; end; destructor TSIPEvent.Destroy; var FN:String; S:TStringStream; begin FreeAndNil(FParameters); if FReportFile<>nil then FN:=FReportFile.FileName else FN:=''; FreeAndNil(FReportFile); if (FN<>'') and (dmAlarm<>nil) then begin S:=TStringStream.Create(Format('{status:[%s],log:%s}',[FQueueStatus,StrEscape(FileToString(FN))])); try dmAlarm.AddReport(FormatDateTime('yyyy-mm-dd hh-nn-ss ',FTime)+FName,S,Database); finally S.Free; end; end; FreeAndNil(FLock); inherited; end; procedure TSIPEvent.EndItem; begin Dec(FQueueItems); if FQueueItems=0 then FWait:=GetTick64+MaxMonitor; end; function TSIPEvent.Finished: Boolean; begin Result:=(FWait>0) and (FWait<GetTick64); end; function TSIPEvent.GetEventScript(Index: Integer): TSIPEventScript; begin Result := Items[Index] as TSIPEventScript; end; function TSIPEvent.GetText: String; var C:TSIPEventComponent; begin C:=TSIPEventComponent.Create(nil); try C.Event:=Self; Result:=ComponentToString(C); finally C.Free; end; end; procedure TSIPEvent.SetCrisisKind(const Value: Integer); begin FCrisisKind := Value; end; procedure TSIPEvent.SetDatabase(const Value: Integer); begin FDatabase := Value; end; procedure TSIPEvent.SetEventKind(const Value: Integer); begin FEventKind := Value; end; procedure TSIPEvent.SetID(const Value: Integer); begin FID := Value; end; procedure TSIPEvent.SetLog(const Value: Boolean); begin FLog := Value; end; procedure TSIPEvent.SetMode(const Value: Integer); begin FMode := Value; end; procedure TSIPEvent.SetName(const Value: String); begin FName := Value; end; procedure TSIPEvent.SetParameters(const Value: TStrings); begin FParameters.Assign(Value); end; procedure TSIPEvent.SetText(const Value: String); var S:TSIPEventComponent; begin if Value='' then begin Clear; Exit; end; S:=TSIPEventComponent.Create(nil); S.Event:=Self; try StringToComponent(Value,S); finally S.Free; end; end; procedure TSIPEvent.UpdateWait; begin FWait:=GetTick64+W; end; { TSIPEventScript } procedure TSIPEventScript.SetCount(const Value: Integer); begin FCount := Value; end; procedure TSIPEventScript.SetRingGroup(const Value: Integer); begin FRingGroup := Value; end; procedure TSIPEventScript.SetScriptID(const Value: Integer); begin FScriptID := Value; end; procedure TSIPEventLibrary.AddEvent(Event: TSipEvent); begin AddObject(IntToStr(Event.DatabaseID),Event); end; function TSIPEventLibrary.AsJSON: String; var I:Integer; E:TSIPEvent; begin Result:=''; for I := 0 to Count - 1 do begin E:=Objects[I] as TSIPEvent; if E<>nil then begin if Result<>'' then Result:=Result+','; Result:=Result+Format('{eventid:%d,eventname:%s}',[E.DatabaseID,StrEscape(E.Name)]); end; end; end; procedure TSIPEventLibrary.Clear; var O:TObject; I:Integer; begin for I := 0 to Count - 1 do begin O:=Objects[I]; Objects[I]:=nil; FreeAndNil(O); end; inherited; end; destructor TSIPEventLibrary.Destroy; begin Clear; inherited; end; function TSIPEventLibrary.GetEvent(ID:Integer): TSipEvent; var I:Integer; begin I:=IndexOf(IntToStr(ID)); if I>=0 then Result:=Objects[I] as TSipEvent else Result:=nil; end; function TSIPEventLibrary.GetEventDatabase(ID: Integer): Integer; var S:TSIPEvent; begin S:=Event[ID]; if S=nil then Result:=-1 else Result:=Event[ID].Database; end; function TSIPEventLibrary.GetEventName(ID: Integer): String; var S:TSIPEvent; begin S:=Event[ID]; if S=nil then Result:='' else Result:=Event[ID].Name; end; function TSIPEventLibrary.GetEventText(ID:Integer): String; var S:TSIPEvent; begin S:=Event[ID]; if S=nil then Result:='' else Result:=Event[ID].Text; end; procedure TSIPEventLibrary.SetEventDatabase(ID: Integer; const Value: Integer); var S:TSIPEvent; begin if IndexOf(IntToStr(ID))<0 then S:=TSIPEvent.Create else S:=Event[ID]; S.Database:=Value; S.DatabaseID:=ID; if IndexOf(IntToStr(ID))<0 then AddEvent(S); end; procedure TSIPEventLibrary.SetEventName(ID: Integer; const Value: String); var S:TSIPEvent; begin if IndexOf(IntToStr(ID))<0 then S:=TSIPEvent.Create else S:=Event[ID]; S.Name:=Value; S.DatabaseID:=ID; if IndexOf(IntToStr(ID))<0 then AddEvent(S); end; procedure TSIPEventLibrary.SetEventText(ID:Integer; const Value: String); var S:TSIPEvent; begin if IndexOf(IntToStr(ID))<0 then S:=TSIPEvent.Create else S:=Event[ID]; S.Text:=Value; S.DatabaseID:=ID; if IndexOf(IntToStr(ID))<0 then AddEvent(S); end; initialization ReportDir:=ExtractFilePath(ParamStr(0))+'Reports\'; ForceDirectories(ReportDir); end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 本单元是工程数据集窗体的基本单元 // //主要实现: // 1、EasyUtilADOConn // 发布数据连接:所有与数据库通信的模块均从此单元获得ADO连接 // 2、初始化指定控件的IME //-----------------------------------------------------------------------------} unit untEasyPlateDBBaseForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, untEasyPlateBaseForm, untEasyDBConnection, DB, ADODB, ExtCtrls, untEasyGroupBox, untEasyWaterImage; type TfrmEasyPlateDBBaseForm = class(TfrmEasyPlateBaseForm) procedure FormCreate(Sender: TObject); private { Private declarations } FEasyDBConn: TADOConnection; function GetUtilADOConn: TADOConnection; procedure SetUtilADOConn(const Value: TADOConnection); public { Public declarations } //发布ADO数据连接 property EasyUtilADOConn: TADOConnection read GetUtilADOConn write SetUtilADOConn; end; var frmEasyPlateDBBaseForm: TfrmEasyPlateDBBaseForm; implementation {$R *.dfm} procedure TfrmEasyPlateDBBaseForm.FormCreate(Sender: TObject); //var // I : Integer; begin inherited; FEasyDBConn := DMEasyDBConnection.EasyADOConn; { for i := 0 to ComponentCount - 1 do begin if Self.Components[i] is TEasyDevDBTextEdit then begin (Components[i] as TEasyDevDBTextEdit).ImeName := ''; (Components[i] as TEasyDevDBTextEdit).ImeMode := imDontCare end else if Components[i] is TEasyDevDBMemo then begin (Components[i] as TEasyDevDBMemo).ImeName := ''; (Components[i] as TEasyDevDBMemo).ImeMode := imDontCare; end else if Components[i] is TEasyDevDBDateEdit then begin (Components[i] as TEasyDevDBDateEdit).ImeName := ''; (Components[i] as TEasyDevDBDateEdit).ImeMode := imDontCare; end else if Components[i] is TEasyDevDBTimeEdit then begin (Components[i] as TEasyDevDBTimeEdit).ImeName := ''; (Components[i] as TEasyDevDBTimeEdit).ImeMode := imDontCare; end else if Components[i] is TEasyDevDBButtonEdit then begin (Components[i] as TEasyDevDBButtonEdit).ImeName := ''; (Components[i] as TEasyDevDBButtonEdit).ImeMode := imDontCare; end else if Components[i] is TEasyDevDBImageComboBox then begin (Components[i] as TEasyDevDBImageComboBox).ImeName := ''; (Components[i] as TEasyDevDBImageComboBox).ImeMode := imDontCare; end else if Components[i] is TEasyDevDBLookupComboBox then begin (Components[i] as TEasyDevDBLookupComboBox).ImeName := ''; (Components[i] as TEasyDevDBLookupComboBox).ImeMode := imDontCare; end else if Components[i] is TEasyDevDBSpinEdit then begin (Components[i] as TEasyDevDBSpinEdit).ImeName := ''; (Components[i] as TEasyDevDBSpinEdit).ImeMode := imDontCare; end else if Components[i] is TEasyDevDBCalcEdit then begin (Components[i] as TEasyDevDBCalcEdit).ImeName := ''; (Components[i] as TEasyDevDBCalcEdit).ImeMode := imDontCare; end; end; } end; function TfrmEasyPlateDBBaseForm.GetUtilADOConn: TADOConnection; begin Result := FEasyDBConn; end; procedure TfrmEasyPlateDBBaseForm.SetUtilADOConn( const Value: TADOConnection); begin FEasyDBConn := Value; end; end.
unit StringMetaTestForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, FMX.Edit, FMX.Controls.Presentation, FMX.ScrollBox; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public procedure Show (const msg: string); end; var Form1: TForm1; implementation {$R *.fmx} {$ZEROBASEDSTRINGS ON} var MyStr1, MyStr2: string; procedure TForm1.Button1Click(Sender: TObject); var str1: string; begin str1 := 'F' + string.Create ('o', 2); Show ('SizeOf: ' + SizeOf (str1).ToString); Show ('Length: ' + str1.Length.ToString); Show ('StringElementSize: ' + StringElementSize (str1).ToString); Show ('StringRefCount: ' + StringRefCount (str1).ToString); Show ('StringCodePage: ' + StringCodePage (str1).ToString); if StringCodePage (str1) = DefaultUnicodeCodePage then Show ('Is Unicode'); Show ('Size in bytes: ' + (Length (str1) * StringElementSize (str1)).ToString); Show ('ByteLength: ' + ByteLength (str1).ToString); end; function StringStatus (const Str: string): string; begin Result := 'Addr: ' + IntToStr (Integer (Str)) + ', Len: ' + IntToStr (Length (Str)) + ', Ref: ' + IntToStr (PInteger (Integer (Str) - 8)^) + ', Val: ' + Str; end; procedure TForm1.Button2Click(Sender: TObject); begin Show ('MyStr1 - ' + StringStatus (MyStr1)); Show ('MyStr2 - ' + StringStatus (MyStr2)); MyStr1 [1] := 'a'; Show ('Change 2nd char'); Show ('MyStr1 - ' + StringStatus (MyStr1)); Show ('MyStr2 - ' + StringStatus (MyStr2)); end; procedure TForm1.FormCreate(Sender: TObject); begin MyStr1 := string.Create(['H', 'e', 'l', 'l', 'o']); MyStr2 := MyStr1; end; procedure TForm1.Show(const Msg: string); begin Memo1.Lines.Add(Msg); end; end.
unit Web.HTTP; interface uses SysUtils, Classes, IdComponent, IdExceptionCore, IdHttp, IdURI, IdStack, Web; type THTTPWeb = class(TWeb) private InnerConnector: TIdHttp; InnerEncodedURI: String; procedure SetEncodedURIByPath(const PathToGet: String); function GetFromEncodedURIToStringList: TStringList; procedure SetRequestHeader; function HeadByEncodedURI: Boolean; function GetFromEncodedURIToStringStream: TStringStream; protected property Connector: TIdHttp read InnerConnector; property EncodedURI: String read InnerEncodedURI write SetEncodedURIByPath; public constructor Create; destructor Destroy; override; function GetToStringList(const PathToGet: String): TStringList; override; function GetToStringStream(const PathToGet: String): TStringStream; override; function Head(const PathToGet: String): Boolean; virtual; procedure SetOnWorkHandler(const OnWorkHandler: TWorkEvent); end; implementation { THTTPWeb } constructor THTTPWeb.Create; const Timeout = 1500; begin inherited; InnerConnector := TIdHttp.Create(nil); InnerConnector.ReadTimeout := Timeout; InnerConnector.ConnectTimeout := Timeout; end; destructor THTTPWeb.Destroy; begin FreeAndNil(InnerConnector); inherited; end; procedure THTTPWeb.SetEncodedURIByPath(const PathToGet: String); begin InnerEncodedURI := TIdURI.URLEncode(PathToGet); end; procedure THTTPWeb.SetOnWorkHandler(const OnWorkHandler: TWorkEvent); begin Connector.OnWork := OnWorkHandler; end; function THTTPWeb.GetFromEncodedURIToStringList: TStringList; begin result := TStringList.Create; try result.Text := InnerConnector.Get(InnerEncodedURI); except on E: EIdReadTimeout do; on E: EIdConnectTimeout do; on E: EIdNotASocket do; else raise; end; end; function THTTPWeb.GetFromEncodedURIToStringStream: TStringStream; begin result := TStringStream.Create('', TEncoding.Unicode); InnerConnector.Get(InnerEncodedURI, result); end; function THTTPWeb.HeadByEncodedURI: Boolean; begin try InnerConnector.HandleRedirects := True; InnerConnector.Head(InnerEncodedURI); result := (InnerConnector.response.ResponseCode = 200); except result := false; end; end; function THTTPWeb.Head(const PathToGet: String): Boolean; begin if not IsWebAccessible then exit(false); SetEncodedURIByPath(PathToGet); SetRequestHeader; result := HeadByEncodedURI; end; procedure THTTPWeb.SetRequestHeader; begin InnerConnector.Request.UserAgent := UserAgent; InnerConnector.Request.CharSet := CharacterSet; end; function THTTPWeb.GetToStringList(const PathToGet: String): TStringList; begin if not IsWebAccessible then exit(TStringList.Create); SetEncodedURIByPath(PathToGet); SetRequestHeader; result := GetFromEncodedURIToStringList; end; function THTTPWeb.GetToStringStream(const PathToGet: String): TStringStream; begin if not IsWebAccessible then exit(TStringStream.Create); SetEncodedURIByPath(PathToGet); SetRequestHeader; result := GetFromEncodedURIToStringStream; end; end.
// TPageProducerHandler // By: Shane Hausle // Usage: // As cgi: // pass the PageProducer Template as an argument to the url // like so 'http://monkey1:90/cgi-bin/PageProducerCGI.exe/index.html.en' // Where /index.html.en would be the template based on the relative path. // NOTE: Images must Contain the Literal Path to work. unit PageProducerHandlerU; interface uses {$IFDEF MSWINDOWS} Windows, Messages, DBWeb, {$ENDIF} SysUtils, Classes, HTTPApp, HTTPProd, Sockets ; type TWebModule1 = class(TWebModule) tppGrok: TPageProducer; procedure WebModule1waProcessTPPAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure tppGrokHTMLTag(Sender: TObject; Tag: TTag; const TagString: String; TagParams: TStrings; var ReplaceText: String); private { Private declarations } public constructor create(aOwner : TComponent); override; end; var WebModule1: TWebModule1; cCell, cTitle, cBackground: String; implementation {$R *.dfm} constructor TWebModule1.create(aOwner: TComponent); begin inherited; end; procedure TWebModule1.WebModule1waProcessTPPAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var FilePath, s : String; begin if (Request.PathInfo <> '') then begin tppGrok.HTMLFile:= Request.PathTranslated ; if Request.Method = 'POST' then begin cTitle := Request.ContentFields.Values['TITLECOLOR']; cCell := Request.ContentFields.Values['CELLCOLOR']; cBackground := Request.ContentFields.Values['BACKGROUNDCOLOR']; end else begin cTitle := Request.QueryFields.Values['TITLECOLOR']; cCell := Request.QueryFields.Values['CELLCOLOR']; cBackground := Request.QueryFields.Values['BACKGROUNDCOLOR']; end; if cTitle = ' ' then cTitle := 'gainsboro'; if cCell = ' ' then cCell := 'White'; if cBackground = ' ' then cBackground := 'White'; Response.Content := tppGrok.Content(); end else Response.Content := 'Invalid Params <BR> Try : <BR>' + 'Path to CGI + FullPath To PageTemplate + ColorParams <BR> ' + 'Example: <BR>' + 'http://localhost/cgi-bin/PageProducerCGI/kylix_sample_html/company.ppt?TITLECOLOR=green&CELLCOLER=gainsboro&BACKGROUNDCOLOR=white' + '<BR>'; end; procedure TWebModule1.tppGrokHTMLTag(Sender: TObject; Tag: TTag; const TagString: String; TagParams: TStrings; var ReplaceText: String); begin if (CompareText(TagString,'TITLECOLOR')=0) then ReplaceText := 'BGCOLOR = "' + cTitle + '"' ; if (CompareText(TagString,'CELLCOLOR')=0) then ReplaceText := 'BGCOLOR = "' + cCell + '"' ; if (CompareText(TagString, 'BACKGROUNDCOLOR')=0) then ReplaceText := 'BGCOLOR = "' + cBackground + '"'; end; end.
unit MainFormUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Menus, MMSystem, Buttons, CardsUnit, System.UITYpes; type TMainForm = class(TForm) MainMenu: TMainMenu; N1: TMenuItem; N2: TMenuItem; StartMI: TMenuItem; ExitMI: TMenuItem; AboutMI: TMenuItem; CommandBtn: TBitBtn; MsgPanel: TPanel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ExitMIClick(Sender: TObject); procedure CommandBtnClick(Sender: TObject); procedure StartNewGameMIClick(Sender: TObject); procedure FormPaint(Sender: TObject); procedure AboutMIClick(Sender: TObject); procedure RepaintCards(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private gameState : integer; cardBackImg: TBitmap; cardImgs: TCardImages; cardDeck, playingNowCards: TCardArray; playerCards, aiCards, trumpSet, beatenCardSet: TSet36; aiCardCount, playerCardCount, unplayedCardCount, playingNowCardCount, AddedCardCount: byte; gameTableImg, BackgroundImg: TBitmap; playerWinCount, aiWinCount: integer; procedure ShowAICardsAndDeck; procedure DrawPlayerCards; procedure DoAICourse; procedure OnPlayerCardSelected(card: TObject); procedure OnPlayerCardDoubleClick(card: TObject); function AddCardFromDeck(isAICourse: Boolean): Boolean; procedure RefreshPanelAndCommandBtn(gameState: byte); function GetCardSetByNumber(cardId: TCardId): TSet36; procedure OutText(text: string); procedure DrawBackground; procedure LoadCardImgs(); function ShowQuery(text : string) : boolean; end; var MainForm: TMainForm; implementation uses AboutFormUnit, RxGIF; {$R *.DFM} const PLAYER_CARD_SELECTED_TOP = 245; PLAYER_CARD_TOP = PLAYER_CARD_SELECTED_TOP + 15; DECK_TOP = 5; DECK_LEFT = 520; CARD_RECT_RADIUS = 16; START_NEW_GAME = 0; PLAYER_COURSE = 1; AI_COURSE = 2; ADD_TO_AI = 3; FONT_NAME = 'Segoe UI'; CARDLINE_LEFT_MARGIN = 10; START_CARD_COUNT = 6; DECK_CARD_COUNT = 36; procedure TMainForm.ShowAICardsAndDeck; var i: byte; leftMargin, cardGap: integer; begin with gameTableImg.Canvas do begin DrawBackground; leftMargin := CARDLINE_LEFT_MARGIN; // Show AI cards // Composing cards in line if aiCardCount > START_CARD_COUNT then cardGap := round((490 - CardWidth - leftMargin) / aiCardCount) else cardGap := 80; for i := 1 to aiCardCount do begin Draw(leftMargin, 5, cardBackImg); inc(leftMargin, cardGap); end; if unplayedCardCount > 0 then // Show a deck if not empty begin // Draw trump card DrawCard(DECK_LEFT, DECK_TOP, cardDeck[1], gameTableImg.Canvas); // Draw rest of the deck if unplayedCardCount > 1 then for i := 1 to unplayedCardCount - 1 do Draw(DECK_LEFT + 20 + (i - 1) * 2, DECK_TOP + i * 2, cardBackImg); end; // Show cards playing now (in the middle of a table) for i := 1 to playingNowCardCount do DrawCard(CARDLINE_LEFT_MARGIN + (i - 1) * 15, 125, playingNowCards[i], gameTableImg.Canvas); end; OnPaint(Self); end; procedure TMainForm.StartNewGameMIClick(Sender: TObject); var i, j, k, cardNumber, min, TrumpCard: byte; IsPlayerCourse: Boolean; begin if gameState <> START_NEW_GAME then begin if not ShowQuery('Начать новую игру?') then exit end; RepaintCards(Application); for i := 1 to DECK_CARD_COUNT do // Set deck cardDeck[i] := i; for i := DECK_CARD_COUNT downto 1 do // Shuffle deck begin cardNumber := random(i) + 1; k := cardDeck[cardNumber]; for j := cardNumber to i - 1 do cardDeck[j] := cardDeck[j + 1]; cardDeck[i] := k; end; unplayedCardCount := DECK_CARD_COUNT - 2 * START_CARD_COUNT; playerCardCount := START_CARD_COUNT; aiCardCount := START_CARD_COUNT; playingNowCardCount := 0; playerCards := []; aiCards := []; trumpSet := []; beatenCardSet := []; TrumpCard := cardDeck[1] mod 4; // Trump card suit is showed on taskbar as app icon Application.Icon.LoadFromFile('./assets/ICO' + IntToStr(TrumpCard + 1) + '.ico'); Self.Icon.LoadFromFile('./assets/ICO' + IntToStr(TrumpCard + 1) + '.ico'); // Add trumps to the set for i := 1 to DECK_CARD_COUNT do if i mod 4 = TrumpCard then Include(trumpSet, i); IsPlayerCourse := true; min := DECK_CARD_COUNT + 1; // Handing cards out for i := DECK_CARD_COUNT downto DECK_CARD_COUNT - START_CARD_COUNT + 1 do begin if (cardDeck[i] in trumpSet) and (cardDeck[i] < min) then min := cardDeck[i]; // player's min rank card Include(playerCards, cardDeck[i]); end; for i := DECK_CARD_COUNT - START_CARD_COUNT downto DECK_CARD_COUNT - 2 * START_CARD_COUNT + 2 do begin if (cardDeck[i] in trumpSet) and (cardDeck[i] < min) then IsPlayerCourse := false; // Min rank card is had by AI Include(aiCards, cardDeck[i]); end; // Draw cards DrawPlayerCards; ShowAICardsAndDeck; // Set appropriate panel message and command button caption if IsPlayerCourse then RefreshPanelAndCommandBtn(PLAYER_COURSE) else DoAICourse; end; procedure TMainForm.CommandBtnClick(Sender: TObject); procedure PlayerPicksUp; var i, j, CardCount: byte; playedCardSet, cardSet: TSet36; begin CardCount := playerCardCount - 1; // card count to add to player playedCardSet := []; for j := 1 to playingNowCardCount do begin cardSet := GetCardSetByNumber(playingNowCards[j]); for i := 1 to DECK_CARD_COUNT do if (i in aiCards) and (i in cardSet) and not(i in trumpSet) then Include(playedCardSet, i); end; for i := 1 to DECK_CARD_COUNT do if (i in playedCardSet) and (CardCount > 0) then begin exclude(aiCards, i); dec(aiCardCount); dec(CardCount); inc(playingNowCardCount); playingNowCards[playingNowCardCount] := i; end; for i := 1 to playingNowCardCount do begin Include(playerCards, playingNowCards[i]); inc(playerCardCount); end; playingNowCardCount := 0; if AddCardFromDeck(true) then DoAICourse; end; procedure AIPicksUp; var i: byte; begin for i := 1 to playingNowCardCount do begin Include(aiCards, playingNowCards[i]); inc(aiCardCount); end; playingNowCardCount := 0; if AddCardFromDeck(false) then RefreshPanelAndCommandBtn(1); end; begin case gameState of START_NEW_GAME : StartNewGameMIClick(Sender); // Start new game PLAYER_COURSE : if AddCardFromDeck(false) then DoAICourse; // player defended, do AI course AI_COURSE : PlayerPicksUp; ADD_TO_AI : AIPicksUp; end; end; procedure TMainForm.OnPlayerCardDoubleClick(card: TObject); var i, cardNumber: byte; cardSet: TSet36; SuccessfulDefending: Boolean; procedure AIDefending; var i, cardNumber: byte; begin dec(AddedCardCount); if gameState = 3 then exit; // if AI picks up cardNumber := 0; if playingNowCards[playingNowCardCount] in trumpSet then // if last card is a trump card for i := 1 to DECK_CARD_COUNT do begin if (i in aiCards) and (i in trumpSet) and (i > playingNowCards[playingNowCardCount]) then begin cardNumber := i; break; end; end else begin for i := 1 to DECK_CARD_COUNT do if (i in aiCards) and (i mod 4 = playingNowCards[playingNowCardCount] mod 4) and (i > playingNowCards[playingNowCardCount]) then begin cardNumber := i; break; end; if cardNumber = 0 then for i := 1 to DECK_CARD_COUNT do if (i in aiCards) and (i in trumpSet) then begin cardNumber := i; break; end; end; if cardNumber > 0 then begin exclude(aiCards, cardNumber); inc(playingNowCardCount); dec(aiCardCount); playingNowCards[playingNowCardCount] := cardNumber; ShowAICardsAndDeck; end else RefreshPanelAndCommandBtn(3); end; procedure ThrowCard(cardNumber: byte); begin exclude(playerCards, cardNumber); inc(playingNowCardCount); dec(playerCardCount); playingNowCards[playingNowCardCount] := cardNumber; DrawPlayerCards; ShowAICardsAndDeck; end; begin cardNumber := 0; for i := 1 to DECK_CARD_COUNT do if card = cardImgs[i] then begin cardNumber := i; break; end; case gameState of PLAYER_COURSE , ADD_TO_AI : begin // do course or adding if playingNowCardCount = 0 then begin ThrowCard(cardNumber); AIDefending; CommandBtn.Show; end else begin cardSet := GetCardSetByNumber(cardNumber); for i := 1 to playingNowCardCount do if playingNowCards[i] in cardSet then begin ThrowCard(cardNumber); AIDefending; break; end; end; if (AddedCardCount = 0) or (playerCardCount = 0) then CommandBtn.Click; end; AI_COURSE: begin // Player Defending if playingNowCards[playingNowCardCount] in trumpSet then SuccessfulDefending := (cardNumber > playingNowCards[playingNowCardCount]) and (cardNumber in trumpSet) else SuccessfulDefending := ((cardNumber > playingNowCards[playingNowCardCount]) and (cardNumber mod 4 = playingNowCards[playingNowCardCount] mod 4)) or (cardNumber in trumpSet); if SuccessfulDefending then begin ThrowCard(cardNumber); DoAICourse; end; end; end; end; procedure TMainForm.DoAICourse; var i, j, cardNumber: byte; playedCardSet, cardSet: TSet36; procedure ThrowCard(cardNumber: byte); begin exclude(aiCards, cardNumber); inc(playingNowCardCount); dec(aiCardCount); playingNowCards[playingNowCardCount] := cardNumber; ShowAICardsAndDeck; end; procedure PlayerCourse; begin if AddCardFromDeck(true) then RefreshPanelAndCommandBtn(1); end; begin if (playerCardCount = 0) or (aiCardCount = 0) then PlayerCourse else if playingNowCardCount = 0 then // first course begin RefreshPanelAndCommandBtn(2); cardNumber := 0; for i := 1 to DECK_CARD_COUNT do if (i in aiCards) and not(i in trumpSet) then begin cardNumber := i; break; end; if cardNumber = 0 then for i := 1 to DECK_CARD_COUNT do if i in aiCards then begin cardNumber := i; break; end; ThrowCard(cardNumber); end else begin playedCardSet := []; for j := 1 to playingNowCardCount do begin cardSet := GetCardSetByNumber(playingNowCards[j]); for i := 1 to DECK_CARD_COUNT do if (i in aiCards) and (i in cardSet) and not(i in trumpSet) then Include(playedCardSet, i); end; if playedCardSet = [] then PlayerCourse else for i := 1 to DECK_CARD_COUNT do if i in playedCardSet then begin ThrowCard(i); break; end; end; end; // Get set in which a card with specified number included function TMainForm.GetCardSetByNumber(cardId: byte): TSet36; begin case cardId of 1 .. 4: Result := [1 .. 4]; // 6 5 .. 8: Result := [5 .. 8]; // 7 9 .. 12: Result := [9 .. 12]; // 8 13 .. 16: Result := [13 .. 16]; // 9 17 .. 20: Result := [17 .. 20]; // 10 21 .. 24: Result := [21 .. 24]; // Jack 25 .. 28: Result := [25 .. 28]; // King 29 .. 32: Result := [29 .. 32]; // Queen 33 .. 36: Result := [33 .. 36]; // Ace end; end; procedure TMainForm.RefreshPanelAndCommandBtn(gameState: byte); var msgPanelText, commandBtnText: string; begin self.gameState:= gameState; CommandBtn.Visible := gameState <> 1; case gameState of START_NEW_GAME: begin msgPanelText := 'Новая игра (нажмите F5)'; commandBtnText := 'Начать игру'; end; PLAYER_COURSE: begin msgPanelText := 'Ваш ход'; commandBtnText := 'Бито'; AddedCardCount := aiCardCount; end; AI_COURSE: begin msgPanelText := 'Ход противника. Отбивайтесь'; commandBtnText := 'Беру'; end; ADD_TO_AI: begin msgPanelText := 'Беру. Добавляйте'; commandBtnText := 'Нечего'; end; end; MsgPanel.Caption := msgPanelText; CommandBtn.Caption := commandBtnText; end; function TMainForm.AddCardFromDeck(isAICourse: Boolean): Boolean; var i: byte; procedure AddCardsToAIFromDeck; begin while (aiCardCount < START_CARD_COUNT) and (unplayedCardCount > 0) do begin Include(aiCards, cardDeck[unplayedCardCount]); inc(aiCardCount); dec(unplayedCardCount); end; ShowAICardsAndDeck; end; procedure AddCardsToPlayerFromDeck; begin while (playerCardCount < START_CARD_COUNT) and (unplayedCardCount > 0) do begin Include(playerCards, cardDeck[unplayedCardCount]); inc(playerCardCount); dec(unplayedCardCount); end; ShowAICardsAndDeck; DrawPlayerCards; end; procedure PrintGameResult; var i, cardLeftPosition, cardGap: integer; begin DrawBackground; if (aiCardCount = 0) and (playerCardCount = 0) then begin OutText('Ничья'); end else if aiCardCount = 0 then begin OutText('Вы проиграли'); inc(aiWinCount); end else with gameTableImg.Canvas do begin OutText('Вы выиграли'); inc(playerWinCount); // Face up AI cards: cardLeftPosition := CARDLINE_LEFT_MARGIN; if aiCardCount > START_CARD_COUNT then cardGap := round((Width - CardWidth - cardLeftPosition) / aiCardCount) else cardGap := 80; for i := 1 to DECK_CARD_COUNT do if i in aiCards then begin DrawCard(cardLeftPosition, 5, i, gameTableImg.Canvas); inc(cardLeftPosition, cardGap); end; end; OnPaint(Self); RefreshPanelAndCommandBtn(0); Caption := format('Подкидной дурак. Счёт игры - %d:%d', [playerWinCount, aiWinCount]); end; begin // Throw beaten cards away for i := 1 to playingNowCardCount do Include(beatenCardSet, playingNowCards[i]); playingNowCardCount := 0; // No playing cards on the table if isAICourse then begin AddCardsToAIFromDeck; AddCardsToPlayerFromDeck; end else begin AddCardsToPlayerFromDeck; AddCardsToAIFromDeck; end; if (aiCardCount = 0) or (playerCardCount = 0) then // Game over PrintGameResult; Result := not((aiCardCount = 0) or (playerCardCount = 0)); end; { ---------------------------------------------------------------------------- } procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := ShowQuery('Вы действительно хотите выйти?'); end; procedure TMainForm.FormCreate(Sender: TObject); var i: byte; begin gameState := 0; playerCardCount := 0; aiCardCount := 0; playingNowCardCount := 0; playerWinCount := 0; aiWinCount := 0; beatenCardSet := []; gameTableImg := TBitmap.Create; with gameTableImg.Canvas.Font do begin Name := FONT_NAME; end; try BackgroundImg := TBitmap.Create; BackgroundImg.LoadFromFile('./assets/background.bmp'); except FreeAndNil(BackgroundImg); ShowMessage('Не найден рисунок фона.'); end; with gameTableImg do begin Width := ClientWidth; Height := ClientHeight - MsgPanel.Height; end; cardBackImg := TBitmap.Create; cardBackImg.Transparent := true; AllCardBitmaps := TBitmap.Create; CardBitmap := TBitmap.Create; CardBitmap.Transparent := true; Randomize; // Creating card components for i := 1 to DECK_CARD_COUNT do begin cardImgs[i] := TCardImg.Create(Self); with cardImgs[i] do begin Parent := Self; Cursor := crHandPoint; Hide; OnClick := OnPlayerCardSelected; cardNumber := i; end; end; // Load and repaint card images RepaintCards(Application); end; procedure TMainForm.OnPlayerCardSelected(card: TObject); var i: byte; begin // Move a card if selected for i := 1 to DECK_CARD_COUNT do if card = cardImgs[i] then begin if cardImgs[i].Top = PLAYER_CARD_SELECTED_TOP then // if the card was up begin OnPlayerCardDoubleClick(card); exit; end else cardImgs[i].Top := PLAYER_CARD_SELECTED_TOP; // Turn the card up end else if i in playerCards then cardImgs[i].Top := PLAYER_CARD_TOP; // Turn the card down end; procedure TMainForm.FormDestroy(Sender: TObject); var i: byte; begin FreeAndNil(cardBackImg); FreeAndNil(gameTableImg); FreeAndNil(CardBitmap); if BackgroundImg <> nil then FreeAndNil(BackgroundImg); for i := 1 to DECK_CARD_COUNT do FreeAndNil(cardImgs[i]); end; procedure TMainForm.ExitMIClick(Sender: TObject); begin Close; end; procedure TMainForm.DrawPlayerCards; var i: byte; playerCardLeftPosition, cardGap: integer; begin playerCardLeftPosition := 10; // Composing cards in line if playerCardCount > START_CARD_COUNT then cardGap := round((CommandBtn.Left - CardWidth - playerCardLeftPosition) / playerCardCount) else cardGap := 80; for i := 1 to DECK_CARD_COUNT do with cardImgs[i] do begin if i in playerCards then begin Top := PLAYER_CARD_TOP; Left := playerCardLeftPosition; inc(playerCardLeftPosition, cardGap); end; Visible := i in playerCards; end; end; procedure TMainForm.OutText(text: string); var x, y: integer; begin with gameTableImg.Canvas do begin Brush.Style := bsClear; Font.Size := 50; while textwidth(text) <= ClientWidth - 100 do Font.Size := Font.Size + 10; x := (Width - textwidth(text)) div 2; y := (Height - textheight(text)) div 2 - 70; // 'shadow' Font.Color := clBlack; textout(x, y, text); Font.Color := clBlue; textout(x + 1, y + 1, text); end; end; procedure TMainForm.DrawBackground; begin with gameTableImg.Canvas do begin Draw(0, 0, BackgroundImg); end; end; // Load card images and repaint cards procedure TMainForm.RepaintCards(Sender: TObject); var i: byte; begin LoadCardImgs(); for i := 1 to DECK_CARD_COUNT do begin cardImgs[i].RefreshRegion; cardImgs[i].Repaint; end; ShowAICardsAndDeck; DrawPlayerCards; OnPaint(Self); end; // Load card face and back sprites from gif images procedure TMainForm.LoadCardImgs(); var GifImg: TGifImage; begin GifImg := TGifImage.Create; GifImg.LoadFromFile('./assets/backside.gif'); CardHeight := GifImg.Height; CardWidth := GifImg.Width; CardRadius := CARD_RECT_RADIUS; cardBackImg.Assign(GifImg); cardBackImg.Transparent := true; GifImg.LoadFromFile('./assets/frontsides.gif'); AllCardBitmaps.Assign(GifImg); FreeAndNil(GifImg); CardBitmap.Width := CardWidth; CardBitmap.Height := CardHeight; end; procedure TMainForm.FormPaint(Sender: TObject); begin Canvas.Draw(0, 0, gameTableImg); end; procedure TMainForm.AboutMIClick(Sender: TObject); begin Application.CreateForm(TAboutForm, AboutForm); AboutForm.ShowModal; FreeAndNil(AboutForm) end; function TMainForm.ShowQuery(text : string):boolean; var buttonSelected: integer; begin buttonSelected := MessageDlg(text, mtCustom, [mbYes, mbNo], 0); if buttonSelected = mrYES then begin result := true; end else begin result := false; end; end; end.
unit Migration; interface uses System.SysUtils, System.Variants, System.Classes, Vcl.StdCtrls, Winapi.Windows, Vcl.Forms, MyUtils; type TVersion = (vrFb21 = 0, vrFb25 = 1, vrFb30 = 2, vrFb40 = 3); TMigrationConnection = class public User: string; Password: string; Version: TVersion; Database: string; end; TMigrationConfig = class strict private function GetVersionName(Version: TVersion): string; function GetResourceName(Version: TVersion): string; function GetPathDll(Version: TVersion): string; public Source: TMigrationConnection; Dest: TMigrationConnection; function GetPathTempFolder: string; function GetPathSourceDll: string; function GetPathDestDll: string; function GetPathBackupFile: string; function GetSourceVersionName: string; function GetDestVersionName: string; constructor Create; destructor Destroy; end; TMigration = class private Config: TMigrationConfig; public constructor Create(Config: TMigrationConfig); procedure Migrate(Log: TMemo = nil; LogErrors: TMemo = nil); end; implementation uses Backup, Restore; { TMigrationConfig } constructor TMigrationConfig.Create; begin Source := TMigrationConnection.Create; Dest := TMigrationConnection.Create; end; destructor TMigrationConfig.Destroy; begin Source.Free; Dest.Free; end; function TMigrationConfig.GetResourceName(Version: TVersion): string; begin case Version of vrFb21: Result := 'Firebird_2_1'; vrFb25: Result := 'Firebird_2_5'; vrFb30: Result := 'Firebird_3_0'; vrFb40: Result := 'Firebird_4_0'; end; end; //Temp folder to work with files function TMigrationConfig.GetPathTempFolder: string; begin Result := TUtils.Temp + 'FirebirdMigrator\'; end; function TMigrationConfig.GetPathBackupFile: string; begin Result := GetPathTempFolder + 'BackupFile.fbk'; end; //Extracts firebird folder to temp folder by version, and returns it's path function TMigrationConfig.GetPathDll(Version: TVersion): string; var Folder: string; begin //Pasta destino Folder := GetPathTempFolder + GetResourceName(Version) + '\'; TUtils.DeleteIfExistsDir(Folder); Application.ProcessMessages; //Extrai resource para a pasta temp TUtils.ExtractResourceZip(GetResourceName(Version), GetPathTempFolder); Application.ProcessMessages; //Copia o firebird.msg para a pasta do executável CopyFile(PWideChar(Folder + 'Firebird.msg'), PWideChar(TUtils.AppPath + 'Firebird.msg'), false); Application.ProcessMessages; Result := Folder + 'fbembed.dll'; end; function TMigrationConfig.GetPathSourceDll: string; begin Result := GetPathDll(Source.Version); end; function TMigrationConfig.GetPathDestDll: string; begin Result := GetPathDll(Dest.Version); end; //Version string description function TMigrationConfig.GetVersionName(Version: TVersion): string; begin case Version of vrFb21: Result := 'Firebird 2.1.7.18553'; vrFb25: Result := 'Firebird 2.5.8.27089'; vrFb30: Result := 'Firebird 3.0.4.33054'; vrFb40: Result := 'Firebird 4.0.0.19630'; end; end; function TMigrationConfig.GetSourceVersionName: string; begin Result := GetVersionName(Source.Version); end; function TMigrationConfig.GetDestVersionName: string; begin Result := GetVersionName(Dest.Version); end; { TMigration } constructor TMigration.Create(Config: TMigrationConfig); begin Self.Config := Config; end; procedure TMigration.Migrate(Log: TMemo = nil; LogErrors: TMemo = nil); var Backup: TBackup; Restore: TRestore; begin Config.Dest.User := Config.Source.User; Config.Dest.Password := Config.Source.Password; CreateDir(Config.GetPathTempFolder); Backup := TBackup.Create(Config); Restore := TRestore.Create(Config); try if Log <> nil then begin with Log.Lines do begin Add('************* MIGRAÇÃO ************'); Add(DateTimeToStr(now)); Add('*Fonte*'); Add('Path: ' + Config.Source.Database); Add('Versão: ' + Config.GetSourceVersionName); Add('***********************************'); Add('*Destino*'); Add('Path: ' + Config.Dest.Database); Add('Versão: ' + Config.GetDestVersionName); Add('***********************************'); Add(''); end; end; Backup.Execute(Log, LogErrors); Restore.Execute(Log, LogErrors); if Log <> nil then begin with Log.Lines do begin Add(''); Add('******** MIGRAÇÃO FINALIZADA ******'); Add(DateTimeToStr(now)); Add(''); end; end; Log.Lines.SaveToFile(Config.GetPathTempFolder + 'Log.txt'); LogErrors.Lines.SaveToFile(Config.GetPathTempFolder + 'Errors.txt'); finally Backup.Free; Restore.Free; end; end; end.
unit Billiards.GameType; interface type TBilliardGameType = class private fNotifyLast: integer; fMaxTurns: integer; fID: integer; public constructor Create; overload; constructor Create(ADate: TDate); overload; function ToString: string; override; property ID: integer read fID write fID; property MaxTurns: integer read fMaxTurns write fMaxTurns; property NotifyLast: integer read fNotifyLast write fNotifyLast; end; implementation uses SysUtils, Classes, IBDatabase, IBQuery, IBCustomDataSet, Billiards.DataModule; { TGameType } constructor TBilliardGameType.Create; begin Create(Now); end; constructor TBilliardGameType.Create(ADate: TDate); var SL: TStringList; begin inherited Create; if not BilliardDataModule.BilliardDB.Connected then BilliardDataModule.BilliardDB.Open; SL := TStringList.Create; try SL.Add('SELECT ID, MAX_TURNS, NOTIFY_LAST'); SL.Add(' FROM GAMETYPES'); SL.Add(' WHERE CODE = :code'); BilliardDataModule.sqlQuery.SQL.Assign(SL); finally SL.Free; end; case DayOfWeek(Now) of 3, 4: BilliardDataModule.sqlQuery.ParamByName('code').AsString := 'OB'; 5, 6: BilliardDataModule.sqlQuery.ParamByName('code').AsString := 'VS'; 7: BilliardDataModule.sqlQuery.ParamByName('code').AsString := '3B'; end; BilliardDataModule.sqlQuery.Open; if BilliardDataModule.sqlQuery.RecordCount = 1 then begin BilliardDataModule.sqlQuery.First; fID := BilliardDataModule.sqlQuery.FieldByName('id').AsInteger; fMaxTurns := BilliardDataModule.sqlQuery.FieldByName('max_turns').AsInteger; fNotifyLast := BilliardDataModule.sqlQuery.FieldByName('notify_last').AsInteger; end; BilliardDataModule.sqlQuery.Close; end; function TBilliardGameType.ToString: string; begin Result := '"GameType": { '; Result := Result + Format(#13#10'"ID": "%d", ', [fID]); Result := Result + Format(#13#10'"MaxTurns": "%d", ', [fMaxTurns]); Result := Result + Format(#13#10'"NotifyLast": "%d"', [fNotifyLast]); Result := Result + #13#10'}'; end; end.
{**********************************************************} { } { TTinyDBIniFile Class } { Last Modified Date: 2003-03-23 } { } {**********************************************************} unit TinyDBIni; interface uses SysUtils, Classes, IniFiles, Graphics, Db, TinyDB; const SFileOpenError = 'Cannot open file %s'; SNameFieldName = 'Name'; SValueFieldName = 'Value'; type TTinyDBIniFile = class(TCustomIniFile) private FTinyDatabase: TTinyDatabase; FTinyTable: TTinyTable; FEncrypt: Boolean; FPassword: string; function CreateDatabase: Boolean; function OpenDatabase: Boolean; function OpenTable(const TableName: string; Write: Boolean): Boolean; public constructor Create(const FileName: string); overload; constructor Create(const FileName, Password: string); overload; 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; function ReadBlob(const Section, Ident: string; Value: TStream): Boolean; procedure WriteBlob(const Section, Ident: string; Value: TStream); function ReadGraphic(const Section, Ident: string; Value: TGraphic): Boolean; procedure WriteGraphic(const Section, Ident: string; Value: TGraphic); property Encrypt: Boolean read FEncrypt; end; implementation { TTinyDBIniFile } constructor TTinyDBIniFile.Create(const FileName: string); begin inherited; FTinyDatabase := TTinyDatabase.Create(nil); FTinyTable := TTinyTable.Create(nil); FEncrypt := False; end; constructor TTinyDBIniFile.Create(const FileName, Password: string); begin inherited Create(FileName); FTinyDatabase := TTinyDatabase.Create(nil); FTinyTable := TTinyTable.Create(nil); FEncrypt := True; FPassword := Password; end; destructor TTinyDBIniFile.Destroy; begin FTinyDatabase.Close; FTinyTable.Free; FTinyDatabase.Free; inherited; end; function TTinyDBIniFile.CreateDatabase: Boolean; begin Result := True; if FileExists(FileName) then Exit; try if FEncrypt then Result := FTinyDatabase.CreateDatabase(FileName, False, clNormal, 'ZLIB', True, 'Blowfish', FPassword) else Result := FTinyDatabase.CreateDatabase(FileName); except Result := False; end; end; function TTinyDBIniFile.OpenDatabase: Boolean; begin Result := True; if not FTinyDatabase.Connected then begin try FTinyDatabase.DatabaseName := FileName; FTinyDatabase.Exclusive := False; FTinyDatabase.KeepConnection := True; FTinyDatabase.Password := FPassword; FTinyDatabase.Open; except Result := False; end; end; end; function TTinyDBIniFile.OpenTable(const TableName: string; Write: Boolean): Boolean; begin Result := True; if Write then Result := CreateDatabase; if not Result then Exit; Result := OpenDatabase; if not Result then Exit; Result := True; if FTinyTable.Active and (CompareText(FTinyTable.TableName, TableName) = 0) then Exit; try if Write and not FTinyDatabase.TableExists(TableName) then begin FTinyDatabase.CreateTable(TableName, [ FieldItem(SNameFieldName, ftString, 64), FieldItem(SValueFieldName, ftBlob) ] ); FTinyDatabase.CreateIndex(TableName, SNameFieldName, [tiCaseInsensitive], [SNameFieldName]) end; FTinyTable.Close; FTinyTable.DatabaseName := FileName; FTinyTable.TableName := TableName; FTinyTable.Open; except Result := False; end; end; function TTinyDBIniFile.ReadString(const Section, Ident, Default: string): string; begin try if OpenTable(Section, False) then begin if FTinyTable.FindKey(SNameFieldName, [Ident]) then Result := FTinyTable.FieldByName(SValueFieldName).AsString else Result := Default; end else Result := Default; except Result := Default; end; end; procedure TTinyDBIniFile.WriteString(const Section, Ident, Value: string); begin if OpenTable(Section, True) then begin FTinyTable.BeginUpdate; try if FTinyTable.FindKey(SNameFieldName, [Ident]) then FTinyTable.Edit else FTinyTable.Append; FTinyTable.FieldByName(SNameFieldName).AsString := Ident; FTinyTable.FieldByName(SValueFieldName).AsString := Value; FTinyTable.Post; finally FTinyTable.EndUpdate; end; end else begin DatabaseErrorFmt(SFileOpenError, [FileName]); end; end; procedure TTinyDBIniFile.ReadSection(const Section: string; Strings: TStrings); var S: string; begin try Strings.BeginUpdate; Strings.Clear; try if OpenTable(Section, False) then begin FTinyTable.First; while not FTinyTable.Eof do begin S := FTinyTable.FieldByName(SNameFieldName).AsString; Strings.Add(S); FTinyTable.Next; end; end; finally Strings.EndUpdate; end; except end; end; procedure TTinyDBIniFile.ReadSections(Strings: TStrings); begin try if not OpenDatabase then Exit; Strings.BeginUpdate; Strings.Clear; try FTinyDatabase.GetTableNames(Strings); finally Strings.EndUpdate; end; except end; end; procedure TTinyDBIniFile.ReadSectionValues(const Section: string; Strings: TStrings); var S: string; begin try Strings.BeginUpdate; Strings.Clear; try if OpenTable(Section, False) then begin FTinyTable.First; while not FTinyTable.Eof do begin S := FTinyTable.FieldByName(SNameFieldName).AsString + '=' + FTinyTable.FieldByName(SValueFieldName).AsString; Strings.Add(S); FTinyTable.Next; end; end; finally Strings.EndUpdate; end; except end; end; procedure TTinyDBIniFile.EraseSection(const Section: string); begin try if not OpenDatabase then Exit; if CompareText(FTinyTable.TableName, Section) = 0 then FTinyTable.Close; FTinyDatabase.DeleteTable(Section); except end; end; procedure TTinyDBIniFile.DeleteKey(const Section, Ident: String); begin if OpenTable(Section, False) then begin if FTinyTable.FindKey(SNameFieldName, [Ident]) then FTinyTable.Delete; end else DatabaseErrorFmt(SFileOpenError, [FileName]); end; procedure TTinyDBIniFile.UpdateFile; begin if FTinyDatabase.Connected then FTinyDatabase.FlushCache; end; function TTinyDBIniFile.ReadBlob(const Section, Ident: string; Value: TStream): Boolean; begin try if OpenTable(Section, False) then begin if FTinyTable.FindKey(SNameFieldName, [Ident]) then begin TBlobField(FTinyTable.FieldByName(SValueFieldName)).SaveToStream(Value); Result := True; end else Result := False; end else Result := False; except Result := False; end; end; procedure TTinyDBIniFile.WriteBlob(const Section, Ident: string; Value: TStream); var S: string; begin SetLength(S, Value.Size); Value.Position := 0; Value.ReadBuffer(S[1], Value.Size); WriteString(Section, Ident, S); end; function TTinyDBIniFile.ReadGraphic(const Section, Ident: string; Value: TGraphic): Boolean; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Result := ReadBlob(Section, Ident, Stream); if Result then begin Stream.Position := 0; Value.LoadFromStream(Stream); end; finally Stream.Free; end; end; procedure TTinyDBIniFile.WriteGraphic(const Section, Ident: string; Value: TGraphic); var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Value.SaveToStream(Stream); Stream.Position := 0; WriteBlob(Section, Ident, Stream); finally Stream.Free; end; end; end.
{------------------------------------------------------------------------------- // EasyComponents For Delphi 7 // 一轩软研第三方开发包 // @Copyright 2010 hehf // ------------------------------------ // // 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何 // 人不得外泄,否则后果自负. // // 使用权限以及相关解释请联系何海锋 // // // 网站地址:http://www.YiXuan-SoftWare.com // 电子邮件:hehaifeng1984@126.com // YiXuan-SoftWare@hotmail.com // QQ :383530895 // MSN :YiXuan-SoftWare@hotmail.com //------------------------------------------------------------------------------ //单元说明: // 系统常量表 //主要实现: //-----------------------------------------------------------------------------} unit untEasyClassSysConst; interface uses Classes, DB, DBClient, Variants; type TEasySysConst = class private { Private declarations } FConstGUID: string; FCName: string; FEName: string; FValue: string; FCreateTime: TDateTime; FCreater: string; FUpdater: string; FUpdateTime: TDateTime; public { Public declarations } property ConstGUID: string read FConstGUID write FConstGUID; property CName: string read FCName write FCName; property EName: string read FEName write FEName; property Value: string read FValue write FValue; property CreateTime: TDateTime read FCreateTime write FCreateTime; property Creater: string read FCreater write FCreater; property Updater: string read FUpdater write FUpdater; property UpdateTime: TDateTime read FUpdateTime write FUpdateTime; class procedure AppendClientDataSet(ACds: TClientDataSet; AObj: TEasySysConst; var AObjList: TList); class procedure EditClientDataSet(ACds: TClientDataSet; AObj: TEasySysConst; var AObjList: TList); class procedure DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasySysConst; var AObjList: TList); end; implementation class procedure TEasySysConst.AppendClientDataSet(ACds: TClientDataSet; AObj: TEasySysConst; var AObjList: TList); begin with ACds do begin Append; //1 ConstGUID FieldByName('ConstGUID').AsString := AObj.ConstGUID; //2 CName FieldByName('CName').AsString := AObj.CName; //3 EName FieldByName('EName').AsString := AObj.EName; //4 Value FieldByName('Value').AsString := AObj.Value; //5 CreateTime FieldByName('CreateTime').AsDateTime := AObj.CreateTime; //6 Creater FieldByName('Creater').AsString := AObj.Creater; //7 Updater FieldByName('Updater').AsString := AObj.Updater; //8 UpdateTime FieldByName('UpdateTime').AsDateTime := AObj.UpdateTime; post; end; AObjList.Add(AObj); end; class procedure TEasySysConst.EditClientDataSet(ACds: TClientDataSet; AObj: TEasySysConst; var AObjList: TList); begin if ACds.Locate('ConstGUID', VarArrayOf([AObj.ConstGUID]), [loCaseInsensitive]) then begin with ACds do begin Edit; //1 ConstGUID FieldByName('ConstGUID').AsString := AObj.ConstGUID; //2 CName FieldByName('CName').AsString := AObj.CName; //3 EName FieldByName('EName').AsString := AObj.EName; //4 Value FieldByName('Value').AsString := AObj.Value; //5 CreateTime FieldByName('CreateTime').AsDateTime := AObj.CreateTime; //6 Creater FieldByName('Creater').AsString := AObj.Creater; //7 Updater FieldByName('Updater').AsString := AObj.Updater; //8 UpdateTime FieldByName('UpdateTime').AsDateTime := AObj.UpdateTime; post; end; end; end; class procedure TEasySysConst.DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasySysConst; var AObjList: TList); var I, DelIndex: Integer; begin DelIndex := -1; if ACds.Locate('ConstGUID', VarArrayOf([AObj.ConstGUID]), [loCaseInsensitive]) then ACds.Delete; for I := 0 to AObjList.Count - 1 do begin if TEasySysConst(AObjList[I]).ConstGUID = TEasySysConst(AObj).ConstGUID then begin DelIndex := I; Break; end; end; if DelIndex <> -1 then begin TEasySysConst(AObjList[DelIndex]).Free; AObjList.Delete(DelIndex); end; end; end.
unit FC.StockChart.UnitTask.MBB.AdjustWidth; interface {$I Compiler.inc} uses SysUtils,Classes, BaseUtils, Serialization, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation uses FC.StockChart.UnitTask.MBB.AdjustWidthDialog; type TStockUnitTaskMBBAdjustWidth = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskMBBAdjustWidth } function TStockUnitTaskMBBAdjustWidth.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorMBB); if result then aOperationName:='MBB: Adjust Channel Width'; end; procedure TStockUnitTaskMBBAdjustWidth.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); begin TfmMBBAdjustWidthDialog.Run(aIndicator as ISCIndicatorMBB); end; initialization StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskMBBAdjustWidth.Create); end.
unit EmailAddressMaintenance; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Db, Wwdatsrc, DBTables, Wwtable, Grids, Wwdbigrd, Wwdbgrid; type TEmailAddressesForm = class(TForm) EmailAddressGrid: TwwDBGrid; EmailAddressTable: TwwTable; EmailAddressDataSource: TwwDataSource; NewButton: TBitBtn; RemoveButton: TBitBtn; SaveButton: TBitBtn; Label1: TLabel; procedure NewButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RemoveButtonClick(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure EmailAddressGridDblClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } EmailAddress : String; end; var EmailAddressesForm: TEmailAddressesForm; implementation {$R *.DFM} {==========================================================================} Procedure TEmailAddressesForm.FormCreate(Sender: TObject); begin try EmailAddressTable.Open; except MessageDlg('Error opening email address table.', mtError, [mbOK], 0); end; end; {FormCreate} {==========================================================================} Procedure TEmailAddressesForm.NewButtonClick(Sender: TObject); begin try EmailAddressTable.Append; EmailAddressGrid.SetActiveField('Person'); EmailAddressGrid.SetFocus; except MessageDlg('Error adding a new email address.', mtError, [mbOK], 0); end; end; {NewButtonClick} {==========================================================================} Procedure TEmailAddressesForm.RemoveButtonClick(Sender: TObject); begin If (MessageDlg('Are you sure you want to remove ' + Trim(EmailAddressTable.FieldByName('Person').Text) + '?', mtConfirmation, [mbYes, mbNo], 0) = idYes) then try EmailAddressTable.Delete; except MessageDlg('Error removing email address.', mtError, [mbOK], 0); end; end; {RemoveButtonClick} {==========================================================================} Procedure TEmailAddressesForm.SaveButtonClick(Sender: TObject); begin If (EmailAddressTable.State in [dsEdit, dsInsert]) then try EmailAddressTable.Post; except MessageDlg('Error saving email address.', mtError, [mbOK], 0); end; end; {SaveButtonClick} {==========================================================================} Procedure TEmailAddressesForm.EmailAddressGridDblClick(Sender: TObject); begin ModalResult := mrOK; Close; end; {==========================================================================} Procedure TEmailAddressesForm.FormClose( Sender: TObject; var Action: TCloseAction); begin SaveButtonClick(Sender); EmailAddress := EmailAddressTable.FieldByName('EmailAddress').Text; end; end.
unit ANU_CFB; (************************************************************************* DESCRIPTION : Anubis (tweaked) CFB128 functions Because of buffering en/decrypting is associative REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : B.Schneier, Applied Cryptography, 2nd ed., ch. 9.6 Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 05.08.08 W.Ehrhardt Initial version analog AES_CFB 0.11 24.11.08 we Uses BTypes 0.12 01.08.10 we Longint ILen in ANU_CFB_En/Decrypt **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2008-2010 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} interface uses BTypes, ANU_Base; {$ifdef CONST} function ANU_CFB_Init(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer; {-Anubis key expansion, error if invalid key size, encrypt IV} {$ifdef DLL} stdcall; {$endif} {$else} function ANU_CFB_Init(var Key; KeyBits: word; var IV: TANUBlock; var ctx: TANUContext): integer; {-Anubis key expansion, error if invalid key size, encrypt IV} {$endif} function ANU_CFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CFB128 mode} {$ifdef DLL} stdcall; {$endif} function ANU_CFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CFB128 mode} {$ifdef DLL} stdcall; {$endif} implementation {---------------------------------------------------------------------------} {$ifdef CONST} function ANU_CFB_Init(const Key; KeyBits: word; const IV: TANUBlock; var ctx: TANUContext): integer; {$else} function ANU_CFB_Init(var Key; KeyBits: word; var IV: TANUBlock; var ctx: TANUContext): integer; {$endif} {-Anubis key expansion, error if invalid key size, encrypt IV} var err: integer; begin {-Anubis key expansion, error if invalid key size} err := ANU_Init_Encr(Key, KeyBits, ctx); ANU_CFB_Init := err; if err=0 then begin {encrypt IV} ANU_Encrypt(ctx, IV, ctx.IV); end; end; {---------------------------------------------------------------------------} function ANU_CFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CFB128 mode} begin ANU_CFB_Encrypt := 0; if ctx.Decrypt<>0 then begin ANU_CFB_Encrypt := ANU_Err_Invalid_Mode; exit; end; if (ptp=nil) or (ctp=nil) then begin if ILen>0 then begin ANU_CFB_Encrypt := ANU_Err_NIL_Pointer; exit; end; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin ANU_CFB_Encrypt := ANU_Err_Invalid_16Bit_Length; exit; end; {$endif} if ctx.blen=0 then begin {Handle full blocks first} while ILen>=ANUBLKSIZE do with ctx do begin {Cipher text = plain text xor encr(IV/CT), cf. [3] 6.3} ANU_XorBlock(PANUBlock(ptp)^, IV, PANUBlock(ctp)^); ANU_Encrypt(ctx, PANUBlock(ctp)^, IV); inc(Ptr2Inc(ptp), ANUBLKSIZE); inc(Ptr2Inc(ctp), ANUBLKSIZE); dec(ILen, ANUBLKSIZE); end; end; {Handle remaining bytes} while ILen>0 do with ctx do begin {Test buffer empty} if bLen>=ANUBLKSIZE then begin ANU_Encrypt(ctx, buf, IV); bLen := 0; end; buf[bLen] := IV[bLen] xor pByte(ptp)^; pByte(ctp)^ := buf[bLen]; inc(bLen); inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); dec(ILen); end; end; {---------------------------------------------------------------------------} function ANU_CFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CFB128 mode} begin ANU_CFB_Decrypt := 0; if ctx.Decrypt<>0 then begin ANU_CFB_Decrypt := ANU_Err_Invalid_Mode; exit; end; if (ptp=nil) or (ctp=nil) then begin if ILen>0 then begin ANU_CFB_Decrypt := ANU_Err_NIL_Pointer; exit; end; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin ANU_CFB_Decrypt := ANU_Err_Invalid_16Bit_Length; exit; end; {$endif} if ctx.blen=0 then begin {Handle full blocks first} while ILen>=ANUBLKSIZE do with ctx do begin {plain text = cypher text xor encr(IV/CT), cf. [3] 6.3} {must use buf, otherwise overwrite bug if ctp=ptp} buf := PANUBlock(ctp)^; ANU_XorBlock(buf, IV, PANUBlock(ptp)^); ANU_Encrypt(ctx, buf, IV); inc(Ptr2Inc(ptp), ANUBLKSIZE); inc(Ptr2Inc(ctp), ANUBLKSIZE); dec(ILen, ANUBLKSIZE); end; end; {Handle remaining bytes} while ILen>0 do with ctx do begin {Test buffer empty} if bLen>=ANUBLKSIZE then begin ANU_Encrypt(ctx, buf, IV); bLen := 0; end; buf[bLen] := pByte(ctp)^; pByte(ptp)^ := buf[bLen] xor IV[bLen]; inc(bLen); inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); dec(ILen); end; end; end.
unit HYService; interface uses GSPInterface; type THYService = class private FProjModel: IGSPModel; function GetProjModel: IGSPModel; public property ProjModel: IGSPModel read GetProjModel; procedure Save; end; implementation uses HYUtils; const CHYModelFile = 'HY.GSP'; { THYService } function THYService.GetProjModel: IGSPModel; begin if not Assigned(FProjModel) then FProjModel := LoadGSPModel(CHYModelFile); Result := FProjModel; end; procedure THYService.Save; begin if Assigned(FProjModel) then SaveModelToFile(FProjModel, CHYModelFile); end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_RecastArea; interface uses Math, SysUtils, RN_Helper, RN_Recast; /// Erodes the walkable area within the heightfield by the specified radius. /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in] radius The radius of erosion. [Limits: 0 < value < 255] [Units: vx] /// @param[in,out] chf The populated compact heightfield to erode. /// @returns True if the operation completed successfully. function rcErodeWalkableArea(ctx: TrcContext; radius: Integer; chf: PrcCompactHeightfield): Boolean; /// Applies a median filter to walkable area types (based on area id), removing noise. /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in,out] chf A populated compact heightfield. /// @returns True if the operation completed successfully. function rcMedianFilterWalkableArea(ctx: TrcContext; chf: PrcCompactHeightfield): Boolean; /// Applies an area id to all spans within the specified bounding box. (AABB) /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in] bmin The minimum of the bounding box. [(x, y, z)] /// @param[in] bmax The maximum of the bounding box. [(x, y, z)] /// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] /// @param[in,out] chf A populated compact heightfield. procedure rcMarkBoxArea(ctx: TrcContext; const bmin, bmax: PSingle; areaId: Byte; chf: PrcCompactHeightfield); /// Applies the area id to the all spans within the specified convex polygon. /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in] verts The vertices of the polygon [Fomr: (x, y, z) * @p nverts] /// @param[in] nverts The number of vertices in the polygon. /// @param[in] hmin The height of the base of the polygon. /// @param[in] hmax The height of the top of the polygon. /// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] /// @param[in,out] chf A populated compact heightfield. procedure rcMarkConvexPolyArea(ctx: TrcContext; const verts: PSingle; const nverts: Integer; const hmin, hmax: Single; areaId: Byte; chf: PrcCompactHeightfield); /// Helper function to offset voncex polygons for rcMarkConvexPolyArea. /// @ingroup recast /// @param[in] verts The vertices of the polygon [Form: (x, y, z) * @p nverts] /// @param[in] nverts The number of vertices in the polygon. /// @param[out] outVerts The offset vertices (should hold up to 2 * @p nverts) [Form: (x, y, z) * return value] /// @param[in] maxOutVerts The max number of vertices that can be stored to @p outVerts. /// @returns Number of vertices in the offset polygon or 0 if too few vertices in @p outVerts. function rcOffsetPoly(const verts: PSingle; const nverts: Integer; const offset: Single; out outVerts: PSingle; const maxOutVerts: Integer): Integer; /// Applies the area id to all spans within the specified cylinder. /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in] pos The center of the base of the cylinder. [Form: (x, y, z)] /// @param[in] r The radius of the cylinder. /// @param[in] h The height of the cylinder. /// @param[in] areaId The area id to apply. [Limit: <= #RC_WALKABLE_AREA] /// @param[in,out] chf A populated compact heightfield. procedure rcMarkCylinderArea(ctx: TrcContext; const pos: PSingle; const r, h: Single; areaId: Byte; chf: PrcCompactHeightfield); implementation uses RN_RecastHelper; /// @par /// /// Basically, any spans that are closer to a boundary or obstruction than the specified radius /// are marked as unwalkable. /// /// This method is usually called immediately after the heightfield has been built. /// /// @see rcCompactHeightfield, rcBuildCompactHeightfield, rcConfig::walkableRadius function rcErodeWalkableArea(ctx: TrcContext; radius: Integer; chf: PrcCompactHeightfield): Boolean; var w,h: Integer; dist: PByte; x,y,i: Integer; c: PrcCompactCell; s: PrcCompactSpan; nc,dir: Integer; nx,ny,nidx: Integer; ax,ay,ai: Integer; nd: Byte; as1: PrcCompactSpan; aax,aay,aai: Integer; thr: Byte; begin //rcAssert(ctx); w := chf.width; h := chf.height; ctx.startTimer(RC_TIMER_ERODE_AREA); GetMem(dist, sizeof(Byte)*chf.spanCount); // Init distance. FillChar(dist[0], SizeOf(Byte)*chf.spanCount, $ff); // Mark boundary cells. for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin c := @chf.cells[x+y*w]; for i := c.index to Integer(c.index+c.count) - 1 do begin if (chf.areas[i] = RC_NULL_AREA) then begin dist[i] := 0; end else begin s := @chf.spans[i]; nc := 0; for dir := 0 to 3 do begin if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then begin nx := x + rcGetDirOffsetX(dir); ny := y + rcGetDirOffsetY(dir); nidx := chf.cells[nx+ny*w].index + rcGetCon(s, dir); if (chf.areas[nidx] <> RC_NULL_AREA) then begin Inc(nc); end; end; end; // At least one missing neighbour. if (nc <> 4) then dist[i] := 0; end; end; end; end; // Pass 1 for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin c := @chf.cells[x+y*w]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; if (rcGetCon(s, 0) <> RC_NOT_CONNECTED) then begin // (-1,0) ax := x + rcGetDirOffsetX(0); ay := y + rcGetDirOffsetY(0); ai := chf.cells[ax+ay*w].index + rcGetCon(s, 0); as1 := @chf.spans[ai]; nd := rcMin(dist[ai]+2, 255); if (nd < dist[i]) then dist[i] := nd; // (-1,-1) if (rcGetCon(as1, 3) <> RC_NOT_CONNECTED) then begin aax := ax + rcGetDirOffsetX(3); aay := ay + rcGetDirOffsetY(3); aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 3); nd := rcMin(dist[aai]+3, 255); if (nd < dist[i]) then dist[i] := nd; end; end; if (rcGetCon(s, 3) <> RC_NOT_CONNECTED) then begin // (0,-1) ax := x + rcGetDirOffsetX(3); ay := y + rcGetDirOffsetY(3); ai := chf.cells[ax+ay*w].index + rcGetCon(s, 3); as1 := @chf.spans[ai]; nd := rcMin(dist[ai]+2, 255); if (nd < dist[i]) then dist[i] := nd; // (1,-1) if (rcGetCon(as1, 2) <> RC_NOT_CONNECTED) then begin aax := ax + rcGetDirOffsetX(2); aay := ay + rcGetDirOffsetY(2); aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 2); nd := rcMin(dist[aai]+3, 255); if (nd < dist[i]) then dist[i] := nd; end; end; end; end; end; // Pass 2 for y := h - 1 downto 0 do begin for x := w - 1 downto 0 do begin c := @chf.cells[x+y*w]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; if (rcGetCon(s, 2) <> RC_NOT_CONNECTED) then begin // (1,0) ax := x + rcGetDirOffsetX(2); ay := y + rcGetDirOffsetY(2); ai := chf.cells[ax+ay*w].index + rcGetCon(s, 2); as1 := @chf.spans[ai]; nd := rcMin(dist[ai]+2, 255); if (nd < dist[i]) then dist[i] := nd; // (1,1) if (rcGetCon(as1, 1) <> RC_NOT_CONNECTED) then begin aax := ax + rcGetDirOffsetX(1); aay := ay + rcGetDirOffsetY(1); aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 1); nd := rcMin(dist[aai]+3, 255); if (nd < dist[i]) then dist[i] := nd; end; end; if (rcGetCon(s, 1) <> RC_NOT_CONNECTED) then begin // (0,1) ax := x + rcGetDirOffsetX(1); ay := y + rcGetDirOffsetY(1); ai := chf.cells[ax+ay*w].index + rcGetCon(s, 1); as1 := @chf.spans[ai]; nd := rcMin(dist[ai]+2, 255); if (nd < dist[i]) then dist[i] := nd; // (-1,1) if (rcGetCon(as1, 0) <> RC_NOT_CONNECTED) then begin aax := ax + rcGetDirOffsetX(0); aay := ay + rcGetDirOffsetY(0); aai := chf.cells[aax+aay*w].index + rcGetCon(as1, 0); nd := rcMin(dist[aai]+3, 255); if (nd < dist[i]) then dist[i] := nd; end; end; end; end; end; thr := Byte(radius*2); for i := 0 to chf.spanCount - 1 do if (dist[i] < thr) then chf.areas[i] := RC_NULL_AREA; FreeMem(dist); ctx.stopTimer(RC_TIMER_ERODE_AREA); Result := True; end; procedure insertSort(a: array of Byte; const n: Integer); var i, j: Integer; value: Byte; begin for i := 1 to n - 1 do begin value := a[i]; //for (j := i - 1; j >= 0 && a[j] > value; j--) j := i - 1; while (j >= 0) and (a[j] > value) do begin a[j+1] := a[j]; Dec(j); end; a[j+1] := value; end; end; /// @par /// /// This filter is usually applied after applying area id's using functions /// such as #rcMarkBoxArea, #rcMarkConvexPolyArea, and #rcMarkCylinderArea. /// /// @see rcCompactHeightfield function rcMedianFilterWalkableArea(ctx: TrcContext; chf: PrcCompactHeightfield): Boolean; var w,h: Integer; areas: PByte; x,y,i,j,dir,dir2: Integer; c: PrcCompactCell; s,as1: PrcCompactSpan; nei: array [0..8] of Byte; ax,ay,ai,ax2,ay2,ai2: Integer; begin //rcAssert(ctx); w := chf.width; h := chf.height; ctx.startTimer(RC_TIMER_MEDIAN_AREA); GetMem(areas, sizeof(Byte)*chf.spanCount); // Init distance. FillChar(areas[0], sizeof(Byte)*chf.spanCount, $ff); for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin c := @chf.cells[x+y*w]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; if (chf.areas[i] = RC_NULL_AREA) then begin areas[i] := chf.areas[i]; continue; end; for j := 0 to 8 do nei[j] := chf.areas[i]; for dir := 0 to 3 do begin if (rcGetCon(s, dir) <> RC_NOT_CONNECTED) then begin ax := x + rcGetDirOffsetX(dir); ay := y + rcGetDirOffsetY(dir); ai := chf.cells[ax+ay*w].index + rcGetCon(s, dir); if (chf.areas[ai] <> RC_NULL_AREA) then nei[dir*2+0] := chf.areas[ai]; as1 := @chf.spans[ai]; dir2 := (dir+1) and $3; if (rcGetCon(as1, dir2) <> RC_NOT_CONNECTED) then begin ax2 := ax + rcGetDirOffsetX(dir2); ay2 := ay + rcGetDirOffsetY(dir2); ai2 := chf.cells[ax2+ay2*w].index + rcGetCon(as1, dir2); if (chf.areas[ai2] <> RC_NULL_AREA) then nei[dir*2+1] := chf.areas[ai2]; end; end; end; insertSort(nei, 9); areas[i] := nei[4]; end; end; end; Move(areas[0], chf.areas[0], sizeof(Byte)*chf.spanCount); FreeMem(areas); ctx.stopTimer(RC_TIMER_MEDIAN_AREA); Result := true; end; /// @par /// /// The value of spacial parameters are in world units. /// /// @see rcCompactHeightfield, rcMedianFilterWalkableArea procedure rcMarkBoxArea(ctx: TrcContext; const bmin, bmax: PSingle; areaId: Byte; chf: PrcCompactHeightfield); var minx, miny, minz, maxx, maxy, maxz: Integer; z,x,i: Integer; c: PrcCompactCell; s: PrcCompactSpan; begin //rcAssert(ctx); ctx.startTimer(RC_TIMER_MARK_BOX_AREA); minx := Trunc((bmin[0]-chf.bmin[0])/chf.cs); miny := Trunc((bmin[1]-chf.bmin[1])/chf.ch); minz := Trunc((bmin[2]-chf.bmin[2])/chf.cs); maxx := Trunc((bmax[0]-chf.bmin[0])/chf.cs); maxy := Trunc((bmax[1]-chf.bmin[1])/chf.ch); maxz := Trunc((bmax[2]-chf.bmin[2])/chf.cs); if (maxx < 0) then Exit; if (minx >= chf.width) then Exit; if (maxz < 0) then Exit; if (minz >= chf.height) then Exit; if (minx < 0) then minx := 0; if (maxx >= chf.width) then maxx := chf.width-1; if (minz < 0) then minz := 0; if (maxz >= chf.height) then maxz := chf.height-1; for z := minz to maxz do begin for x := minx to maxx do begin c := @chf.cells[x+z*chf.width]; for i := c.index to Integer(c.index+c.count)- 1 do begin s := @chf.spans[i]; if (s.y >= miny) and (s.y <= maxy) then begin if (chf.areas[i] <> RC_NULL_AREA) then chf.areas[i] := areaId; end; end; end; end; ctx.stopTimer(RC_TIMER_MARK_BOX_AREA); end; function pointInPoly(nvert: Integer; const verts: PSingle; const p: PSingle): Boolean; var i, j: Integer; c: Boolean; vi,vj: PSingle; begin c := False; //for (i = 0, j = nvert-1; i < nvert; j = i++) i := 0; j := nvert-1; while (i < nvert) do begin vi := @verts[i*3]; vj := @verts[j*3]; if (((vi[2] > p[2]) <> (vj[2] > p[2])) and (p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) ) then c := not c; j := i; Inc(i); end; Result := c; end; /// @par /// /// The value of spacial parameters are in world units. /// /// The y-values of the polygon vertices are ignored. So the polygon is effectively /// projected onto the xz-plane at @p hmin, then extruded to @p hmax. /// /// @see rcCompactHeightfield, rcMedianFilterWalkableArea procedure rcMarkConvexPolyArea(ctx: TrcContext; const verts: PSingle; const nverts: Integer; const hmin, hmax: Single; areaId: Byte; chf: PrcCompactHeightfield); var bmin, bmax, p: array [0..2] of Single; i,x,z: Integer; minx, miny, minz, maxx, maxy, maxz: Integer; c: PrcCompactCell; s: PrcCompactSpan; begin //rcAssert(ctx); ctx.startTimer(RC_TIMER_MARK_CONVEXPOLY_AREA); rcVcopy(@bmin[0], @verts[0]); rcVcopy(@bmax[0], @verts[0]); for i := 1 to nverts - 1 do begin rcVmin(@bmin[0], @verts[i*3]); rcVmax(@bmax[0], @verts[i*3]); end; bmin[1] := hmin; bmax[1] := hmax; minx := Trunc((bmin[0]-chf.bmin[0])/chf.cs); miny := Trunc((bmin[1]-chf.bmin[1])/chf.ch); minz := Trunc((bmin[2]-chf.bmin[2])/chf.cs); maxx := Trunc((bmax[0]-chf.bmin[0])/chf.cs); maxy := Trunc((bmax[1]-chf.bmin[1])/chf.ch); maxz := Trunc((bmax[2]-chf.bmin[2])/chf.cs); if (maxx < 0) then Exit; if (minx >= chf.width) then Exit; if (maxz < 0) then Exit; if (minz >= chf.height) then Exit; if (minx < 0) then minx := 0; if (maxx >= chf.width) then maxx := chf.width-1; if (minz < 0) then minz := 0; if (maxz >= chf.height) then maxz := chf.height-1; // TODO: Optimize. for z := minz to maxz do begin for x := minx to maxx do begin c := @chf.cells[x+z*chf.width]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; if (chf.areas[i] = RC_NULL_AREA) then continue; if (s.y >= miny) and (s.y <= maxy) then begin p[0] := chf.bmin[0] + (x+0.5)*chf.cs; p[1] := 0; p[2] := chf.bmin[2] + (z+0.5)*chf.cs; if (pointInPoly(nverts, verts, @p[0])) then begin chf.areas[i] := areaId; end; end; end; end; end; ctx.stopTimer(RC_TIMER_MARK_CONVEXPOLY_AREA); end; function rcOffsetPoly(const verts: PSingle; const nverts: Integer; const offset: Single; out outVerts: PSingle; const maxOutVerts: Integer): Integer; const MITER_LIMIT = 1.20; var n,i: Integer; a,b,c: Integer; va,vb,vc: PSingle; dx0,dy0,d0,dx1,dy1,d1,dlx0,dly0,dlx1,dly1: Single; cross,dmx,dmy,dmr2: Single; bevel: Boolean; scale,d: Single; begin n := 0; for i := 0 to nverts - 1 do begin a := (i+nverts-1) mod nverts; b := i; c := (i+1) mod nverts; va := @verts[a*3]; vb := @verts[b*3]; vc := @verts[c*3]; dx0 := vb[0] - va[0]; dy0 := vb[2] - va[2]; d0 := dx0*dx0 + dy0*dy0; if (d0 > 0.000001) then begin d0 := 1.0/Sqrt(d0); dx0 := dx0 * d0; dy0 := dy0 * d0; end; dx1 := vc[0] - vb[0]; dy1 := vc[2] - vb[2]; d1 := dx1*dx1 + dy1*dy1; if (d1 > 0.000001) then begin d1 := 1.0/Sqrt(d1); dx1 := dx1 * d1; dy1 := dy1 * d1; end; dlx0 := -dy0; dly0 := dx0; dlx1 := -dy1; dly1 := dx1; cross := dx1*dy0 - dx0*dy1; dmx := (dlx0 + dlx1) * 0.5; dmy := (dly0 + dly1) * 0.5; dmr2 := dmx*dmx + dmy*dmy; bevel := dmr2 * MITER_LIMIT*MITER_LIMIT < 1.0; if (dmr2 > 0.000001) then begin scale := 1.0 / dmr2; dmx := dmx * scale; dmy := dmy * scale; end; if bevel and (cross < 0.0) then begin if (n+2 >= maxOutVerts) then Exit(0); d := (1.0 - (dx0*dx1 + dy0*dy1))*0.5; outVerts[n*3+0] := vb[0] + (-dlx0+dx0*d)*offset; outVerts[n*3+1] := vb[1]; outVerts[n*3+2] := vb[2] + (-dly0+dy0*d)*offset; Inc(n); outVerts[n*3+0] := vb[0] + (-dlx1-dx1*d)*offset; outVerts[n*3+1] := vb[1]; outVerts[n*3+2] := vb[2] + (-dly1-dy1*d)*offset; Inc(n); end else begin if (n+1 >= maxOutVerts) then Exit(0); outVerts[n*3+0] := vb[0] - dmx*offset; outVerts[n*3+1] := vb[1]; outVerts[n*3+2] := vb[2] - dmy*offset; Inc(n); end; end; Result := n; end; /// @par /// /// The value of spacial parameters are in world units. /// /// @see rcCompactHeightfield, rcMedianFilterWalkableArea procedure rcMarkCylinderArea(ctx: TrcContext; const pos: PSingle; const r, h: Single; areaId: Byte; chf: PrcCompactHeightfield); var bmin, bmax: array [0..2] of Single; r2: Single; minx, miny, minz, maxx, maxy, maxz: Integer; x,z,i: Integer; c: PrcCompactCell; s: PrcCompactSpan; sx,sz,dx,dz: Single; begin //rcAssert(ctx); ctx.startTimer(RC_TIMER_MARK_CYLINDER_AREA); bmin[0] := pos[0] - r; bmin[1] := pos[1]; bmin[2] := pos[2] - r; bmax[0] := pos[0] + r; bmax[1] := pos[1] + h; bmax[2] := pos[2] + r; r2 := r*r; minx := Trunc((bmin[0]-chf.bmin[0])/chf.cs); miny := Trunc((bmin[1]-chf.bmin[1])/chf.ch); minz := Trunc((bmin[2]-chf.bmin[2])/chf.cs); maxx := Trunc((bmax[0]-chf.bmin[0])/chf.cs); maxy := Trunc((bmax[1]-chf.bmin[1])/chf.ch); maxz := Trunc((bmax[2]-chf.bmin[2])/chf.cs); if (maxx < 0) then Exit; if (minx >= chf.width) then Exit; if (maxz < 0) then Exit; if (minz >= chf.height) then Exit; if (minx < 0) then minx := 0; if (maxx >= chf.width) then maxx := chf.width-1; if (minz < 0) then minz := 0; if (maxz >= chf.height) then maxz := chf.height-1; for z := minz to maxz do begin for x := minx to maxx do begin c := @chf.cells[x+z*chf.width]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; if (chf.areas[i] = RC_NULL_AREA) then Continue; if (s.y >= miny) and (s.y <= maxy) then begin sx := chf.bmin[0] + (x+0.5)*chf.cs; sz := chf.bmin[2] + (z+0.5)*chf.cs; dx := sx - pos[0]; dz := sz - pos[2]; if (dx*dx + dz*dz < r2) then begin chf.areas[i] := areaId; end; end; end; end; end; ctx.stopTimer(RC_TIMER_MARK_CYLINDER_AREA); end; end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program CAR; Const maxN =10000; Type Note =Record id,v :SmallInt; t :ShortInt end; Var n :SmallInt; A :Array[1..maxN] of Note; res :Int64; procedure Enter; var i :SmallInt; begin Read(n); for i:=1 to n do A[i].id:=i; for i:=1 to n do Read(A[i].v); for i:=1 to n do Read(A[i].t); end; function Compare(x,y :Real) :Boolean; begin Exit(x>y); end; procedure Sort(l,r :SmallInt); var i,j,k :SmallInt; key :Real; Tmp :Note; begin if (l>=r) then Exit; i:=l; j:=r; k:=Random(r-l+1)+l; key:=A[k].t/A[k].v; repeat while (Compare(key,A[i].t/A[i].v)) do Inc(i); while (Compare(A[j].t/A[j].v,key)) do Dec(j); if (i<=j) then begin if (i<j) then begin Tmp:=A[i]; A[i]:=A[j]; A[j]:=Tmp; end; Inc(i); Dec(j); end; until (i>j); Sort(l,j); Sort(i,r); end; procedure Greedy; var i :SmallInt; time :Int64; begin res:=0; time:=0; for i:=1 to n do begin Inc(time,A[i].t); Inc(res,A[i].v*time); end; end; procedure Escape; var i :SmallInt; begin WriteLn(res); for i:=1 to n do Write(A[i].id,' '); end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; Sort(1,n); Greedy; Escape; Close(Input); Close(Output); End.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {****************************************************************************} { } { Limitation on Distribution of Programs Created with this Source Code File: } { ========================================================================== } { } { For distribution of an application which you create with this Source } { Code File, your application may not be a general-purpose, interactive } { spreadsheet program, or a substitute for or generally competitive } { with Quattro Pro. } { } {****************************************************************************} unit Vcl.Tabs; {$HPPEMIT LEGACYHPP} {$T-,H+,X+} interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Winapi.Messages, Vcl.ImgList, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Themes, System.Generics.Collections, System.Generics.Defaults; type TScrollBtn = (sbLeft, sbRight); TScrollOrientation = (soLeftRight, soUpDown); TTabPos = record private FSize, FStartPos: Word; public property Size: Word read FSize write FSize; property StartPos: Word read FStartPos write FStartPos; constructor Create(AStartPos, ASize: Word); end; TTabPosList = TList<TTabPos>; TScroller = class(TCustomControl) private { property usage } FMin: Longint; FMax: Longint; FPosition: Longint; FOnClick: TNotifyEvent; FChange: Integer; FScrollOrientation: TScrollOrientation; { private usage } FBitmap: TBitmap; FHover: Boolean; FHoverPoint: TPoint; FPressed: Boolean; FDown: Boolean; FCurrent: TScrollBtn; FWidth: Integer; FHeight: Integer; FDownTimer: TTimer; { property access methods } procedure SetMin(Value: Longint); procedure SetMax(Value: Longint); procedure SetPosition(Value: Longint); { private methods } function CanScrollLeft: Boolean; function CanScrollRight: Boolean; procedure DoMouseDown(X: Integer); procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE; procedure WMMouseLeave(var Message: TWMMouseMove); message WM_MOUSELEAVE; procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure SetScrollOrientation(const Value: TScrollOrientation); procedure DoScrollTimer(Sender: TObject); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnClick: TNotifyEvent read FOnClick write FOnClick; property Min: Longint read FMin write SetMin default 0; property Max: Longint read FMax write SetMax default 0; property Position: Longint read FPosition write SetPosition default 0; property ScrollOrientation: TScrollOrientation read FScrollOrientation write SetScrollOrientation; property Change: Integer read FChange write FChange default 1; end; TTabSet = class; TTabList = class(TStringList) private FTabSet: TTabSet; protected procedure Put(Index: Integer; const S: string); override; public constructor Create(const ATabSet: TTabSet); procedure Insert(Index: Integer; const S: string); override; procedure Delete(Index: Integer); override; function Add(const S: string): Integer; override; procedure Clear; override; procedure AddStrings(Strings: TStrings); override; end; { each TEdgeType is made up of one or two of these parts } TEdgePart = (epSelectedLeft, epUnselectedLeft, epSelectedRight, epUnselectedRight); { represents the intersection between two tabs, or the edge of a tab } TEdgeType = (etNone, etFirstIsSel, etFirstNotSel, etLastIsSel, etLastNotSel, etNotSelToSel, etSelToNotSel, etNotSelToNotSel); TTabSetTabStyle = (tsStandard, tsOwnerDraw, tsSoftTabs, tsModernTabs, tsModernPopout); TTabStyle = TTabSetTabStyle; TMeasureTabEvent = procedure(Sender: TObject; Index: Integer; var TabWidth: Integer) of object; TTabSetDrawTabEvent = procedure(Sender: TObject; TabCanvas: TCanvas; R: TRect; Index: Integer; Selected: Boolean) of object; TDrawTabEvent = TTabSetDrawTabEvent; TTabChangeEvent = procedure(Sender: TObject; NewTab: Integer; var AllowChange: Boolean) of object; TTabSet = class(TCustomControl) private FStartMargin: Integer; FEndMargin: Integer; FTabs: TStrings; FTabIndex: Integer; FFirstIndex: Integer; FVisibleTabs: Integer; FSelectedColor: TColor; FUnselectedColor: TColor; FBackgroundColor: TColor; FDitherBackground: Boolean; FAutoScroll: Boolean; FStyle: TTabStyle; FOwnerDrawHeight: Integer; FOnMeasureTab: TMeasureTabEvent; FOnDrawTab: TDrawTabEvent; FOnChange: TTabChangeEvent; FEdgeImageList: TImageList; FMemBitmap: TBitmap; { used for off-screen drawing } FBrushBitmap: TBitmap; { used for background pattern } FTabPositions: TTabPosList; FSortedTabPositions: TTabPosList; FTabHeight: Integer; FScroller: TScroller; FDoFix: Boolean; FSoftTop: Boolean; FImages: TCustomImageList; FImageChangeLink: TChangeLink; FOnGetImageIndex: TTabGetImageEvent; FShrinkToFit: Boolean; FEdgeWidth: Integer; FTabPosition: TTabPosition; { property access methods } procedure SetSelectedColor(Value: TColor); procedure SetUnselectedColor(Value: TColor); procedure SetBackgroundColor(Value: TColor); procedure SetDitherBackground(Value: Boolean); procedure SetAutoScroll(Value: Boolean); procedure SetStartMargin(Value: Integer); procedure SetEndMargin(Value: Integer); procedure SetFirstIndex(Value: Integer); procedure SetTabList(Value: TStrings); procedure SetTabStyle(Value: TTabStyle); procedure SetTabHeight(Value: Integer); { private methods } procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMSysColorChange(var Message: TMessage); message CM_SYSCOLORCHANGE; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMStyleChanged(var Message: TMessage); message CM_STYLECHANGED; procedure PaintEdge(X, Y, H: Integer; Edge: TEdgeType); procedure CreateBrushPattern(Bitmap: TBitmap); function CalcTabPositions(const AStart, AStop: Integer; Canvas: TCanvas; First: Integer; FullTabs: Boolean): Integer; procedure CreateScroller; procedure InitBitmaps; procedure DoneBitmaps; procedure CreateEdgeParts; procedure FixTabPos; procedure ScrollClick(Sender: TObject); procedure SetSoftTop(const Value: Boolean); procedure SetImages(const Value: TCustomImageList); function ScrollerSize: Integer; procedure SetShrinkToFit(const Value: Boolean); procedure SetTabPosition(const Value: TTabPosition); procedure SetFontOrientation(ACanvas: TCanvas); procedure ImageListChange(Sender: TObject); procedure DoDefaultPainting; procedure DoPopoutModernPainting; function ScrollerShown: Boolean; protected function CanChange(NewIndex: Integer): Boolean; procedure CMHintShow(var Message: TCMHintShow); message CM_HINTSHOW; procedure CreateParams(var Params: TCreateParams); override; procedure DrawTab(TabCanvas: TCanvas; R: TRect; Index: Integer; Selected: Boolean); virtual; function GetImageIndex(TabIndex: Integer): Integer; virtual; procedure MeasureTab(Index: Integer; var TabWidth: Integer); virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetupTabPositions; procedure DoModernPainting; virtual; procedure Paint; override; procedure UpdateStyleElements; override; procedure SetTabIndex(Value: Integer); virtual; procedure DrawLine(Canvas: TCanvas; FromX, FromY, ToX, ToY: Integer); property Scroller: TScroller read FScroller; property MemBitmap: TBitmap read FMemBitmap; property TabPositions: TTabPosList read FTabPositions; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; function ItemAtPos(Pos: TPoint; IgnoreTabHeight: Boolean = False): Integer; function ItemRect(Index: Integer): TRect; function ItemWidth(Index: Integer): Integer; function MinClientRect: TRect; overload; function MinClientRect(IncludeScroller: Boolean): TRect; overload; function MinClientRect(TabCount: Integer; IncludeScroller: Boolean = False): TRect; overload; procedure SelectNext(Direction: Boolean); property Canvas; property FirstIndex: Integer read FFirstIndex write SetFirstIndex default 0; property EdgeWidth: Integer read FEdgeWidth write FEdgeWidth; published property Align; property Anchors; property AutoScroll: Boolean read FAutoScroll write SetAutoScroll default True; property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor default clBtnFace; property Constraints; property DitherBackground: Boolean read FDitherBackground write SetDitherBackground default True; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property EndMargin: Integer read FEndMargin write SetEndMargin default 5; property Font; property Images: TCustomImageList read FImages write SetImages; property ParentBackground default False; property ParentDoubleBuffered; property ParentShowHint; property PopupMenu; property ShowHint; property ShrinkToFit: Boolean read FShrinkToFit write SetShrinkToFit default False; property StartMargin: Integer read FStartMargin write SetStartMargin default 5; property SelectedColor: TColor read FSelectedColor write SetSelectedColor default clBtnFace; property SoftTop: Boolean read FSoftTop write SetSoftTop default False; property Style: TTabStyle read FStyle write SetTabStyle default tsStandard; property TabHeight: Integer read FOwnerDrawHeight write SetTabHeight default 20; property Tabs: TStrings read FTabs write SetTabList; property TabIndex: Integer read FTabIndex write SetTabIndex default -1; property TabPosition: TTabPosition read FTabPosition write SetTabPosition default tpBottom; property Touch; property UnselectedColor: TColor read FUnselectedColor write SetUnselectedColor default clWindow; property Visible; property StyleElements; property VisibleTabs: Integer read FVisibleTabs; property OnAlignInsertBefore; property OnAlignPosition; property OnClick; property OnChange: TTabChangeEvent read FOnChange write FOnChange; property OnDragDrop; property OnDragOver; property OnDrawTab: TDrawTabEvent read FOnDrawTab write FOnDrawTab; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGesture; property OnGetImageIndex: TTabGetImageEvent read FOnGetImageIndex write FOnGetImageIndex; property OnMouseActivate; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMeasureTab: TMeasureTabEvent read FOnMeasureTab write FOnMeasureTab; property OnStartDock; property OnStartDrag; end; implementation {$IF DEFINED(CLR)} {$R Borland.Vcl.Tabs.resources} {$ELSE} {$R Tabs.res} {$ENDIF} uses {$IF DEFINED(CLR)} System.Runtime.InteropServices, System.Reflection, System.Security.Permissions, {$ENDIF} System.SysUtils, System.Types, System.Math, Vcl.GraphUtil, Vcl.Consts; {$IF DEFINED(CLR)} const ResourceBaseName = 'Borland.Vcl.Tabs'; {$ENDIF} function GetThemeColor(Details: TThemedElementDetails; ElementColor: TElementColor; var Color: TColor): Boolean; inline; begin Result := StyleServices.Enabled and StyleServices.GetElementColor(Details, ElementColor, Color) and (Color <> clNone); end; { TTabPos } constructor TTabPos.Create(AStartPos, ASize: Word); begin inherited ; FStartPos := AStartPos; FSize := ASize; end; { TScroller } constructor TScroller.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csOpaque]; FBitmap := TBitmap.Create; FWidth := 24; FHeight := 13; FMin := 0; FMax := 0; FPosition := 0; FChange := 1; FDownTimer := TTimer.Create(nil); FDownTimer.Enabled := False; FDownTimer.Interval := 100; FDownTimer.OnTimer := DoScrollTimer; end; destructor TScroller.Destroy; begin FDownTimer.Free; FBitmap.Free; inherited Destroy; end; const cLeftOrient: array[TScrollOrientation] of string = ('SBLEFT', 'SBUP'); { Do not localize } cLeftDnOrient: array[TScrollOrientation] of string = ('SBLEFTDN', 'SBUPDN'); { Do not localize } cLeftDisOrient: array[TScrollOrientation] of string = ('SBLEFTDIS', 'SBUPDIS'); { Do not localize } cRightOrient: array[TScrollOrientation] of string = ('SBRIGHT', 'SBDOWN'); { Do not localize } cRightDnOrient: array[TScrollOrientation] of string = ('SBRIGHTDN', 'SBDOWNDN'); { Do not localize } cRightDisOrient: array[TScrollOrientation] of string = ('SBRIGHTDIS', 'SBDOWNDIS'); { Do not localize } procedure TScroller.Paint; {$IF DEFINED(CLR)} var BaseAssembly: System.Reflection.Assembly; begin with Canvas do begin BaseAssembly := Assembly.GetExecutingAssembly; { paint left button } if CanScrollLeft then begin if FDown and (FCurrent = sbLeft) then FBitmap.LoadFromResourceName(cLeftDnOrient[FScrollOrientation], ResourceBaseName, BaseAssembly) else FBitmap.LoadFromResourceName(cLeftOrient[FScrollOrientation], ResourceBaseName, BaseAssembly); end else FBitmap.LoadFromResourceName(cLeftDisOrient[FScrollOrientation], ResourceBaseName, BaseAssembly); Draw(0, 0, FBitmap); { paint right button } if CanScrollRight then begin if FDown and (FCurrent = sbRight) then FBitmap.LoadFromResourceName(cRightDnOrient[FScrollOrientation], ResourceBaseName, BaseAssembly) else FBitmap.LoadFromResourceName(cRightOrient[FScrollOrientation], ResourceBaseName, BaseAssembly); end else FBitmap.LoadFromResourceName(cRightDisOrient[FScrollOrientation], ResourceBaseName, BaseAssembly); Draw((FWidth div 2) - 1, 0, FBitmap); end; FBitmap.Assign(nil); // release the bitmap resource end; {$ELSE} const LeftButton: array[Boolean, Boolean] of TThemedSpin = ( (tsDownHorzDisabled, tsDownHorzNormal), (tsDownHorzNormal, tsDownHorzPressed)); RightButton: array[Boolean, Boolean] of TThemedSpin = ( (tsUpHorzDisabled, tsUpHorzNormal), (tsUpHorzNormal, tsUpHorzPressed)); var R: TRect; begin if ThemeControl(Self) then begin R := TRect.Create(0, 0, FWidth div 2, FHeight); if FHover and CanScrollLeft and (R.Contains(FHoverPoint)) and not FDown then StyleServices.DrawElement(Canvas.Handle, StyleServices.GetElementDetails(tsDownHorzHot), R) else StyleServices.DrawElement(Canvas.Handle, StyleServices.GetElementDetails(LeftButton[CanScrollLeft, FDown and (FCurrent = sbLeft)]), R); if TStyleManager.IsCustomStyleActive then R := TRect.Create(FWidth div 2, 0, FWidth - 1, FHeight) else R := TRect.Create(FWidth div 2, 0, FWidth, FHeight); if FHover and CanScrollRight and (R.Contains(FHoverPoint))and not FDown then StyleServices.DrawElement(Canvas.Handle, StyleServices.GetElementDetails(tsUpHorzHot), R) else StyleServices.DrawElement(Canvas.Handle, StyleServices.GetElementDetails(RightButton[CanScrollRight, FDown and (FCurrent = sbRight)]), R); end else with Canvas do begin { paint left button } if CanScrollLeft then begin if FDown and (FCurrent = sbLeft) then FBitmap.LoadFromResourceName(HInstance, cLeftDnOrient[FScrollOrientation]) else FBitmap.LoadFromResourceName(HInstance, cLeftOrient[FScrollOrientation]); end else FBitmap.LoadFromResourceName(HInstance, cLeftDisOrient[FScrollOrientation]); Draw(0, 0, FBitmap); { paint right button } if CanScrollRight then begin if FDown and (FCurrent = sbRight) then FBitmap.LoadFromResourceName(HInstance, cRightDnOrient[FScrollOrientation]) else FBitmap.LoadFromResourceName(HInstance, cRightOrient[FScrollOrientation]); end else FBitmap.LoadFromResourceName(HInstance, cRightDisOrient[FScrollOrientation]); Draw((FWidth div 2) - 1, 0, FBitmap); end; FBitmap.Assign(nil); // release the bitmap resource end; {$ENDIF} procedure TScroller.WMSize(var Message: TWMSize); begin inherited; Width := FWidth - 1; Height := FHeight; end; procedure TScroller.SetMin(Value: Longint); begin if Value < FMax then FMin := Value; end; procedure TScroller.SetMax(Value: Longint); begin if Value > FMin then FMax := Value; end; procedure TScroller.SetPosition(Value: Longint); begin if Value <> FPosition then begin if Value < Min then Value := Min; if Value > Max then Value := Max; FPosition := Value; Invalidate; if Assigned(FOnClick) then FOnClick(Self); end; end; function TScroller.CanScrollLeft: Boolean; begin Result := Position > Min; end; function TScroller.CanScrollRight: Boolean; begin Result := Position < Max; end; procedure TScroller.DoMouseDown(X: Integer); begin if X < FWidth div 2 then FCurrent := sbLeft else FCurrent := sbRight; case FCurrent of sbLeft: if not CanScrollLeft then Exit; sbRight: if not CanScrollRight then Exit; end; FPressed := True; FDown := True; Invalidate; SetCapture(Handle); FDownTimer.Enabled := True; end; procedure TScroller.WMLButtonDown(var Message: TWMLButtonDown); begin DoMouseDown(Message.XPos); end; procedure TScroller.WMLButtonDblClk(var Message: TWMLButtonDblClk); begin DoMouseDown(Message.XPos); end; procedure TScroller.WMMouseLeave(var Message: TWMMouseMove); begin if StyleServices.Enabled then begin FHover := False; Invalidate; end; inherited; end; procedure TScroller.WMMouseMove(var Message: TWMMouseMove); var P: TPoint; R: TRect; begin if FPressed then begin FHover := False; P := Point(Message.XPos, Message.YPos); R := TRect.Create(0, 0, FWidth div 2, FHeight); if FCurrent = sbRight then OffsetRect(R, FWidth div 2, 0); if R.Contains(P) <> FDown then begin FDown := not FDown; FDownTimer.Enabled := FDown; Invalidate; end; end else if StyleServices.Enabled then begin FHoverPoint := TPoint.Create(Message.XPos, Message.YPos); FHover := True; Invalidate; end; end; procedure TScroller.WMLButtonUp(var Message: TWMLButtonUp); var NewPos: Longint; begin FDownTimer.Enabled := False; ReleaseCapture; FPressed := False; if FDown then begin FDown := False; NewPos := Position; case FCurrent of sbLeft: Dec(NewPos, Change); sbRight: Inc(NewPos, Change); end; Position := NewPos; end; end; const cWidthSize: array[TScrollOrientation] of Integer = (24, 26); cHeightSize: array[TScrollOrientation] of Integer = (13, 12); procedure TScroller.SetScrollOrientation(const Value: TScrollOrientation); begin if FScrollOrientation <> Value then begin FWidth := cWidthSize[Value]; FHeight := cHeightSize[Value]; FScrollOrientation := Value; Resize; Invalidate; end; end; procedure TScroller.DoScrollTimer(Sender: TObject); var NewPos: Integer; begin if FDown then begin NewPos := Position; case FCurrent of sbLeft: if CanScrollLeft then Dec(NewPos, Change); sbRight: if CanScrollRight then Inc(NewPos, Change); end; Position := NewPos; end; end; { TTabList } function TTabList.Add(const S: string): Integer; begin Result := inherited Add(S); if FTabSet <> nil then FTabSet.Invalidate; end; procedure TTabList.Insert(Index: Integer; const S: string); begin inherited Insert(Index, S); if FTabSet <> nil then begin if Index <= FTabSet.FTabIndex then Inc(FTabSet.FTabIndex); FTabSet.Invalidate; end; end; procedure TTabList.Delete(Index: Integer); var OldIndex: Integer; LastVisibleTab: Integer; begin OldIndex := FTabSet.Tabindex; inherited Delete(Index); if OldIndex < Count then FTabSet.FTabIndex := OldIndex else FTabSet.FTabIndex := Count - 1; if FTabSet.HandleAllocated then begin { See if we can fit more tabs onto the screen now } if (not FTabSet.FShrinkToFit) and (Count > 0) then begin if FTabSet.FVisibleTabs < Count then FTabSet.SetupTabPositions; { Insure FVisibleTabs is up to date } LastVisibleTab := FTabSet.FFirstIndex + FTabSet.FVisibleTabs - 1; if (LastVisibleTab = Count - 1) and (FTabSet.FFirstIndex > 0) then FTabSet.FFirstIndex := FTabSet.FFirstIndex - 1; { We could probably fit one more on screen } FTabSet.FixTabPos; end; end; FTabSet.SetupTabPositions; FTabSet.Invalidate; if OldIndex = Index then FTabSet.Click; { We deleted the selected tab } end; procedure TTabList.Put(Index: Integer; const S: string); begin inherited Put(Index, S); if FTabSet <> nil then FTabSet.Invalidate; end; procedure TTabList.Clear; begin inherited Clear; FTabSet.FTabIndex := -1; FTabSet.Invalidate; end; procedure TTabList.AddStrings(Strings: TStrings); begin SendMessage(FTabSet.Handle, WM_SETREDRAW, 0, 0); inherited AddStrings(Strings); SendMessage(FTabSet.Handle, WM_SETREDRAW, 1, 0); FTabSet.Invalidate; end; constructor TTabList.Create(const ATabSet: TTabSet); begin inherited Create; FTabSet := ATabSet; end; { TTabSet } const cNonFlatWidth = 9; constructor TTabSet.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csCaptureMouse, csDoubleClicks, csOpaque, csPannable, csGestures]; Width := 185; Height := 21; FTabPositions := TTabPosList.Create; FSortedTabPositions := TTabPosList.Create; FTabHeight := 20; FTabs := TTabList.Create(Self); InitBitmaps; CreateScroller; FTabIndex := -1; FFirstIndex := 0; FVisibleTabs := 0; { set by draw routine } FStartMargin := 5; FEndMargin := 5; FTabPosition := tpBottom; FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := ImageListChange; FEdgeWidth := cNonFlatWidth; { This controls the angle of the tab edges } { initialize default values } FSelectedColor := clBtnFace; FUnselectedColor := clWindow; FBackgroundColor := clBtnFace; FDitherBackground := True; CreateBrushPattern(FBrushBitmap); FAutoScroll := True; FStyle := tsStandard; FOwnerDrawHeight := 20; ParentFont := False; {$IF DEFINED(CLR)} Font.Name := DefFontData.Name; {$ELSE} Font.Name := UTF8ToString(DefFontData.Name); {$ENDIF} Font.Height := DefFontData.Height; Font.Style := []; { create the edge bitmaps } CreateEdgeParts; end; procedure TTabSet.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params.WindowClass do style := style and not (CS_VREDRAW or CS_HREDRAW); end; procedure TTabSet.CreateScroller; begin FScroller := TScroller.Create(Self); with Scroller do begin Parent := Self; Top := 3; Min := 0; Max := 0; Position := 0; Visible := False; OnClick := ScrollClick; end; end; procedure TTabSet.InitBitmaps; begin FMemBitmap := TBitmap.Create; FBrushBitmap := TBitmap.Create; end; destructor TTabSet.Destroy; begin FTabs.Free; FTabPositions.Free; FSortedTabPositions.Free; DoneBitmaps; FImageChangeLink.Free; inherited Destroy; end; procedure TTabSet.DoneBitmaps; begin FMemBitmap.Free; FBrushBitmap.Free; FEdgeImageList.Free; end; procedure TTabSet.ScrollClick(Sender: TObject); begin FirstIndex := TScroller(Sender).Position; end; { cache the tab position data, and return number of visible tabs } function TTabSet.CalcTabPositions(const AStart, AStop: Integer; Canvas: TCanvas; First: Integer; FullTabs: Boolean): Integer; var Index: Integer; TabPos, NextTabPos: TTabPos; Start, Stop: Integer; CutAmount, CurrentCut: Integer; I, J: Integer; MaxSize: Integer; begin FTabPositions.Clear;{ Erase all previously cached data } FSortedTabPositions.Clear; Index := First; Start := AStart; Stop := AStop; while (Start < Stop) and (Index < Tabs.Count) do begin TabPos := TTabPos.Create(Start, ItemWidth(Index)); Inc(Start, TabPos.Size + FEdgeWidth); { next usable position } if (Start <= Stop) or (not FullTabs) then { Allowing this allows partial tabs } begin FTabPositions.Add(TabPos); { add to list } Inc(Index); end; FSortedTabPositions.Add(TabPos); end; { If we are to "resize" tabs, then do that } if FShrinkToFit and (Index < Tabs.Count) then begin Inc(Index); { Last one already added in the above loop } { First, finish "adding" in all the tabs. } while (Index < Tabs.Count) do begin TabPos := TTabPos.Create(Start, ItemWidth(Index)); Inc(Start, TabPos.Size + FEdgeWidth); FSortedTabPositions.Add(TabPos); Inc(Index); end; CutAmount := Start - AStop; { Now sort them, so we can shrink the largest ones down to make them fit. } FSortedTabPositions.Sort(TComparer<TTabPos>.Construct( function(const Left, Right: TTabPos): Integer begin Result := Right.Size - Left.Size; end )); { Trim off what we have to cut } while (CutAmount > 0) and (FSortedTabPositions.Count > 0) do begin TabPos := FSortedTabPositions[0]; CurrentCut := CutAmount; J := 1; { Number of tabs the same size } for I := 1 to FSortedTabPositions.Count - 1 do begin NextTabPos := FSortedTabPositions[I]; if TabPos.Size <> NextTabPos.Size then begin { Take the difference between the tab sizes, or the whole cut amount, if it is smaller } CurrentCut := Min(TabPos.Size - NextTabPos.Size, CutAmount); Break; end; Inc(J); end; { Divide the cut amount among the tabs of the same size } CurrentCut := Max(1, CurrentCut div J); { Cut all those tabs the same amount, but at least one pixel. } for I := 0 to J - 1 do begin TabPos := FSortedTabPositions[I]; Dec(TabPos.FSize, CurrentCut); FSortedTabPositions[I] := TabPos; Dec(CutAmount, CurrentCut); if CutAmount <= 0 then Break; { We are done } end; end; if FSortedTabPositions.Count > 0 then begin { The largest one's size is the max size to use } MaxSize := FSortedTabPositions[0].Size; { Now, add all the tabs again, using this size as the maxsize for a tab } FTabPositions.Clear; Index := First; Start := AStart; Stop := AStop; while (Start < Stop) and (Index < Tabs.Count) do begin TabPos := TTabPos.Create(Start, Min(ItemWidth(Index), MaxSize)); Inc(Start, TabPos.Size + FEdgeWidth); { next usable position } if Start <= Stop then begin FTabPositions.Add(TabPos); { add to list } Inc(Index); end; end; end; end; Result := Index - First; end; function TTabSet.ItemAtPos(Pos: TPoint; IgnoreTabHeight: Boolean): Integer; var TabPos: TTabPos; I: Integer; YStart: Integer; Extra: Integer; MinLeft, MaxRight: Integer; begin Result := -1; if (Pos.X < 0) or (Pos.X > ClientWidth) or (Pos.Y < 0) or (Pos.Y > ClientHeight) then Exit; case FTabPosition of tpBottom: YStart := 0; tpTop: YStart := ClientHeight - FTabHeight; tpLeft: begin { Switch the X and Y } I := Pos.X; Pos.X := Pos.Y; Pos.Y := I; YStart := ClientWidth - FTabHeight; { Really the "X" start } end; tpRight: begin { Switch the X and Y } I := Pos.X; Pos.X := Pos.Y; Pos.Y := I; YStart := 0; { Really the "X" start } end; else YStart := 0; end; if IgnoreTabHeight or ((Pos.Y >= YStart) and (Pos.Y <= YStart + FTabHeight)) then begin if Pos.Y < YStart + FTabHeight div 2 then Extra := FEdgeWidth div 3 else Extra := FEdgeWidth div 2; for I := 0 to FTabPositions.Count - 1 do begin TabPos := FTabPositions[I]; MinLeft := TabPos.StartPos - Extra; MaxRight := TabPos.StartPos + TabPos.Size + Extra; if (Pos.X >= MinLeft) and (Pos.X <= MaxRight) then begin Result := FirstIndex + I; Break; end; end; end; end; procedure TTabSet.UpdateStyleElements; begin CreateEdgeParts; CreateBrushPattern(FBrushBitmap); Invalidate; end; function TTabSet.ItemRect(Index: Integer): TRect; var TabPos: TTabPos; TabTop: Integer; begin if FFirstIndex > 0 then Index := Index - FFirstIndex; if (FTabPositions.Count > 0) and (Index >= 0) and (Index < FTabPositions.Count) then begin TabPos := FTabPositions[Index]; if FTabPosition in [tpBottom, tpRight] then TabTop := 0 else if FTabPosition = tpTop then TabTop := ClientHeight - FTabHeight else { FTabPosition = tpLeft } TabTop := ClientWidth - FTabHeight; if FTabPosition in [tpTop, tpBottom] then begin Result := TRect.Create(TabPos.StartPos, TabTop, TabPos.StartPos + TabPos.Size, TabTop + FTabHeight); InflateRect(Result, 1, -2); end else { Flip the X and Y if the position is vertical } begin Result := TRect.Create(TabTop, TabPos.StartPos, TabTop + FTabHeight, TabPos.StartPos + TabPos.Size); InflateRect(Result, -1, 1); end; end else Result := Rect(0, 0, 0, 0); end; procedure TTabSet.DrawLine(Canvas: TCanvas; FromX, FromY, ToX, ToY: Integer); var T: Integer; begin if FTabPosition in [tpLeft, tpRight] then begin T := FromX; FromX := FromY; FromY := T; T := ToX; ToX := ToY; ToY := T; end; Canvas.MoveTo(FromX, FromY); Canvas.LineTo(ToX, ToY); end; procedure TTabSet.DoDefaultPainting; const TabState: array[Boolean] of TThemedTabSet = (tbsTabNormal, tbsTabSelected); var YStart, YEnd, YMod: Integer; TabPos: TTabPos; Tab: Integer; Leading: TEdgeType; Trailing: TEdgeType; isFirst, isLast, isSelected, isPrevSelected: Boolean; R: TRect; MinRect: Integer; S: string; ImageIndex: Integer; TabTop: Integer; TotalSize: Integer; LColor: TColor; LStyle: TCustomStyleServices; LDetails: TThemedElementDetails; begin { Calculate our true drawing positions } if FTabPosition in [tpBottom, tpRight] then begin TabTop := 0; YStart := 0; YEnd := FTabHeight; YMod := 1; end else if FTabPosition = tpTop then begin TabTop := ClientHeight - FTabHeight; YStart := ClientHeight - 1; YMod := -1; YEnd := TabTop - 1; end else { tpLeft } begin TabTop := ClientWidth - FTabHeight; YStart := ClientWidth - 1; YMod := -1; YEnd := TabTop - 1; end; if FTabPosition in [tpTop, tpBottom] then TotalSize := FMemBitmap.Width else TotalSize := FMemBitmap.Height; { draw background of tab area } with FMemBitmap.Canvas do begin Brush.Bitmap := FBrushBitmap; LStyle := StyleServices; if LStyle.Enabled and ParentBackground then Perform(WM_ERASEBKGND, WPARAM(FMemBitmap.Canvas.Handle), 0) else FillRect(TRect.Create(0, 0, FMemBitmap.Width, FMemBitmap.Height)); // draw top edge // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // \ /--------------/ // \ /\ / // \___________/ \___________/ Pen.Width := 1; if LStyle.Enabled then LDetails := LStyle.GetElementDetails(tbsTabNormal); if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; DrawLine(FMemBitmap.Canvas, 0, YStart, TotalSize + 1, YStart); if not FSoftTop then begin if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawLine(FMemBitmap.Canvas, 0, YStart + YMod, TotalSize + 1, YStart + YMod); end; MinRect := TextWidth('X...'); { Do not localize } end; for Tab := 0 to FTabPositions.Count - 1 do begin TabPos := FTabPositions[Tab]; TabPos.Size := TabPos.Size + 1; TabPos.StartPos := TabPos.StartPos + Tab - 1; isFirst := Tab = 0; isLast := Tab = VisibleTabs - 1; isSelected := Tab + FirstIndex = TabIndex; isPrevSelected := (Tab + FirstIndex) - 1 = TabIndex; if LStyle.Enabled then LDetails := LStyle.GetElementDetails(TabState[isSelected]); { Rule: every tab paints its leading edge, only the last tab paints a trailing edge } Trailing := etNone; if isLast then begin if isSelected then Trailing := etLastIsSel else Trailing := etLastNotSel; end; if isFirst then begin if isSelected then Leading := etFirstIsSel else Leading := etFirstNotSel; end else { not first } begin if isPrevSelected then Leading := etSelToNotSel else if isSelected then Leading := etNotSelToSel else Leading := etNotSelToNotSel; end; { draw leading edge } // |XXXX|================================ // | X | /--------------/ // | X | /\ / // | X|___________/ \___________/ if Leading <> etNone then PaintEdge(TabPos.StartPos - FEdgeWidth, TabTop, FTabHeight - 1, Leading); { set up the canvas } if FTabPosition in [tpTop, tpBottom] then R := TRect.Create(TabPos.StartPos, TabTop, TabPos.StartPos + TabPos.Size, TabTop + FTabHeight) else { Switch X and Y } R := TRect.Create(TabTop, TabPos.StartPos, TabTop + FTabHeight, TabPos.StartPos + TabPos.Size); if isSelected then if GetThemeColor(LDetails, ecFillColor, LColor) then FMemBitmap.Canvas.Brush.Color := LColor else FMemBitmap.Canvas.Brush.Color := SelectedColor else if GetThemeColor(LDetails, ecFillColor, LColor) then FMemBitmap.Canvas.Brush.Color := LColor else FMemBitmap.Canvas.Brush.Color := UnselectedColor; FMemBitmap.Canvas.FillRect(R); if (FStyle = tsOwnerDraw) then DrawTab(FMemBitmap.Canvas, R, Tab + FirstIndex, isSelected) else begin with FMemBitmap.Canvas do begin if FTabPosition in [tpTop, tpBottom] then begin Inc(R.Top, 2); { Move a little to the right; it looks better with newer fonts } Inc(R.Left, 1); Inc(R.Right, 1); end else begin { Flip the width and height of the rect so we get correct clipping of the text when writing at a non-0 orientation } if FTabPosition = tpRight then begin Inc(R.Left, 1 + TextHeight('X')) { Do not localize } end else { tpLeft } begin Inc(R.Left, 2); { For vertical text consideration, the drawing starts at the "bottom" } R.Top := R.Top + TabPos.Size; end; R.Right := R.Left + TabPos.Size; R.Bottom := R.Top + FTabHeight; end; { Draw the image first } if (FImages <> nil) then begin ImageIndex := GetImageIndex(Tab + FirstIndex); if (ImageIndex > -1) and (ImageIndex < FImages.Count) then begin if FTabPosition in [tpTop, tpBottom] then begin FImages.Draw(FMemBitmap.Canvas, R.Left, R.Top, ImageIndex); Inc(R.Left, 2 + FImages.Width); Inc(R.Top, 2); end else if FTabPosition = tpRight then begin FImages.Draw(FMemBitmap.Canvas, R.Left - TextHeight('X'), R.Top, ImageIndex); Inc(R.Top, 2 + FImages.Height); Dec(R.Right, FImages.Height); { For proper clipping } Inc(R.Left, 2); end else begin FImages.Draw(FMemBitmap.Canvas, R.Left, R.Top - FImages.Height, ImageIndex); Dec(R.Top, 2 + FImages.Height); Dec(R.Right, FImages.Height); { For proper clipping } Inc(R.Left, 2); end; end; end; S := Tabs[Tab + FirstIndex]; if (R.Right - R.Left >= MinRect) or (TextWidth(S) <= (R.Right - R.Left)) then begin if TStyleManager.IsCustomStyleActive then begin if seFont in StyleElements then FMemBitmap.Canvas.Font.Color := StyleServices.GetSystemColor(clBtnText) else FMemBitmap.Canvas.Font.Color := Self.Font.Color; end else if GetThemeColor(StyleServices.GetElementDetails(TabState[isSelected]), ecTextColor, LColor) then FMemBitmap.Canvas.Font.Color := LColor else FMemBitmap.Canvas.Font.Color := Self.Font.Color; TextRect(R, S, [tfEndEllipsis, tfNoClip]); end; end; end; { draw trailing edge } // ===============|XXXX|================= // \ | XX|-------------/ // \ | XX | / // \___________|X X|___________/ // or // ==============================|XXXX|== // \ /------------|XXX | // \ /\ | X | // \___________/ \___________|X | if Trailing <> etNone then PaintEdge(TabPos.StartPos + TabPos.Size, TabTop, FTabHeight - 1, Trailing); { draw connecting lines above and below the text } // ==================================== // \ /-XXXXXXXXXXX--/ // \ /\ / // \XXXXXXXXXXX/ \XXXXXXXXXXX/ with FMemBitmap.Canvas do begin if FStyle = tsSoftTabs then if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow else if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawLine(FMemBitmap.Canvas, TabPos.StartPos, YEnd - YMod, TabPos.StartPos + TabPos.Size, YEnd - YMod); if not isSelected then begin if SoftTop then if GetThemeColor(LStyle.GetElementDetails(tbsBackground), ecFillColor, LColor) then Pen.Color := LColor else Pen.Color := BackgroundColor else if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawLine(FMemBitmap.Canvas, TabPos.StartPos, YStart + YMod, TabPos.StartPos + TabPos.Size, YStart + YMod); if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; DrawLine(FMemBitmap.Canvas, TabPos.StartPos, YStart, TabPos.StartPos + TabPos.Size + 1, YStart); end; end; end; end; procedure TTabSet.Paint; begin SetupTabPositions; FDoFix := False; if FStyle in [tsStandard, tsOwnerDraw, tsSoftTabs] then DoDefaultPainting else if FStyle = tsModernTabs then DoModernPainting else DoPopoutModernPainting; Canvas.Draw(0, 0, FMemBitmap); end; procedure TTabSet.CreateEdgeParts; var H: Integer; Working: TBitmap; EdgePart: TEdgePart; MaskColor: TColor; Y: Integer; YEnd: Integer; YMod: Integer; LStyle: TCustomStyleServices; LColor: TColor; LDetails, LBkDetails: TThemedElementDetails; procedure DrawPoly(Canvas: TCanvas; Polygon: Boolean; Points: array of TPoint); var I: Integer; TempX: Integer; begin if FTabPosition in [tpLeft, tpRight] then begin { Switch the X and Y in the points } for I := Low(Points) to High(Points) do begin TempX := Points[I].X; Points[I].X := Points[I].Y; Points[I].Y := TempX; end; end; if Polygon then Canvas.Polygon(Points) else Canvas.Polyline(Points); end; procedure DrawUL(Canvas: TCanvas); begin if LStyle.Enabled then LDetails := LStyle.GetElementDetails(tbsTabNormal); with Canvas do begin { Draw the top line } if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; DrawPoly(Canvas, False, [Point(0, Y), Point(FEdgeWidth + 1, Y)]); { Fill in the middle } if GetThemeColor(LDetails, ecFillColor, LColor) then begin Pen.Color := LColor; Brush.Color := LColor; end else begin Pen.Color := UnselectedColor; Brush.Color := UnselectedColor; end; DrawPoly(Canvas, True, [Point(3, Y + YMod), Point(FEdgeWidth - 1, YEnd), Point(FEdgeWidth, YEnd), Point(FEdgeWidth, Y + YMod), Point(3, Y + YMod)]); if SoftTop then begin if GetThemeColor(LBkDetails, ecFillColor, LColor) then Pen.Color := LColor else Pen.Color := BackgroundColor; DrawPoly(Canvas, False, [Point(4, Y + YMod), Point(FEdgeWidth + 1, Y + YMod)]); if FStyle = tsSoftTabs then if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow else if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawPoly(Canvas, False, [Point(3, Y + YMod), Point(FEdgeWidth - 1, YEnd), Point(FEdgeWidth, YEnd)]); end else begin if FStyle = tsSoftTabs then if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow else if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawPoly(Canvas, False, [Point(0, Y + YMod), Point(FEdgeWidth + 1, Y + YMod), Point(3, Y + YMod), Point(FEdgeWidth - 1, YEnd), Point(FEdgeWidth, YEnd)]); end; end; end; procedure DrawSL(Canvas: TCanvas); begin if LStyle.Enabled then LDetails := LStyle.GetElementDetails(tbsTabSelected); with Canvas do begin if GetThemeColor(LDetails, ecFillColor, LColor) then begin Pen.Color := LColor; Brush.Color := LColor; end else begin Pen.Color := SelectedColor; Brush.Color := SelectedColor; end; { Fill the inside with the selected color } DrawPoly(Canvas, True, [Point(3, Y), Point(FEdgeWidth - 1, YEnd), Point(FEdgeWidth, YEnd), Point(FEdgeWidth, Y), Point(3, Y)]); if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; if not (FStyle = tsSoftTabs) then begin { Draw 3-D edges on the left } DrawPoly(Canvas, False, [Point(0, Y), Point(4, Y)]); if GetThemeColor(LDetails, ecEdgeHighLightColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnHighlight; DrawPoly(Canvas, False, [Point(4, Y + YMod), Point(FEdgeWidth, YEnd + 1)]); if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; end; if SoftTop then DrawPoly(Canvas, False, [Point(3, Y + YMod), Point(FEdgeWidth - 1, YEnd), Point(FEdgeWidth, YEnd)]) else DrawPoly(Canvas, False, [Point(0, Y + YMod), Point(3, Y + YMod), Point(FEdgeWidth - 1, YEnd), Point(FEdgeWidth, YEnd)]); end; end; procedure DrawUR(Canvas: TCanvas); begin if LStyle.Enabled then LDetails := LStyle.GetElementDetails(tbsTabNormal); with Canvas do begin if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; DrawPoly(Canvas, False, [Point(-1, Y), Point(FEdgeWidth + 1, Y)]); if GetThemeColor(LDetails, ecFillColor, LColor) then begin Pen.Color := LColor; Brush.Color := LColor; end else begin Pen.Color := UnselectedColor; Brush.Color := UnselectedColor; end; DrawPoly(Canvas, True, [Point(FEdgeWidth - 3, Y + YMod), Point(1, YEnd), Point(0, YEnd), Point(0, Y + YMod), Point(FEdgeWidth - 3, Y + YMod)]); { workaround for bug in S3 driver } if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; DrawPoly(Canvas, False, [Point(-1, Y), Point(FEdgeWidth + 1, Y)]); if SoftTop then begin if GetThemeColor(LBkDetails, ecFillColor, LColor) then Pen.Color := LColor else Pen.Color := BackgroundColor; DrawPoly(Canvas, False, [Point(0, Y + YMod), Point(FEdgeWidth - 1, Y + YMod)]); if FStyle = tsSoftTabs then if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow else if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawPoly(Canvas, False, [Point(FEdgeWidth - 2, Y + YMod), Point(2, YEnd), Point(-1, YEnd)]); end else begin if FStyle = tsSoftTabs then if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow else if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawPoly(Canvas, False, [Point(0, Y + YMod), Point(FEdgeWidth + 1, Y + YMod), Point(FEdgeWidth - 2, Y + YMod), Point(2, YEnd), Point(-1, YEnd)]); end; end; end; procedure DrawSR(Canvas: TCanvas); begin if LStyle.Enabled then LDetails := LStyle.GetElementDetails(tbsTabSelected); with Canvas do begin if GetThemeColor(LDetails, ecFillColor, LColor) then begin Pen.Color := LColor; Brush.Color := LColor; end else begin Pen.Color := SelectedColor; Brush.Color := SelectedColor; end; DrawPoly(Canvas, True, [Point(FEdgeWidth - 3, Y + YMod), Point(2, YEnd), Point(0, YEnd), Point(0, Y), Point(FEdgeWidth + 1, Y)]); if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; if FStyle = tsSoftTabs then DrawLine(Canvas, FEdgeWidth + 1, Y, FEdgeWidth - 2, Y) else begin DrawPoly(Canvas, False, [Point(FEdgeWidth + 1, Y), Point(FEdgeWidth - 3, Y), Point(FEdgeWidth - 3, Y + YMod), Point(1, YEnd), Point(-1, YEnd)]); if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; end; if SoftTop then DrawPoly(Canvas, False, [Point(FEdgeWidth - 2, Y + YMod), Point(2, YEnd), Point(-1, YEnd)]) else DrawPoly(Canvas, False, [Point(FEdgeWidth, Y + YMod), Point(FEdgeWidth - 2, Y + YMod), Point(2, YEnd), Point(-1, YEnd)]); end; end; var TempList: TImageList; SaveHeight: Integer; ActualWidth, ActualHeight: Integer; begin FMemBitmap.Canvas.Font := Font; { Owner } SaveHeight := FTabHeight; try if FStyle = tsOwnerDraw then FTabHeight := FOwnerDrawHeight else begin FTabHeight := FMemBitmap.Canvas.TextHeight('T') + 4; if (FImages <> nil) and (FTabHeight < FImages.Height + 4) then FTabHeight := FImages.Height + 4; end; H := FTabHeight - 1; if FTabPosition in [tpBottom, tpTop] then begin ActualWidth := FEdgeWidth; ActualHeight := FTabHeight; end else begin { Switch the values } ActualWidth := FTabHeight; ActualHeight := FEdgeWidth; end; TempList := TImageList.CreateSize(ActualWidth, ActualHeight); {exceptions} except FTabHeight := SaveHeight; raise; end; FEdgeImageList.Free; FEdgeImageList := TempList; if not (FStyle in [tsModernTabs, tsModernPopout]) then begin { These parts aren't used in the "modern" painting look } Working := TBitmap.Create; try Working.Width := ActualWidth; Working.Height := ActualHeight; MaskColor := clOlive; if FTabPosition in [tpBottom, tpRight] then begin Y := 0; YMod := 1; YEnd := H; end else begin { Flip the Y positions } Y := H; YMod := -1; YEnd := 0; end; LStyle := StyleServices; if LStyle.Enabled then LBkDetails := LStyle.GetElementDetails(tbsBackground); for EdgePart := Low(TEdgePart) to High(TEdgePart) do begin with Working.Canvas do begin Brush.Color := MaskColor; Brush.Style := bsSolid; FillRect(TRect.Create(0, 0, ActualWidth, ActualHeight)); end; case EdgePart of epSelectedLeft: DrawSL(Working.Canvas); epUnselectedLeft: DrawUL(Working.Canvas); epSelectedRight: DrawSR(Working.Canvas); epUnselectedRight: DrawUR(Working.Canvas); end; FEdgeImageList.AddMasked(Working, MaskColor); end; finally Working.Free; end; end; end; procedure TTabSet.PaintEdge(X, Y, H: Integer; Edge: TEdgeType); var TempX: Integer; begin if FTabPosition in [tpLeft, tpRight] then begin { Switch X and Y } TempX := X; X := Y; Y := TempX; end; case Edge of etFirstIsSel: FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epSelectedLeft)); etLastIsSel: FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epSelectedRight)); etFirstNotSel: FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epUnselectedLeft)); etLastNotSel: FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epUnselectedRight)); etNotSelToSel: begin FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epUnselectedRight)); FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epSelectedLeft)); end; etSelToNotSel: begin FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epUnselectedLeft)); FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epSelectedRight)); end; etNotSelToNotSel: begin FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epUnselectedLeft)); FEdgeImageList.Draw(FMemBitmap.Canvas, X, Y, Ord(epUnselectedRight)); end; end; end; procedure TTabSet.CreateBrushPattern(Bitmap: TBitmap); var X, Y: Integer; LColor: TColor; begin Bitmap.Width := 8; Bitmap.Height := 8; with Bitmap.Canvas do begin Brush.Style := bsSolid; if not (not (seClient in StyleElements) and (TStyleManager.IsCustomStyleActive)) and GetThemeColor(StyleServices.GetElementDetails(tbsBackground), ecFillColor, LColor) then Brush.Color := LColor else Brush.Color := FBackgroundColor; FillRect(TRect.Create(0, 0, Width, Height)); if FDitherBackground and not TStyleManager.IsCustomStyleActive then for Y := 0 to 7 do for X := 0 to 7 do if (Y mod 2) = (X mod 2) then { toggles between even/odd pixles } Pixels[X, Y] := clWhite; { on even/odd rows } end; end; function TTabSet.ScrollerSize: Integer; begin if FTabPosition in [tpTop, tpBottom] then Result := Scroller.Width + 4 else Result := Scroller.Height + 4; end; procedure TTabSet.FixTabPos; var LastVisibleTab: Integer; function GetRightSide: Integer; begin if FTabPosition in [tpTop, tpBottom] then Result := Width - EndMargin else Result := Height - EndMargin; if AutoScroll and (FVisibleTabs < Tabs.Count - 1) then Dec(Result, ScrollerSize); end; function ReverseCalcNumTabs(Start, Stop: Integer; Canvas: TCanvas; Last: Integer): Integer; var W: Integer; begin if HandleAllocated then begin Result := Last; while (Start >= Stop) and (Result >= 0) do begin with Canvas do begin W := ItemWidth(Result) + FEdgeWidth; Dec(Start, W); { next usable position } if Start >= Stop then Dec(Result); end; end; if (Start < Stop) or (Result < 0) then Inc(Result); end else Result := FFirstIndex; end; begin if (not FShrinkToFit) and (Tabs.Count > 0) then begin if FVisibleTabs < Tabs.Count then SetupTabPositions; { Insure FVisibleTabs is up to date } LastVisibleTab := FFirstIndex + FVisibleTabs - 1; if (LastVisibleTab > 0) and (FTabIndex >= LastVisibleTab) then begin FFirstIndex := ReverseCalcNumTabs(GetRightSide, StartMargin, Canvas, FTabIndex); LastVisibleTab := FFirstIndex + FVisibleTabs - 1; if FTabIndex > LastVisibleTab then Inc(FFirstIndex); end else if (FTabIndex >= 0) and (FTabIndex < FFirstIndex) then FFirstIndex := FTabIndex; end; end; procedure TTabSet.SetSelectedColor(Value: TColor); begin if Value <> FSelectedColor then begin FSelectedColor := Value; CreateEdgeParts; Invalidate; end; end; procedure TTabSet.SetUnselectedColor(Value: TColor); begin if Value <> FUnselectedColor then begin FUnselectedColor := Value; CreateEdgeParts; Invalidate; end; end; procedure TTabSet.SetBackgroundColor(Value: TColor); begin if Value <> FBackgroundColor then begin FBackgroundColor := Value; CreateBrushPattern(FBrushBitmap); FMemBitmap.Canvas.Brush.Style := bsSolid; Invalidate; end; end; procedure TTabSet.SetDitherBackground(Value: Boolean); begin if Value <> FDitherBackground then begin FDitherBackground := Value; CreateBrushPattern(FBrushBitmap); FMemBitmap.Canvas.Brush.Style := bsSolid; Invalidate; end; end; procedure TTabSet.SetAutoScroll(Value: Boolean); begin if Value <> FAutoScroll then begin FAutoScroll := Value; Scroller.Visible := False; ShowWindow(Scroller.Handle, SW_HIDE); Invalidate; end; end; procedure TTabSet.SetStartMargin(Value: Integer); begin if Value <> FStartMargin then begin FStartMargin := Value; Invalidate; end; end; procedure TTabSet.SetEndMargin(Value: Integer); begin if Value <> FEndMargin then begin FEndMargin := Value; Invalidate; end; end; function TTabSet.CanChange(NewIndex: Integer): Boolean; begin Result := True; if Assigned(FOnChange) then FOnChange(Self, NewIndex, Result); end; procedure TTabSet.SetTabIndex(Value: Integer); var F: TCustomForm; begin if Value <> FTabIndex then begin if (Value < -1) or (Value >= Tabs.Count) then raise Exception.CreateRes({$IFNDEF CLR}@{$ENDIF}SInvalidTabIndex); if CanChange(Value) then begin if Visible then begin F := GetParentForm(Self); if F <> nil then F.SendCancelMode(Self) else SendCancelMode(Self); end; FTabIndex := Value; if HandleAllocated then FixTabPos; Click; Invalidate; end; end; end; procedure TTabSet.SelectNext(Direction: Boolean); var NewIndex: Integer; begin if Tabs.Count > 1 then begin NewIndex := TabIndex; if Direction then Inc(NewIndex) else Dec(NewIndex); if NewIndex = Tabs.Count then NewIndex := 0 else if NewIndex < 0 then NewIndex := Tabs.Count - 1; SetTabIndex(NewIndex); end; end; procedure TTabSet.SetFirstIndex(Value: Integer); begin if (Value >= 0) and (Value < Tabs.Count) then begin FFirstIndex := Value; Invalidate; end; end; procedure TTabSet.SetTabList(Value: TStrings); begin FTabs.Assign(Value); FTabIndex := -1; if FTabs.Count > 0 then TabIndex := 0 else Invalidate; end; procedure TTabSet.SetTabStyle(Value: TTabStyle); begin if Value <> FStyle then begin FStyle := Value; if FStyle = tsSoftTabs then FSoftTop := True; { Force a soft top in this case } CreateEdgeParts; Invalidate; end; end; procedure TTabSet.SetTabHeight(Value: Integer); var SaveHeight: Integer; begin if Value <> FOwnerDrawHeight then begin SaveHeight := FOwnerDrawHeight; try FOwnerDrawHeight := Value; CreateEdgeParts; Invalidate; except FOwnerDrawHeight := SaveHeight; raise; end; end; end; procedure TTabSet.DrawTab(TabCanvas: TCanvas; R: TRect; Index: Integer; Selected: Boolean); begin if Assigned(FOnDrawTab) then FOnDrawTab(Self, TabCanvas, R, Index, Selected); end; [UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)] procedure TTabSet.GetChildren(Proc: TGetChildProc; Root: TComponent); begin end; procedure TTabSet.MeasureTab(Index: Integer; var TabWidth: Integer); begin if Assigned(FOnMeasureTab) then FOnMeasureTab(Self, Index, TabWidth); end; procedure TTabSet.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; begin inherited MouseDown(Button, Shift, X, Y); if Button = mbLeft then begin I := ItemAtPos(Point(X, Y)); if I <> -1 then SetTabIndex(I); end; end; procedure TTabSet.WMSize(var Message: TWMSize); var NumVisTabs, LastTabPos: Integer; function CalcNumTabs(Start, Stop: Integer; Canvas: TCanvas; First: Integer): Integer; begin Result := First; while (Start < Stop) and (Result < Tabs.Count) do with Canvas do begin Inc(Start, ItemWidth(Result) + FEdgeWidth); { next usable position } if Start <= Stop then Inc(Result); end; end; begin inherited; if (not FShrinkToFit) and (Tabs.Count > 1) then begin if FTabPosition in [tpTop, tpBottom] then LastTabPos := Width - EndMargin else LastTabPos := Height - EndMargin; NumVisTabs := CalcNumTabs(StartMargin + FEdgeWidth, LastTabPos, Canvas, 0); if (FTabIndex = Tabs.Count) or (NumVisTabs > FVisibleTabs) or (NumVisTabs = Tabs.Count) then FirstIndex := Tabs.Count - NumVisTabs; FDoFix := True; end; Invalidate; end; procedure TTabSet.CMSysColorChange(var Message: TMessage); begin inherited; CreateEdgeParts; CreateBrushPattern(FBrushBitmap); FMemBitmap.Canvas.Brush.Style := bsSolid; { Windows follows this message with a WM_PAINT } end; procedure TTabSet.CMFontChanged(var Message: TMessage); begin inherited; Canvas.Font := Font; CreateEdgeParts; Invalidate; end; procedure TTabSet.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTALLKEYS; end; procedure TTabSet.CMStyleChanged(var Message: TMessage); begin CreateEdgeParts; CreateBrushPattern(FBrushBitmap); Invalidate; end; procedure TTabSet.CMDialogChar(var Message: TCMDialogChar); var I: Integer; begin for I := 0 to FTabs.Count - 1 do begin if IsAccel(Message.CharCode, FTabs[I]) then begin Message.Result := 1; if FTabIndex <> I then SetTabIndex(I); Exit; end; end; inherited; end; function TTabSet.MinClientRect: TRect; begin Result := MinClientRect(Tabs.Count, False); end; function TTabSet.MinClientRect(IncludeScroller: Boolean): TRect; begin Result := MinClientRect(Tabs.Count, IncludeScroller); end; function TTabSet.MinClientRect(TabCount: Integer; IncludeScroller: Boolean): TRect; var I: Integer; begin Result := TRect.Create(0, 0, StartMargin, FTabHeight + 5); for I := 0 to TabCount - 1 do Inc(Result.Right, ItemWidth(I) + FEdgeWidth); Inc(Result.Right, EndMargin); if IncludeScroller then Inc(Result.Right, ScrollerSize); { If the orientation isn't top/bottom, switch the end points } if FTabPosition in [tpLeft, tpRight] then begin I := Result.Right; Result.Right := Result.Left; Result.Left := I; end; end; procedure TTabSet.SetFontOrientation(ACanvas: TCanvas); begin if FTabPosition = tpRight then ACanvas.Font.Orientation := 2700 { 90 degrees to the right } else if FTabPosition = tpLeft then ACanvas.Font.Orientation := 900 { 90 degrees to the left } else ACanvas.Font.Orientation := 0; end; function TTabSet.ItemWidth(Index: Integer): Integer; var I: Integer; begin with Canvas do begin SetFontOrientation(Canvas); Result := TextWidth(Tabs[Index]); if (FImages <> nil) then begin I := GetImageIndex(Index); if (I > -1) and (I < FImages.Count) then Result := Result + FImages.Width + 2; end; end; if (FStyle = tsOwnerDraw) then MeasureTab(Index, Result); end; procedure TTabSet.SetSoftTop(const Value: Boolean); begin if Value <> SoftTop then begin FSoftTop := Value; CreateEdgeParts; Invalidate; end; end; procedure TTabSet.SetImages(const Value: TCustomImageList); begin if Images <> Value then begin if Images <> nil then Images.UnRegisterChanges(FImageChangeLink); FImages := Value; if Images <> nil then begin Images.RegisterChanges(FImageChangeLink); Images.FreeNotification(Self); end; if not (csDestroying in ComponentState) then begin CreateEdgeParts; { Height is changed if Value <> nil } Invalidate; end; end; end; procedure TTabSet.ImageListChange(Sender: TObject); begin Invalidate; end; procedure TTabSet.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = Images) then Images := nil; end; function TTabSet.GetImageIndex(TabIndex: Integer): Integer; begin Result := TabIndex; if Assigned(FOnGetImageIndex) then FOnGetImageIndex(Self, TabIndex, Result); end; procedure TTabSet.SetShrinkToFit(const Value: Boolean); begin if FShrinkToFit <> Value then begin FShrinkToFit := Value; Invalidate; end; end; procedure TTabSet.CMHintShow(var Message: TCMHintShow); var R, Calced: TRect; I: Integer; S: string; {$IF DEFINED(CLR)} HI: THintInfo; {$ELSE} HI: PHintInfo; {$ENDIF} begin Message.Result := 1; { Don't show the hint } if FShrinkToFit and (Message.HintInfo.HintControl = Self) then begin HI := Message.HintInfo; with HI{$IFNDEF CLR}^{$ENDIF} do begin I := ItemAtPos(CursorPos); if I <> -1 then begin { See if it has truncated text } R := ItemRect(I); if (FImages <> nil) and (GetImageIndex(I) <> -1) then Inc(R.Left, FImages.Width + 2); Calced := R; S := FTabs[I]; Canvas.TextRect(Calced, S, [tfCalcRect]); if R.Right < Calced.Right then begin Message.Result := 0; { Show the hint } HI.CursorRect := R; HintStr := FTabs[I]; {$IF DEFINED(CLR)} Message.HintInfo := HI; {$ENDIF} end; end; end; end; end; procedure TTabSet.SetTabPosition(const Value: TTabPosition); begin if FTabPosition <> Value then begin FTabPosition := Value; SetFontOrientation(Canvas); SetFontOrientation(FMemBitmap.Canvas); if FTabPosition in [tpTop, tpBottom] then Scroller.ScrollOrientation := soLeftRight else Scroller.ScrollOrientation := soUpDown; CreateEdgeParts; { Updates the parts with the new look } Invalidate; end; end; procedure TTabSet.DoModernPainting; const TabState: array[Boolean] of TThemedTabSet = (tbsTabNormal, tbsTabSelected); var YStart: Integer; TabPos: TTabPos; Tab: Integer; isSelected, isNextSelected: Boolean; R: TRect; MinRect: Integer; S: string; ImageIndex: Integer; TabTop: Integer; TotalSize: Integer; BitmapRect: TRect; TabOffset: Integer; DrawImage: Boolean; BGColor: TColor; LColor: TColor; LDetails: TThemedElementDetails; begin { Calculate our true drawing positions } if FTabPosition in [tpBottom, tpRight] then begin TabTop := 2; YStart := 1; end else if FTabPosition = tpTop then begin TabTop := ClientHeight - FTabHeight - 2; YStart := ClientHeight - 2; end else { tpLeft } begin TabTop := ClientWidth - FTabHeight - 2; YStart := ClientWidth - 2; end; if FTabPosition in [tpTop, tpBottom] then TotalSize := FMemBitmap.Width else TotalSize := FMemBitmap.Height; { draw background of tab area } with FMemBitmap.Canvas do begin { Fill in with the background color } if GetThemeColor(StyleServices.GetElementDetails(tbsBackground), ecFillColor, LColor) then BGColor := LColor else BGColor := GetHighlightColor(FBackgroundColor); Brush.Color := BGColor; Pen.Width := 1; Pen.Color := BGColor; BitmapRect := TRect.Create(0, 0, FMemBitmap.Width, FMemBitmap.Height); Rectangle(BitmapRect); { First, draw two lines that are the background color } DrawLine(FMemBitmap.Canvas, 0, YStart, TotalSize, YStart); if FTabPosition in [tpBottom, tpRight] then Inc(YStart) else Dec(YStart); { draw the top edge } { XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX | | | | | | | | | | | |___________| | | |__________________________________________________ } if StyleServices.Enabled then LDetails := StyleServices.GetElementDetails(tbsTabNormal); if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then Pen.Color := LColor else Pen.Color := clWindowFrame; DrawLine(FMemBitmap.Canvas, 0, YStart, TotalSize, YStart); MinRect := TextWidth('X...'); { Do not localize } end; TabOffset := FEdgeWidth div 2; for Tab := 0 to FTabPositions.Count - 1 do begin TabPos := FTabPositions[Tab]; isSelected := Tab + FirstIndex = TabIndex; isNextSelected := (Tab + FirstIndex) + 1 = TabIndex; if isSelected then begin if StyleServices.Enabled then LDetails := StyleServices.GetElementDetails(tbsTabSelected); { Draw the first leading edge darkened. } if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then FMemBitmap.Canvas.Pen.Color := LColor else FMemBitmap.Canvas.Pen.Color := clWindowFrame; DrawLine(FMemBitmap.Canvas, TabPos.StartPos - TabOffset + 1, TabTop, TabPos.StartPos - TabOffset + 1, TabTop + FTabHeight); if GetThemeColor(LDetails, ecFillColor, LColor) then FMemBitmap.Canvas.Pen.Color := GetHighlightColor(LColor) else FMemBitmap.Canvas.Pen.Color := GetHighlightColor(SelectedColor); { Draw the next leading edge as highlighted. } DrawLine(FMemBitmap.Canvas, TabPos.StartPos - TabOffset + 2, TabTop, TabPos.StartPos - TabOffset + 2, TabTop + FTabHeight); if GetThemeColor(LDetails, ecEdgeDkShadowColor, LColor) then FMemBitmap.Canvas.Pen.Color := LColor else FMemBitmap.Canvas.Pen.Color := clWindowFrame; { Draw the bottom edge. } if FTabPosition in [tpBottom, tpRight] then DrawLine(FMemBitmap.Canvas, TabPos.StartPos + 1 - TabOffset, TabTop + FTabHeight - 1, TabPos.StartPos + TabPos.Size + 1 + TabOffset, TabTop + FTabHeight - 1) else DrawLine(FMemBitmap.Canvas, { Really the top edge, in this case } TabPos.StartPos + 1 - TabOffset + 1, TabTop, TabPos.StartPos + TabPos.Size + 1 + TabOffset, TabTop); { Draw the right edge } DrawLine(FMemBitmap.Canvas, TabPos.StartPos + TabPos.Size + TabOffset, TabTop, TabPos.StartPos + TabPos.Size + TabOffset, TabTop + FTabHeight - 1); { Fill in the inside up with the button face } if GetThemeColor(LDetails, ecFillColor, LColor) then FMemBitmap.Canvas.Brush.Color := LColor else FMemBitmap.Canvas.Brush.Color := SelectedColor; if FTabPosition in [tpTop, tpBottom] then R := TRect.Create(TabPos.StartPos + 2 - TabOffset, TabTop, TabPos.StartPos + TabPos.Size + TabOffset, TabTop + FTabHeight - 1) else R := TRect.Create(TabTop, TabPos.StartPos + 2 - TabOffset, TabTop + FTabHeight - 1, TabPos.StartPos + TabPos.Size + TabOffset); if FTabPosition = tpTop then begin { Move the rect down and to the right a little } Inc(R.Left); Inc(R.Top); Inc(R.Bottom); end else if FTabPosition = tpLeft then begin Inc(R.Left); Inc(R.Top); Inc(R.Right); end else if FTabPosition = tpRight then Inc(R.Top) else Inc(R.Left); FMemBitmap.Canvas.FillRect(R); end else if not isNextSelected then begin { Draw a little vertical line at the end to seperate the tabs } if GetThemeColor(LDetails, ecEdgeShadowColor, LColor) then FMemBitmap.Canvas.Pen.Color := LColor else FMemBitmap.Canvas.Pen.Color := clBtnShadow; DrawLine(FMemBitmap.Canvas, TabPos.StartPos + TabPos.Size + TabOffset, TabTop + 3, TabPos.StartPos + TabPos.Size + TabOffset, TabTop + FTabHeight - 1 - 2); end; { set up the canvas } if FTabPosition in [tpTop, tpBottom] then R := TRect.Create(TabPos.StartPos, TabTop, TabPos.StartPos + TabPos.Size, TabTop + FTabHeight) else { Switch X and Y } R := TRect.Create(TabTop, TabPos.StartPos, TabTop + FTabHeight, TabPos.StartPos + TabPos.Size); with FMemBitmap.Canvas do begin Brush.Style := bsClear; { For painting text } if FTabPosition in [tpTop, tpBottom] then begin Inc(R.Top, 2); Inc(R.Left, 1); Inc(R.Right, 1); end else begin { Flip the width and height of the rect so we get correct clipping of the text when writing at a non-0 orientation } if FTabPosition = tpRight then Inc(R.Left, 1 + TextHeight('X')) { Do not localize } else begin Inc(R.Left, 2); R.Top := R.Top + TabPos.Size; { Vertical text consideration } end; R.Right := R.Left + TabPos.Size + 2; R.Bottom := R.Top + FTabHeight; end; { Draw the image first } if (FImages <> nil) then begin ImageIndex := GetImageIndex(Tab + FirstIndex); DrawImage := (ImageIndex > -1) and (ImageIndex < FImages.Count); if FTabPosition in [tpTop, tpBottom] then begin if DrawImage and (R.Left + 2 + FImages.Width < R.Right) then begin FImages.Draw(FMemBitmap.Canvas, R.Left, R.Top, ImageIndex); Inc(R.Left, 2 + FImages.Width); end; Inc(R.Top, 2); end else if FTabPosition = tpRight then begin if DrawImage then begin FImages.Draw(FMemBitmap.Canvas, R.Left - TextHeight('X') + 2, R.Top, ImageIndex); Inc(R.Top, 2 + FImages.Height); Dec(R.Right, FImages.Height); { For proper clipping } end; Inc(R.Left, 2); end else begin if DrawImage then begin FImages.Draw(FMemBitmap.Canvas, R.Left, R.Top - FImages.Height, ImageIndex); Dec(R.Top, 2 + FImages.Height); Dec(R.Right, FImages.Height); { For proper clipping } end; Inc(R.Left, 2); end; end; S := Tabs[Tab + FirstIndex]; if (R.Right - R.Left >= MinRect) or (TextWidth(S) <= (R.Right - R.Left)) then begin if TStyleManager.IsCustomStyleActive then begin if seFont in StyleElements then FMemBitmap.Canvas.Font.Color := StyleServices.GetSystemColor(clBtnText) else FMemBitmap.Canvas.Font.Color := Self.Font.Color; end else if GetThemeColor(StyleServices.GetElementDetails(TabState[isSelected]), ecTextColor, LColor) then FMemBitmap.Canvas.Font.Color := LColor else FMemBitmap.Canvas.Font.Color := Self.Font.Color; TextRect(R, S, [tfEndEllipsis, tfNoClip]); end; end; end; end; procedure TTabSet.DoPopoutModernPainting; const TabState: array[Boolean] of TThemedTabSet = (tbsTabNormal, tbsTabSelected); var TabPos: TTabPos; Tab: Integer; isSelected: Boolean; MinRect: Integer; S: string; ImageIndex: Integer; TabTop: Integer; BitmapRect: TRect; TabOffset: Integer; DrawImage: Boolean; TabRect: TRect; ImageY: Integer; LColor: TColor; begin { Calculate our true drawing positions } if FTabPosition in [tpBottom, tpRight] then begin TabTop := 0; end else if FTabPosition = tpTop then begin TabTop := ClientHeight - FTabHeight; end else { tpLeft } begin TabTop := ClientWidth - FTabHeight; end; { Fill in with the background color } if GetThemeColor(StyleServices.GetElementDetails(tbsBackground), ecFillColor, LColor) then FMemBitmap.Canvas.Brush.Color := LColor else FMemBitmap.Canvas.Brush.Color := GetHighlightColor(FBackgroundColor); BitmapRect := TRect.Create(0, 0, FMemBitmap.Width, FMemBitmap.Height); FMemBitmap.Canvas.FillRect(BitmapRect); MinRect := FMemBitmap.Canvas.TextWidth('X...'); { Do not localize } TabOffset := FEdgeWidth div 2; FMemBitmap.Canvas.Pen.Width := 1; for Tab := 0 to FTabPositions.Count - 1 do begin TabPos := FTabPositions[Tab]; isSelected := Tab + FirstIndex = TabIndex; if FTabPosition in [tpTop, tpBottom] then TabRect := TRect.Create(TabPos.StartPos - TabOffset, TabTop, TabPos.StartPos + TabPos.Size + 2 + TabOffset, TabTop + FTabHeight) else { Switch the values } TabRect := TRect.Create(TabTop, TabPos.StartPos - TabOffset, TabTop + FTabHeight, TabPos.StartPos + TabPos.Size + 2 + TabOffset); if isSelected then begin { Make it stand out by being a little higher } case TabPosition of tpTop: Dec(TabRect.Top); tpLeft: Dec(TabRect.Left); tpBottom: Inc(TabRect.Bottom); tpRight: Inc(TabRect.Right); end; end; with FMemBitmap.Canvas do begin if GetThemeColor(StyleServices.GetElementDetails(TabState[False]), ecEdgeFillColor, LColor) then Pen.Color := LColor else Pen.Color := clBtnShadow; Pen.Width := 1; if isSelected then begin if GetThemeColor(StyleServices.GetElementDetails(TabState[isSelected]), ecFillColor, LColor) then Brush.Color := LColor else Brush.Color := FSelectedColor end else begin if GetThemeColor(StyleServices.GetElementDetails(TabState[isSelected]), ecFillColor, LColor) then Brush.Color := LColor else Brush.Color := FUnselectedColor; end; Rectangle(TabRect); Brush.Style := bsClear; { For painting text } { Pop out a little } if isSelected then if TabPosition = tpRight then Inc(TabRect.Left) else if TabPosition = tpBottom then Inc(TabRect.Top); if FTabPosition in [tpTop, tpBottom] then begin Inc(TabRect.Top, 1); Inc(TabRect.Left, 3); { Buffer for text/images } end else begin Inc(TabRect.Top, 2); { Buffer for text/images } { Flip the width and height of the rect so we get correct clipping of the text when writing at a non-0 orientation } if FTabPosition = tpRight then Inc(TabRect.Left, 1 + TextHeight('X')) { Do not localize } else begin Inc(TabRect.Left, 2); TabRect.Top := TabRect.Top + TabPos.Size + TabOffset; { Vertical text consideration } end; TabRect.Right := TabRect.Left + TabPos.Size + TabOffset; TabRect.Bottom := TabRect.Top + FTabHeight; end; { Draw the image first } if (FImages <> nil) then begin ImageIndex := GetImageIndex(Tab + FirstIndex); DrawImage := (ImageIndex > -1) and (ImageIndex < FImages.Count); if FTabPosition in [tpTop, tpBottom] then begin if DrawImage then begin FImages.Draw(FMemBitmap.Canvas, TabRect.Left, TabRect.Top + 1, ImageIndex); Inc(TabRect.Left, 2 + FImages.Width); end; Inc(TabRect.Top, 2); end else if FTabPosition = tpRight then begin if DrawImage then begin FImages.Draw(FMemBitmap.Canvas, TabRect.Left - TextHeight('X') + 2, TabRect.Top, ImageIndex); Inc(TabRect.Top, 2 + FImages.Height); Dec(TabRect.Right, FImages.Height); { For proper clipping } end; Inc(TabRect.Left, 2); end else { tpLeft } begin ImageY := TabRect.Top - FImages.Height; { Make sure it doesn't go up too far } if DrawImage and (ImageY >= (TabRect.Top - TabPos.Size - TabOffset)) then begin FImages.Draw(FMemBitmap.Canvas, TabRect.Left, ImageY, ImageIndex); Dec(TabRect.Top, 2 + FImages.Height); Dec(TabRect.Right, FImages.Height); { For proper clipping } end; Inc(TabRect.Left, 2); end; end; S := Tabs[Tab + FirstIndex]; if (TabRect.Right - TabRect.Left >= MinRect) or (TextWidth(S) <= (TabRect.Right - TabRect.Left)) then begin if TStyleManager.IsCustomStyleActive then begin if seFont in StyleElements then FMemBitmap.Canvas.Font.Color := StyleServices.GetSystemColor(clBtnText) else FMemBitmap.Canvas.Font.Color := Self.Font.Color; end else if GetThemeColor(StyleServices.GetElementDetails(TabState[isSelected]), ecTextColor, LColor) then FMemBitmap.Canvas.Font.Color := LColor else FMemBitmap.Canvas.Font.Color := Self.Font.Color; TextRect(TabRect, S, [tfEndEllipsis, tfNoClip]); end; end; end; end; procedure TTabSet.SetupTabPositions; var TabStart, LastTabPos: Integer; EndPixels: Integer; WholeVisibleTabs: Integer; begin if not HandleAllocated then Exit; { Set the size of the off-screen bitmap. Make sure that it is tall enough to display the entire tab, even if the screen won't display it all. This is required to avoid problems with using FloodFill. } if FTabPosition in [tpTop, tpBottom] then begin FMemBitmap.Width := ClientWidth; if ClientHeight < FTabHeight + 5 then FMemBitmap.Height := FTabHeight + 5 else FMemBitmap.Height := ClientHeight; EndPixels := Width; Scroller.Left := EndPixels - Scroller.Width - 2; Scroller.Top := 3; end else begin { Sideways } FMemBitmap.Height := ClientHeight; if ClientWidth < FTabHeight + 5 then FMemBitmap.Width := FTabHeight + 5 else FMemBitmap.Width := ClientWidth; EndPixels := Height; Scroller.Top := EndPixels - Scroller.Height - 2; if FTabPosition = tpRight then Scroller.Left := 3 else Scroller.Left := Width - Scroller.Width - 2; end; SetFontOrientation(Canvas); FMemBitmap.Canvas.Font := Canvas.Font; TabStart := StartMargin + FEdgeWidth; { where does first text appear? } LastTabPos := EndPixels - EndMargin; { tabs draw until this position } { do initial calculations for how many tabs are visible } FVisibleTabs := CalcTabPositions(TabStart, LastTabPos, FMemBitmap.Canvas, FirstIndex, True); { enable the scroller if FAutoScroll = True and not all tabs are visible } if ScrollerShown then begin Dec(LastTabPos, ScrollerSize); { recalc the tab positions } WholeVisibleTabs := FVisibleTabs; FVisibleTabs := CalcTabPositions(TabStart, LastTabPos, FMemBitmap.Canvas, FirstIndex, False); { set the scroller's range } Scroller.Visible := True; Scroller.Min := 0; Scroller.Max := Tabs.Count - WholeVisibleTabs; Scroller.Position := FirstIndex; // partial tabs are not currently supported // the last tab may not be displayed because of the recalculation of visible tabs // after LastTabPos has been decremented; in this case, we must increment Max // to let the user scroll tabs one more time and display the last one if (Scroller.Position = Scroller.Max) and (FVisibleTabs <> WholeVisibleTabs) then Scroller.Max := Scroller.Max + 1; end else if VisibleTabs >= Tabs.Count then Scroller.Visible := False; if FDoFix then begin FDoFix := False; FixTabPos; FVisibleTabs := CalcTabPositions(TabStart, LastTabPos, FMemBitmap.Canvas, FirstIndex, not Scroller.Visible); end; end; function TTabSet.ScrollerShown: Boolean; begin Result := AutoScroll and (FVisibleTabs < Tabs.Count); end; procedure TTabSet.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin if StyleServices.Enabled and ParentBackground then inherited else Message.Result := 0; end; end.
unit classTimeRecord; interface uses SysUtils, DateUtils; type TRecord = class private RecordID : Integer; RecordClient : String; RecordUser : String; RecordTimeDate : TDateTime; RecordTimeFrom : TDateTime; RecordTimeTo : TDateTime; RecordTimeHours: Double; RecordRate : Double; RecordQuantity : Integer; RecordAmount : Double; RecordInv : Integer; RecordComment : String; published property ID : Integer read RecordId write RecordID; property Client : String read RecordClient write RecordClient; property User : String read RecordUser write RecordUser; property TimeDate : TDateTime read RecordTimeDate write RecordTimeDate; property TimeFrom : TDateTime read RecordTimeFrom; property TimeTo : TDateTime read RecordTimeTo; property TimeHours: Double read RecordTimeHours; property Rate : Double read RecordRate write RecordRate; property Quantity : Integer read RecordQuantity write RecordQuantity; property Amount : Double read RecordAmount write RecordAmount; property Inv : Integer read RecordInv write RecordInv; property Comment : String read RecordComment write RecordComment; procedure SetTimeFrom(NewFrom : TDateTime); procedure SetTimeTo(NewTo : TDateTime); function ToString : String; constructor Create(ID : Integer; User : String; Client : String; TimeDate: TDateTime; TimeFrom : TDateTime; TimeTo : TDateTime; TimeHours : Double; Rate : Double; Quantity : Integer; Amount : Double; Inv : Integer; Comment : String); end; type // Arr is array of records, IDs is array of those records IDs before they are changed TRecordArray = class private Arr : Array of TRecord; IDs : Array of Integer; published procedure Add(Item : TRecord; Index : Integer); procedure Edit(Item : TRecord; Index : Integer); function GetCount : Integer; function GetRecord(Index : Integer) : TRecord; function GetOldID(Index : Integer) : Integer; constructor Create(Count: Integer); end; implementation uses DataController; procedure TRecord.SetTimeFrom(NewFrom: TDateTime); begin RecordTimeFrom := NewFrom; RecordTimeHours:= DataController.GetTimeHours(RecordTimeFrom, RecordTimeTo); end; procedure TRecord.SetTimeTo(NewTo: TDateTime); begin RecordTimeTo := NewTo; RecordTimeHours:= DataController.GetTimeHours(RecordTimeFrom, RecordTimeTo); end; function TRecord.ToString : String; begin Result := RecordClient; // Quantity if Quantity > 0 then begin Result := Result + ' - $' + (RecordAmount*RecordQuantity).ToString + sLineBreak + 'Quantity: ' + RecordQuantity.ToString + sLineBreak + 'Amount: $' + RecordAmount.ToString + sLineBreak + RecordComment; end else // Hourly begin Result := Result + ' - $' + (RecordTimeHours*RecordRate).ToString + sLineBreak + formatdatetime('hh:nn am/pm',RecordTimeFrom)+' - '+formatdatetime('hh:nn am/pm',RecordTimeTo) + sLineBreak + RecordTimeHours.ToString + ' hrs' + sLineBreak + RecordComment; end end; constructor TRecord.Create( ID : Integer; User: string; Client : String; TimeDate : TDateTime; TimeFrom: TDateTime; TimeTo: TDateTime; TimeHours : Double; Rate: Double; Quantity: Integer; Amount: Double; Inv : Integer; Comment : String); begin RecordID := ID; RecordClient := Client; RecordUser := User; RecordTimeDate := trunc(TimeDate); RecordTimeFrom := TimeDate + TimeFrom - trunc(TimeFrom); RecordTimeTo := TimeDate + TimeTo - trunc(TimeTo); RecordTimeHours:= TimeHours; RecordRate := Rate; RecordQuantity := Quantity; RecordAmount := Amount; RecordInv := Inv; RecordComment := Comment; end; procedure TRecordArray.Add(Item : TRecord; Index : Integer); begin Arr[Index] := Item; IDs[Index] := Item.ID; end; procedure TRecordArray.Edit(Item : TRecord; Index : Integer); begin Arr[Index] := Item; end; function TRecordArray.GetCount : Integer; begin Result := length(Arr); end; function TRecordArray.GetRecord(index : Integer) : TRecord; begin Result := Arr[Index]; end; function TRecordArray.GetOldID(Index: Integer) : Integer; begin Result := IDs[Index]; end; constructor TRecordArray.Create(Count : Integer); begin SetLength(Arr,Count); SetLength(Ids,Count); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLTriangulation<p> Classes and methods for 2D triangulation of scatter points.<p> <b>History : </b><font size=-1><ul> <li>17/05/15 - PW - Created, based on code from Paul Bourke (http://paulbourke.net/) and conversion from VB to Delphi by Dr Steve Evans (steve@lociuk.com) </ul></font> } unit GLTriangulation; interface uses System.Classes, System.Types, Vcl.Dialogs, Vcl.Graphics, //GLS GLVectorGeometry; // Set these as applicable const MaxVertices = 500000; const MaxTriangles = 1000000; const ExPtTolerance = 0.000001; type TDProgressEvent = procedure(State: string; Pos, Max: Integer; AlwaysUpdate: Boolean = False) of object; // Points (Vertices) type DVertex = record X: Single; Y: Single; Z: Single; // Added to save height of terrain. U: Single; V: Single; MatIndex: Integer; end; // Created Triangles, vv# are the vertex pointers type DTriangle = record vv0: LongInt; vv1: LongInt; vv2: LongInt; PreCalc: Integer; Xc, Yc, R: Single; end; type TDVertex = array of DVertex; TDTriangle = array of DTriangle; TDComplete = array of Boolean; TDEdges = array of array of LongInt; { : TDelaunay2D is a class for Delaunay triangulation of arbitrary points Credit to Paul Bourke (http://paulbourke.net/) for the original Fortran 77 Program :)) Conversion to Visual Basic by EluZioN (EluZioN@casesladder.com) Conversion from VB to Delphi6 by Dr Steve Evans (steve@lociuk.com) June 2002 Update by Dr Steve Evans (steve@lociuk.com): Heap memory allocation added to prevent stack overflow when MaxVertices and MaxTriangles are very large. Additional Updates in June 2002: Bug in InCircle function fixed. Radius r := Sqrt(rsqr). Check for duplicate points added when inserting new point. For speed, all points pre-sorted in x direction using quicksort algorithm and triangles flagged when no longer needed. The circumcircle centre and radius of the triangles are now stored to improve calculation time. You can use this code however you like providing the above credits remain in tact } type TDelaunay2D = class private { Private declarations } function InCircle(Xp, Yp, X1, Y1, X2, Y2, X3, Y3: Single; var Xc: Single; var Yc: Single; var R: Single; j: Integer): Boolean; function Triangulate(nvert: Integer): Integer; public { Public declarations } Vertex: TDVertex; Triangle: TDTriangle; HowMany: Integer; tPoints: Integer; // Variable for total number of points (vertices) OnProgress: TDProgressEvent; constructor Create; destructor Destroy; procedure Mesh(sort: Boolean); procedure AddPoint(X, Y, Z, U, V: Single; MatIndex: Integer); procedure AddPointNoCheck(X, Y, Z, U, V: Single; MatIndex: Integer); procedure RemoveLastPoint; procedure QuickSort(var A: TDVertex; Low, High: Integer); end; //------------------------------------------------------------------------ //------------------------------------------------------------------------ //------------------------------------------------------------------------ implementation //------------------------------------------------------------------------ //------------------------------------------------------------------------ //------------------------------------------------------------------------ constructor TDelaunay2D.Create; begin // Initiate total points to 1, using base 0 causes problems in the functions inherited; tPoints := 1; HowMany := 0; SetLength(Vertex, MaxVertices); SetLength(Triangle, MaxTriangles); OnProgress := nil; end; destructor TDelaunay2D.Destroy; begin SetLength(Vertex, 0); SetLength(Triangle, 0); inherited; end; function TDelaunay2D.InCircle(Xp, Yp, X1, Y1, X2, Y2, X3, Y3: Single; var Xc: Single; var Yc: Single; var R: Single; j: Integer): Boolean; // Return TRUE if the point (xp,yp) lies inside the circumcircle // made up by points (x1,y1) (x2,y2) (x3,y3) // The circumcircle centre is returned in (xc,yc) and the radius r // NOTE: A point on the edge is inside the circumcircle var eps: Single; m1: Single; m2: Single; mx1: Single; mx2: Single; my1: Single; my2: Single; dx: Single; dy: Single; rsqr: Single; drsqr: Single; begin eps := 0.000001; InCircle := False; // Check if xc,yc and r have already been calculated if Triangle[j].PreCalc = 1 then begin Xc := Triangle[j].Xc; Yc := Triangle[j].Yc; R := Triangle[j].R; rsqr := R * R; dx := Xp - Xc; dy := Yp - Yc; drsqr := dx * dx + dy * dy; end else begin if (Abs(Y1 - Y2) < eps) and (Abs(Y2 - Y3) < eps) then begin ShowMessage('INCIRCUM - F - Points are coincident !!'); Exit; end; if Abs(Y2 - Y1) < eps then begin m2 := -(X3 - X2) / (Y3 - Y2); mx2 := (X2 + X3) / 2; my2 := (Y2 + Y3) / 2; Xc := (X2 + X1) / 2; Yc := m2 * (Xc - mx2) + my2; end else if Abs(Y3 - Y2) < eps then begin m1 := -(X2 - X1) / (Y2 - Y1); mx1 := (X1 + X2) / 2; my1 := (Y1 + Y2) / 2; Xc := (X3 + X2) / 2; Yc := m1 * (Xc - mx1) + my1; end else begin m1 := -(X2 - X1) / (Y2 - Y1); m2 := -(X3 - X2) / (Y3 - Y2); mx1 := (X1 + X2) / 2; mx2 := (X2 + X3) / 2; my1 := (Y1 + Y2) / 2; my2 := (Y2 + Y3) / 2; if (m1 - m2) <> 0 then // se begin Xc := (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2); Yc := m1 * (Xc - mx1) + my1; end else begin Xc := (X1 + X2 + X3) / 3; Yc := (Y1 + Y2 + Y3) / 3; end; end; dx := X2 - Xc; dy := Y2 - Yc; rsqr := dx * dx + dy * dy; R := Sqrt(rsqr); dx := Xp - Xc; dy := Yp - Yc; drsqr := dx * dx + dy * dy; // store the xc,yc and r for later use Triangle[j].PreCalc := 1; Triangle[j].Xc := Xc; Triangle[j].Yc := Yc; Triangle[j].R := R; end; if drsqr <= rsqr then InCircle := True; end; function TDelaunay2D.Triangulate(nvert: Integer): Integer; // Takes as input NVERT vertices in arrays Vertex() // Returned is a list of NTRI triangular faces in the array // Triangle(). These triangles are arranged in clockwise order. var Complete: TDComplete; Edges: TDEdges; Nedge: LongInt; // For Super Triangle xmin: Single; xmax: Single; ymin: Single; ymax: Single; xmid: Single; ymid: Single; dx: Single; dy: Single; dmax: Single; // General Variables i: Integer; j: Integer; k: Integer; ntri: Integer; Xc: Single; Yc: Single; R: Single; inc: Boolean; begin // Allocate memory SetLength(Complete, MaxTriangles); SetLength(Edges, 2, MaxTriangles * 3); // Find the maximum and minimum vertex bounds. // This is to allow calculation of the bounding triangle xmin := Vertex[1].X; ymin := Vertex[1].Y; xmax := xmin; ymax := ymin; for i := 2 to nvert do begin if Vertex[i].X < xmin then xmin := Vertex[i].X; if Vertex[i].X > xmax then xmax := Vertex[i].X; if Vertex[i].Y < ymin then ymin := Vertex[i].Y; if Vertex[i].Y > ymax then ymax := Vertex[i].Y; end; dx := xmax - xmin; dy := ymax - ymin; if dx > dy then dmax := dx else dmax := dy; xmid := Trunc((xmax + xmin) / 2); ymid := Trunc((ymax + ymin) / 2); // Set up the supertriangle // This is a triangle which encompasses all the sample points. // The supertriangle coordinates are added to the end of the // vertex list. The supertriangle is the first triangle in // the triangle list. Vertex[nvert + 1].X := (xmid - 2 * dmax); Vertex[nvert + 1].Y := (ymid - dmax); Vertex[nvert + 2].X := xmid; Vertex[nvert + 2].Y := (ymid + 2 * dmax); Vertex[nvert + 3].X := (xmid + 2 * dmax); Vertex[nvert + 3].Y := (ymid - dmax); Triangle[1].vv0 := nvert + 1; Triangle[1].vv1 := nvert + 2; Triangle[1].vv2 := nvert + 3; Triangle[1].PreCalc := 0; Complete[1] := False; ntri := 1; // Include each point one at a time into the existing mesh for i := 1 to nvert do begin if Assigned(OnProgress) then OnProgress('Delaunay triangulation', i - 1, nvert); Nedge := 0; // Set up the edge buffer. // If the point (Vertex(i).x,Vertex(i).y) lies inside the circumcircle then the // three edges of that triangle are added to the edge buffer. j := 0; repeat j := j + 1; if Complete[j] <> True then begin inc := InCircle(Vertex[i].X, Vertex[i].Y, Vertex[Triangle[j].vv0].X, Vertex[Triangle[j].vv0].Y, Vertex[Triangle[j].vv1].X, Vertex[Triangle[j].vv1].Y, Vertex[Triangle[j].vv2].X, Vertex[Triangle[j].vv2].Y, Xc, Yc, R, j); // Include this if points are sorted by X if { usingsort and } ((Xc + R) < Vertex[i].X) then // Complete[j] := True // else // if inc then begin Edges[0, Nedge + 1] := Triangle[j].vv0; Edges[1, Nedge + 1] := Triangle[j].vv1; Edges[0, Nedge + 2] := Triangle[j].vv1; Edges[1, Nedge + 2] := Triangle[j].vv2; Edges[0, Nedge + 3] := Triangle[j].vv2; Edges[1, Nedge + 3] := Triangle[j].vv0; Nedge := Nedge + 3; Triangle[j].vv0 := Triangle[ntri].vv0; Triangle[j].vv1 := Triangle[ntri].vv1; Triangle[j].vv2 := Triangle[ntri].vv2; Triangle[j].PreCalc := Triangle[ntri].PreCalc; Triangle[j].Xc := Triangle[ntri].Xc; Triangle[j].Yc := Triangle[ntri].Yc; Triangle[j].R := Triangle[ntri].R; Triangle[ntri].PreCalc := 0; Complete[j] := Complete[ntri]; j := j - 1; ntri := ntri - 1; end; end; until j >= ntri; // Tag multiple edges // Note: if all triangles are specified anticlockwise then all // interior edges are opposite pointing in direction. for j := 1 to Nedge - 1 do begin if not(Edges[0, j] = 0) and not(Edges[1, j] = 0) then begin for k := j + 1 to Nedge do begin if not(Edges[0, k] = 0) and not(Edges[1, k] = 0) then begin if Edges[0, j] = Edges[1, k] then begin if Edges[1, j] = Edges[0, k] then begin Edges[0, j] := 0; Edges[1, j] := 0; Edges[0, k] := 0; Edges[1, k] := 0; end; end; end; end; end; end; // Form new triangles for the current point // Skipping over any tagged edges. // All edges are arranged in clockwise order. for j := 1 to Nedge do begin if not(Edges[0, j] = 0) and not(Edges[1, j] = 0) then begin ntri := ntri + 1; Triangle[ntri].vv0 := Edges[0, j]; Triangle[ntri].vv1 := Edges[1, j]; Triangle[ntri].vv2 := i; Triangle[ntri].PreCalc := 0; Complete[ntri] := False; end; end; end; // Remove triangles with supertriangle vertices // These are triangles which have a vertex number greater than NVERT i := 0; repeat i := i + 1; if (Triangle[i].vv0 > nvert) or (Triangle[i].vv1 > nvert) or (Triangle[i].vv2 > nvert) then begin Triangle[i].vv0 := Triangle[ntri].vv0; Triangle[i].vv1 := Triangle[ntri].vv1; Triangle[i].vv2 := Triangle[ntri].vv2; i := i - 1; ntri := ntri - 1; end; until i >= ntri; Triangulate := ntri; // Free memory SetLength(Complete, 0); SetLength(Edges, 2, 0); end; procedure TDelaunay2D.Mesh(sort: Boolean); begin if sort then QuickSort(Vertex, 1, tPoints - 1); { usingsort:=sort; } if tPoints > 3 then HowMany := Triangulate(tPoints - 1); // 'Returns number of triangles created. end; procedure TDelaunay2D.AddPoint(X, Y, Z, U, V: Single; MatIndex: Integer); var i, AE: Integer; begin // Check for duplicate points AE := 0; i := 1; while i < tPoints do begin if (Abs(X - Vertex[i].X) < ExPtTolerance) and (Abs(Y - Vertex[i].Y) < ExPtTolerance) then AE := 1; inc(i); end; if AE = 0 then begin // Set Vertex coordinates where you clicked the pic box Vertex[tPoints].X := X; Vertex[tPoints].Y := Y; Vertex[tPoints].Z := Z; Vertex[tPoints].U := U; Vertex[tPoints].V := V; Vertex[tPoints].MatIndex := MatIndex; // Increment the total number of points tPoints := tPoints + 1; end; end; procedure TDelaunay2D.AddPointNoCheck(X, Y, Z, U, V: Single; MatIndex: Integer); begin Vertex[tPoints].X := X; Vertex[tPoints].Y := Y; Vertex[tPoints].Z := Z; Vertex[tPoints].U := U; Vertex[tPoints].V := V; Vertex[tPoints].MatIndex := MatIndex; tPoints := tPoints + 1; end; procedure TDelaunay2D.RemoveLastPoint; begin tPoints := tPoints - 1; end; procedure TDelaunay2D.QuickSort(var A: TDVertex; Low, High: Integer); // Sort all points by x procedure DoQuickSort(var A: TDVertex; iLo, iHi: Integer); var Lo, Hi: Integer; Mid: Single; T: DVertex; begin Lo := iLo; Hi := iHi; Mid := A[(Lo + Hi) div 2].X; repeat while A[Lo].X < Mid do inc(Lo); while A[Hi].X > Mid do Dec(Hi); if Lo <= Hi then begin T := A[Lo]; A[Lo] := A[Hi]; A[Hi] := T; inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > iLo then DoQuickSort(A, iLo, Hi); if Lo < iHi then DoQuickSort(A, Lo, iHi); end; begin DoQuickSort(A, Low, High); end; end.
unit AddMissingAliasesUnit; interface uses BDE, DBTables, Classes, SysUtils, Forms, Dialogs; Procedure AddMissingAliases(Session : TSession; Application : TApplication); implementation {===================================================} Function CreateBDEAlias( Session : TSession; AliasName : String; AliasPath : String; var ResultMsg : String) : Boolean; var Error : Boolean; begin Error := False; Result := True; with Session do try ConfigMode := cmPersistent; AddStandardAlias(AliasName, AliasPath, 'DBASE'); SaveConfigFile; except Error := True; ResultMsg := 'Alias ' + AliasName + ' was NOT added successfully.'; Result := False; end; If not Error then begin Result := True; ResultMsg := 'Alias ' + AliasName + ' was added successfully.' end; end; {CreateBDEAlias} {$H+} {===========================================================================} Function StripLeadingAndEndingDuplicateChar(TempStr : String; CharToStrip : Char) : String; begin Result := TempStr; If ((Length(Result) > 1) and (Result[1] = CharToStrip) and (Result[Length(Result)] = CharToStrip)) then begin Delete(Result, Length(Result), 1); Delete(Result, 1, 1); end; end; {StripLeadingAndEndingDuplicateChar} {$H-} {$H+} {===========================================================================} Procedure ParseCommaDelimitedStringIntoFields(TempStr : String; FieldList : TStringList; CapitalizeStrings : Boolean); var InEmbeddedQuote : Boolean; CurrentField : String; I : Integer; begin FieldList.Clear; InEmbeddedQuote := False; CurrentField := ''; For I := 1 to Length(TempStr) do begin If (TempStr[I] = '"') then InEmbeddedQuote := not InEmbeddedQuote; {New field if we have found comma and we are not in an embedded quote.} If ((TempStr[I] = ',') and (not InEmbeddedQuote)) then begin {If the field starts and ends with a double quote, strip it.} CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"'); If CapitalizeStrings then CurrentField := ANSIUpperCase(CurrentField); FieldList.Add(CurrentField); CurrentField := ''; end else CurrentField := CurrentField + TempStr[I]; end; {For I := 1 to Length(TempStr) do} CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"'); If CapitalizeStrings then CurrentField := ANSIUpperCase(CurrentField); FieldList.Add(CurrentField); end; {ParseCommaDelimitedStringIntoFields} {$H-} {================================================================================} Procedure AddMissingAliases(Session : TSession; Application : TApplication); var AliasFile : TextFile; DatabaseList, FieldList : TStringList; TempStr, AliasName, ResultMsg, AppPath : String; Done : Boolean; begin Done := False; FieldList := TStringList.Create; DatabaseList := TStringList.Create; Session.GetDatabaseNames(DatabaseList); AppPath := ExtractFilePath(ExpandFileName(Application.ExeName)); try AssignFile(AliasFile, AppPath + 'Aliases.txt'); Reset(AliasFile); repeat Readln(AliasFile, TempStr); If EOF(AliasFile) then Done := True; ParseCommaDelimitedStringIntoFields(TempStr, FieldList, False); AliasName := FieldList[0]; If (DatabaseList.IndexOf(AliasName) = -1) then CreateBDEAlias(Session, AliasName, FieldList[1], ResultMsg); until Done; CloseFile(AliasFile); except end; DatabaseList.Free; FieldList.Free; end; {AddMissingAliases} end.
unit GUI_PokePasApp; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, LCLType, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Menus, DT_Pokedex, DT_Especie, DT_TipoElemental, Utilidades; CONST MAX_NUMERO_ESPECIES= 1000; type { TPokePas } TPokePas = class(TForm) Buscar: TButton; LogoPokePas: TImage; MainMenu: TMainMenu; Creador: TMenuItem; BattleCenter: TMenuItem; Aventura: TMenuItem; Acerca: TMenuItem; PanelPokePas: TPanel; Salir: TMenuItem; PokedexGeneral: TMenuItem; Bienvenida: TStaticText; Busqueda: TEdit; ImagenPokemon: TImage; Inicio: TMenuItem; Info: TStaticText; txtCrecimiento: TEdit; txtPS: TEdit; txtDEF: TEdit; txtDEFSp: TEdit; txtRATIO: TEdit; txtPSE: TEdit; txtVELE: TEdit; txtATKE: TEdit; txtATKSpE: TEdit; txtDEFE: TEdit; txtDEFSpE: TEdit; Id: TEdit; Nombre: TEdit; Tipo: TEdit; txtVEL: TEdit; txtAMISTAD: TEdit; txtATK: TEdit; txtATKSp: TEdit; txtEXP: TEdit; Pokemon: TGroupBox; Estadisticas: TGroupBox; Esfuerzo: TGroupBox; Crecimiento: TLabel; AMISTAD: TLabel; DEF: TLabel; DEFSp: TLabel; RATIO: TLabel; PSE: TLabel; VELE: TLabel; ATKE: TLabel; ATKSpE: TLabel; DEFE: TLabel; DEFSpE: TLabel; PS: TLabel; VEL: TLabel; EXP: TLabel; ATK: TLabel; ATKSp: TLabel; ListaEspecies: TListBox; MainMenu1: TMainMenu; PanelPokedex: TPanel; procedure AcercaClick(Sender: TObject); procedure AventuraClick(Sender: TObject); procedure BattleCenterClick(Sender: TObject); procedure BuscarClick(Sender: TObject); procedure CreadorClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure InicioClick(Sender: TObject); procedure ListaEspeciesClick(Sender: TObject); procedure ListaEspeciesKeyDown(Sender: TObject; var Key: Word); procedure PokedexGeneralClick(Sender: TObject); procedure SalirClick(Sender: TObject); private { private declarations } public { public declarations } end; var PokePas: TPokePas; pokedexStart: BOOLEAN; pokedex: DatosPokedex; key: CHAR; implementation {$R *.lfm} { Controlador Pokedex } (*Devuelve TRUE si la pokedex ya fue iniciada, FALSE sino.*) FUNCTION PokedexStarted(): BOOLEAN; Begin PokedexStarted:= pokedexStart; end; (*Dibuja en pantalla los datos de la especie seleccionada, tal como se describe en los documentos.*) PROCEDURE DrawPokedex(p: DatosPokedex); VAR especieActual: Especie; tipo1, tipo2: STRING; i: INTEGER; BEGIN pokedex := p; especieActual:= EspecieSeleccionada(p); //Mostramos la imagen de la especie actual. PokePas.ImagenPokemon.Picture.LoadFromFile('Images\'+ NumeroEspecie(especieActual) + '.png'); //Escribimos los datos específicos de esta especie. PokePas.Id.Caption := '#' + NumeroEspecie(especieActual); PokePas.Nombre.Caption:= NombreEspecie(especieActual); tipo1:= NombreTipoElemental(ObtenerTipoElemental(TipoEspecie(1,especieActual),p)); tipo2:= NombreTipoElemental(ObtenerTipoElemental(TipoEspecie(2,especieActual),p)); IF tipo2<>'NULL' THEN PokePas.Tipo.Caption := tipo1+'/'+tipo2 ELSE PokePas.Tipo.Caption := tipo1; // Escribimos las estadísticas base. PokePas.txtPS.Text := IntToStr(EstadisticaEspecie(PS_Base,especieActual)); PokePas.txtATK.Text := IntToStr(EstadisticaEspecie(ATK_Base,especieActual)); PokePas.txtDEF.Text := IntToStr(EstadisticaEspecie(DEF_Base,especieActual)); PokePas.txtVEL.Text := IntToStr(EstadisticaEspecie(VEL_Base,especieActual)); PokePas.txtATKSp.Text := IntToStr(EstadisticaEspecie(ATKSp_Base,especieActual)); PokePas.txtDEFSp.Text := IntToStr(EstadisticaEspecie(DEFSp_Base,especieActual)); PokePas.txtAMISTAD.Text := IntToStr(EstadisticaEspecie(AMISTAD_Base,especieActual)); PokePas.txtEXP.Text := IntToStr(EstadisticaEspecie(EXP_Base,especieActual)); PokePas.txtRATIO.Text := IntToStr(EstadisticaEspecie(RatioCaptura,especieActual)); //Escribimos los datos de puntos de efuerzo. PokePas.txtPSE.Text := IntToStr(EstadisticaEspecie(PS_Esfuerzo,especieActual)); PokePas.txtATKE.Text := IntToStr(EstadisticaEspecie(ATK_Esfuerzo,especieActual)); PokePas.txtDEFE.Text := IntToStr(EstadisticaEspecie(DEF_Esfuerzo,especieActual)); PokePas.txtVELE.Text := IntToStr(EstadisticaEspecie(VEL_Esfuerzo,especieActual)); PokePas.txtATKSpE.Text := IntToStr(EstadisticaEspecie(ATKSp_Esfuerzo,especieActual)); PokePas.txtDEFSpE.Text := IntToStr(EstadisticaEspecie(DEFSp_Esfuerzo,especieActual)); //Escribimos el tipo de crecimiento. PokePas.txtCrecimiento.Caption := CrecimientoEspecie(especieActual); //Dibujamos la lista de selección. if PokePas.ListaEspecies.Count = 0 then begin //for i := 1 to MAX_NUMERO_ESPECIES do i := 1; while EsIndiceValidoListaEspecies(i, p.especies) do begin PokePas.ListaEspecies.Items.Add(NombreEspecie(EspecieListaEspecies(i,ListaDeEspecies(p)))); i := i + 1; end; end; PokePas.ListaEspecies.ClearSelection; PokePas.ListaEspecies.ItemIndex := IndiceEspecieSeleccionada(pokedex)-1; end; (*Inicia los datos de la pokedex cargando desde la base de datos. Se establece una bandera indicando que la pokedex ya fue iniciada.*) PROCEDURE StartPokedex(); Begin IF NOT PokedexStarted THEN Begin IniciarPokedex(pokedex); pokedexStart:= true; DrawPokedex(pokedex); End; end; procedure SeleccionarEspecie(i: INTEGER); begin WHILE i<IndiceEspecieSeleccionada(pokedex) do begin AnteriorEspecie(pokedex); end; WHILE i>IndiceEspecieSeleccionada(pokedex) do begin SiguienteEspecie(pokedex); end; DrawPokedex(pokedex); end; { TPokePas } procedure TPokePas.FormCreate(Sender: TObject); begin pokedexStart := false; end; procedure TPokePas.ListaEspeciesClick(Sender: TObject); var i: INTEGER; flag : Boolean; begin i := 0; flag := true; while (i < PokePas.ListaEspecies.Items.Count) and flag do begin if PokePas.ListaEspecies.Selected[i] then begin SeleccionarEspecie(BuscarEspecie(PokePas.ListaEspecies.Items[i],pokedex)); flag := false; end; i := i + 1; end; end; procedure TPokePas.ListaEspeciesKeyDown(Sender: TObject; var Key: Word); begin case Key of VK_DOWN: Begin DrawPokedex(pokedex); end; VK_UP: Begin DrawPokedex(pokedex); end; end; end; procedure TPokePas.BuscarClick(Sender: TObject); var indiceEspecieBuscada : INTEGER; begin indiceEspecieBuscada := BuscarEspecie(PokePas.Busqueda.Caption,pokedex); IF indiceEspecieBuscada=0 THEN Begin MessageDlg('No existe la especie buscada.',mtError, mbOKCancel, 0); end else begin SeleccionarEspecie(indiceEspecieBuscada); end; PokePas.Busqueda.Caption := ''; end; { Menu } procedure TPokePas.InicioClick(Sender: TObject); begin PokePas.PanelPokePas.Visible := true; PokePas.PanelPokedex.Visible := false; PokePas.Bienvenida.Caption := 'Bienvenido/a a PokePas V1.1 -- Elige una de las opciones del menú. '; end; procedure TPokePas.PokedexGeneralClick(Sender: TObject); begin StartPokedex(); PokePas.PanelPokePas.Visible := false; PokePas.PanelPokedex.Visible := true; PokePas.Info.Caption := 'Para buscar una especie, ingrese su número o nombre'; end; procedure TPokePas.CreadorClick(Sender: TObject); begin PokePas.PanelPokePas.Visible := true; PokePas.PanelPokedex.Visible := false; PokePas.Bienvenida.Caption := 'LO SIENTO... AÚN NO HEMOS DESARROLLADO ESTA FUNCIONALIDAD'; end; procedure TPokePas.BattleCenterClick(Sender: TObject); begin PokePas.PanelPokePas.Visible := true; PokePas.PanelPokedex.Visible := false; PokePas.Bienvenida.Caption := 'LO SIENTO... AÚN NO HEMOS DESARROLLADO ESTA FUNCIONALIDAD'; end; procedure TPokePas.AventuraClick(Sender: TObject); begin PokePas.PanelPokePas.Visible := true; PokePas.PanelPokedex.Visible := false; PokePas.Bienvenida.Caption := 'LO SIENTO... AÚN NO HEMOS DESARROLLADO ESTA FUNCIONALIDAD'; end; procedure TPokePas.AcercaClick(Sender: TObject); begin PokePas.PanelPokePas.Visible := true; PokePas.PanelPokedex.Visible := false; PokePas.Bienvenida.Caption := 'PokePas es un proyecto independiente pensado para enseñar.' + LineEnding + 'Muchas gracias por formar parte de esta iniciativa.' + LineEnding + 'Espero te haya sido de utilidad ;-) ' + LineEnding + LineEnding + 'Kyshuo Ayame - KAEduSoft 2015 - Proyecto independiente sin fines de lucro. '+ LineEnding + 'El uso que hagas de este proyecto y su código queda 100% bajo tu responsabilidad.'; end; procedure TPokePas.SalirClick(Sender: TObject); begin PokePas.Close; end; end.
(* StackADT4: SWa, 2020-04-15 *) (* ---------- *) (* Stack abstract data type - version 4. *) (* ========================================================================= *) UNIT StackADT4; INTERFACE TYPE Stack = POINTER; FUNCTION NewStack(max: INTEGER): Stack; PROCEDURE DisposeStack(VAR s: Stack); PROCEDURE Push(s: Stack; value: INTEGER); FUNCTION Pop(s: Stack): INTEGER; FUNCTION Empty(s: Stack): BOOLEAN; IMPLEMENTATION TYPE StackPtr = ^StackRec; StackRec = RECORD max: INTEGER; top: INTEGER; data: ARRAY [1..1] OF INTEGER; END; (* StackRec *) FUNCTION NewStack(max: INTEGER): Stack; VAR s: StackPtr; BEGIN (* NewStack *) GetMem(s, (2 + max) * SizeOf(INTEGER)); s^.max := max; s^.top := 0; NewStack := s; END; (* NewStack *) PROCEDURE DisposeStack(VAR s: Stack); BEGIN (* DisposeStack *) FreeMem(s, (2 + StackPtr(s)^.max) * SizeOf(INTEGER)); s := NIL; END; (* DisposeStack *) PROCEDURE Push(s: Stack; value: INTEGER); BEGIN (* Push *) IF (StackPtr(s)^.top = StackPtr(s)^.max) THEN BEGIN WriteLn('ERROR: stack full'); HALT; END; (* IF *) StackPtr(s)^.top := StackPtr(s)^.top + 1; {$R-} StackPtr(s)^.data[StackPtr(s)^.top] := value; {$R+} END; (* Push *) FUNCTION Pop(s: Stack): INTEGER; VAR value: INTEGER; BEGIN (* Pop *) IF (StackPtr(s)^.top = 0) THEN BEGIN WriteLn('ERROR: stack empty'); HALT; END; (* IF *) {$R-} value := StackPtr(s)^.data[StackPtr(s)^.top]; {$R+} StackPtr(s)^.top := StackPtr(s)^.top - 1; Pop := value; END; (* Pop *) FUNCTION Empty(s: Stack): BOOLEAN; BEGIN (* Empty *) Empty := (StackPtr(s)^.top = 0); END; (* Empty *) END. (* StackADT4 *)
{ "RTC Image Playback (FMX)" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcFImgPlayback; interface {$include rtcDefs.inc} uses Classes, System.Types, {$IFDEF IDE_XE5up} FMX.Graphics, {$ENDIF} FMX.Types, rtcTypes, rtcXImgPlayback, rtcFBmpUtils; type {$IFDEF IDE_XE2up} [ComponentPlatformsAttribute(pidAll)] {$ENDIF} TRtcImageFMXPlayback=class(TRtcImagePlayback) private FBmp:TBitmap; protected procedure DoImageCreate; override; procedure DoImageUpdate; override; procedure DoReceiveStop; override; public constructor Create(AOwner:TComponent); override; procedure DrawBitmap(Canvas:TCanvas); property Bitmap:TBitmap read FBmp; end; implementation { TRtcImagePlaybackFMX } constructor TRtcImageFMXPlayback.Create(AOwner: TComponent); begin inherited; FBmp:=nil; end; procedure TRtcImageFMXPlayback.DoImageCreate; begin Image:=NewBitmapInfo(False); inherited; end; procedure TRtcImageFMXPlayback.DoImageUpdate; begin CopyInfoToBitmap(Image, FBmp); inherited; end; function RectF(Left, Top, Right, Bottom: Single): TRectF; begin Result.Left := Left; Result.Top := Top; Result.Bottom := Bottom; Result.Right := Right; end; procedure TRtcImageFMXPlayback.DoReceiveStop; begin inherited; RtcFreeAndNil(FBmp); end; procedure TRtcImageFMXPlayback.DrawBitmap(Canvas: TCanvas); begin if assigned(Bitmap) then begin Canvas.DrawBitmap(Bitmap,RectF(0,0,Bitmap.Width, Bitmap.Height), RectF(0,0,Bitmap.Width, Bitmap.Height),1,True); PaintCursor(Decoder.Cursor, Canvas, Bitmap, LastMouseX, LastMouseY, MouseControl); end; end; end.
unit MediaProcessing.Convertor.HHH264.H264.Impl; interface uses SysUtils,Windows,Classes, Graphics, MediaProcessing.Definitions,MediaProcessing.Global,HHCommon,MediaProcessing.Convertor.HHH264.H264; type TMediaProcessor_Convertor_Hh_H264_H624_Impl=class (TMediaProcessor_Convertor_Hh_H264_H624,IMediaProcessorImpl) private FLastVideoFrameTimeStamp: TDateTime; protected procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override; public end; implementation uses uBaseClasses; procedure TMediaProcessor_Convertor_Hh_H264_H624_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); type TNALSignature = array [0..2] of byte; var aStreamData: PHV_FRAME; aMinDelta : cardinal; b: boolean; // aNALSignature: ^TNALSignature; begin TArgumentValidation.NotNil(aInData); Assert(aInfoSize=sizeof(HHAV_INFO)); aStreamData:=aInData; Assert(aStreamData.zeroFlag=0); Assert(aStreamData.oneFlag=1); aOutData:=nil; aOutDataSize:=0; aOutInfo:=nil; aOutInfoSize:=0; aOutFormat:=aInFormat; aOutFormat.biStreamType:=stH264; if not (aStreamData.streamFlag in [FRAME_FLAG_VP,FRAME_FLAG_VI]) then exit; if aStreamData.streamFlag=FRAME_FLAG_VI then Assert(ffKeyFrame in aOutFormat.biFrameFlags) else if aStreamData.streamFlag=FRAME_FLAG_VP then Assert(not (ffKeyFrame in aOutFormat.biFrameFlags)); b:=false; if HHCommon.GetH264Data(aStreamData,aOutData,aOutDataSize) then begin if FChangeFPSMode=cfmNone then begin b:=true; end //Только опорные кадры else if (FChangeFPSMode = cfmVIFrameOnly) and (aStreamData.streamFlag=FRAME_FLAG_VI) then begin b:=true; end //Прореживание кадров else if FChangeFPSMode=cfmAbsolute then begin if (FLastVideoFrameTimeStamp<>0) and (FLastVideoFrameTimeStamp<aStreamData.nTimestamp) then begin aMinDelta:=25 div FFPSValue; if aStreamData.nTimestamp-FLastVideoFrameTimeStamp>=aMinDelta then b:=true; end else FLastVideoFrameTimeStamp:=aStreamData.nTimestamp; end; end; if not b then begin aOutData:=nil; aOutDataSize:=0; end else begin (* if b then begin aOutData:=PAnsiChar(aStreamData)+sizeof(HV_FRAME_HEAD)+sizeof(EXT_FRAME_HEAD); aOutDataSize:=aStreamData.nByteNum-sizeof(EXT_FRAME_HEAD); Assert(PAnsiChar(aOutData)^=#0); Assert((PAnsiChar(aOutData)+1)^=#0); Assert((PAnsiChar(aOutData)+2)^=#0); Assert((PAnsiChar(aOutData)+3)^=#1); *) FLastVideoFrameTimeStamp:=aStreamData.nTimestamp; end; end; initialization MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_Convertor_Hh_H264_H624_Impl); end.
unit uSolicitacaoModel; interface uses uEnumerado, FireDAC.Comp.Client; type TSolicitacaoModel = class private FAcao: TAcao; FIdLivro: string; FIdUsuario: string; FData: string; FHora: string; FOrigem: string; FDestino: string; procedure SetAcao(const Value: TAcao); procedure setData(const Value: string); procedure setLivro(const Value: string); procedure setUsuario(const Value: string); procedure setDestino(const Value: string); function Buscar: TFDQuery; procedure setHora(const Value: string); public function Obter: TFDQuery; function ObterSelecionadas(Cpf: string): TFDQuery; function Salvar: Boolean; property IdLivro: string read FIdLivro write setLivro; property IdUsuario: string read FIdUsuario write setUsuario; property Data: string read FData write setData; property Hora: string read FHora write setHora; property Destino: string read FDestino write setDestino; property Acao: TAcao read FAcao write SetAcao; end; implementation { TLivro } uses uSolicitacaoDao; function TSolicitacaoModel.Buscar: TFDQuery; begin end; function TSolicitacaoModel.Obter: TFDQuery; var Dao: TSolicitacaoDao; begin Dao := TSolicitacaoDao.Create; try Result := Dao.Obter; finally Dao.Free; end; end; function TSolicitacaoModel.Salvar: Boolean; var Dao: TSolicitacaoDao; begin Result := False; Dao := TSolicitacaoDao.Create; try case FAcao of uEnumerado.tacIncluir: Result := Dao.Incluir(Self); uEnumerado.tacExcluir: Result := Dao.Excluir(Self); end; finally Dao.Free; end; end; procedure TSolicitacaoModel.SetAcao(const Value: TAcao); begin FAcao := Value; end; procedure TSolicitacaoModel.setData(const Value: string); begin FData := Value; end; procedure TSolicitacaoModel.setDestino(const Value: string); begin FDestino := Value; end; procedure TSolicitacaoModel.setHora(const Value: string); begin FHora := Value; end; procedure TSolicitacaoModel.setLivro(const Value: string); begin FIdLivro := Value; end; procedure TSolicitacaoModel.setUsuario(const Value: string); begin FIdUsuario := Value; end; function TSolicitacaoModel.ObterSelecionadas(Cpf: string): TFDQuery; var Dao: TSolicitacaoDao; begin Dao := TSolicitacaoDao.Create; try Result := Dao.ObterSelecionadas(Cpf); finally Dao.Free; end; end; end.
unit TreeIntf; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, DesignIntf, DesignEditors, DesignMenus, TypInfo, Contnrs, IniFiles, Menus, ImgList; type { TSprig } { sprig \Sprig\, n. [AS. sprec; akin to Icel. sprek a stick. Cf. Spray a branch.] 1. A small shoot or twig of a tree or other plant; a spray; as, a sprig of laurel or of parsley. 2. A youth; a lad; -- used humorously or in slight disparagement. A sprig whom I remember, with a whey-face and a satchel, not so many years ago. --Sir W. Scott. 3. A brad, or nail without a head. 4. (Naut.) A small eyebolt ragged or barbed at the point. 5. A leaf in Delphi's object treeview Source: Webster's Revised Unabridged Dictionary, well sort of anyway } TSprig = class; TSprigClass = class of TSprig; TSprigAction = procedure(AItem: TSprig) of object; TSprigIndex = class; TRootSprig = class; TRootSprigClass = class of TRootSprig; TSprigTreeNode = class; ISprigDesigner = interface; ISprigCollection = interface ['{0B6ABAEE-E1A4-4DAC-8E20-C6B741A5082D}'] function RootSprigAssigned: Boolean; function RootSprig: TRootSprig; function GetSprigDesigner: ISprigDesigner; procedure SetSprigDesigner(const ASprigDesigner: ISprigDesigner); property SprigDesigner: ISprigDesigner read GetSprigDesigner write SetSprigDesigner; end; ISprigDesigner = interface ['{6AC141E3-2FBE-425E-B299-AB29E7DF3FBB}'] function GetTreeView: TCustomTreeView; procedure BeforeItemsModified; procedure AfterItemsModified; function GetRootSprig: TRootSprig; procedure SetRootSprig(ARootSprig: TRootSprig); property RootSprig: TRootSprig read GetRootSprig write SetRootSprig; end; TInformant = class(TObject) private FNotifyList: TList; FDisableNotify: Integer; FNotifyNeeded: Boolean; FDestroying: Boolean; protected procedure Changed(AObj: TInformant); virtual; public procedure BeforeDestruction; override; destructor Destroy; override; property Destroying: Boolean read FDestroying; procedure DisableNotify; procedure EnableNotify; procedure Notification; procedure Notify(AObj: TInformant); procedure Unnotify(AObj: TInformant); end; TSprigDeleteStyle = (dsNormal, dsIgnore, dsAbort, dsCustom); TSprig = class(TInformant) private FRoot: TRootSprig; FParent: TSprig; FList: TObjectList; FItem: TPersistent; FTreeNode: TTreeNode; FImageIndex: TImageIndex; FCaption: string; FExpanded, FInvalid, FCollectionsDone, FHidden, FHiddenTested: Boolean; procedure SetExpanded(const Value: Boolean); protected function GetItem(Index: Integer): TSprig; function UniqueName: string; virtual; function CaptionFor(const AName: string; const ALabel: string = ''; const AClass: string = ''): string; procedure ReparentChildren; procedure SelectItems(const AItems: array of TPersistent; ARuntimeChange: Boolean = True); virtual; procedure RuntimeChange; virtual; procedure DesigntimeChange; virtual; function FindItem(AItem: TPersistent; Recurse: Boolean): TSprig; virtual; function FindItemByName(const AName: string; AClass: TClass; Recurse: Boolean): TSprig; virtual; function FindItemByPath(const APath: string; Recurse: Boolean = True): TSprig; virtual; function GetDesigner(out ADesigner: IDesigner): Boolean; virtual; function GetImageIndex: TImageIndex; virtual; procedure SetImageIndex(const Value: TImageIndex); virtual; function GetStateIndex: TImageIndex; virtual; procedure BeginUpdate; virtual; procedure EnsureUpdate; virtual; procedure EndUpdate; virtual; function GetAddType(Index: Integer): string; virtual; public constructor Create(AItem: TPersistent); overload; virtual; destructor Destroy; override; procedure Invalidate; function Transient: Boolean; virtual; function AnyProblems: Boolean; virtual; property Invalid: Boolean read FInvalid; property Item: TPersistent read FItem; function Hidden: Boolean; virtual; function Ghosted: Boolean; virtual; function FocusItem: TPersistent; virtual; function ItemClass: TClass; virtual; function Owner: TSprig; virtual; procedure VisualRefresh; virtual; function TreeNodeFor(ATreeView: TCustomTreeView): TTreeNode; virtual; property TreeNode: TTreeNode read FTreeNode; property Expanded: Boolean read FExpanded write SetExpanded; property ImageIndex: TImageIndex read GetImageIndex write SetImageIndex; property StateIndex: TImageIndex read GetStateIndex; procedure ClearTreeNode; overload; procedure ClearTreeNode(ARecurse: Boolean; AFreeNode: Boolean = True); overload; function Name: string; virtual; function Caption: string; virtual; function Hint: string; virtual; procedure PrepareMenu(const AItems: IMenuItems); virtual; function ShowRegisteredMenus: Boolean; virtual; function DragClass: TClass; function DragOver(AItem: TSprig): Boolean; virtual; function DragOverTo(AParent: TSprig): Boolean; virtual; function DragDrop(AItem: TSprig): Boolean; virtual; function DragDropTo(AParent: TSprig): Boolean; virtual; function PaletteOver(ASprigClass: TSprigClass; AClass: TClass): Boolean; virtual; class function PaletteOverTo(AParent: TSprig; AClass: TClass): Boolean; virtual; function Add(AItem: TSprig): TSprig; function Find(AItem: TPersistent; Recurse: Boolean = True): TSprig; overload; function Find(const AName: string; Recurse: Boolean = True): TSprig; overload; function Find(const AName: string; AClass: TClass; Recurse: Boolean = True): TSprig; overload; function FindPath(const APath: string; Recurse: Boolean = True): TSprig; function IndexOf(AItem: TSprig): Integer; procedure ForEach(ABefore: TSprigAction; AAfter: TSprigAction = nil); procedure ClearUnneededSprigs; function DeleteStyle: TSprigDeleteStyle; virtual; function CustomDelete: Boolean; virtual; function CanMove(AUp: Boolean): Boolean; virtual; function Move(AUp: Boolean): Boolean; virtual; function CanAdd: Boolean; virtual; function AddTypeCount: Integer; virtual; property AddTypes[Index: Integer]: string read GetAddType; procedure AddType(Index: Integer); virtual; procedure SortItems; virtual; function SortByIndex: Boolean; virtual; function IncludeIndexInCaption: Boolean; virtual; function ItemIndex: Integer; virtual; function CopyGlyph(ABitmap: TBitmap): Boolean; virtual; property Root: TRootSprig read FRoot; property Parent: TSprig read FParent; function Parents(ASprig: TSprig): Boolean; function Path: string; property Items[Index: Integer]: TSprig read GetItem; default; function Count: Integer; function Index: Integer; procedure Reparent; virtual; function Construct(AClass: TComponentClass): TComponent; virtual; function SeekParent(AItem: TPersistent; Recurse: Boolean = True): TSprig; overload; function SeekParent(const AName: string; Recurse: Boolean = True): TSprig; overload; function SeekParent(const AName: string; AClass: TClass; Recurse: Boolean = True): TSprig; overload; class function ParentProperty: string; virtual; procedure FigureParent; virtual; procedure FigureChildren; virtual; end; // a sprig that represents something that doesn't actually exist TAbstractSprig = class(TSprig) public function Ghosted: Boolean; override; end; // an abstract sprig that only exists if it has children TTransientSprig = class(TAbstractSprig) public function Transient: Boolean; override; end; // collection variants of the above TAbstractCollectionSprig = class(TAbstractSprig) public constructor Create(AItem: TPersistent); override; end; TTransientCollectionSprig = class(TTransientSprig) public constructor Create(AItem: TPersistent); override; end; // a sprig that points to a persistent TPersistentSprig = class(TSprig) end; // a sprig that points to a component TComponentSprig = class(TPersistentSprig) private FOwner: TSprig; public constructor Create(AItem: TPersistent); override; constructor Create(AItem: TPersistent; AOwner: TSprig); overload; function UniqueName: string; override; function Owner: TSprig; override; //function ShowRegisteredMenus: Boolean; override; // TSprig's implimentation of FigureParent is TComponent aware end; TComponentSprigClass = class of TComponentSprig; TRootSprig = class(TPersistentSprig) private FIndex: TSprigIndex; FNamedItems, FPathedItems: TList; FRepopulating, FParentChanges: Boolean; FSprigDesigner: ISprigDesigner; FDesigner: IDesigner; FRepopulateNeeded: Boolean; FNeedUpdate: Boolean; FUpdateLocks: Integer; procedure ValidateParent(AItem: TSprig); procedure PreRefreshTreeView(AItem: TSprig); procedure PostRefreshTreeView(AItem: TSprig); procedure DepopulateTreeView(AItem: TSprig); procedure RestoreExpandState(AItem: TSprig); procedure StoreExpandState(AItem: TSprig); procedure SetSprigDesigner(const ASprigDesigner: ISprigDesigner); procedure SelectionSurvey(out ADeleteStyle: TSprigDeleteStyle; out AAllVisible: Boolean); protected function FindItem(AItem: TPersistent; Recurse: Boolean = True): TSprig; override; function FindItemByName(const AName: string; AClass: TClass; Recurse: Boolean): TSprig; override; function FindItemByPath(const APath: string; Recurse: Boolean = True): TSprig; override; procedure AddItem(ASprig: TSprig); procedure RemoveItem(ASprig: TSprig); function GetDesigner(out ADesigner: IDesigner): Boolean; override; function GetAddType(Index: Integer): String; override; function SelectedSprig(var ASprig: TSprig): Boolean; public constructor Create(AItem: TPersistent); override; destructor Destroy; override; procedure FigureParent; override; property SprigDesigner: ISprigDesigner read FSprigDesigner write SetSprigDesigner; property Designer: IDesigner read FDesigner write FDesigner; property Repopulating: Boolean read FRepopulating; function Repopulate: Boolean; function TreeView: TCustomTreeView; procedure RefreshTreeView; procedure StoreTreeState; procedure BeginUpdate; override; procedure EnsureUpdate; override; procedure EndUpdate; override; procedure ItemDeleted(AItem: TPersistent); procedure ItemInserted; procedure ItemsModified(AForceRepopulate: Boolean = True); procedure RuntimeChange; override; procedure DesigntimeChange; override; procedure SelectItems(const AItems: array of TPersistent; ARuntimeChange: Boolean = True); override; // these are not used to operate on the root but its children function CanMove(AUp: Boolean): Boolean; override; function Move(AUp: Boolean): Boolean; override; function CanAdd: Boolean; override; procedure AddType(Index: Integer); override; function AddTypeCount: Integer; override; function EditAction(Action: TEditAction): Boolean; function GetEditState: TEditState; function DeleteStyle: TSprigDeleteStyle; override; function PaletteOver(ASprigClass: TSprigClass; AClass: TClass): Boolean; override; function AcceptsClass(AClass: TClass): Boolean; virtual; property RepopulateNeeded: Boolean read FRepopulateNeeded write FRepopulateNeeded; end; TSprigTreeNode = class(TTreeNode) public destructor Destroy; override; end; TSprigIndex = class(TObject) private FList: TObjectList; public constructor Create; destructor Destroy; override; procedure Add(ASprig: TSprig); procedure Remove(ASprig: TSprig); function Find(AItem: TPersistent): TSprig; end; TPropertySprig = class(TPersistentSprig) public function Ghosted: Boolean; override; function DeleteStyle: TSprigDeleteStyle; override; end; TCollectionSprig = class(TPropertySprig) private FPropName: string; FOwner: TSprig; protected function GetAddType(Index: Integer): string; override; public constructor Create(AItem: TPersistent); override; function Name: string; override; function Caption: string; override; procedure FigureParent; override; procedure FigureChildren; override; function Owner: TSprig; override; function SortByIndex: Boolean; override; procedure AddType(Index: Integer); override; function AddTypeCount: Integer; override; function DeleteStyle: TSprigDeleteStyle; override; function CustomDelete: Boolean; override; end; TCollectionItemSprig = class(TPersistentSprig) private FOwner: TSprig; protected function GetAddType(Index: Integer): string; override; public function Name: string; override; procedure FigureParent; override; function Owner: TSprig; override; function Ghosted: Boolean; override; function ItemIndex: Integer; override; function IncludeIndexInCaption: Boolean; override; function DragOverTo(AParent: TSprig): Boolean; override; function DragDropTo(AParent: TSprig): Boolean; override; procedure AddType(Index: Integer); override; function AddTypeCount: Integer; override; end; TSprigType = class(TObject) private FGroup: Integer; FClass: TClass; FSprigClass: TSprigClass; public constructor Create(const AClass: TClass; const ASprigClass: TSprigClass); function Score(const AClass: TClass): Integer; property SprigClass: TSprigClass read FSprigClass; end; TGUIDArray = array of TGUID; TSprigIntfType = class(TObject) private FGroup: Integer; FInterfaces: TGUIDArray; FSprigClass: TSprigClass; public constructor Create(const AInterfaces: TGUIDArray; const ASprigClass: TSprigClass); function Match(const AClass: TClass): Boolean; property SprigClass: TSprigClass read FSprigClass; end; TSprigTypeList = class(TObject) private FList: TObjectList; FLastClass: TClass; FLastSprigClass: TSprigClass; FInterfaceList: TObjectList; protected procedure ClearCache; function MatchCache(const AClass: TClass): TSprigClass; function MatchClass(const AClass: TClass): TSprigClass; public constructor Create; destructor Destroy; override; function Match(const AClass: TClass): TSprigClass; procedure Add(const AClass: TClass; const ASprigClass: TSprigClass); overload; procedure Add(const AInterfaces: TGUIDArray; const ASprigClass: TSprigClass); overload; procedure FreeEditorGroup(AGroup: Integer); end; TDragSprigs = class(TDragControlObjectEx) private FSprigs: TList; function GetSprig(Index: Integer): TSprig; public constructor Create(AControl: TControl); override; destructor Destroy; override; procedure Add(ASprig: TSprig); function Count: Integer; property Sprigs[Index: Integer]: TSprig read GetSprig; end; procedure RegisterSprigType(const AClass: TClass; ASprigClass: TSprigClass); overload; procedure RegisterSprigType(const AInterfaces: TGUIDArray; ASprigClass: TSprigClass); overload; function FindBestSprigClass(AClass: TClass): TSprigClass; overload; function FindBestSprigClass(AClass: TClass; AMinimumSprigClass: TSprigClass): TSprigClass; overload; procedure RegisterRootSprigType(const AClass: TClass; ASprigClass: TRootSprigClass); overload; procedure RegisterRootSprigType(const AInterfaces: TGUIDArray; ASprigClass: TRootSprigClass); overload; function FindBestRootSprigClass(AClass: TClass): TRootSprigClass; overload; function FindBestRootSprigClass(AClass: TClass; AMinimumSprigClass: TRootSprigClass): TRootSprigClass; overload; var GShowClassNameInTreeView: Boolean = False; const CFakeSprigImage = 0; CFakeCollectionSprigImage = 1; CPersistentSprigImage = 2; CCollectionSprigImage = 3; CComponentSprigImage = 4; CDataModuleSprigImage = 5; CControlSprigImage = 6; CUIControlSprigImage = 7; CUIContainerSprigImage = 8; CFormSprigImage = 9; CGhostedOffset = 10; CNoStateImage = 0; CCheckOutStateImage = 1; CCollectionName = '<Collection.%s>'; // DO NOT LOCALIZE const CUIControlImageIndex: array [Boolean] of Integer = (CUIControlSprigImage, CUIContainerSprigImage); type TRootSprigList = class(TObject) private FList: TBucketList; public constructor Create; destructor Destroy; override; function FindRoot(const ADesigner: IDesigner; out ARootSprig: TRootSprig): Boolean; procedure DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean); procedure DesignerOpened(const ADesigner: IDesigner; AResurrecting: Boolean); procedure ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent); procedure ItemInserted(const ADesigner: IDesigner; AItem: TPersistent); procedure ItemsModified(const ADesigner: IDesigner); end; function RootSprigList: TRootSprigList; type TCopySprigGlyphFunc = function(ASprig: TSprig; ABitmap: TBitmap): Boolean of object; var CopySprigGlyphFunc: TCopySprigGlyphFunc; implementation uses DesignConst; var InternalSprigTypeList: TSprigTypeList = nil; InternalRootSprigTypeList: TSprigTypeList = nil; procedure RegisterSprigType(const AClass: TClass; ASprigClass: TSprigClass); begin if InternalSprigTypeList = nil then InternalSprigTypeList := TSprigTypeList.Create; InternalSprigTypeList.Add(AClass, ASprigClass); end; procedure RegisterSprigType(const AInterfaces: TGUIDArray; ASprigClass: TSprigClass); begin if InternalSprigTypeList = nil then InternalSprigTypeList := TSprigTypeList.Create; InternalSprigTypeList.Add(AInterfaces, ASprigClass); end; function FindBestSprigClass(AClass: TClass): TSprigClass; begin Result := FindBestSprigClass(AClass, TSprig); end; function FindBestSprigClass(AClass: TClass; AMinimumSprigClass: TSprigClass): TSprigClass; begin Result := nil; if InternalSprigTypeList <> nil then begin Result := InternalSprigTypeList.Match(AClass); if (Result <> nil) and not Result.InheritsFrom(AMinimumSprigClass) then Result := nil; end; end; procedure RegisterRootSprigType(const AClass: TClass; ASprigClass: TRootSprigClass); begin if InternalRootSprigTypeList = nil then InternalRootSprigTypeList := TSprigTypeList.Create; InternalRootSprigTypeList.Add(AClass, ASprigClass); end; procedure RegisterRootSprigType(const AInterfaces: TGUIDArray; ASprigClass: TRootSprigClass); begin if InternalRootSprigTypeList = nil then InternalRootSprigTypeList := TSprigTypeList.Create; InternalRootSprigTypeList.Add(AInterfaces, ASprigClass); end; function FindBestRootSprigClass(AClass: TClass): TRootSprigClass; begin Result := FindBestRootSprigClass(AClass, TRootSprig); end; function FindBestRootSprigClass(AClass: TClass; AMinimumSprigClass: TRootSprigClass): TRootSprigClass; begin Result := nil; if InternalRootSprigTypeList <> nil then begin Result := TRootSprigClass(InternalRootSprigTypeList.Match(AClass)); if (Result <> nil) and not Result.InheritsFrom(AMinimumSprigClass) then Result := nil; end; end; procedure FlushSprigTypes(AGroup: Integer); begin if InternalRootSprigTypeList <> nil then InternalRootSprigTypeList.FreeEditorGroup(AGroup); if InternalSprigTypeList <> nil then InternalSprigTypeList.FreeEditorGroup(AGroup); end; { TInformant } procedure TInformant.BeforeDestruction; begin FDestroying := True; Notification; inherited; end; procedure TInformant.Changed(AObj: TInformant); begin if AObj.Destroying then AObj.Unnotify(Self); end; destructor TInformant.Destroy; begin FreeAndNil(FNotifyList); inherited; end; procedure TInformant.DisableNotify; begin Inc(FDisableNotify); end; procedure TInformant.EnableNotify; begin Dec(FDisableNotify); if (FDisableNotify = 0) and FNotifyNeeded then Notification; end; procedure TInformant.Notification; var I: Integer; begin if (FDisableNotify = 0) and (FNotifyList <> nil) then begin for I := FNotifyList.Count - 1 downto 0 do TInformant(FNotifyList[I]).Changed(Self); FNotifyNeeded := False; end else FNotifyNeeded := True; end; procedure TInformant.Notify(AObj: TInformant); begin if FNotifyList = nil then FNotifyList := TList.Create; if FNotifyList.IndexOf(AObj) = -1 then begin FNotifyList.Add(AObj); AObj.Notify(Self); end; end; procedure TInformant.Unnotify(AObj: TInformant); var I: Integer; begin if FNotifyList <> nil then begin I := FNotifyList.IndexOf(AObj); if I <> -1 then begin FNotifyList.Delete(I); AObj.Unnotify(Self); end; if (FNotifyList <> nil) and (FNotifyList.Count = 0) then FreeAndNil(FNotifyList); end; end; { TSprig } function TSprig.Add(AItem: TSprig): TSprig; begin // hey is it already in us? if (AItem.Parent <> Self) and (not AItem.Parents(Self)) then begin // remove the item from its old parent and clear any tree nodes it may have if (AItem.Parent <> nil) and (AItem.Parent.FList <> nil) then begin AItem.ClearTreeNode; AItem.Parent.FList.Extract(AItem); end; // make sure we have a list if not Assigned(FList) then FList := TObjectList.Create; // add it to our list FList.Add(AItem); // populate its parent AItem.FParent := Self; // populate the root? if AItem.Root = nil then begin AItem.FRoot := Root; // add it to the root's index? if Root <> nil then Root.AddItem(AItem); end; // we changed something! Root.FRepopulateNeeded := True; {AItem.FRoot := Root; if (AItem.Root = nil) and (Self is TRootSprig) then AItem.FRoot := TRootSprig(Self); // remove ourselve from the root index if AItem.FRoot <> nil then AItem.FRoot.FIndex.Add(Self);} end; // return it Result := AItem; end; function TSprig.AnyProblems: Boolean; var LProp: PPropInfo; begin Result := False; if ParentProperty <> '' then begin LProp := GetPropInfo(Item, ParentProperty, [tkClass]); Result := (LProp = nil) or (GetObjectProp(Item, LProp, TPersistent) = nil); end; end; function TSprig.Caption: string; begin Result := CaptionFor(Name); if IncludeIndexInCaption then Result := Format('%d - %s', [ItemIndex, Result]); // DO NOT LOCALIZE end; procedure TSprig.ClearTreeNode(ARecurse, AFreeNode: Boolean); var I: Integer; LNode: TTreeNode; begin EnsureUpdate; // first do our children if ARecurse then for I := Count - 1 downto 0 do Items[I].ClearTreeNode(True); // now do ourself if TreeNode <> nil then begin LNode := TreeNode; FTreeNode := nil; LNode.Data := nil; if AFreeNode and not (csDestroying in LNode.TreeView.ComponentState) then LNode.Delete; end; end; procedure TSprig.ClearTreeNode; begin ClearTreeNode(True, True); end; procedure TSprig.ClearUnneededSprigs; var I: Integer; begin for I := Count - 1 downto 0 do with Items[I] do begin ClearUnneededSprigs; if (Transient and (Count = 0)) or Invalid then Free; end; end; function TSprig.Count: Integer; begin Result := 0; if Assigned(FList) then Result := FList.Count; end; constructor TSprig.Create(AItem: TPersistent); const CImageIndex: array [Boolean] of TImageIndex = (CFakeSprigImage, CPersistentSprigImage); begin inherited Create; FItem := AItem; FHiddenTested := Item = nil; FHidden := Item = nil; ImageIndex := CImageIndex[Item <> nil]; end; destructor TSprig.Destroy; begin // just in case it hasn't happen already Invalidate; // we know nothing! FItem := nil; // remove ourselves from the tree ClearTreeNode(False); // remove ourselves from the parent if (Parent <> nil) and (Parent.FList <> nil) then Parent.FList.Extract(Self); FParent := nil; // wipe out the lists if FList <> nil then begin while FList.Count > 0 do FList.Last.Free; FreeAndNil(FList); end; // remove ourselves inherited; end; function TSprig.DragClass: TClass; begin if Item <> nil then Result := Item.ClassType else Result := ClassType; end; function TSprig.DragDrop(AItem: TSprig): Boolean; begin Result := False; if Assigned(AItem) then Result := AItem.DragDropTo(Self); end; function TSprig.DragDropTo(AParent: TSprig): Boolean; var LProp: PPropInfo; begin Result := False; if (ParentProperty <> '') and (AParent <> Parent) then begin LProp := GetPropInfo(Item, ParentProperty, [tkClass]); if LProp <> nil then begin if AParent is TRootSprig then SetObjectProp(Item, LProp, nil) else SetObjectProp(Item, LProp, AParent.Item); Result := True; end; end; end; function TSprig.DragOver(AItem: TSprig): Boolean; begin Result := False; if AItem <> nil then Result := AItem.DragOverTo(Self); end; function TSprig.DragOverTo(AParent: TSprig): Boolean; var LProp: PPropInfo; begin Result := False; if ParentProperty <> '' then begin LProp := GetPropInfo(Item, ParentProperty, [tkClass]); if LProp <> nil then Result := (AParent is TRootSprig) or (AParent.Item is GetTypeData(LProp^.PropType^)^.ClassType); end; end; function TSprig.Find(AItem: TPersistent; Recurse: Boolean): TSprig; begin Result := FindItem(AItem, Recurse); end; function TSprig.FindItem(AItem: TPersistent; Recurse: Boolean): TSprig; var I: Integer; LItem: TSprig; begin Result := nil; if AItem <> nil then if AItem = Item then Result := Self else for I := 0 to Count - 1 do begin LItem := Items[I]; if LItem.Item = AItem then begin Result := LItem; Break; end else if Recurse then begin Result := LItem.FindItem(AItem, True); if Result <> nil then Break; end; end; end; function TSprig.Find(const AName: string; Recurse: Boolean): TSprig; begin Result := FindItemByName(AName, nil, Recurse); end; function TSprig.Find(const AName: string; AClass: TClass; Recurse: Boolean): TSprig; begin Result := FindItemByName(AName, AClass, Recurse); end; function TSprig.FindItemByName(const AName: string; AClass: TClass; Recurse: Boolean): TSprig; var I: Integer; LItem: TSprig; begin Result := nil; if AName <> '' then // if class is nil then just check name if AClass = nil then begin if AnsiSameText(Name, AName) then Result := Self else for I := 0 to Count - 1 do begin LItem := Items[I]; if AnsiSameText(LItem.Name, AName) then begin Result := LItem; Break; end else if Recurse then begin Result := LItem.FindItemByName(AName, nil, True); if Result <> nil then Break; end; end; end // use both name and class then else begin if (Item is AClass) and AnsiSameText(Name, AName) then Result := Self else for I := 0 to Count - 1 do begin LItem := Items[I]; if (LItem.Item is AClass) and AnsiSameText(LItem.Name, AName) then begin Result := LItem; Break; end else if Recurse then begin Result := LItem.FindItemByName(AName, AClass, True); if Result <> nil then Break; end; end; end; end; function TSprig.FindPath(const APath: string; Recurse: Boolean): TSprig; begin Result := FindItemByPath(APath, Recurse); end; function TSprig.FindItemByPath(const APath: string; Recurse: Boolean = True): TSprig; var I: Integer; LItem: TSprig; begin Result := nil; if APath <> '' then if AnsiSameText(Path, APath) then Result := Self else for I := 0 to Count - 1 do begin LItem := Items[I]; if AnsiSameText(LItem.Path, APath) then begin Result := LItem; Break; end else if Recurse then begin Result := LItem.FindPath(APath, True); if Result <> nil then Break; end; end; end; procedure TSprig.ForEach(ABefore, AAfter: TSprigAction); var I: Integer; begin if not Invalid then begin if Assigned(ABefore) then ABefore(Self); for I := Count - 1 downto 0 do Items[I].ForEach(ABefore, AAfter); if Assigned(AAfter) then AAfter(Self); end; end; function TSprig.GetItem(Index: Integer): TSprig; begin Result := nil; if Assigned(FList) then Result := TSprig(FList[Index]); end; function TSprig.Hint: string; begin Result := ''; end; function TSprig.Index: Integer; begin Result := -1; if Parent <> nil then Result := Parent.IndexOf(Self); end; function TSprig.IndexOf(AItem: TSprig): Integer; begin Result := -1; if Assigned(FList) then Result := FList.IndexOf(AItem); end; function TSprig.UniqueName: string; begin Result := ''; if Item <> nil then Result := Item.GetNamePath; end; function TSprig.Name: string; begin Result := UniqueName; end; procedure TSprig.PrepareMenu(const AItems: IMenuItems); begin // end; function TSprig.SeekParent(AItem: TPersistent; Recurse: Boolean): TSprig; begin Result := nil; if AItem <> nil then begin if (Parent <> nil) and (Parent.Item = AItem) then Result := Parent else if Owner <> nil then Result := Owner.Find(AItem, Recurse); if Result = nil then begin if Root <> nil then Result := Root.Find(AItem, Recurse); if Result = nil then Result := Root; end; end else Result := Root; end; function TSprig.SeekParent(const AName: string; Recurse: Boolean): TSprig; begin Result := nil; if AName <> '' then begin if (Parent <> nil) and AnsiSameText(Parent.Name, AName) then Result := Parent else if Owner <> nil then Result := Owner.Find(AName, Recurse); if Result = nil then begin if Root <> nil then Result := Root.Find(AName, Recurse); if Result = nil then Result := Root; end; end else Result := Root; end; function TSprig.SeekParent(const AName: string; AClass: TClass; Recurse: Boolean): TSprig; begin Result := Root; if (AName <> '') and (AClass <> nil) then begin if (Parent <> nil) and (Parent.Item <> nil) and (Parent.Item is AClass) and AnsiSameText(Parent.Name, AName) then Result := Parent else if Owner <> nil then Result := Owner.Find(AName, AClass, Recurse); if Result = nil then begin if Root <> nil then Result := Root.Find(AName, AClass, Recurse); if Result = nil then Result := Root; end; end else Result := Root; end; function TSprig.Transient: Boolean; begin Result := False; end; type THackTreeView = class(TCustomTreeView) end; function TSprig.TreeNodeFor(ATreeView: TCustomTreeView): TTreeNode; var LParent: TTreeNode; begin if TreeNode = nil then begin EnsureUpdate; LParent := nil; if Parent <> nil then LParent := Parent.TreeNode; FTreeNode := THackTreeView(ATreeView).Items.AddNode( TSprigTreeNode.Create(THackTreeView(ATreeView).Items), LParent, Caption, Self, naAddChild); //FTreeNode := THackTreeView(ATreeView).Items.AddChildObject(LParent, Caption, Self); end; Result := TreeNode; end; procedure TSprig.VisualRefresh; function Trimmed(const AText: string): string; begin if Length(AText) >= 80 then Result := Copy(AText, 1, 76) + '... ' { Do not localize } else Result := AText; end; begin if TreeNode <> nil then with TreeNode do begin if Self.FCaption <> Self.Caption then Self.FCaption := Trimmed(Self.Caption); Text := Self.FCaption; ImageIndex := Self.ImageIndex; SelectedIndex := Self.ImageIndex; StateIndex := Self.StateIndex; //HasChildren := Self.Count > 0; end; end; function TSprig.CaptionFor(const AName, ALabel, AClass: string): string; begin Result := AName; if ALabel <> '' then begin if Result = '' then Result := '<?>'; // DO NOT LOCALIZE Result := Format('%s {%s}', [Result, ALabel]); // DO NOT LOCALIZE end; if GShowClassNameInTreeView then begin if AClass = '' then Result := Format('%s (%s)', [Result, AClass]) // DO NOT LOCALIZE else if Item <> nil then Result := Format('%s (%s)', [Result, Item.ClassName]); // DO NOT LOCALIZE end; end; function TSprig.PaletteOver(ASprigClass: TSprigClass; AClass: TClass): Boolean; begin Result := False; if ASprigClass <> nil then Result := ASprigClass.PaletteOverTo(Self, AClass); end; class function TSprig.PaletteOverTo(AParent: TSprig; AClass: TClass): Boolean; var LProp: PPropInfo; begin Result := False; if ParentProperty <> '' then begin LProp := GetPropInfo(AClass.ClassInfo, ParentProperty, [tkClass]); if LProp <> nil then Result := (AParent is TRootSprig) or (AParent.Item is GetTypeData(LProp^.PropType^)^.ClassType); end; end; function TSprig.Path: string; begin Result := UniqueName; if Parent <> nil then Result := Format('%s\%s', [Parent.Path, Result]); // DO NOT LOCALIZE end; function TSprig.DeleteStyle: TSprigDeleteStyle; const cDeleteStyle: array [Boolean] of TSprigDeleteStyle = (dsAbort, dsNormal); begin Result := cDeleteStyle[Item <> nil]; end; function TSprig.CustomDelete: Boolean; begin Result := False; end; function TSprig.ItemClass: TClass; begin Result := nil; if Item <> nil then Result := Item.ClassType; end; class function TSprig.ParentProperty: string; begin Result := ''; end; procedure TSprig.FigureParent; var LProp: PPropInfo; LParentItem: TPersistent; begin // assume nowhere! LParentItem := nil; // if we actually point to something if Item <> nil then begin // parent property based? if ParentProperty <> '' then begin LProp := GetPropInfo(Item, ParentProperty, [tkClass]); if LProp <> nil then LParentItem := TPersistent(GetObjectProp(Item, LProp, TPersistent)); end; // still nothing but we have a component if (LParentItem = nil) and (Item is TComponent) then LParentItem := TComponent(Item).GetParentComponent; end; // plug in! if LParentItem <> nil then SeekParent(LParentItem).Add(Self) else if Owner <> nil then Owner.Add(Self) else Root.Add(Self); end; procedure TSprig.FigureChildren; var LProps: TPropList; LProp: TObject; LPropCount, I: Integer; LParent: TSprig; LParentClass: TSprigClass; begin // something to do? if (Item <> nil) and not FCollectionsDone then begin FCollectionsDone := True; // grab the list of properties LPropCount := GetPropList(Item.ClassInfo, [tkClass], @LProps); // we need to make this a optimized as possible for I := 0 to LPropCount - 1 do begin // got a collection? LProp := TObject(GetOrdProp(Item, LProps[I])); if (LProp is TCollection) and (GetUltimateOwner(TCollection(LProp)) <> nil) then begin // does it exists already? LParent := Find(TCollection(LProp), False); if LParent = nil then begin LParentClass := FindBestSprigClass(TCollection(LProp).ClassType, TCollectionSprig); if LParentClass <> nil then begin LParent := LParentClass.Create(TCollection(LProp)); TCollectionSprig(LParent).FPropName := LProps[I].Name; TCollectionSprig(LParent).FOwner := Self; // made some additions Add(LParent); end; end; end; end; end; end; function TSprig.FocusItem: TPersistent; begin Result := Item; if (Result = nil) and (Parent <> nil) then Result := Parent.FocusItem; end; function SortBySprigItemIndex(Node1, Node2: TTreeNode; lParam: Integer): Integer; stdcall; begin Result := TSprig(Node1.Data).ItemIndex - TSprig(Node2.Data).ItemIndex; end; procedure TSprig.SortItems; begin if (TreeNode <> nil) and (TreeNode.HasChildren) then if SortByIndex then TreeNode.CustomSort(@SortBySprigItemIndex, 0) else TreeNode.CustomSort(nil, 0); end; function TSprig.SortByIndex: Boolean; begin Result := False; end; function TSprig.ItemIndex: Integer; begin Result := 0; end; procedure TSprig.Reparent; begin // we don't care end; function TSprig.ShowRegisteredMenus: Boolean; begin Result := Item <> nil; end; procedure TSprig.ReparentChildren; var I: Integer; begin for I := Count - 1 downto 0 do Items[I].Reparent; end; function TSprig.IncludeIndexInCaption: Boolean; begin Result := False; end; procedure TSprig.SetExpanded(const Value: Boolean); begin if FExpanded <> Value then begin FExpanded := Value; if Expanded and (Parent <> nil) then Parent.Expanded := True; end; end; procedure TSprig.Invalidate; var I: Integer; begin if not Invalid then begin FInvalid := True; // remove ourselve from the root index if Root <> nil then Root.RemoveItem(Self); // don't point there anymore FItem := nil; for I := Count - 1 downto 0 do Items[I].Invalidate; end; end; procedure TSprig.SelectItems(const AItems: array of TPersistent; ARuntimeChange: Boolean); begin if Root <> nil then Root.SelectItems(AItems, ARuntimeChange); end; function TSprig.Parents(ASprig: TSprig): Boolean; begin repeat Result := ASprig = Self; ASprig := ASprig.Parent; until (Result = True) or (ASprig = nil); end; procedure TSprig.DesigntimeChange; begin if Root <> nil then Root.DesigntimeChange; end; procedure TSprig.RuntimeChange; begin if Root <> nil then Root.RuntimeChange; end; function TSprig.GetDesigner(out ADesigner: IDesigner): Boolean; begin if Root <> nil then Result := Root.GetDesigner(ADesigner) else Result := False; end; function TSprig.GetImageIndex: TImageIndex; begin Result := FImageIndex; if Ghosted then Inc(Result, CGhostedOffset); end; procedure TSprig.SetImageIndex(const Value: TImageIndex); begin FImageIndex := Value; end; function TSprig.GetStateIndex: TImageIndex; const CStateIndex: array [Boolean] of TImageIndex = (CNoStateImage, CCheckOutStateImage); begin Result := CStateIndex[AnyProblems]; end; function TSprig.Construct(AClass: TComponentClass): TComponent; var LDesigner: IDesigner; LParent: TPersistent; begin Result := nil; if (Item <> nil) and (Item is TComponent) then LParent := Item else if Owner <> nil then LParent := Owner.Item else LParent := Root.Item; if (LParent is TComponent) and GetDesigner(LDesigner) then Result := LDesigner.CreateComponent(AClass, TComponent(LParent), 0, 0, 0, 0); end; procedure TSprig.BeginUpdate; begin if Root <> nil then Root.BeginUpdate; end; procedure TSprig.EndUpdate; begin if Root <> nil then Root.EndUpdate; end; procedure TSprig.EnsureUpdate; begin if Root <> nil then Root.EnsureUpdate; end; function TSprig.Hidden: Boolean; var LDesigner: IDesigner; begin if not FHiddenTested and GetDesigner(LDesigner) then begin FHiddenTested := True; FHidden := not (Item is TComponent) or LDesigner.IsComponentHidden(TComponent(Item)); end; Result := FHidden; end; function TSprig.Ghosted: Boolean; begin Result := Hidden; end; function TSprig.CanMove(AUp: Boolean): Boolean; var LSibling: TSprig; begin Result := Assigned(Parent) and Parent.SortByIndex and Assigned(TreeNode) and Assigned(TreeNode.Parent); if Result then begin LSibling := nil; if AUp and (TreeNode.Index > 0) then LSibling := TSprig(TreeNode.Parent.Item[TreeNode.Index - 1].Data) else if not AUp and (TreeNode.Index < TreeNode.Parent.Count - 1) then LSibling := TSprig(TreeNode.Parent.Item[TreeNode.Index + 1].Data); Result := Assigned(LSibling) and LSibling.DragOver(Self) end; end; function TSprig.Move(AUp: Boolean): Boolean; var LSibling: TSprig; begin BeginUpdate; try if AUp then LSibling := TSprig(TreeNode.Parent.Item[TreeNode.Index - 1].Data) else LSibling := TSprig(TreeNode.Parent.Item[TreeNode.Index + 1].Data); Result := LSibling.DragDrop(Self); if Result then SelectItems([Item]); finally EndUpdate; end; end; procedure TSprig.AddType(Index: Integer); begin // end; function TSprig.AddTypeCount: Integer; begin Result := 0; end; function TSprig.CanAdd: Boolean; begin Result := AddTypeCount > 0; end; function TSprig.GetAddType(Index: Integer): string; begin Result := ''; end; function TSprig.Owner: TSprig; begin Result := nil; end; function TSprig.CopyGlyph(ABitmap: TBitmap): Boolean; begin Result := Assigned(CopySprigGlyphFunc) and CopySprigGlyphFunc(Self, ABitmap); end; { TRootSprig } procedure TRootSprig.AddItem(ASprig: TSprig); begin if ASprig.Item <> nil then FIndex.Add(ASprig); end; function TRootSprig.DeleteStyle: TSprigDeleteStyle; begin Result := dsAbort; end; procedure TRootSprig.SelectionSurvey(out ADeleteStyle: TSprigDeleteStyle; out AAllVisible: Boolean); var I: Integer; LSprig: TSprig; LAbort, LAllCustom, LAllNormal: Boolean; begin AAllVisible := True; LAbort := False; LAllCustom := True; LAllNormal := True; for I := 0 to TreeView.SelectionCount - 1 do begin LSprig := TSprig(TreeView.Selections[I].Data); if LSprig <> nil then begin // calculate if all are visible? AAllVisible := AAllVisible and not LSprig.Hidden; // calculate delete style case LSprig.DeleteStyle of dsNormal: LAllCustom := False; dsIgnore:; dsAbort: LAbort := True; dsCustom: LAllNormal := False; end; end; end; ADeleteStyle := dsAbort; if not LAbort then if LAllNormal then ADeleteStyle := dsNormal else if LAllCustom then ADeleteStyle := dsCustom; end; function TRootSprig.EditAction(Action: TEditAction): Boolean; function DoCustomDelete(out ASprig: TSprig): Boolean; var I: Integer; LSprig: TSprig; begin Result := False; ASprig := nil; for I := 0 to TreeView.SelectionCount - 1 do begin LSprig := TSprig(TreeView.Selections[I].Data); if LSprig <> nil then begin Result := LSprig.CustomDelete or Result; if not LSprig.Invalid then ASprig := LSprig; end; end; end; var LEditQuery: IDesignEditQuery; LDeleteStyle: TSprigDeleteStyle; LAllVisible: Boolean; LSprig: TSprig; begin Result := False; if Supports(Designer, IDesignEditQuery, LEditQuery) then begin // one we care about? if Action in [eaDelete, eaCut, eaCopy] then begin SelectionSurvey(LDeleteStyle, LAllVisible); // delete if Action = eaDelete then case LDeleteStyle of dsNormal: begin Designer.DeleteSelection(True); Result := True; end; dsCustom: begin Result := DoCustomDelete(LSprig); if Result then if (LSprig <> nil) and (LSprig.Item <> nil) then SelectItems([LSprig.Item], True) else RuntimeChange; end; else Result := False; end // cut/copy else if (LDeleteStyle = dsNormal) and LAllVisible then Result := LEditQuery.EditAction(Action); end else Result := LEditQuery.EditAction(Action); end; end; function TRootSprig.GetEditState: TEditState; var LEditQuery: IDesignEditQuery; LDeleteStyle: TSprigDeleteStyle; LAllVisible: Boolean; begin Result := []; if Supports(Designer, IDesignEditQuery, LEditQuery) then begin Result := LEditQuery.GetEditState; Result := Result - [esCanZOrder, esCanAlignGrid, esCanEditOle, esCanTabOrder, esCanCreationOrder, esCanCreateTemplate]; SelectionSurvey(LDeleteStyle, LAllVisible); if LDeleteStyle = dsAbort then Result := Result - [esCanDelete]; if not LAllVisible then Result := Result - [esCanCopy, esCanCut, esCanPaste]; end; end; function TRootSprig.SelectedSprig(var ASprig: TSprig): Boolean; begin Result := (TreeView <> nil) and (TreeView.SelectionCount = 1) and (TreeView.Selections[0].Data <> Self); if Result then ASprig := TSprig(TreeView.Selections[0].Data); end; function TRootSprig.CanMove(AUp: Boolean): Boolean; var LSprig: TSprig; begin Result := SelectedSprig(LSprig) and LSprig.CanMove(AUp); end; function TRootSprig.Move(AUp: Boolean): Boolean; var LSprig: TSprig; begin Result := SelectedSprig(LSprig) and LSprig.Move(AUp); end; procedure TRootSprig.AddType(Index: Integer); var LSprig: TSprig; begin if SelectedSprig(LSprig) then LSprig.AddType(Index); end; function TRootSprig.AddTypeCount: Integer; var LSprig: TSprig; begin Result := 0; if SelectedSprig(LSprig) then Result := LSprig.AddTypeCount; end; function TRootSprig.GetAddType(Index: Integer): String; var LSprig: TSprig; begin Result := ''; if SelectedSprig(LSprig) then Result := LSprig.GetAddType(Index); end; function TRootSprig.CanAdd: Boolean; var LSprig: TSprig; begin Result := SelectedSprig(LSprig) and LSprig.CanAdd; end; constructor TRootSprig.Create(AItem: TPersistent); begin inherited; FRoot := Self; FIndex := TSprigIndex.Create; FNamedItems := TList.Create; FPathedItems := TList.Create; FRepopulateNeeded := True; end; procedure TRootSprig.DesigntimeChange; {var LDesigner: IDesigner;} begin { if GetDesigner(LDesigner) then LDesigner.Modified;} //!! end; destructor TRootSprig.Destroy; begin SprigDesigner := nil; inherited; FreeAndNil(FIndex); FreeAndNil(FNamedItems); FreeAndNil(FPathedItems); end; procedure TRootSprig.FigureParent; begin // we do nothing end; function TRootSprig.FindItem(AItem: TPersistent; Recurse: Boolean): TSprig; begin if AItem = Item then Result := Self else if not Recurse then Result := inherited FindItem(AItem, False) else Result := FIndex.Find(AItem); end; function TRootSprig.FindItemByName(const AName: string; AClass: TClass; Recurse: Boolean): TSprig; function MatchingItem(ASprig: TSprig): Boolean; begin Result := AnsiSameText(ASprig.Name, AName) and ((AClass = nil) or (ASprig.Item is AClass)); end; var I: Integer; begin if MatchingItem(Self) then Result := Self else begin Result := nil; for I := 0 to FNamedItems.Count - 1 do if MatchingItem(TSprig(FNamedItems[I])) then begin Result := TSprig(FNamedItems[I]); Break; end; if Result = nil then begin Result := inherited FindItemByName(AName, AClass, Recurse); if Result <> nil then FNamedItems.Add(Result); end; end; end; function TRootSprig.FindItemByPath(const APath: string; Recurse: Boolean): TSprig; var I: Integer; begin if AnsiSameText(Path, APath) then Result := Self else begin Result := nil; for I := 0 to FPathedItems.Count - 1 do if AnsiSameText(TSprig(FPathedItems[I]).Path, APath) then begin Result := TSprig(FPathedItems[I]); Break; end; if Result = nil then begin Result := inherited FindItemByPath(APath, Recurse); if Result <> nil then FPathedItems.Add(Result); end; end; end; procedure TRootSprig.SelectItems(const AItems: array of TPersistent; ARuntimeChange: Boolean); var LDesigner: IDesigner; LSelections: IDesignerSelections; I: Integer; begin if GetDesigner(LDesigner) then begin if ARuntimeChange then LDesigner.Modified; LSelections := CreateSelectionlist; for I := Low(AItems) to High(AItems) do LSelections.Add(AItems[I]); LDesigner.SetSelections(LSelections); end; end; function TRootSprig.PaletteOver(ASprigClass: TSprigClass; AClass: TClass): Boolean; begin Result := True; end; procedure TRootSprig.RemoveItem(ASprig: TSprig); begin if ASprig.Item <> nil then FIndex.Remove(ASprig); FNamedItems.Remove(ASprig); FPathedItems.Remove(ASprig); end; procedure TRootSprig.ValidateParent(AItem: TSprig); var LParent: TSprig; begin if not AItem.Invalid then begin // figure out the parent LParent := AItem.Parent; AItem.FigureParent; FParentChanges := FParentChanges or (LParent <> AItem.Parent); // figure out the children AItem.FigureChildren; end; end; function TRootSprig.Repopulate: Boolean; var LToDo: TList; procedure ValidateSprigs(ASprig: TSprig); var I: Integer; begin // only if the sprig is valid if not ASprig.Invalid then begin // expando? StoreExpandState(ASprig); // remove it from the todo list? if ASprig.Item <> nil then LToDo.Remove(ASprig.Item); end; // now validate the children for I := ASprig.Count - 1 downto 0 do ValidateSprigs(ASprig[I]); // now the sprig itself if ASprig.Invalid then ASprig.Free; end; procedure RemoveInvalidSprigs(ASprig: TSprig); var I: Integer; begin for I := ASprig.Count - 1 downto 0 do RemoveInvalidSprigs(ASprig); if ASprig.Invalid then ASprig.Free; end; var I: Integer; LSprigClass: TSprigClass; LSprig: TSprig; LItem: TComponent; begin // assume no additions Result := False; if FRepopulateNeeded then begin BeginUpdate; FRepopulating := True; LToDo := TList.Create; try // For each component, add to the ToDo list with TComponent(Item) do for I := 0 to ComponentCount - 1 do begin LItem := Components[I]; if not (csTransient in LItem.ComponentStyle) and (csDesigning in LItem.ComponentState) and not (csDestroying in LItem.ComponentState) then LToDo.Add(Components[I]); end; // clear the invalid items ValidateSprigs(Self); // For each item in the ToDo list for I := 0 to LToDo.Count - 1 do begin // Find best sprig class LSprigClass := FindBestSprigClass(TComponent(LToDo[I]).ClassType, TComponentSprig); // Create the sprig at the root if LSprigClass <> nil then begin LSprig := LSprigClass.Create(TComponent(LToDo[I])); TComponentSprig(LSprig).FOwner := Self; // made some additions Add(LSprig); Result := True; end; end; // For each sprig until there are no more parent changes repeat FParentChanges := False; ForEach(ValidateParent); until not FParentChanges; // prune the tree of sprigs (transient or any remaining invalid ones ClearUnneededSprigs; // make sure we are expanded FExpanded := True; finally // clean up LToDo.Free; FRepopulateNeeded := False; FRepopulating := False; EndUpdate; end; end; end; procedure TRootSprig.RuntimeChange; var LDesigner: IDesigner; begin if GetDesigner(LDesigner) then LDesigner.Modified; end; procedure TRootSprig.PreRefreshTreeView(AItem: TSprig); begin with AItem do begin TreeNodeFor(TreeView); VisualRefresh; end; end; procedure TRootSprig.PostRefreshTreeView(AItem: TSprig); begin with AItem do begin SortItems; RestoreExpandState(AItem); end; end; procedure TRootSprig.RestoreExpandState(AItem: TSprig); {var I: Integer;} procedure MakeExpanded(ANode: TTreeNode); begin if ANode <> nil then begin if not ANode.Expanded then ANode.Expanded := True; MakeExpanded(ANode.Parent); end; end; begin if AItem.TreeNode <> nil then begin {if FExpandedItems.Count > 0 then begin I := FExpandedItems.IndexOf(AItem.Path); if I >= 0 then begin FExpandedItems.Delete(I); AItem.Expanded := True; end; end;} if AItem.Expanded or (AItem = Self) then MakeExpanded(AItem.TreeNode); end; end; procedure TRootSprig.StoreExpandState(AItem: TSprig); begin with AItem do Expanded := (TreeNode <> nil) and (TreeNode.Expanded) and (TreeNode.IsVisible); end; procedure TRootSprig.StoreTreeState; begin if TreeView <> nil then ForEach(StoreExpandState); end; procedure TRootSprig.DepopulateTreeView(AItem: TSprig); begin with AItem do begin Expanded := (TreeNode <> nil) and (TreeNode.Expanded) and (TreeNode.IsVisible); ClearTreeNode; end; end; procedure TRootSprig.RefreshTreeView; begin BeginUpdate; if RepopulateNeeded then Repopulate; if TreeView <> nil then ForEach(PreRefreshTreeView, PostRefreshTreeView); EndUpdate; end; function TRootSprig.GetDesigner(out ADesigner: IDesigner): Boolean; begin ADesigner := Designer; Result := ADesigner <> nil; end; procedure TRootSprig.ItemDeleted(AItem: TPersistent); var LSprig: TSprig; begin LSprig := Find(AItem); if (LSprig <> nil) and (LSprig <> Self) and (not LSprig.Invalid) then begin LSprig.Invalidate; FRepopulateNeeded := True; end; end; procedure TRootSprig.ItemInserted; begin FRepopulateNeeded := True; end; procedure TRootSprig.ItemsModified(AForceRepopulate: Boolean); begin if AForceRepopulate then FRepopulateNeeded := True; if SprigDesigner <> nil then begin SprigDesigner.BeforeItemsModified; try RefreshTreeView; finally SprigDesigner.AfterItemsModified; end; end; end; function TRootSprig.AcceptsClass(AClass: TClass): Boolean; begin Result := AClass.InheritsFrom(TComponent); end; procedure TRootSprig.BeginUpdate; begin Inc(FUpdateLocks); end; procedure TRootSprig.EndUpdate; begin if FUpdateLocks > 0 then begin Dec(FUpdateLocks); if (FUpdateLocks = 0) and (FNeedUpdate) then begin if TreeView <> nil then THackTreeView(TreeView).Items.EndUpdate; FNeedUpdate := False; end; end; end; procedure TRootSprig.EnsureUpdate; begin if (FUpdateLocks > 0) and (not FNeedUpdate) then begin if TreeView <> nil then THackTreeView(TreeView).Items.BeginUpdate; FNeedUpdate := True; end; end; procedure TRootSprig.SetSprigDesigner(const ASprigDesigner: ISprigDesigner); var LSprigDesigner: ISprigDesigner; begin if SprigDesigner <> nil then begin Assert(FUpdateLocks = 0); ForEach(nil, DepopulateTreeView); LSprigDesigner := SprigDesigner; FSprigDesigner := nil; LSprigDesigner.RootSprig := nil; //LSprigDesigner.Collection := nil; end; FSprigDesigner := ASprigDesigner; FUpdateLocks := 0; FNeedUpdate := False; if SprigDesigner <> nil then RefreshTreeView; end; function TRootSprig.TreeView: TCustomTreeView; begin Result := nil; if SprigDesigner <> nil then Result := SprigDesigner.GetTreeView; end; { TSprigType } constructor TSprigType.Create(const AClass: TClass; const ASprigClass: TSprigClass); begin inherited Create; FClass := AClass; FSprigClass := ASprigClass; FGroup := CurrentGroup; end; function TSprigType.Score(const AClass: TClass): Integer; begin Result := High(Integer); if AClass.InheritsFrom(FClass) then Result := CountGenerations(FClass, AClass); end; { TSprigIntfType } constructor TSprigIntfType.Create(const AInterfaces: TGUIDArray; const ASprigClass: TSprigClass); begin inherited Create; FInterfaces := AInterfaces; FSprigClass := ASprigClass; FGroup := CurrentGroup; end; function TSprigIntfType.Match(const AClass: TClass): Boolean; var I: Integer; begin for I := 0 to Length(FInterfaces) - 1 do if not Supports(AClass, FInterfaces[I]) then begin Result := False; Exit; end; Result := True; end; { TSprigTypeList } procedure TSprigTypeList.Add(const AClass: TClass; const ASprigClass: TSprigClass); begin FList.Insert(0, TSprigType.Create(AClass, ASprigClass)); end; procedure TSprigTypeList.Add(const AInterfaces: TGUIDArray; const ASprigClass: TSprigClass); begin FInterfaceList.Insert(0, TSprigIntfType.Create(AInterfaces, ASprigClass)); end; procedure TSprigTypeList.ClearCache; begin FLastClass := nil; FLastSprigClass := nil; end; constructor TSprigTypeList.Create; begin inherited; FList := TObjectList.Create; FInterfaceList := TObjectList.Create; end; destructor TSprigTypeList.Destroy; begin FList.Free; FInterfaceList.Free; inherited; end; procedure TSprigTypeList.FreeEditorGroup(AGroup: Integer); var I: Integer; begin ClearCache; for I := FList.Count - 1 downto 0 do if TSprigType(FList[I]).FGroup = AGroup then FList.Delete(I); for I := FInterfaceList.Count - 1 downto 0 do if TSprigIntfType(FInterfaceList[I]).FGroup = AGroup then FInterfaceList.Delete(I); end; function TSprigTypeList.Match(const AClass: TClass): TSprigClass; begin Result := MatchCache(AClass); if Result = nil then Result := MatchClass(AClass); end; function TSprigTypeList.MatchCache(const AClass: TClass): TSprigClass; begin Result := nil; if FLastClass = AClass then Result := FLastSprigClass; end; function TSprigTypeList.MatchClass(const AClass: TClass): TSprigClass; var I, LBestScore, LScore: Integer; begin Result := nil; for I := 0 to FInterfaceList.Count - 1 do if TSprigIntfType(FInterfaceList[I]).Match(AClass) then begin Result := TSprigIntfType(FInterfaceList[I]).SprigClass; Break; end; if Result = nil then begin LBestScore := High(Integer); for I := 0 to FList.Count - 1 do begin LScore := TSprigType(FList[I]).Score(AClass); if LScore < LBestScore then begin LBestScore := LScore; Result := TSprigType(FList[I]).SprigClass; end; end; end; if Result <> nil then begin FLastClass := AClass; FLastSprigClass := Result; end; end; { TDragSprig } procedure TDragSprigs.Add(ASprig: TSprig); begin FSprigs.Add(ASprig); end; constructor TDragSprigs.Create(AControl: TControl); begin inherited Create(AControl); FSprigs := TList.Create; end; destructor TDragSprigs.Destroy; begin FSprigs.Free; inherited; end; function TDragSprigs.GetSprig(Index: Integer): TSprig; begin Result := TSprig(FSprigs[Index]); end; function TDragSprigs.Count: Integer; begin Result := FSprigs.Count; end; { TPropertySprig } function TPropertySprig.DeleteStyle: TSprigDeleteStyle; begin Result := dsAbort; end; function TPropertySprig.Ghosted: Boolean; begin Result := False; end; { TCollectionSprig } function TCollectionSprig.DeleteStyle: TSprigDeleteStyle; begin Result := dsCustom; end; function TCollectionSprig.CustomDelete: Boolean; begin Result := TCollection(Item).Count > 0; if Result then TCollection(Item).Clear; end; function TCollectionSprig.Caption: string; begin Result := CaptionFor(FPropName); end; procedure TCollectionSprig.FigureParent; begin SeekParent(FOwner.Item); end; function TCollectionSprig.SortByIndex: Boolean; begin Result := True; end; function TCollectionSprig.Name: string; begin Result := Format(CCollectionName, [FPropName]); end; constructor TCollectionSprig.Create(AItem: TPersistent); begin inherited; ImageIndex := CCollectionSprigImage; end; procedure TCollectionSprig.AddType(Index: Integer); begin SelectItems([TCollection(Item).Add]); end; function TCollectionSprig.AddTypeCount: Integer; begin Result := 1; end; resourcestring sAddCaption = 'Add item'; function TCollectionSprig.GetAddType(Index: Integer): string; begin case Index of 0: Result := sAddCaption; end; end; function TCollectionSprig.Owner: TSprig; begin Result := FOwner; end; procedure TCollectionSprig.FigureChildren; var I: Integer; LChildItem: TCollectionItem; LChild: TSprig; LChildClass: TSprigClass; begin // let it go first inherited; // now lets loop through the component items for I := 0 to TCollection(Item).Count - 1 do begin // find the best class LChildItem := TCollection(Item).Items[I]; LChild := Find(LChildItem, False); // if not then create it if LChild = nil then begin LChildClass := FindBestSprigClass(LChildItem.ClassType, TCollectionItemSprig); if LChildClass <> nil then begin LChild := LChildClass.Create(LChildItem); TCollectionItemSprig(LChild).FOwner := Self; // made some additions Add(LChild); end; end; end; end; { TCollectionItemSprig } procedure TCollectionItemSprig.FigureParent; begin SeekParent(FOwner.Item); end; function TCollectionItemSprig.Name: string; begin Result := TCollectionItem(Item).DisplayName; end; function TCollectionItemSprig.ItemIndex: Integer; begin Result := TCollectionItem(Item).Index; end; function TCollectionItemSprig.DragDropTo(AParent: TSprig): Boolean; var LOrigIndex: Integer; begin LOrigIndex := ItemIndex; if AParent.Parent = Parent then TCollectionItem(Item).Index := TCollectionItem(AParent.Item).Index; Result := LOrigIndex <> ItemIndex; end; function TCollectionItemSprig.DragOverTo(AParent: TSprig): Boolean; begin Result := AParent.Parent = Parent; end; function TCollectionItemSprig.IncludeIndexInCaption: Boolean; begin Result := True; end; procedure TCollectionItemSprig.AddType(Index: Integer); begin Parent.AddType(Index); end; function TCollectionItemSprig.AddTypeCount: Integer; begin Result := Parent.AddTypeCount; end; function TCollectionItemSprig.GetAddType(Index: Integer): string; begin Result := Parent.AddTypes[Index]; end; function TCollectionItemSprig.Owner: TSprig; begin Result := FOwner; end; function TCollectionItemSprig.Ghosted: Boolean; begin Result := False; end; { TSprigIndex } procedure TSprigIndex.Add(ASprig: TSprig); var I, L: Integer; begin L := WordRec(LongRec(ASprig.Item).Lo).Hi; // grab xxxxLLxx byte if FList[L] = nil then FList[L] := TList.Create; for I := 0 to TList(FList[L]).Count - 1 do if TList(FList[L]).Items[I] = ASprig then Assert(False); TList(FList[L]).Add(ASprig); end; constructor TSprigIndex.Create; begin inherited; FList := TObjectList.Create; FList.Count := 256; end; destructor TSprigIndex.Destroy; begin FList.Free; inherited; end; function TSprigIndex.Find(AItem: TPersistent): TSprig; var I, L: Integer; begin Result := nil; L := WordRec(LongRec(AItem).Lo).Hi; // grab xxxxLLxx byte if FList[L] <> nil then for I := 0 to TList(FList[L]).Count - 1 do if TSprig(TList(FList[L]).Items[I]).Item = AItem then begin Result := TSprig(TList(FList[L]).Items[I]); Break; end; end; procedure TSprigIndex.Remove(ASprig: TSprig); var I, L: Integer; begin L := WordRec(LongRec(ASprig.Item).Lo).Hi; // grab xxxxLLxx byte if FList[L] <> nil then begin for I := 0 to TList(FList[L]).Count - 1 do if TList(FList[L]).Items[I] = ASprig then begin TList(FList[L]).Delete(I); Break; end; if TList(FList[L]).Count = 0 then FList[L] := nil; // this will free and nil the sub-list reference end; end; { TSprigTreeNode } destructor TSprigTreeNode.Destroy; begin if Data <> nil then TSprig(Data).ClearTreeNode(True, False); inherited; end; { TComponentSprig } constructor TComponentSprig.Create(AItem: TPersistent); begin inherited; ImageIndex := CComponentSprigImage; end; constructor TComponentSprig.Create(AItem: TPersistent; AOwner: TSprig); begin Create(AItem); FOwner := AOwner; end; resourcestring SUnnamedItemCaption = '<Components[%d]>'; //function TComponentSprig.ShowRegisteredMenus: Boolean; //begin // Result := not Hidden; //end; function TComponentSprig.Owner: TSprig; begin Result := FOwner; end; function TComponentSprig.UniqueName: string; begin if Item <> nil then begin Result := TComponent(Item).Name; if Result = '' then Result := Format(SUnnamedItemCaption, [TComponent(Item).ComponentIndex]); end else Result := inherited UniqueName; end; { TAbstractSprig } function TAbstractSprig.Ghosted: Boolean; begin Result := False; end; { TTransientSprig } function TTransientSprig.Transient: Boolean; begin Result := True; end; { TAbstractCollectionSprig } constructor TAbstractCollectionSprig.Create(AItem: TPersistent); begin inherited; ImageIndex := CFakeCollectionSprigImage; end; { TTransientCollectionSprig } constructor TTransientCollectionSprig.Create(AItem: TPersistent); begin inherited; ImageIndex := CFakeCollectionSprigImage; end; { RootSprigList support } var InternalRootSprigList: TRootSprigList = nil; function RootSprigList: TRootSprigList; begin if InternalRootSprigList = nil then InternalRootSprigList := TRootSprigList.Create; Result := InternalRootSprigList; end; { TRootSprigList } constructor TRootSprigList.Create; begin inherited; FList := TBucketList.Create; end; procedure TRootSprigList.DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean); var LRootSprig: Pointer; LRoot: TComponent; begin if ADesigner <> nil then begin LRoot := ADesigner.Root; if FList.Find(LRoot, LRootSprig) then begin FList.Remove(LRoot); TRootSprig(LRootSprig).Designer := nil; TRootSprig(LRootSprig).SprigDesigner := nil; FreeAndNil(LRootSprig); end; end; end; procedure TRootSprigList.DesignerOpened(const ADesigner: IDesigner; AResurrecting: Boolean); var LRoot: TComponent; LRootSprigClass: TRootSprigClass; LRootSprig: TRootSprig; begin if ADesigner <> nil then begin LRoot := ADesigner.Root; if not FList.Exists(LRoot) then begin LRootSprigClass := FindBestRootSprigClass(LRoot.ClassType); LRootSprig := LRootSprigClass.Create(LRoot); LRootSprig.Designer := ADesigner; FList.Add(LRoot, LRootSprig); end; end; end; destructor TRootSprigList.Destroy; begin FreeAndNil(FList); inherited; end; function TRootSprigList.FindRoot(const ADesigner: IDesigner; out ARootSprig: TRootSprig): Boolean; var LRootSprig: Pointer; begin Result := (ADesigner <> nil) and FList.Find(ADesigner.Root, LRootSprig); if Result then ARootSprig := TRootSprig(LRootSprig); end; procedure TRootSprigList.ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent); var LRootSprig: TRootSprig; begin if FindRoot(ADesigner, LRootSprig) then LRootSprig.ItemDeleted(AItem); end; procedure TRootSprigList.ItemInserted(const ADesigner: IDesigner; AItem: TPersistent); var LRootSprig: TRootSprig; begin if FindRoot(ADesigner, LRootSprig) then LRootSprig.ItemInserted; end; procedure TRootSprigList.ItemsModified(const ADesigner: IDesigner); var LRootSprig: TRootSprig; begin if FindRoot(ADesigner, LRootSprig) then LRootSprig.ItemsModified; end; initialization NotifyGroupChange(FlushSprigTypes); finalization FreeAndNil(InternalRootSprigList); FreeAndNil(InternalSprigTypeList); FreeAndNil(InternalRootSprigTypeList); UnNotifyGroupChange(FlushSprigTypes); end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Data.DBXMetaDataWriterFactory; interface uses System.Classes, Data.DBXMetaDataWriter ; const SWriterPrefix = 'Borland.MetaDataWriter.'; type TDBXMetaDataWriterFactory = class private class var FProviderRegistry: TStringList; public class procedure RegisterWriter(DialectName: String; WriterClass: TClass); class procedure UnRegisterWriter(DialectName: String; WriterClass: TClass); class procedure FreeWriterRegistry; class function CreateWriter(DialectName: String): TDBXMetaDataWriter; end; implementation uses Data.DBXCommon, System.SysUtils, Data.DBXClassRegistry, Data.DBXCommonResStrs ; type TWriterItem = class private FClass: TClass; constructor Create(WriterClass: TClass); end; { TDBXMetaDataWriterFactory } class function TDBXMetaDataWriterFactory.CreateWriter( DialectName: String): TDBXMetaDataWriter; var WriterItem: TWriterItem; Index: Integer; begin Index := FProviderRegistry.IndexOf(DialectName); if Index < 0 then begin raise TDBXError.Create(TDBXErrorCodes.DriverInitFailed, Format(SNoMetadataProvider, [DialectName])+' Add driver unit to your uses (DbxInterBase or DbxDb2 or DbxMsSql or DBXMySQL or DbxOracle or DbxSybaseASA or DbxSybaseASE)'); end; WriterItem := FProviderRegistry.Objects[Index] as TWriterItem;; Result := TClassRegistry.GetClassRegistry.CreateInstance(WriterItem.FClass.ClassName) as TDBXMetaDataWriter; Result.Open; end; class procedure TDBXMetaDataWriterFactory.FreeWriterRegistry; var Index: Integer; begin for Index := 0 to FProviderRegistry.Count - 1 do FProviderRegistry.Objects[Index].Free; FProviderRegistry.Free; FProviderRegistry := nil; end; class procedure TDBXMetaDataWriterFactory.RegisterWriter( DialectName: String; WriterClass: TClass); var ClassRegistry: TClassRegistry; ClassName: String; begin FProviderRegistry.AddObject(DialectName, TWriterItem.Create(WriterClass)); ClassRegistry := TClassRegistry.GetClassRegistry; ClassName := WriterClass.ClassName; if not ClassRegistry.HasClass(ClassName) then ClassRegistry.RegisterClass(ClassName, WriterClass, nil); end; class procedure TDBXMetaDataWriterFactory.UnRegisterWriter(DialectName: String; WriterClass: TClass); begin TClassRegistry.GetClassRegistry.UnregisterClass(WriterClass.ClassName); end; { TWriterItem } constructor TWriterItem.Create(WriterClass: TClass); begin FClass := WriterClass; inherited Create; end; initialization TDBXMetaDataWriterFactory.FProviderRegistry := TStringList.Create; finalization TDBXMetaDataWriterFactory.FreeWriterRegistry; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Datasnap.DSProxyDelphi; interface uses Datasnap.DSProxyWriter; type TDSCustomExtendedProxyWriter = class abstract(TDSCustomProxyWriter) protected function GetClassNameSuffix: string; virtual; public function GetProxyClassNames: TArray<string>; virtual; end; implementation uses Datasnap.DSCommonProxy; { TDSCustomExtendedProxyWriter } function TDSCustomExtendedProxyWriter.GetClassNameSuffix: string; begin Result := 'Client'; end; function TDSCustomExtendedProxyWriter.GetProxyClassNames: TArray<string>; var Item: TDSProxyClass; begin SetLength(Result, 0); Item := Metadata.Classes; while Item <> nil do begin if IncludeClass(Item) then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := Item.ProxyClassName + GetClassNameSuffix; end; Item := Item.Next; end; end; end.
{ Module of routines for handling child windows. } module gui_child; define gui_win_childpos_first; define gui_win_childpos_last; define gui_win_childpos_next; define gui_win_childpos_prev; define gui_win_childpos_wentry; %include 'gui2.ins.pas'; { ************************************************************************* * * Local subroutine GUI_WIN_CHILDPOS_FIRST (WIN, POS) * * Init the child window list position handle POS to the first child of * window WIN. } procedure gui_win_childpos_first ( {init child position to first child in list} in out win: gui_win_t; {window object} out pos: gui_win_childpos_t); {returned child list position object} val_param; begin pos.win_p := addr(win); pos.block_p := win.childblock_first_p; if win.n_child <= 0 then begin {there are no child windows in list} pos.n := 0; pos.ind := 0; pos.child_p := nil; end else begin {there is at least one child in list} pos.n := 1; pos.ind := 1; pos.child_p := pos.block_p^.child_p_ar[pos.ind]; end ; end; { ************************************************************************* * * Local subroutine GUI_WIN_CHILDPOS_LAST (WIN, POS) * * Init the child window list position handle POS to the last child of * window WIN. } procedure gui_win_childpos_last ( {init child position to last child in list} in out win: gui_win_t; {window object} out pos: gui_win_childpos_t); {returned child list position object} val_param; begin pos.win_p := addr(win); pos.block_p := win.childblock_last_p; if win.n_child <= 0 then begin {there are no child windows in list} pos.n := 0; pos.ind := 0; pos.child_p := nil; end else begin {there is at least one child in list} pos.n := win.n_child; pos.ind := win.child_ind; pos.child_p := pos.block_p^.child_p_ar[pos.ind]; end ; end; { ************************************************************************* * * Local subroutine GUI_WIN_CHILDPOS_NEXT (POS) * * Advance the child list position to the next child in the list. If * the end of the list is reached, then the position is left one entry * past the end of the list, but there is no guarantee that a list * entry for this next position exists. The position is never advanced * to more than one entry past the list. } procedure gui_win_childpos_next ( {move position to next child in list} in out pos: gui_win_childpos_t); {child list position object} val_param; begin if pos.n >= pos.win_p^.n_child then begin {will be past end of list ?} pos.n := pos.win_p^.n_child + 1; {indicate one entry past end of list} pos.child_p := nil; {there is no child here} return; end; if pos.ind >= gui_childblock_size_k then begin {new position will be in next block} pos.block_p := pos.block_p^.next_p; pos.ind := 1; end else begin {new position is in same block} pos.ind := pos.ind + 1; end ; {BLOCK_P and IND all set} pos.n := pos.n + 1; {update current child number} pos.child_p := pos.block_p^.child_p_ar[pos.ind]; {fetch this list entry} end; { ************************************************************************* * * Local subroutine GUI_WIN_CHILDPOS_PREV (POS) * * Move the current child list position to the previous entry, if there * is one. } procedure gui_win_childpos_prev ( {move position to previous child in list} in out pos: gui_win_childpos_t); {child list position object} val_param; begin if pos.n <= 1 then begin {will be before start of list ?} pos.child_p := nil; pos.ind := 0; pos.n := 0; return; end; if pos.ind <= 1 then begin {new position is in previous list block} pos.block_p := pos.block_p^.prev_p; pos.ind := gui_childblock_size_k; end else begin {new position is in same list block} pos.ind := pos.ind - 1; end ; pos.n := pos.n - 1; pos.child_p := pos.block_p^.child_p_ar[pos.ind]; {fetch this list entry} end; { ************************************************************************* * * Local subroutine GUI_WIN_CHILDPOS_WENTRY (POS, CHILD_P) * * Write the child window pointer CHILD_P at the current child list position. * If the current position is past the end of the list, then the new list * entry is created if needed. } procedure gui_win_childpos_wentry ( {write value to child list entry} in out pos: gui_win_childpos_t; {child list position object} in child_p: gui_win_p_t); {pointer to new child window} val_param; var block_p: gui_childblock_p_t; {pointer to new child list block} begin pos.n := max(1, pos.n); {go to first entry if before list start} if pos.n > pos.win_p^.n_child then begin {need to create list position first ?} if pos.win_p^.child_ind >= gui_childblock_size_k then begin {next position is in new block ?} if pos.block_p^.next_p = nil then begin {need to allocate new block ?} util_mem_grab ( {allocate memory for new list block} sizeof(child_p^), {amount of memory to allocate} pos.win_p^.mem_p^, {memory context} false, {use pool if possible} block_p); {returned pointer to new block} block_p^.prev_p := pos.block_p; {link new block to end of chain} block_p^.next_p := nil; pos.block_p^.next_p := block_p; end; {a next block now definitely exists} pos.block_p := pos.block_p^.next_p; {advance to next block in list} pos.win_p^.childblock_last_p := pos.block_p; {update pnt to last used block} pos.ind := 1; {new entry is first entry in new block} end else begin {next position is still in current block} pos.ind := pos.win_p^.child_ind + 1; end ; pos.win_p^.child_ind := pos.ind; {update info for end of child list} pos.win_p^.n_child := pos.n; {update number of child windows} end; pos.block_p^.child_p_ar[pos.ind] := child_p; {stuff value into this list entry} pos.child_p := child_p; {indicate list entry contents here} end;
unit ArchIntervalBuilder; interface uses Windows, GMSqlQuery, Classes, Generics.Collections, DB; type ArchReqInterval = record UTime1, UTime2: LongWord; end; TArchIntervalBuilder = class private FQuery: TGMSqlQuery; FOwnQuery: bool; protected // такой изврат нам нужен, чтобы отвязаться от TGMSqlQuery при тестировании алгоритма function GetNextHole(): LongWord; virtual; function IsAllProcessed: bool; virtual; procedure OpenQuery; virtual; public constructor Create(q: TGMSqlQuery); overload; constructor Create(const sql: string); overload; destructor Destroy; override; function BuildIntervalList(step, maxreq: Cardinal): TList<ArchReqInterval>; end; implementation { TArchIntervalBuilder } // На выходе вернутся начальные даты интервалов! function TArchIntervalBuilder.BuildIntervalList(step, maxreq: Cardinal): TList<ArchReqInterval>; var a: ArchReqInterval; ut: LongWord; begin Result := TList<ArchReqInterval>.Create(); OpenQuery(); if IsAllProcessed() then Exit; a.UTime1 := 0; a.UTime2 := 0; while not IsAllProcessed() do begin ut := GetNextHole(); if a.UTime1 = 0 then begin a.UTime1 := ut; a.UTime2 := ut; end else if ut - a.UTime2 > step then begin // разрыв. т.е. между предыдущей и текущей дырой есть интервал с данными // в таком случае мы добавляем предыдущий интервал и стартуем новый. Result.Add(a); a.UTime1 := ut; a.UTime2 := ut; end else if ut - a.UTime1 >= step * maxreq then begin // набралось нужное количество запросов // добавим и начнем жизнь с чистого листа Result.Add(a); a.UTime1 := ut; a.UTime2 := ut; end else begin // дырка продолжается a.UTime2 := ut; end; end; if a.UTime1 > 0 then Result.Add(a); end; constructor TArchIntervalBuilder.Create(q: TGMSqlQuery); begin inherited Create(); FQuery := q; FOwnQuery := false; end; constructor TArchIntervalBuilder.Create(const sql: string); begin inherited Create(); FQuery := TGMSqlQuery.Create(); FQuery.SQL.Text := sql; FOwnQuery := true; end; destructor TArchIntervalBuilder.Destroy; begin if FOwnQuery then FQuery.Free(); inherited; end; function TArchIntervalBuilder.GetNextHole: LongWord; begin Result := FQuery.Fields[0].AsInteger; FQuery.Next(); end; function TArchIntervalBuilder.IsAllProcessed: bool; begin Result := FQuery.Eof; end; procedure TArchIntervalBuilder.OpenQuery; begin if FQuery.State <> dsBrowse then FQuery.Open(); end; end.
unit IdAuthenticationManager; interface Uses Classes, SysUtils, IdAuthentication, IdURI, IdGlobal, IdBaseComponent; Type TIdAuthenticationItem = class(TCollectionItem) protected FURI: TIdURI; FParams: TStringList; procedure SetParams(const Value: TStringList); procedure SetURI(const Value: TIdURI); public constructor Create(ACollection: TCOllection); override; destructor Destroy; override; property URL: TIdURI read FURI write SetURI; property Params: TStringList read FParams write SetParams; end; TIdAuthenticationCollection = class(TOwnedCollection) protected function GetAuthItem(AIndex: Integer): TIdAuthenticationItem; procedure SetAuthItem(AIndex: Integer; const Value: TIdAuthenticationItem); public constructor Create(AOwner: Tpersistent); function Add: TIdAuthenticationItem; property Items[AIndex: Integer]: TIdAuthenticationItem read GetAuthItem write SetAuthItem; end; TIdAuthenticationManager = class(TIdBaseComponent) protected FAuthentications: TIdAuthenticationCollection; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddAuthentication(AAuthtetication: TIdAuthentication; AURL: TIdURI); property Authentications: TIdAuthenticationCollection read FAuthentications; end; implementation { TIdAuthenticationManager } function TIdAuthenticationCollection.Add: TIdAuthenticationItem; begin result := TIdAuthenticationItem.Create(self); end; constructor TIdAuthenticationCollection.Create(AOwner: Tpersistent); begin inherited Create(AOwner, TIdAuthenticationItem); end; function TIdAuthenticationCollection.GetAuthItem( AIndex: Integer): TIdAuthenticationItem; begin result := TIdAuthenticationItem(inherited Items[AIndex]); end; procedure TIdAuthenticationCollection.SetAuthItem(AIndex: Integer; const Value: TIdAuthenticationItem); begin if Items[AIndex] <> nil then begin Items[AIndex].Assign(Value); end; end; { TIdAuthenticationManager } procedure TIdAuthenticationManager.AddAuthentication( AAuthtetication: TIdAuthentication; AURL: TIdURI); begin with Authentications.Add do begin URL.URI := AURL.URI; Params.Assign(AAuthtetication.Params); end; end; constructor TIdAuthenticationManager.Create(AOwner: TComponent); begin inherited Create(AOwner); FAuthentications := TIdAuthenticationCollection.Create(self); end; destructor TIdAuthenticationManager.Destroy; begin FreeAndNil(FAuthentications); inherited Destroy; end; { TIdAuthenticationItem } constructor TIdAuthenticationItem.Create(ACollection: TCOllection); begin inherited Create(ACollection); FURI := TIdURI.Create; FParams := TStringList.Create; end; destructor TIdAuthenticationItem.Destroy; begin FreeAndNil(FURI); FreeAndNil(FParams); inherited Destroy; end; procedure TIdAuthenticationItem.SetParams(const Value: TStringList); begin FParams.Assign(Value); end; procedure TIdAuthenticationItem.SetURI(const Value: TIdURI); begin FURI.URI := Value.URI; end; end.
PROGRAM Snowflak; {$n+} {$R+} { USAGE: Snowflak <DataFile> <Sides> <Level> where <DataFile> is the file containing the turn angles of the generator <Sides> is the number of sides on the a regular polygon initiatior <Level> is the depth of the recursion } Uses GraphPrm, TurtleGr; CONST MaxGeneratorFacets = 50; MaxInitiatorSides = 20; Triangle = 3; Square = 4; TYPE InitiatorRec = RECORD Sides : BYTE { number of sides }; { points on a 1..-1 grid. Will be scaled to display size } x,y : ARRAY[1..MaxInitiatorSides+1] OF SINGLE; END; VonKochRec = RECORD Facets : BYTE {number of facets}; Divisor : SINGLE { segment length per initator side }; { sequence of turtle turn angles } Angle : ARRAY[1..MaxGeneratorFacets] OF SINGLE; END; VAR i, level, sides : BYTE; { T : TurtleObj; } Initiator : InitiatorRec; Generator : VonKochRec; { -------------------------------------------------------- } FUNCTION LineLength(x1,y1,x2,y2 : SINGLE) : SINGLE; BEGIN LineLength := sqrt(sqr(x2-x1) + sqr(y2-y1)); END; { -------------------------------------------------------- } PROCEDURE ScalePoint(VAR x,y : SINGLE); BEGIN x := x * HalfWidth; y := y * HalfHeight; END; { -------------------------------------------------------- } PROCEDURE ScaleInitiator(VAR I : InitiatorRec); VAR n : WORD; BEGIN FOR n := 1 TO I.Sides+1 DO ScalePoint(I.x[n],I.y[n]); END; { -------------------------------------------------------- } PROCEDURE DrawInitiator(PGon : InitiatorRec); VAR k : INTEGER; T : TurtleRec; BEGIN WITH PGon DO BEGIN init(T,x[1],y[1]); ChangeStep(T,LineLength(x[1],y[1],x[2],y[2])); StartDrawing(T); FOR k := 1 TO Sides DO BEGIN Point(T,x[k],Y[k],x[k+1],Y[k+1]); Step(T); END; END; END; { -------------------------------------------------------- } PROCEDURE Generate( x1,y1,x2,y2 : SINGLE; Level : INTEGER; VAR Gen : VonKochRec); VAR T : TurtleRec; i, j, k : INTEGER; Xpoints, Ypoints : ARRAY[0..MaxGeneratorFacets] OF SINGLE; BEGIN Level := Level - 1; Init(T,x1,y1); ChangeStep(T,LineLength(x1,y1,x2,y2) / Gen.Divisor); Xpoints[0] := x1; Ypoints[0] := y1; Xpoints[Gen.Facets] := x2; Ypoints[Gen.Facets] := y2; Point(T,x1,y1,x2,y2); FOR i := 1 TO Gen.Facets - 1 DO BEGIN Turn(T,Gen.Angle[i]); Step(T); Xpoints[i] := T.x; Ypoints[i] := T.y; END; IF Level > 0 THEN FOR j := 0 TO Gen.Facets - 1 DO BEGIN x1 := Xpoints[j]; x2 := Xpoints[j+1]; y1 := Ypoints[j]; y2 := Ypoints[j+1]; Generate(x1,y1,x2,y2,Level,Gen); END ELSE FOR k := 0 TO Gen.Facets - 1 DO DrawLine(TRUNC(Xpoints[k]),TRUNC(Ypoints[k]), TRUNC(Xpoints[k+1]),TRUNC(Ypoints[k+1]),15); END {Generate}; { -------------------------------------------------------- } PROCEDURE Initialize(VAR PGon : InitiatorRec; PolySides : WORD); { creates a regular polygon scaled to display size } CONST SizeFactor = 1.75; VAR PolyAngle, StepSize, x0,y0 : SINGLE; i : WORD; T : TurtleRec; BEGIN PolyAngle := 360 / PolySides; StepSize := DisplayHeight/PolySides * SizeFactor; x0 := StepSize / 2 {offset to the right}; y0 := -DisplayHeight/(2*Pi) * SizeFactor; Init(T,x0,y0); ChangeStep(T,StepSize); PGon.sides := PolySides; {set start and end point the same } PGon.x[1] := x0; PGon.y[1] := y0; PGon.x[PolySides+1] := x0; PGon.y[PolySides+1] := y0; FOR i := 2 to PolySides DO BEGIN Turn(T,PolyAngle); Step(T); PGon.x[i] := T.x; PGon.y[i] := T.y; END; END; { -------------------------------------------------------- } PROCEDURE GetParams( VAR Gen : VonKochRec; VAR Sides, Level : BYTE); VAR vkfile : TEXT; instr : STRING; err, i : INTEGER; PROCEDURE NextDataLine; {skip lines with ';' as comments} BEGIN REPEAT readln(vkfile,instr) UNTIL pos(';',instr) = 0; END; BEGIN val(paramstr(2),Sides,err); val(paramstr(3),Level,err); assign(vkFile,paramstr(1)); reset(vkFile); NextDataLine; val(instr,Gen.Divisor,err); Gen.Facets := 0; WHILE NOT eof(vkFile) DO BEGIN inc(Gen.Facets); NextDataLine; val(instr,Gen.angle[Gen.Facets],err); IF err > 0 THEN dec(Gen.Facets); END; END; { -------------------------------------------------------- } BEGIN (* Write('What Data File? '); Read(level); IF level < 1 THEN level := 1; Write('Enter Level (number from 1 to 10) '); Read(level); IF level < 1 THEN level := 1; Write('How many Initiator Sides? (number from 3 to 20) '); Read(Sides); Readln; IF Sides < 3 THEN Sides := 3; IF Sides > 20 THEN Sides := 20; *) GetParams(Generator,Sides,Level); Initialize(Initiator,Sides); setmode(16); cls(0); IF Level = 0 THEN DrawInitiator(Initiator) ELSE FOR i := 1 TO Initiator.Sides DO generate(Initiator.x[i],Initiator.Y[i], Initiator.x[i+1],Initiator.y[i+1],level, Generator); ReadLn; SetMode(0); END. 
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Datasnap.DSHTTPWebBroker; interface uses Web.AutoDisp, System.Classes, Datasnap.DSHTTPCommon, Datasnap.DSHTTP, Web.HTTPApp, System.Masks, System.SysUtils, DataSnap.DSSession; type TDSHTTPContextWebBroker = class; TDSRESTWebDispatcher = class; TDSHTTPWebDispatcher = class; /// <summary>Base class for DataSnap dispatchers that defines their default /// properties.</summary> TDSWebDispatch = class(TWebDispatch) private FCustomPathInfo: Boolean; function IsPathInfoStored: Boolean; virtual; function GetDefaultPathInfo: string; virtual; abstract; protected procedure SetPathInfo(const Value: string); override; function GetPathInfo: string; override; public constructor Create(AComponent: TComponent); published property MethodType default mtAny; property PathInfo stored IsPathInfoStored nodefault; end; /// <summary>Base class for DataSnap dispatchers that defines their default /// properties.</summary> TDSHTTPWebDispatch = class(TDSWebDispatch) private FDispatcher: TDSHTTPWebDispatcher; function GetDefaultPathInfo: string; override; public constructor Create(AComponent: TDSHTTPWebDispatcher); end; /// <summary>Base class for DataSnap dispatchers that defines their default /// properties.</summary> TDSRESTWebDispatch = class(TDSWebDispatch) private FDispatcher: TDSRESTWebDispatcher; function GetDefaultPathInfo: string; override; public constructor Create(AComponent: TDSRESTWebDispatcher); end; /// <summary> Webbroker component that dispatches DataSnap REST requests /// </summary> TDSRESTWebDispatcher = class(TDSRESTServerTransport, IWebDispatch) private FWebDispatch: TDSWebDispatch; procedure SetWebDispatch(const Value: TDSWebDispatch); function GetDefaultPathInfo: string; protected function CreateRESTServer: TDSRESTServer; override; function DispatchEnabled: Boolean; function DispatchMask: TMask; function DispatchMethodType: TMethodType; function DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published /// <summary>Dispatch criteria. Indicate the types of requests that will be processed by this dispatcher. /// </summary> property WebDispatch: TDSWebDispatch read FWebDispatch write SetWebDispatch; end; /// <summary> Webbroker component that dispatches DataSnap REST and HTTP tunnel requests /// </summary> TDSHTTPWebDispatcher = class(TDSHTTPServerTransport, IWebDispatch) private FWebDispatch: TDSWebDispatch; procedure SetWebDispatch(const Value: TDSWebDispatch); function GetDefaultPathInfo: string; protected function CreateHttpServer: TDSHTTPServer; override; function DispatchEnabled: Boolean; function DispatchMask: TMask; function DispatchMethodType: TMethodType; function DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published /// <summary>Dispatch criteria. Indicate the types of requests that will be processed by this dispatcher. /// </summary> property WebDispatch: TDSWebDispatch read FWebDispatch write SetWebDispatch; end; TDSHTTPRequestWebBroker = class; TDSHTTPResponseWebBroker = class; TDSHTTPContextWebBroker = class(TDSHTTPContext) private FRequest: TDSHTTPRequestWebBroker; FResponse: TDSHTTPResponseWebBroker; public constructor Create(const ARequest: TWebRequest; const AResponse: TWebResponse); destructor Destroy; override; function Connected: Boolean; override; end; TDSHTTPRequestWebBroker = class(TDSHTTPRequest) strict private FRequestInfo: TWebRequest; FPostStream: TMemoryStream; FParams: TStrings; FAuthUserName: string; FAuthPassword: string; FHaveAuth: Boolean; procedure UpdateAuthStrings; protected function GetCommand: string; override; function GetCommandType: TDSHTTPCommandType; override; function GetDocument: string; override; function GetParams: TStrings; override; function GetPostStream: TStream; override; function GetAuthUserName: string; override; function GetAuthPassword: string; override; function GetURI: string; override; function GetPragma: string; override; function GetAccept: string; override; function GetRemoteIP: string; override; function GetUserAgent: string; override; function GetProtocolVersion: string; override; public constructor Create(ARequestInfo: TWebRequest); destructor Destroy; override; /// <summary>WebBroker Request. Provided so that event handlers can get to WebBroker specific properties. /// </summary> property WebRequest: TWebRequest read FRequestInfo; end; TDSHTTPResponseWebBroker = class(TDSHTTPResponse) strict private FResponseInfo: TWebResponse; FCloseConnection: Boolean; strict protected function GetContentStream: TStream; override; function GetResponseNo: Integer; override; function GetResponseText: String; override; procedure SetContentStream(const Value: TStream); override; procedure SetResponseNo(const Value: Integer); override; procedure SetResponseText(const Value: String); override; function GetContentText: string; override; procedure SetContentText(const Value: string); override; function GetContentLength: Int64; override; procedure SetContentLength(const Value: Int64); override; function GetCloseConnection: Boolean; override; procedure SetCloseConnection(const Value: Boolean); override; function GetPragma: string; override; procedure SetPragma(const Value: string); override; function GetContentType: string; override; procedure SetContentType(const Value: string); override; function GetFreeContentStream: Boolean; override; procedure SetFreeContentStream(const Value: Boolean); override; public constructor Create(AResponseInfo: TWebResponse); procedure SetHeaderAuthentication(const Value: String; const Realm: String); override; /// <summary>WebBroker Response. Provided so that event handlers can get to WebBroker specific properties. /// </summary> property WebResponse: TWebResponse read FResponseInfo; end; /// <summary>Get the Web Module currently processing a DataSnap HTTP request. /// </summary> function GetDataSnapWebModule: TWebModule; implementation uses Data.DBXClientResStrs, {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF MSWINDOWS} {$IFDEF POSIX} Posix.String_, {$ENDIF POSIX} System.NetEncoding, System.Math; type TDSRESTServerWebBroker = class(TDSRESTServer) protected function Decode(Data: string): string; override; public procedure DispatchDataSnap(ARequest: TWebRequest; AResponse: TWebResponse); end; TDSHTTPServerWebBroker = class(TDSHTTPServer) protected function Decode(Data: string): string; override; public procedure DispatchDataSnap(ARequest: TWebRequest; AResponse: TWebResponse); end; threadvar DataSnapWebModule: TWebModule; function GetDataSnapWebModule: TWebModule; begin Result := DataSnapWebModule; end; { TDSRESTWebDispatcher } constructor TDSRESTWebDispatcher.Create(AOwner: TComponent); begin inherited Create(AOwner); FWebDispatch := TDSRESTWebDispatch.Create(Self); end; function TDSRESTWebDispatcher.CreateRESTServer: TDSRESTServer; begin Result := TDSRESTServerWebBroker.Create(Self.Server); end; destructor TDSRESTWebDispatcher.Destroy; begin FWebDispatch.Free; inherited Destroy; end; procedure TDSRESTWebDispatcher.SetWebDispatch(const Value: TDSWebDispatch); begin FWebDispatch.Assign(Value); end; function TDSRESTWebDispatcher.DispatchEnabled: Boolean; begin Result := FWebDispatch.Enabled; end; function TDSRESTWebDispatcher.DispatchMask: TMask; begin Result := FWebDispatch.Mask; end; function TDSRESTWebDispatcher.DispatchMethodType: TMethodType; begin Result := FWebDispatch.MethodType; end; function TDSRESTWebDispatcher.DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; begin try if Owner is TWebModule then DataSnapWebModule := TWebModule(Owner); try try RequiresServer; TDSRESTServerWebBroker(Self.FRESTServer).DispatchDataSnap(Request, Response); Result := True; except on E: Exception do begin { Default to 500, like web services. } Response.StatusCode := 500; Result := True; end; end; except { Swallow any unexpected exception, it will bring down some web servers } Result := False; end; finally { Reset current DataSnapWebModule } DataSnapWebModule := nil; end; end; function TDSRESTWebDispatcher.GetDefaultPathInfo: string; begin Result := ''; if DSContext <> '/' then Result := DSContext; if RestContext <> '/' then Result := Result + RESTContext; Result := Result + '*'; end; { TDSHTTPWebDispatcher } constructor TDSHTTPWebDispatcher.Create(AOwner: TComponent); begin inherited Create(AOwner); FWebDispatch := TDSHTTPWebDispatch.Create(Self); end; function TDSHTTPWebDispatcher.CreateHttpServer: TDSHTTPServer; begin Result := TDSHTTPServerWebBroker.Create; end; destructor TDSHTTPWebDispatcher.Destroy; begin FWebDispatch.Free; inherited Destroy; end; procedure TDSHTTPWebDispatcher.SetWebDispatch(const Value: TDSWebDispatch); begin FWebDispatch.Assign(Value); end; function TDSHTTPWebDispatcher.DispatchEnabled: Boolean; begin Result := FWebDispatch.Enabled; end; function TDSHTTPWebDispatcher.DispatchMask: TMask; begin Result := FWebDispatch.Mask; end; function TDSHTTPWebDispatcher.DispatchMethodType: TMethodType; begin Result := FWebDispatch.MethodType; end; function TDSHTTPWebDispatcher.DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; begin try if Owner is TWebModule then DataSnapWebModule := TWebModule(Owner); try try RequiresServer; TDSHTTPServerWebBroker(Self.FHttpServer).DispatchDataSnap(Request, Response); Result := True; except on E: Exception do begin { Default to 500, like web services. } Response.StatusCode := 500; Result := True; end; end; except { Swallow any unexpected exception, it will bring down some web servers } Result := False; end; finally { Reset current DataSnapWebModule } DataSnapWebModule := nil; end; end; function TDSHTTPWebDispatcher.GetDefaultPathInfo: string; begin Result := ''; if DSContext <> '/' then Result := DSContext; Result := Result + '*'; end; { TDSRESTServerWebBroker } function TDSRESTServerWebBroker.Decode(Data: string): string; begin Result := Data; end; procedure TDSRESTServerWebBroker.DispatchDataSnap(ARequest: TWebRequest; AResponse: TWebResponse); var LDispatch: TDSHTTPDispatch; LContext: TDSHTTPContextWebBroker; begin LDispatch := TDSHTTPApplication.Instance.HTTPDispatch; if LDispatch <> nil then DoCommand(LDispatch.Context, LDispatch.Request, LDispatch.Response) else begin LContext := TDSHTTPContextWebBroker.Create(ARequest, AResponse); try DoCommand(LContext, LContext.FRequest, LContext.FResponse); finally LContext.Free; end; end; end; { TDSHTTPServerWebBroker } function TDSHTTPServerWebBroker.Decode(Data: string): string; begin Result := Data; end; procedure TDSHTTPServerWebBroker.DispatchDataSnap(ARequest: TWebRequest; AResponse: TWebResponse); var LDispatch: TDSHTTPDispatch; LContext: TDSHTTPContextWebBroker; begin LDispatch := TDSHTTPApplication.Instance.HTTPDispatch; if LDispatch <> nil then DoCommand(LDispatch.Context, LDispatch.Request, LDispatch.Response) else begin LContext := TDSHTTPContextWebBroker.Create(ARequest, AResponse); try DoCommand(LContext, LContext.FRequest, LContext.FResponse); finally LContext.Free; end; end; end; { TDSHTTPResponseWebBroker } constructor TDSHTTPResponseWebBroker.Create(AResponseInfo: TWebResponse); begin FResponseInfo := AResponseInfo; end; function TDSHTTPResponseWebBroker.GetCloseConnection: Boolean; begin Result := FCloseConnection; end; function TDSHTTPResponseWebBroker.GetContentLength: Int64; begin Result := FResponseInfo.ContentLength; end; function TDSHTTPResponseWebBroker.GetContentStream: TStream; begin Result := FResponseInfo.ContentStream; end; function TDSHTTPResponseWebBroker.GetContentText: string; begin Result := FResponseInfo.Content; end; function TDSHTTPResponseWebBroker.GetContentType: string; begin Result := FResponseInfo.ContentType; end; function TDSHTTPResponseWebBroker.GetFreeContentStream: Boolean; begin Result := FResponseInfo.FreeContentStream; end; function TDSHTTPResponseWebBroker.GetPragma: string; begin Result := FResponseInfo.GetCustomHeader('Pragma'); end; function TDSHTTPResponseWebBroker.GetResponseNo: Integer; begin Result := FResponseInfo.StatusCode; end; function TDSHTTPResponseWebBroker.GetResponseText: String; begin // Expect reason string to be 8 bit characters only Result := string(FResponseInfo.ReasonString); end; procedure TDSHTTPResponseWebBroker.SetCloseConnection(const Value: Boolean); begin FCloseConnection := Value; end; procedure TDSHTTPResponseWebBroker.SetContentLength(const Value: Int64); begin FResponseInfo.ContentLength := Value; end; procedure TDSHTTPResponseWebBroker.SetContentStream(const Value: TStream); begin FResponseInfo.ContentStream := Value; end; procedure TDSHTTPResponseWebBroker.SetContentText(const Value: string); begin FResponseInfo.Content := Value; end; procedure TDSHTTPResponseWebBroker.SetContentType(const Value: string); begin FResponseInfo.ContentType := Value; end; procedure TDSHTTPResponseWebBroker.SetFreeContentStream(const Value: Boolean); begin FResponseInfo.FreeContentStream := Value; end; procedure TDSHTTPResponseWebBroker.SetPragma(const Value: string); begin FResponseInfo.SetCustomHeader('Pragma', Value); end; procedure TDSHTTPResponseWebBroker.SetHeaderAuthentication(const Value, Realm: String); begin FResponseInfo.WWWAuthenticate := Value; FResponseInfo.Realm := Realm; end; procedure TDSHTTPResponseWebBroker.SetResponseNo(const Value: Integer); begin FResponseInfo.StatusCode := Value; end; procedure TDSHTTPResponseWebBroker.SetResponseText(const Value: String); begin // Expect reason phrase to 8 bit characters only. FResponseInfo.ReasonString := Value; end; constructor TDSHTTPRequestWebBroker.Create(ARequestInfo: TWebRequest); begin FRequestInfo := ARequestInfo; end; destructor TDSHTTPRequestWebBroker.Destroy; begin FPostStream.Free; FParams.Free; inherited; end; function Base64DecodeToString(const S: string): string; inline; begin Result := TNetEncoding.Base64.Decode(S); end; procedure TDSHTTPRequestWebBroker.UpdateAuthStrings; var LAuthorization: string; LDecodedAuthorization: string; LPos: NativeInt; begin if not FHaveAuth then begin FHaveAuth := True; LAuthorization := string(FRequestInfo.Authorization); if LAuthorization.StartsWith('Basic') then begin LDecodedAuthorization := Base64DecodeToString(LAuthorization.SubString(5, LAuthorization.Length).Trim); LPos := LDecodedAuthorization.IndexOf(':'); if LPos > 0 then begin FAuthUserName := LDecodedAuthorization.SubString(0, LPos); FAuthPassword := LDecodedAuthorization.SubString(LPos + 1, LDecodedAuthorization.Length); end; end; end; end; function TDSHTTPRequestWebBroker.GetAuthPassword: string; begin UpdateAuthStrings; Result := FAuthPassword; end; function TDSHTTPRequestWebBroker.GetAuthUserName: string; begin UpdateAuthStrings; Result := FAuthUserName; end; function TDSHTTPRequestWebBroker.GetCommand: string; begin Result := string(FRequestInfo.Method); end; function TDSHTTPRequestWebBroker.GetCommandType: TDSHTTPCommandType; begin if GetCommand.Equals('DELETE') then { do not localize } // WebBroker doesn't have code for delete Result := TDSHTTPCommandType.hcDELETE else case FRequestInfo.MethodType of TMethodType.mtAny: Result := TDSHTTPCommandType.hcUnknown; TMethodType.mtHead: Result := TDSHTTPCommandType.hcOther; TMethodType.mtGet: Result := TDSHTTPCommandType.hcGET; TMethodType.mtPost: Result := TDSHTTPCommandType.hcPOST; TMethodType.mtPut: Result := TDSHTTPCommandType.hcPUT; else raise Exception.Create(sUnknownCommandType); end; end; function TDSHTTPRequestWebBroker.GetDocument: string; begin Result := string(FRequestInfo.InternalPathInfo); end; function TDSHTTPRequestWebBroker.GetParams: TStrings; var LField: string; begin if FParams = nil then begin FParams := TStringList.Create; FParams.AddStrings(FRequestInfo.QueryFields); if (FRequestInfo.MethodType = mtPost) and AnsiSameText(string(FRequestInfo.ContentType), 'application/x-www-form-urlencoded') then // Do not localize begin for LField in FRequestInfo.ContentFields do if LField.StartsWith('dss', True) then FParams.Add(LField); end; end; Result := FParams; end; function TDSHTTPRequestWebBroker.GetPostStream: TStream; begin if FPostStream = nil then begin FPostStream := TMemoryStream.Create; FRequestInfo.ReadTotalContent; if Length(FRequestInfo.RawContent) > 0 then begin FPostStream.Write(FRequestInfo.RawContent[Low(FRequestInfo.RawContent)], Length(FRequestInfo.RawContent)); FPostStream.Seek(0, TSeekOrigin.soBeginning); end; end; Result := FPostStream; end; function TDSHTTPRequestWebBroker.GetPragma: string; begin Result := String(FRequestInfo.GetFieldByName('Pragma')); end; function TDSHTTPRequestWebBroker.GetRemoteIP: string; begin Result := String(FRequestInfo.RemoteIP); end; function TDSHTTPRequestWebBroker.GetAccept: string; begin Result := String(FRequestInfo.GetFieldByName('Accept')); end; function TDSHTTPRequestWebBroker.GetURI: string; begin Result := String(FRequestInfo.RawPathInfo); end; function TDSHTTPRequestWebBroker.GetUserAgent: string; begin Result := String(FRequestInfo.UserAgent); end; function TDSHTTPRequestWebBroker.GetProtocolVersion: string; begin Result := String(FRequestInfo.ProtocolVersion); end; { TDSHTTPContextWebBroker } function TDSHTTPContextWebBroker.Connected: Boolean; begin Result := True; end; constructor TDSHTTPContextWebBroker.Create(const ARequest: TWebRequest; const AResponse: TWebResponse); begin inherited Create; FRequest := TDSHTTPRequestWebBroker.Create(ARequest); FResponse := TDSHTTPResponseWebBroker.Create(AResponse); end; destructor TDSHTTPContextWebBroker.Destroy; begin FRequest.Free; FResponse.Free; inherited; end; { TDSWebDispatch } constructor TDSWebDispatch.Create(AComponent: TComponent); begin inherited; MethodType := mtAny; PathInfo := GetDefaultPathInfo; end; function TDSWebDispatch.IsPathInfoStored: Boolean; begin Result := PathInfo <> GetDefaultPathInfo; end; procedure TDSWebDispatch.SetPathInfo(const Value: string); begin FCustomPathInfo := (Value <> '') and not SameText(GetDefaultPathInfo, Value); if Value = '' then inherited SetPathInfo(GetDefaultPathInfo) else inherited SetPathInfo(Value); end; function TDSWebDispatch.GetPathInfo: string; begin if FCustomPathInfo then Result := inherited else Result := GetDefaultPathInfo; end; { TDSHTTPWebDispatch } constructor TDSHTTPWebDispatch.Create(AComponent: TDSHTTPWebDispatcher); begin FDispatcher := AComponent; inherited Create(AComponent); end; function TDSHTTPWebDispatch.GetDefaultPathInfo: string; begin Result := FDispatcher.GetDefaultPathInfo; end; { TDSRESTWebDispatch } constructor TDSRESTWebDispatch.Create(AComponent: TDSRESTWebDispatcher); begin FDispatcher := AComponent; inherited Create(AComponent); end; function TDSRESTWebDispatch.GetDefaultPathInfo: string; begin Result := FDispatcher.GetDefaultPathInfo; end; end.
unit RestoreCmd; interface procedure Restore(storeName, fileName : String; promptOnUsingNewest : Boolean; // indicates we want to ask the user to verify the name of the newest backup to use. databaseName : String; userId, password : String; hostName : String; hostPort : Integer); implementation uses SysUtils, DB, edbcomps, SessionManager, ConsoleHelper; procedure Restore(storeName, fileName : String; promptOnUsingNewest : Boolean; // indicates we want to ask the user to verify the name of the newest backup to use. databaseName : String; userId, password : String; hostName : String; hostPort : Integer); var sessionMgr : TSessionManager; db : TEDBDatabase; ds : TEDBQuery; promptAnswer : String; function GetNewestBackup : String; begin ds.SQL.Clear; // This will get the latest backup that is in the backup store. ds.SQL.Add('Select Name from Configuration.Backups Order By CreatedOn Desc Range 1 to 1'); ds.ExecSQL; Result := ''; if not ds.EOF then Result := ds.FieldByName('Name').AsString; end; begin sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort); db := TEDBDatabase.Create(nil); ds := TEDBQuery.Create(nil); try db.OnStatusMessage := sessionMgr.Status; db.OnLogMessage := sessionMgr.Status; db.SessionName := sessionMgr.session.Name; db.Database := 'Configuration'; // make sure that we are not in the database we are restoring. db.LoginPrompt := true; db.DatabaseName := databaseName + DateTimeToStr(now); ds.SessionName := sessionMgr.session.SessionName; ds.DatabaseName := db.Database; ds.OnStatusMessage := sessionMgr.Status; ds.OnLogMessage := sessionMgr.Status; // ds.SQL.Add('Select * from Configuration.Stores'); // ds.ExecSQL; // while not ds.EOF do // begin // writeln(ds.FieldByName('Name').AsString); // ds.Next; // end; ds.SQL.Add('Set Backups Store to "' + storeName + '"'); ds.ExecSQL; if fileName = '*' then begin fileName := GetNewestBackup; if fileName = '' then WritelnError('There were no backups.') else begin if promptOnUsingNewest then begin Write('The newest backup is called "' + fileName + '". Do you want to use that? (y/n)'); Readln(promptAnswer); if lowercase(promptAnswer) = 'y' then WritelnInfo(' Using backup file "' + fileName + '"') else fileName := ''; end else WritelnInfo(' Using backup file "' + fileName + '"') end; end; if fileName <> '' then begin ds.SQL.Clear; ds.SQL.Add('Restore Database "' + databaseName + '" From "' + fileName + '" In Store "' + storeName + '" Include Catalog'); ds.ExecSQL; end; finally FreeAndNil(db); FreeAndNil(sessionMgr); end; end; end.
unit SpriteReact; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, Dialogs; type TReactThreadManager = class (TThread) private Reactable: boolean; Idle: boolean; Launched : boolean; Killed: boolean; aControl: TControl; aPoint: TPoint; ReactThreads : TList; FOnIdle: TNotifyEvent; procedure Execute; override; procedure SyncReact; procedure Reaction; procedure SetFOnIdle(aEvent: TNotifyEvent); procedure SyncIdle; public procedure Pause; procedure Resume; procedure Kill; procedure Launch; constructor Create; procedure RegisterControl(aControl: TControl); procedure UnregisterControl(aControl: Tcontrol); function Running: boolean; protected published property OnIdle: TNotifyEvent read FOnIdle write SetFOnIdle; end; var ReactManager: TReactThreadManager = nil; implementation uses SpriteClass; procedure TReactThreadManager.SetFOnIdle(aEvent: TNotifyEvent); begin FOnIdle := aEvent; end; constructor TReactThreadManager.Create; begin ReactThreads := Tlist.Create; FreeOnTerminate:=True; Killed := False; Launched:=False; inherited Create(True); end; function TReactThreadManager.Running: boolean; begin Result := Suspended; end; procedure TReactThreadManager.SyncReact; begin try TSprite(aControl).React(aPoint); except end; end; procedure TReactThreadManager.Reaction; begin try Reactable := TSprite(aControl).Reacting(aPoint, idle) except end; end; procedure TReactThreadManager.Execute; var i: integer; hadReaction: boolean; begin try while not Killed do begin hadReaction := False; for i:=0 to ReactThreads.Count - 1 do begin try GetCursorPos(aPoint); if not Killed then aControl := ReactThreads[i]; if aControl.Visible and Application.Active and (not Killed) then begin Synchronize(Reaction); if not idle then begin hadReaction := True; //Screen.Cursor := (aControl as TSprite).Cursor; end; if Reactable and (not Killed) then Synchronize(SyncReact); end; except end; Application.ProcessMessages; end; if not hadReaction then begin if Assigned(OnIdle) then Synchronize(SyncIdle); Application.ProcessMessages; //Screen.Cursor := crDefault; end; end; except end; end; procedure TReactThreadManager.SyncIdle; begin OnIdle(Self); end; procedure TReactThreadManager.RegisterControl(aControl: TControl); begin try ReactThreads.Add(aControl); if Launched then Suspended := False; except end; end; procedure TReactThreadManager.UnRegisterControl(aControl: TControl); var i: integer; begin try if not Killed then begin i := ReactThreads.IndexOf(aControl); if (i <> -1) and (not Killed) then begin ReactThreads.Remove(aControl); if ReactThreads.Count = 0 then Suspended := True; end; end; except end; end; procedure TReactThreadManager.Kill; begin try Killed := True; Suspended := False; except end; end; procedure TReactThreadManager.Launch; begin try Suspended:=False; Launched := True; except end; end; procedure TReactThreadManager.Pause; begin Suspended:=True; end; procedure TReactThreadManager.Resume; begin Suspended:=False; end; begin //ReactManager := TReactThreadManager.Create; //ReactManager.Launch; end.
unit Demo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, DlgCountdown; type TForm2 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private procedure Log(const Msg: string); end; var Form2: TForm2; implementation {$R *.dfm} {$I dlg.inc} // оконная процедура диалога function DialogProc(hWnd: HWND; msg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; var EndDlgCmd: Boolean; i: Integer; begin case Msg of // Нотифай от дочернего контрола. Проверяем, если это нажата кнопка либо Escape, то завершить диалог. WM_COMMAND: begin EndDlgCmd := False; // Нажат Escape? HIWORD(wParam) = 0, LOWORD(wParam) = IDCANCEL if (HIWORD(wParam) = 0) and (LOWORD(wParam) = IDCANCEL) then EndDlgCmd := True // Нажата кнопка? HIWORD(wParam) = BN_CLICKED, LOWORD(wParam) = Btn_ID else if HIWORD(wParam) = BN_CLICKED then if LOWORD(wParam) in [IDOK, IDRETRY] then // ищем ID кнопки в списке ID, завершающих диалог EndDlgCmd := True; // Диалог действительно завершается if EndDlgCmd then EndDialog(hWnd, LOWORD(wParam)); end; // WM_COMMAND end; // case // все остальные случаи - предварительно ставим отрицательный результат и запускаем обработчик Result := LRESULT(False); end; procedure TForm2.Button1Click(Sender: TObject); const ModalResults: array[1..11] of string = ('OK', 'Cancel', 'Abort', 'Retry', 'Ignore', 'Yes', 'No', 'Close', 'Help', 'TryAgain', 'Continue'); type TTestFunc = reference to procedure(var Res: NativeInt); var TestCounter, FailCounter: Integer; procedure DoTest(const TestDescr: string; Func: TTestFunc; RequiredResult: NativeInt); var res: NativeInt; begin Inc(TestCounter); Log('~ Test #'+IntToStr(TestCounter)+'. '+TestDescr); Log(' Dlg starting'); Func(res); Log(' Dlg finished with result "'+ModalResults[res]+'"'); if res <> RequiredResult then begin Log('!!! Test failed'); Inc(FailCounter); end else Log('~ Test #'+IntToStr(TestCounter)+' passed'); end; function CreateTestForm: TForm; begin Result := TForm.Create(Self); Result.SetBounds(0, 0, 300, 300); Result.Position := poScreenCenter; with TButton.Create(Result) do begin Parent := Result; Name := 'btnOK'; Caption := 'OK'; ModalResult := mrYes; SetBounds(0, 0, 60, 30); end; with TButton.Create(Result) do begin Parent := Result; Name := 'btnNo'; Caption := 'No'; ModalResult := mrNo; SetBounds(70, 0, 60, 30); end; end; var form: TForm; btnwnd: HWND; Func: TTestFunc; const Countdown = 3; begin TestCounter := 0; FailCounter := 0; // ### MsgBox ### Func := procedure(var Res: NativeInt) begin Res := MessageBox(Handle, 'Do something bad?', 'Mmm?', MB_YESNOCANCEL); end; LaunchCountdown(Handle, Countdown, cdsByClass, 1, 'Button'); DoTest('MsgBox, 1st button by class', Func, mrYes); LaunchCountdown(Handle, Countdown, cdsByText, 0, '&Нет'); DoTest('MsgBox, button by text',Func, mrNo); LaunchCountdown(Handle, Countdown, cdsByClass, 2, 'Button', 'Nein!'); DoTest('MsgBox, change initial button text', Func, mrNo); // ### Form ### Func := procedure(var Res: NativeInt) begin Res := form.ShowModal; end; form := CreateTestForm; LaunchCountdown(Handle, Countdown, cdsByClass, 2, 'TButton'); DoTest('Form, 1st button by class', Func, mrYes); form.Free; form := CreateTestForm; LaunchCountdown(Handle, Countdown, cdsByText, 0, 'No'); DoTest('Form, button by text', Func, mrNo); form.Free; form := CreateTestForm; btnwnd := (form.FindChildControl('btnOK') as TButton).Handle; LaunchCountdown(Handle, Countdown, cdsHwnd, btnwnd, ''); DoTest('Form, button by handle', Func, mrYes); form.Free; // ### Dialog ### Func := procedure(var Res: NativeInt) begin Res := DialogBoxParam(HInstance, MakeIntResource(IDD_DLGMSGBOX), Handle, @DialogProc, LPARAM(Self)); end; LaunchCountdown(Handle, Countdown, cdsByClass, 1, 'Button'); DoTest('Dialog, 2nd button by class', Func, mrRetry); LaunchCountdown(Handle, Countdown, cdsByDlgID, IDRETRY, ''); DoTest('Dialog, button by dialog ID', Func, mrRetry); LaunchCountdown(Handle, Countdown, cdsByClass, 2, 'Button', 'Dismiss'); DoTest('Dialog, change initial button text', Func, mrCancel); // ### Resume ### if FailCounter = 0 then Log(Format('@@ All %d tests passed @@', [TestCounter])) else Log(Format('@@ %d/%d test(s) failed', [FailCounter, TestCounter])); end; procedure TForm2.Log(const Msg: string); begin Memo1.Lines.Add(Msg); end; end.
unit DbfDataSet; interface uses SysUtils, Classes, Db, DsgnIntf; const EndHeaderChar: Char = #13; EndFileChar: Char = #$1A; type TFilenameProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; EDBFError = class (Exception); pDateTime = ^TDateTime; pBoolean = ^Boolean; pInteger = ^Integer; PRecInfo = ^TRecInfo; TRecInfo = record Bookmark: Longint; BookmarkFlag: TBookmarkFlag; end; TDbfHeader = packed record { Dbase III + header definition } VersionNumber :byte; { version number (03h or 83h ) 1} LastUpdateYear :byte; { last update YY MM DD 1} LastUpdateMonth :byte; {1} LastUpdateDay :byte; {1} NumberOfRecords :longint; { number of record in database 4} BytesInHeader :smallint;{ number of bytes in header 2} BytesInRecords :smallint;{ number of bytes in records 2} ReservedInHeader :array[1..20] of char; { reserved bytes in header 20} end; {= 32} TDbfField = packed record fdName :array[0..10] of char; { Name of this record 11} fdType :Char; { type of record - C,N,D,L,etc. 1} fdOffset :Longint; { offset 4} fdWidth :Byte; { total field width of this record 1} fdDecimals :Byte; { number of digits to right of decimal 1} fdReserved :array[1..14] of byte; { 8 bytes reserved 14} end; { record starts = 32} PRecordHeader = ^TRecordHeader; TRecordHeader = record DeletedFlag : Char; end; TDbfDataSet = class(TDataSet) private FStream: TStream; // the physical table FTableName: string; // table path and file name FDBFHeader : TdbfHeader; // record data FRecordHeaderSize : Integer; // The size of the record header FRecordCount, // current number of record FRecordSize, // the size of the actual data FRecordBufferSize, // data + housekeeping (TRecInfo) FRecordInfoOffset, // offset of RecInfo in record buffer FCurrentRecord, // current record (0 to FRecordCount - 1) BofCrack, // before the first record (crack) EofCrack: Integer; // after the last record (crack) FIsTableOpen: Boolean; // status FFileWidth, // field widths in record FFileDecimals, // field decimals in record FFileOffset: TList; // field offsets in record FReadOnly : Boolean; // Enhancements FStartData : Integer; // Position in file where data starts procedure _ReadRecord(Buffer:PChar;IntRecNum: Integer); procedure _WriteRecord(Buffer:PChar;IntRecNum: Integer); procedure _AppendRecord(Buffer: PChar); procedure _SwapRecords(Rec1,REc2: Integer); function _CompareRecords(SortFields: array of String; Rec1, Rec2: Integer): Integer; function _ProcessFilter(Buffer: PChar): Boolean; protected procedure DBFToFieldType(const Fld: TDBFField; var FD: TFieldDef); procedure FieldToDBFDef(const FD: TField; var Fld: TDbfField); protected // TDataSet virtual abstract method function AllocRecordBuffer: PChar; override; procedure FreeRecordBuffer(var Buffer: PChar); override; procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override; function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override; function GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override; function GetRecordSize: Word; override; procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override; procedure InternalClose; override; procedure InternalDelete; override; procedure InternalFirst; override; procedure InternalGotoBookmark(Bookmark: Pointer); override; procedure InternalHandleException; override; procedure InternalInitFieldDefs; override; procedure InternalInitRecord(Buffer: PChar); override; procedure InternalLast; override; procedure InternalOpen; override; procedure InternalPost; override; procedure InternalSetToRecord(Buffer: PChar); override; function IsCursorOpen: Boolean; override; procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override; procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override; procedure SetFieldData(Field: TField; Buffer: Pointer); override; // TDataSet virtual method (optional) function GetRecordCount: Integer; override; procedure SetRecNo(Value: Integer); override; function GetRecNo: Integer; override; Procedure WriteHeader; public constructor Create(AOwner:tComponent); override; function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override; procedure CreateTable; procedure PackTable; procedure SortTable(SortFields : array of String); procedure UnsortTable; published property TableName: string read FTableName write FTableName; property ReadOnly: Boolean read FReadOnly write FReadonly default False; property DBFHeader: TDBFHeader read FDBFHeader; // redeclared data set properties property Active; property Filter; property Filtered; property BeforeOpen; property AfterOpen; property BeforeClose; property AfterClose; property BeforeInsert; property AfterInsert; property BeforeEdit; property AfterEdit; property BeforePost; property AfterPost; property BeforeCancel; property AfterCancel; property BeforeDelete; property AfterDelete; property BeforeScroll; property AfterScroll; property OnCalcFields; property OnDeleteError; property OnEditError; property OnNewRecord; property OnPostError; end; procedure Register; implementation uses TypInfo, Dialogs, Windows, Forms, Controls, IniFiles; procedure TDbfDataSet._ReadRecord(Buffer: PChar; IntRecNum: Integer); begin FStream.Position := FStartData + (FRecordSize * IntRecNum); try FStream.ReadBuffer(Buffer^, FRecordSize); except end; end; procedure TDbfDataSet._WriteRecord(Buffer: PChar; IntRecNum: Integer); begin if not FReadOnly then begin FStream.Position := FStartData + (FRecordSize * IntRecNum); FStream.WriteBuffer (Buffer^, FRecordSize); end; end; procedure TDbfDataSet._AppendRecord(Buffer: PChar); begin if not FReadOnly then begin FStream.Position := FStartData + (FRecordSize * (FRecordCount{+FDeletedCount})); FStream.WriteBuffer(Buffer^, FRecordSize); end; end; procedure TDbfDataSet.InternalOpen; var Field : TField; I,J : integer; D : string; begin if not FileExists(FTableName) then raise EDBFError.Create ('Open: Таблица не найдена'); if FReadOnly then FStream := TFileStream.Create(FTableName, fmOpenRead or fmShareDenyWrite) else FStream := TFileStream.Create(FTableName, fmOpenReadWrite or fmShareExclusive); fStream.ReadBuffer(FDBFHeader, SizeOf(TDBFHeader)); BofCrack := -1; EofCrack := FRecordCount; FCurrentRecord := BofCrack; BookmarkSize := sizeOf(Integer); if not (assigned(FFileOffset)) then FFileOffset := TList.Create; if not (assigned(FFileWidth)) then FFileWidth := TList.Create; if not (assigned(FFileDecimals)) then FFileDecimals := TList.Create; InternalInitFieldDefs; FRecordInfoOffset := FRecordSize; FRecordBufferSize := FRecordSize + SizeOf(TRecInfo); if DefaultFields then CreateFields; BindFields(True); for i := 0 to FieldCount-1 do begin Field := Fields[i]; if (Field.DataType = ftFloat) and (Integer(FFileDecimals[i])>0) then begin d := '0.'; for j := 1 to Integer(FFileDecimals[i]) do d := d + '0'; (Field as TFloatField).DisplayFormat := d; end; end; // get the number of records and check size FRecordCount := fDBFHeader.NumberOfRecords; // everything OK: table is now open FIsTableOpen := True; // ShowMessage ('InternalOpen: RecCount: ' + IntToStr (FRecordCount)); end; procedure TDbfDataSet.DBFToFieldType(const Fld: TDBFField; var FD: TFieldDef); begin with FD do begin Size := 0; case Fld.fdType of 'C': begin DataType := ftString; Size := Fld.fdWidth; end; 'N', 'F': begin if Fld.fdDecimals>0 then begin DataType := ftFloat; Precision := Fld.fdDecimals; end else DataType := ftInteger; end; 'L': DataType := ftBoolean; 'D': DataType := ftDate; else DataType := ftUnknown; end; Name := Fld.fdName; Required := False; end; end; procedure TDbfDataSet.FieldToDBFDef(const FD: TField; var Fld: TDbfField); begin FillChar(Fld, SizeOf(TDbfField), #0); with FD do begin StrPLCopy(Fld.fdName, FieldName, SizeOf(Fld.fdName)); case DataType of ftFloat, ftInteger, ftLargeInt, ftWord, ftSmallInt: begin Fld.fdType := 'N'; Fld.fdWidth := DisplayWidth; if (FD is TFloatField) then Fld.fdDecimals := (FD as TFloatField).Precision; end; ftBoolean: begin Fld.fdType := 'L'; Fld.fdWidth := 1; end; ftDate: begin Fld.fdType := 'D'; Fld.fdWidth := 8; end; else begin Fld.fdType := 'C'; Fld.fdWidth := Size; end; end; end; end; procedure TDbfDataSet.InternalInitFieldDefs; var Il: Integer; TmpFileOffset: Integer; NumberOfFields: Integer; Fld: TDBFField; FldName: array[0..11] of Char; NewFieldDef: TFieldDef; begin FieldDefs.Clear; FStream.Seek(SizeOf(TDbfHeader), soFromBeginning); NumberOfFields := (FDbfHeader.BytesInHeader-SizeOf(DbfHeader)) div SizeOf(TDbfField); if not Assigned(FFileOffset) then FFileOffset := TList.Create; FFileOffset.Clear; if not Assigned(FFileWidth) then FFileWidth := TList.Create; FFileWidth.Clear; if not Assigned(FFileDecimals) then FFileDecimals := TList.Create; FFileDecimals.Clear; if NumberOfFields>0 then begin TmpFileOffset := 0; for Il := 0 to NumberOfFields-1 do begin FStream.Read(Fld, SizeOf(Fld)); FFileOffset.Add(Pointer(TmpFileOffset)); FFileWidth.Add(Pointer(Fld.fdWidth)); FFileDecimals.Add(Pointer(Fld.fdDecimals)); StrLCopy(FldName, Fld.fdName, SizeOf(FldName)-1); NewFieldDef := TFieldDef.Create(FieldDefs); DBFToFieldType(Fld, NewFieldDef); NewFieldDef.FieldNo := Il+1; Inc(TmpFileOffset, Fld.fdWidth); end; FRecordSize := TmpFileOffset + FrecordHeaderSize; FStartData := FDbfHeader.BytesInHeader; end; end; procedure TDbfDataSet.InternalClose; begin // if required, save updated header if (fDBFHeader.NumberOfRecords <> FRecordCount) or (fDBFHeader.BytesInRecords = 0) then begin FDBFHeader.BytesInRecords := FRecordSize; FDBFHeader.NumberOfRecords := FRecordCount; WriteHeader; end; if not FReadOnly then begin FStream.Position := FStartData + (FRecordSize * FRecordCount); FStream.WriteBuffer(EndFileChar, 1); end; // disconnet field objects BindFields(False); // destroy field object (if not persistent) if DefaultFields then DestroyFields; // free the internal list field offsets if Assigned(FFileOffset) then FFileOffset.Free; FFileOffset := nil; if Assigned(FFileWidth) then FFileWidth.Free; FFileWidth := nil; if Assigned(FFileDecimals) then FFileDecimals.Free; FFileDecimals := nil; FCurrentRecord := -1; // close the file FIsTableOpen := False; FStream.Free; FStream := nil; end; function TDbfDataSet.IsCursorOpen: Boolean; begin Result := FIsTableOpen; end; procedure TDbfDataSet.WriteHeader; begin if (FStream <> nil) and not FReadOnly then begin FSTream.Seek(0, soFromBeginning); FStream.WriteBuffer(fDBFHeader, SizeOf(TDbfHeader)); end; end; constructor TDbfDataSet.Create(AOwner:tComponent); begin inherited create(aOwner); FRecordHeaderSize := SizeOf(TRecordHeader); end; function ParentWnd: hWnd; begin Result := GetForegroundWindow {GetTopWindow(0)}; end; procedure TDbfDataSet.CreateTable; var Ix : Integer; Offs : Integer; Fld : TDbfField; begin CheckInactive; // InternalInitFieldDefs; if not FileExists(FTableName) or (MessageBox(ParentWnd, PChar('Файл ' + FTableName + ' уже существует. Перезаписать его?'), 'Создание таблицы', MB_YESNOCANCEL+MB_ICONWARNING) = ID_YES) then begin if FieldDefs.Count = 0 then begin for Ix := 0 to FieldCount - 1 do begin with Fields[Ix] do begin if FieldKind = fkData then FieldDefs.Add(FieldName, DataType, Size, Required); end; end; end; FStream := TFileStream.Create(FTableName, fmCreate{ or fmShareExclusive}); try FillChar(fDBFHeader, SizeOf(TDbfHeader), #0); WriteHeader; Offs := 0; for Ix := 0 to FieldCount - 1 do begin FieldToDBFDef(Fields[Ix], Fld); Fld.fdOffset := 1 + Offs; Inc(Offs, Fld.fdWidth); FStream.Write(Fld, SizeOf(TDbfField)); end; FStream.Write(EndHeaderChar, 1); {"заморочка" нортоновского просмотрщика} with FDbfHeader do begin VersionNumber := $03; BytesInHeader := FStream.Position; BytesInRecords := Offs; end; FRecordSize := Offs + FRecordHeaderSize; FStartData := FDbfHeader.BytesInHeader; WriteHeader; finally fStream.Free; fStream := nil; end; end; end; Procedure TDbfDataSet.PackTable; var NewStream, OldStream : tStream; PC : PChar; Ix : Integer; // DescribF : TBDescribField; NewDataFileHeader : tDBFHeader; DataBuffer : Pointer; NumberOfFields : integer; Fld : TDBFField; BEGIN OldStream := Nil; NewStream := Nil; CheckInactive; // if Active then // raise eBinaryDataSetError.Create ('Dataset must be closed before packing.'); if fTableName = '' then raise EDBFError.Create('Table name not specified.'); if not FileExists (FTableName) then raise EDBFError.Create('Table '+fTableName+' does not exist.'); PC := @fTablename[1]; CopyFile(PChar(PC),PChar(PC+',old'+#0),False); // create the new file if FieldDefs.Count = 0 then begin for Ix := 0 to FieldCount - 1 do begin with Fields[Ix] do begin if FieldKind = fkData then FieldDefs.Add(FieldName,DataType,Size,Required); end; end; end; TRY NewStream := TFileStream.Create (FTableName+',new', fmCreate or fmShareExclusive); OldStream := tFileStream.Create (fTableName+',old', fmOpenRead or fmShareExclusive); OldStream.ReadBuffer(NewDataFileHeader,SizeOf(TDbfHeader)); NewStream.WriteBuffer(NewDataFileHeader,SizeOf(TDbfHeader)); NumberOfFields := ((NewDataFileHeader.BytesInHeader-sizeof(TDbfHeader))div 32); for IX := 0 to NumberOfFields do BEGIN OldStream.Read(Fld,SizeOf(TDbfField)); NewStream.Write(Fld,SizeOf(TDbfField)); END; GetMem(DataBuffer,NewDataFileHeader.BytesInRecords); REPEAT IX := OldStream.Read(DataBuffer^,NewDataFileHeader.BytesInRecords); if (IX = NewDataFileHeader.BytesInRecords) and (pRecordHeader(DataBuffer)^.DeletedFlag <> '*') then NewStream.WRite(DataBuffer^,NewDataFileHeader.BytesInRecords); Until IX <> NewDataFileHeader.BytesInRecords; FreeMem(DataBuffer,NewDataFileHeader.BytesInRecords); finally // close the file NewStream.Free; OldStream.Free; end; CopyFile(PChar(PC+',new'+#0),PChar(PC),False); DeleteFile(Pchar(PC+',new'+#0)); DeleteFile(Pchar(PC+',old'+#0)); end; procedure TDbfDataSet._SwapRecords(Rec1, Rec2: Integer); var Buffer1, Buffer2 : PChar; Bookmark1, BOokmark2 : TBookmarkFlag; begin if Rec1 < 0 then Exit; if Rec2 < 0 then Exit; Buffer1 := AllocRecordBuffer; Buffer2 := AllocRecordBuffer; _ReadRecord(Buffer1, Rec1); _ReadRecord(Buffer2, Rec2); Bookmark1 := GetBookmarkFlag(Buffer1); Bookmark2 := GetBookmarkFlag(Buffer2); SetBookmarkFlag(Buffer1,Bookmark2); SetBookmarkFlag(Buffer2,Bookmark1); _WriteRecord(Buffer1, Rec2); _WriteRecord(Buffer2, Rec1); StrDispose(Buffer1); StrDispose(Buffer2); end; function TDbfDataSet._CompareRecords(SortFields:Array of String;Rec1,Rec2:Integer):Integer; FAR; {-Compare the records Rec1, Rec2 and return -1 if Rec1 < Rec2, 0 if Rec1 = Rec2, 1 if Rec1 > Rec2 } var IX : Integer; function CompareHelper(KeyId: string;Rec1,Rec2:Integer):Integer; var SKey1, SKey2 : string; IKey1, IKey2 : Integer; fKey1, fKey2 : Double; dKey1, dKey2 : tDateTime; CompareType : tFieldType; KeyField : tField; begin KeyField := FieldByName(KeyID); CompareType := KeyField.DataType; Case CompareType of ftFloat, ftCurrency, ftBCD : BEGIN _ReadRecord(ActiveBuffer,Rec1-1); fKey1 := KeyField.AsFloat; _ReadRecord(ActiveBuffer,Rec2-1); fKey2 := KeyField.AsFloat; if fKey1 < fKey2 then Result := -1 else if fKey1 > fKey2 then Result := 1 else Result := 0; END; ftSmallInt, ftInteger, ftWord : BEGIN _ReadRecord(ActiveBuffer, Rec1-1); IKey1 := KeyField.AsInteger; _ReadRecord(ActiveBuffer, Rec2-1); IKey2 := KeyField.AsInteger; if IKey1 < IKey2 then Result := -1 else if IKey1 > IKey2 then Result := 1 else Result := 0; END; ftDate, ftTime, ftDateTime : BEGIN _ReadRecord(ActiveBuffer, Rec1-1); dKey1 := KeyField.AsDateTime; _ReadRecord(ActiveBuffer, Rec2-1); dKey2 := KeyField.AsDateTime; if dKey1 < dKey2 then Result := -1 else if dKey1 > dKey2 then Result := 1 else Result := 0; END; else BEGIN _ReadRecord(ActiveBuffer, Rec1-1); SKey1 := KeyField.AsString; _ReadRecord(ActiveBuffer, Rec2-1); SKey2 := KeyField.AsString; if SKey1 < SKey2 then Result := -1 else if SKey1 > SKey2 then Result := 1 else Result := 0; END; END; END; begin IX := 0; repeat // Loop through all available sortfields until not equal or no more sort fiels. Result := CompareHelper(SortFields[IX],Rec1,Rec2); Inc(IX); until (Result <> 0) or (IX > High(SortFields)); end; procedure TDbfDataSet.SortTable(SortFields : Array of String); { This is the main sorting routine. It is passed the number of elements and the two callback routines. The first routine is the function that will perform the comparison between two elements. The second routine is the procedure that will swap two elements if necessary } // Source: UNDU #8 procedure QSort(uNElem: Integer); { uNElem - number of elements to sort } procedure qSortHelp(pivotP: Integer; nElem: word); label TailRecursion, qBreak; var leftP, rightP, pivotEnd, pivotTemp, leftTemp: word; lNum: Integer; retval: integer; begin TailRecursion: if (nElem <= 2) then begin if (nElem = 2) then begin rightP := pivotP +1; if (_CompareRecords(SortFields,pivotP, rightP) > 0) then _SwapRecords(pivotP, rightP); end; exit; end; rightP := (nElem -1) + pivotP; leftP := (nElem shr 1) + pivotP; { sort pivot, left, and right elements for "median of 3" } if (_CompareRecords(SortFields,leftP, rightP) > 0) then _SwapRecords(leftP, rightP); if (_CompareRecords(SortFields,leftP, pivotP) > 0) then _SwapRecords(leftP, pivotP) else if (_CompareRecords(SortFields,pivotP, rightP) > 0) then _SwapRecords(pivotP, rightP); if (nElem = 3) then begin _SwapRecords(pivotP, leftP); exit; end; { now for the classic Horae algorithm } pivotEnd := pivotP + 1; leftP := pivotEnd; repeat retval := _CompareRecords(SortFields,leftP, pivotP); while (retval <= 0) do begin if (retval = 0) then begin _SwapRecords(LeftP, PivotEnd); Inc(PivotEnd); end; if (leftP < rightP) then Inc(leftP) else goto qBreak; retval := _CompareRecords(SortFields,leftP, pivotP); end; {while} while (leftP < rightP) do begin retval := _CompareRecords(SortFields,pivotP, rightP); if (retval < 0) then Dec(rightP) else begin _SwapRecords(leftP, rightP); if (retval <> 0) then begin Inc(leftP); Dec(rightP); end; break; end; end; {while} until (leftP >= rightP); qBreak: if (_CompareRecords(SortFields,leftP, pivotP) <= 0) then Inc(leftP); leftTemp := leftP -1; pivotTemp := pivotP; while ((pivotTemp < pivotEnd) and (leftTemp >= pivotEnd)) do begin _SwapRecords(pivotTemp, leftTemp); Inc(pivotTemp); Dec(leftTemp); end; {while} lNum := (leftP - pivotEnd); nElem := ((nElem + pivotP) -leftP); if (nElem < lNum) then begin qSortHelp(leftP, nElem); nElem := lNum; end else begin qSortHelp(pivotP, lNum); pivotP := leftP; end; goto TailRecursion; end; {qSortHelp } begin if (uNElem < 2) then exit; { nothing to sort } qSortHelp(1, uNElem); end; { QSort } BEGIN CheckActive; if FReadOnly then raise eDBFError.Create ('Dataset must be opened for read/write to perform sort.'); // if fDataFileHeader.DeletedCount > 0 then // BEGIN // Close; // PackTable; // Open; // END; QSort(FRecordCount {+ fDeletedCount}); First; END; procedure TDbfDataSet.UnsortTable; var IX : Integer; begin First; Randomize; for IX := 0 to RecordCOunt do begin _SwapRecords(IX, Random(RecordCount+1)); end; First; end; procedure TDbfDataSet.InternalGotoBookmark(Bookmark: Pointer); var ReqBookmark: Integer; begin ReqBookmark := PInteger(Bookmark)^; // ShowMessage ('InternalGotoBookmark: ' + // IntToStr (ReqBookmark)); if (ReqBookmark >= 0) and (ReqBookmark < FRecordCount {+ fDeletedCount}) then FCurrentRecord := ReqBookmark else raise eDBFError.Create ('Bookmark ' + IntToStr(ReqBookmark) + ' not found'); end; procedure TDbfDataSet.InternalSetToRecord(Buffer: PChar); var ReqBookmark: Integer; begin ReqBookmark := PRecInfo(Buffer + FRecordInfoOffset).Bookmark; InternalGotoBookmark(@ReqBookmark); end; function TDbfDataSet.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; begin Result := PRecInfo(Buffer + FRecordInfoOffset).BookmarkFlag; end; procedure TDbfDataSet.SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); begin PRecInfo(Buffer + FRecordInfoOffset).BookmarkFlag := Value; end; procedure TDbfDataSet.GetBookmarkData(Buffer: PChar; Data: Pointer); begin PInteger(Data)^ := PRecInfo(Buffer + FRecordInfoOffset).Bookmark; end; procedure TDbfDataSet.SetBookmarkData(Buffer: PChar; Data: Pointer); begin PRecInfo(Buffer + FRecordInfoOffset).Bookmark := PInteger(Data)^; end; procedure TDbfDataSet.InternalFirst; begin FCurrentRecord := BofCrack; end; procedure TDbfDataSet.InternalLast; begin EofCrack := FRecordCount {+ fDeletedCount}; FCurrentRecord := EofCrack; end; function TDbfDataSet.GetRecordCount: Longint; begin CheckActive; Result := FRecordCount; end; function TDbfDataSet.GetRecNo: Longint; begin UpdateCursorPos; if FCurrentRecord < 0 then Result := 1 else Result := FCurrentRecord + 1; end; procedure TDbfDataSet.SetRecNo(Value: Integer); begin CheckBrowseMode; if (Value > 1) and (Value <= (FRecordCount{+FDeletedCount})) then begin FCurrentRecord := Value - 1; Resync([]); end; end; function TDbfDataSet.GetRecordSize: Word; begin Result := FRecordSize; // data only end; function TDbfDataSet.AllocRecordBuffer: PChar; begin Result := StrAlloc(FRecordBufferSize+1); end; procedure TDbfDataSet.InternalInitRecord(Buffer: PChar); (*var Field : TField; i : integer; FieldOffset : integer; S : string; *) begin FillChar(Buffer^, FRecordBufferSize, 32); (* for i := 0 to FieldCount-1 do begin Field := Fields[i]; FieldOffset := Integer(FFileOffset[Field.FieldNo-1])+FRecordHeaderSize; if Field.DataType = ftString then begin pChar(Buffer+FieldOffset)^ := #0; end else if Field.DataType = ftFloat then begin pChar(Buffer+FieldOffset)^ := '0'; pChar(Buffer+FieldOffset+1)^ := #0; end else if Field.DataType = ftDate then begin S := '19900101'; CopyMemory(PChar(Buffer+FieldOffset),PChar(S),8); end else if Field.DataType = ftBoolean then begin pChar(Buffer+FieldOffset)^ := 'F'; end; end; *) end; procedure TDbfDataSet.FreeRecordBuffer (var Buffer: PChar); begin StrDispose(Buffer); end; function TDbfDataSet.GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; var Acceptable : Boolean; begin result := grOk; if FRecordCount < 1 then Result := grEOF else repeat case GetMode of gmCurrent : begin // ShowMessage ('GetRecord Current'); if (FCurrentRecord >= FRecordCount{+fDeletedCount}) or (FCurrentRecord < 0) then Result := grError; end; gmNext : begin if (fCurrentRecord < (fRecordCount{+fDeletedCount})-1) then Inc (FCurrentRecord) else Result := grEOF; end; gmPrior : begin if (fCurrentRecord > 0) then Dec(fCurrentRecord) else Result := grBOF; end; end; // fill record data area of buffer if Result = grOK then begin _ReadRecord(Buffer, fCurrentRecord ); {FStream.Position := FDataFileHeader.StartData + FRecordSize * FCurrentRecord; FStream.ReadBuffer (Buffer^, FRecordSize);} ClearCalcFields(Buffer); GetCalcFields(Buffer); with PRecInfo(Buffer + FRecordInfoOffset)^ do begin BookmarkFlag := bfCurrent; Bookmark := FCurrentRecord; end; end else if (Result = grError) and DoCheck then raise eDBFError.Create('GetRecord: Invalid record'); Acceptable := pRecordHeader(Buffer)^.DeletedFlag <> '*'; if Filtered then Acceptable := Acceptable and (_ProcessFilter(Buffer)); if (GetMode=gmCurrent) and Not Acceptable then Result := grError; until (Result <> grOK) or Acceptable; if ((Result=grEOF)or(Result=grBOF)) and Filtered and not (_ProcessFilter(Buffer)) then Result := grError; end; procedure TDbfDataSet.InternalPost; begin CheckActive; if State = dsEdit then begin // replace data with new data {FStream.Position := FDataFileHeader.StartData + (FRecordSize * FCurrentRecord); FStream.WriteBuffer (ActiveBuffer^, FRecordSize);} _WriteRecord(ActiveBuffer, FCurrentRecord); end else begin // always append InternalLast; {FStream.Seek (0, soFromEnd); FStream.WriteBuffer (ActiveBuffer^, FRecordSize);} pRecordHeader(ActiveBuffer)^.DeletedFlag := ' '; _AppendRecord(ActiveBuffer); Inc(FRecordCount); end; end; procedure TDbfDataSet.InternalAddRecord(Buffer:Pointer; Append:Boolean); begin // always append InternalLast; // add record at the end of the file {FStream.Seek (0, soFromEnd);} pRecordHeader(ActiveBuffer)^.DeletedFlag := ' '; _AppendRecord(ActiveBuffer); {FStream.WriteBuffer (ActiveBuffer^, FRecordSize);} Inc(FRecordCount); end; procedure TDbfDataSet.InternalDelete; begin CheckActive; // not supported in this version { raise eBinaryDataSetError.Create ( 'Delete: Operation not supported');} // pRecordHeader(ActiveBuffer)^.DeletedFlag := fDataFileHeader.LastDeleted; PChar(ActiveBuffer)^ := '*'; _WriteRecord(ActiveBuffer, FCurrentRecord); {FStream.Position := FDataFileHeader.StartData + (FRecordSize * FCurrentRecord); FStream.WriteBuffer (ActiveBuffer^, FRecordSize);} // fDBFHeader.LastDeleted := GetRecNo; // Inc(fDeletedCount); // Dec(fRecordCount); // fDBFHeader.NumberOfRecords := fRecordCount; // WriteHeader; Resync([]); end; type PDate = ^TDate; function TDbfDataSet.GetFieldData(Field: TField; Buffer: Pointer):Boolean; const MesTitle: PChar = 'GetFieldData'; var FieldOffset, I, Err: Integer; S, OldDateFormat : string; D : Double; Buf: array[0..1023] of Char; Buf2: PChar; begin Result := False; Buf2 := ActiveBuffer; if (FRecordCount>0) and (Field.FieldNo >= 0) and (Assigned(Buffer)) and (Assigned(Buf2)) and (Field.FieldNo<=FFileOffset.Count) then begin FieldOffset := Integer(FFileOffset[Field.FieldNo-1])+FRecordHeaderSize; case Field.DataType of ftString: begin StrLCopy(Buffer, @Buf2[FieldOffset], Integer(FFileWidth[Field.FieldNo-1])); Result := True; end; ftFloat: begin StrLCopy(Buf, @Buf2[FieldOffset], Integer(FFileWidth[Field.FieldNo-1])); S := StrPas(Buf); Val(Trim(S), D, Err); PDouble(Buffer)^ := D; Result := True; end; ftInteger: begin StrLCopy(Buf, @Buf2[FieldOffset], Integer(FFileWidth[Field.FieldNo-1])); S := StrPas(Buf); Val(Trim(S), I, Err); PInteger(Buffer)^ := I; Result := True; end; ftDate: begin StrLCopy(Buf, @Buf2[FieldOffset], Integer(FFileWidth[Field.FieldNo-1])); S := StrPas(Buf); while Length(S)<8 do S := S+'0'; S := Copy(S,7,2) + DateSeparator + Copy(S,5,2) + DateSeparator + Copy(S,1,4); OldDateFormat := ShortDateFormat; ShortDateFormat := 'dd/mm/yyyy'; try try PInteger(Buffer)^ := Trunc(Double(StrToDate(S)))+693594; Result := True; except end; finally ShortDateFormat := OldDateFormat; end; end; ftBoolean: begin Result := True; if Buf2[FieldOffset] in ['S','T','Y'] then PBoolean(Buffer)^ := True else if Buf2[FieldOffset] in ['N','F'] then PBoolean(Buffer)^ := False else Result := False; end else begin MessageBox(ParentWnd, 'Недопустимый тип поля', MesTitle, MB_OK+MB_ICONERROR); Result := False; end; end; end; end; function CharCopy(Dest, Source: PChar; MaxLen: Cardinal): PChar; var Len: Cardinal; begin Len := StrLen(Source); if Len>MaxLen then Len := MaxLen; Move(Source^, Dest^, Len); Result := Dest; end; procedure TDbfDataSet.SetFieldData(Field: TField; Buffer: Pointer); const MesTitle: PChar = 'SetFieldData'; var N, FieldOffset: Integer; Buf2 : PChar; S: string; begin Buf2 := ActiveBuffer; if (Field.FieldNo >= 0) and Assigned(Buffer) and Assigned(Buf2) then begin FieldOffset := Integer(FFileOffset[Field.FieldNo-1])+FRecordHeaderSize; N := Integer(FFileWidth[Field.FieldNo-1]); case Field.DataType of ftString: CharCopy(@Buf2[FieldOffset], Buffer, N); ftFloat: begin Str(pDouble(Buffer)^:0:Integer(FFileDecimals[Field.FieldNo-1]), S); while Length(S)<N do S := ' '+S; CharCopy(@Buf2[FieldOffset], PChar(S), N); end; ftInteger: begin Str(PInteger(Buffer)^, S); while Length(S)<N do S := ' '+S; CharCopy(@Buf2[FieldOffset], PChar(S), N); end; ftDate: begin S := FormatDateTime('yyyymmdd', PInteger(Buffer)^-693594); CharCopy(@Buf2[FieldOffset], pChar(S), N); end; ftBoolean: begin if PBoolean(Buffer)^ then Buf2[FieldOffset] := 'T' else Buf2[FieldOffset] := 'F'; end else MessageBox(ParentWnd, 'Недопустимый тип поля', MesTitle, MB_OK+MB_ICONERROR); end; DataEvent(deFieldChange, Longint(Field)); end; end; procedure TDbfDataSet.InternalHandleException; begin Application.HandleException(Self); end; function TDbfDataSet._ProcessFilter(Buffer:PChar):boolean; var FilterExpresion : string; PosComp : integer; FName : string; FieldPos : integer; FieldOffset : integer; FieldValue : Variant; TestValue : Variant; FieldText : string; OldShortDateFormat : string; begin FilterExpresion := Filter; PosComp := Pos('>',FilterExpresion); if PosComp=0 then PosComp := Pos('<',FilterExpresion); if PosComp=0 then PosComp := Pos('=',FilterExpresion); if PosComp=0 then begin _ProcessFilter := True; Exit; end; FName := Trim(Copy(FilterExpresion,1,PosComp-1)); FieldPos := FieldDefs.IndexOf(FName); FieldOffset := integer(FFileOffset[FieldPos]); if FieldPos < 0 then _ProcessFilter := True else if FieldDefs.Items[FieldPos].DataType = ftString then begin // STRING try FieldValue := ''; FieldOffset := FieldOffset+1; While (Buffer[FieldOffset]<>#0) and (Length(FieldValue)<integer(FFileWidth[FieldPos])) do begin FieldValue := FieldValue + Buffer[FieldOffset]; FieldOffset := FieldOffset+1; end; FieldValue := Trim(FieldValue); TestValue := Trim(Copy(FilterExpresion,PosComp+2,Length(FilterExpresion)-PosComp-2)); if FilterExpresion[PosComp]='=' then _ProcessFilter := (FieldValue=TestValue) else if FilterExpresion[PosComp]='>' then begin if FilterExpresion[PosComp+1]='=' then _ProcessFilter := (FieldValue>=Copy(TestValue,2,(Length(TestValue)-1))) else _ProcessFilter := (FieldValue>TestValue); end else if FilterExpresion[PosComp]='<' then begin if FilterExpresion[PosComp+1]='=' then _ProcessFilter := (FieldValue<=Copy(TestValue,2,(Length(TestValue)-1))) else _ProcessFilter := (FieldValue<TestValue); end else _ProcessFilter := False; except _ProcessFilter := False; end; end else if FieldDefs.Items[FieldPos].DataType = ftFloat then begin // FLOAT try FieldText := ''; FieldOffset := FieldOffset+1; While (Buffer[FieldOffset]<>#0) and (Length(FieldText)<integer(FFileWidth[FieldPos])) do begin FieldText := FieldText + Buffer[FieldOffset]; FieldOffset := FieldOffset+1; end; FieldText := Trim(FieldText); if Pos('.',FieldText)>0 then FieldText[Pos('.',FieldText)] := DecimalSeparator; FieldValue := StrToFloat(FieldText); if FilterExpresion[PosComp+1]='='then FieldText := Trim(Copy(FilterExpresion,PosComp+2,Length(FilterExpresion)-PosComp-1)) else FieldText := Trim(Copy(FilterExpresion,PosComp+1,Length(FilterExpresion)-PosComp)); if Pos('.',FieldText)>0 then FieldText[Pos('.',FieldText)] := DecimalSeparator; TestValue := StrToFloat(FieldText); if FilterExpresion[PosComp]='=' then _ProcessFilter := (FieldValue=TestValue) else if FilterExpresion[PosComp]='>'then begin if FilterExpresion[PosComp+1]='='then _ProcessFilter := (FieldValue>=TestValue) else _ProcessFilter := (FieldValue>TestValue); end else if FilterExpresion[PosComp]='<'then begin if FilterExpresion[PosComp+1]='='then _ProcessFilter := (FieldValue<=TestValue) else _ProcessFilter := (FieldValue<TestValue); end else _ProcessFilter := False; except _ProcessFilter := False; end; end else if FieldDefs.Items[FieldPos].DataType = ftDate then begin // DATE OldShortDateFormat := ShortDateFormat; try FieldText := ''; FieldOffset := FieldOffset+1; While (Buffer[FieldOffset]<>#0) and (Length(FieldText)<integer(FFileWidth[FieldPos])) do begin FieldText := FieldText + Buffer[FieldOffset]; FieldOffset := FieldOffset+1; end; FieldText := Trim(FieldText); FieldText := Copy(FieldText,1,4)+DateSeparator+Copy(FieldText,5,2)+DateSeparator+Copy(FieldText,7,2); ShortDateFormat := 'yyyy/mm/dd'; FieldValue := StrToDate(FieldText); if FilterExpresion[PosComp+1]='=' then FieldText := Trim(Copy(FilterExpresion,PosComp+2,Length(FilterExpresion)-PosComp-1)) else FieldText := Trim(Copy(FilterExpresion,PosComp+1,Length(FilterExpresion)-PosComp)); FieldText := Copy(FieldText,1,4)+DateSeparator+Copy(FieldText,5,2)+DateSeparator+Copy(FieldText,7,2); TestValue := StrToDate(FieldText); if FilterExpresion[PosComp]='=' then begin _ProcessFilter := (FieldValue=TestValue); end else if FilterExpresion[PosComp]='>' then begin if FilterExpresion[PosComp+1]='='then _ProcessFilter := (FieldValue>=TestValue) else _ProcessFilter := (FieldValue>TestValue); end else if FilterExpresion[PosComp]='<' then begin if FilterExpresion[PosComp+1]='='then _ProcessFilter := (FieldValue<=TestValue) else _ProcessFilter := (FieldValue<TestValue); end else _ProcessFilter := False; except _ProcessFilter := False; end; ShortDateFormat := OldShortDateFormat; end else _ProcessFilter := False; end; procedure TFilenameProperty.Edit; var FileOpen: TOpenDialog; begin FileOpen := TOpenDialog.Create(Nil); FileOpen.Filename := GetValue; FileOpen.Filter := 'dBase Files (*.DBF)|*.DBF|All Files (*.*)|*.*'; FileOpen.Options := FileOpen.Options + [ofPathMustExist, ofFileMustExist]; try if FileOpen.Execute then SetValue(FileOpen.Filename); finally FileOpen.Free; end; end; function TFilenameProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; procedure Register; begin RegisterComponents('BankClient', [TDbfDataSet]); RegisterPropertyEditor(TypeInfo(String), TDbfDataSet, 'TableName', TFileNameProperty); end; end.
unit GlobalUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Imaging.jpeg, Vcl.StdCtrls, Vcl.ComCtrls, ShellApi, Vcl.Forms, FileCtrl; type TString = class Value: string; end; const ACAPO = #13#10; function GetLocalComputerName: string; function RoundEx(Value: Double): Double; function StringToRoundEx(Value: string): Double; procedure WriteDebug(Value: Integer); overload; procedure WriteDebug(Value: string); overload; function GetStringValue(Value: TObject): string; function SetStringValue(Value: string): TString; procedure ListBoxAddItem(ListBox: TCustomListBox; Value1, Value2: string); function LoadImage(Filename: string): TBitmap; function ProportionalPictureResizing(Filename: string): TBitmap; overload; function ProportionalPictureResizing(Image: TBitmap): TBitmap; overload; function ThumbNail(Filename: string): TBitmap; overload; function ThumbNail(Image: TBitmap): TBitmap; overload; procedure SaveStringToFile(Filename: string; Value: string; const AppendString: Boolean = False); function LoadStringToFile(Filename: string): string; procedure ToolBarButtonFitWidht(ToolBar: TToolBar); function ResourceToString(Name: string): string; function IIF(Condition: Boolean; IFTrue: string; IFFalse: string): string; function GetPlatform: string; procedure WindowsVirtualKeyboard(); procedure Execute(Filename: string; const Params: string = ''; const DirPath: string = ''; const Visibility: Integer = SW_NORMAL); procedure Explode(Delimiter: Char; Str: string; ListOfStrings: TStrings); function Implode(Delimiter: Char; ListOfStrings: TStrings): string; function GetSubDirectories(const Directory: string): TStringList; function Wow64DisableWow64FsRedirection(var Wow64FsEnableRedirection: LongBool): LongBool; stdcall; external 'Kernel32.dll' name 'Wow64DisableWow64FsRedirection'; procedure RunDosInMemo(DosApp: string; AMemo: TMemo); function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string; function SelectFolder(const InitialPath: string = ''): string; implementation procedure WriteDebug(Value: Integer); overload; begin OutputDebugString(PChar(Value.ToString)); end; procedure WriteDebug(Value: string); overload; begin OutputDebugString(PChar(Value)); end; //------------------------------------------------------------------------------/// function GetSubDirectories(const directory: string): TStringList; var sr: TSearchRec; begin Result := TStringList.Create; try if FindFirst(IncludeTrailingPathDelimiter(directory) + '*.*', faDirectory, sr) < 0 then Exit else repeat if ((sr.Attr and faDirectory <> 0) and (sr.Name <> '.') and (sr.Name <> '..')) then Result.Add(IncludeTrailingPathDelimiter(directory) + sr.Name); until FindNext(sr) <> 0; finally FindClose(sr); end; end; procedure Explode(Delimiter: Char; Str: string; ListOfStrings: TStrings); begin ListOfStrings.Clear; ListOfStrings.Delimiter := Delimiter; ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer. ListOfStrings.DelimitedText := Str; end; function Implode(Delimiter: Char; ListOfStrings: TStrings): string; begin ListOfStrings.Delimiter := Delimiter; ListOfStrings.QuoteChar := #0; // for higher delphi versions Result := ListOfStrings.DelimitedText; end; procedure Execute(Filename: string; const Params: string = ''; const DirPath: string = ''; const Visibility: Integer = SW_NORMAL); begin ShellExecute(GetForegroundWindow, 'open', PChar(Filename), PChar(Params), PChar(DirPath), Visibility); end; function GetPlatform: string; begin //Result := SizeOf(Pointer) * 8; //PER VEDERE LA TUA ARCHITETTURA Result := GetEnvironmentVariable('ProgramW6432'); if Result <> '' then Result := 'x64' else Result := 'x86'; WriteDebug(Result); // Result := GetEnvironmentVariable('PROCESSOR_ARCHITECTURE'); end; procedure WindowsVirtualKeyboard(); var Wow64FsEnableRedirection: LongBool; begin if Wow64DisableWow64FsRedirection(Wow64FsEnableRedirection) then ShellExecute(0, nil, 'osk.exe', nil, nil, SW_SHOW); end; function IIF(Condition: Boolean; IFTrue: string; IFFalse: string): string; begin if Condition then Result := IFTrue else Result := IFFalse; end; function ResourceToString(Name: string): string; var ResStream: TResourceStream; begin Result := ''; ResStream := TResourceStream.Create(HInstance, Name, RT_RCDATA); if ResStream.Size = 0 then begin ResStream.Free; Exit; end; with TStringList.Create do begin LoadFromStream(ResStream); Result := Text; Free end; ResStream.Free; end; procedure ToolBarButtonFitWidht(ToolBar: TToolBar); var I: SmallInt; W, Width: Integer; Button: TToolButton; begin I := 0; Width := ToolBar.Width; Button := TToolButton(ToolBar.Controls[ToolBar.ControlCount - 1]); W := Button.Width; while W < Width do begin Button.Caption := ' ' + Button.Caption + ' '; W := Button.Width; Inc(I); if I > 100 then //PER PRECAUZIONE Break; end; end; function GetLocalComputerName: string; var c1: DWORD; arrCh: array[0..MAX_PATH] of Char; begin c1 := MAX_PATH; GetComputerName(arrCh, c1); if c1 > 0 then Result := arrCh else Result := ''; end; function RoundEx(Value: Double): Double; begin Result := Round(Value * 100) / 100 end; function StringToRoundEx(Value: string): Double; begin Result := Round(StrToFloat(Value) * 100) / 100 end; function GetStringValue(Value: TObject): string; begin Result := TString(Value).Value; end; function SetStringValue(Value: string): TString; begin Result := TString.Create; Result.Value := Value; end; procedure ListBoxAddItem(ListBox: TCustomListBox; Value1, Value2: string); begin ListBox.AddItem(Value1, SetStringValue(Value2)); end; function LoadImage(Filename: string): TBitmap; var Picture: TPicture; begin Picture := TPicture.Create; try Picture.LoadFromFile(Filename); Result := TBitmap.Create; try Result.Width := Picture.Width; Result.Height := Picture.Height; Result.Canvas.Draw(0, 0, Picture.Graphic); finally end; finally Picture.Free; end; end; function ProportionalPictureResizing(Filename: string): TBitmap; var Image: TBitmap; begin Image := LoadImage(Filename); Result := TBitmap.Create; Result := ProportionalPictureResizing(Image); Image.Free; end; function ProportionalPictureResizing(Image: TBitmap): TBitmap; const maxWidth = 125; maxHeight = 125; var thumbRect: TRect; begin try thumbRect.Left := 0; thumbRect.Top := 0; if Image.Width > Image.Height then begin thumbRect.Right := maxWidth; thumbRect.Bottom := (maxWidth * Image.Height) div Image.Width; end else begin thumbRect.Bottom := maxHeight; thumbRect.Right := (maxHeight * Image.Width) div Image.Height; end; Image.Canvas.StretchDraw(thumbRect, Image); Image.Width := thumbRect.Right; Image.Height := thumbRect.Bottom; //Image.SaveToFile('ThumbNailProportional.bmp'); Result := TBitmap.Create; Result.SetSize(maxWidth, maxHeight); Result.Canvas.Brush.Color := clWhite; Result.Canvas.FillRect(Result.Canvas.ClipRect); Result.Canvas.Draw((maxWidth div 2) - (Image.Width div 2), (maxHeight div 2) - (Image.Height div 2), Image); //Result.SaveToFile('ThumbNailProportional2.bmp'); finally end; end; function ThumbNail(Image: TBitmap): TBitmap; overload; var Pic: TPicture; begin Pic := TPicture.Create; try Pic.Assign(Image); Result := TBitmap.Create; try if Pic.Graphic is TBitmap then Result.PixelFormat := TBitmap(Pic.Graphic).PixelFormat else Result.PixelFormat := pf32bit; Result.Width := 125; Result.Height := 125; Result.Canvas.StretchDraw(Rect(0, 0, Result.Width, Result.Height), Pic.Graphic); //Result.SaveToFile('thumb.bmp'); except Result.Free; raise; end; finally Pic.Free; end; end; function ThumbNail(Filename: string): TBitmap; overload; var Image: TPicture; begin Image := TPicture.Create; Image.LoadFromFile(Filename); Result := ThumbNail(Image.Bitmap); Image.Free; end; procedure SaveStringToFile(Filename: string; Value: string; const AppendString: Boolean = False); begin with TStringList.Create do begin if AppendString then if FileExists(Filename) then LoadFromFile(Filename); Add(Value); if AppendString then Add(''); SaveToFile(Filename); Free; end; end; function LoadStringToFile(Filename: string): string; begin with TStringList.Create do begin if FileExists(Filename) then LoadFromFile(Filename); Result := Text; Free; end; end; procedure RunDosInMemo(DosApp: string; AMemo: TMemo); const READ_BUFFER_SIZE = 2400; var Security: TSecurityAttributes; readableEndOfPipe, writeableEndOfPipe: THandle; start: TStartupInfo; ProcessInfo: TProcessInformation; Buffer: PAnsiChar; BytesRead: DWORD; AppRunning: DWORD; begin Security.nLength := SizeOf(TSecurityAttributes); Security.bInheritHandle := True; Security.lpSecurityDescriptor := nil; if CreatePipe(readableEndOfPipe, writeableEndOfPipe, @Security, 0) then begin Buffer := AllocMem(READ_BUFFER_SIZE + 1); FillChar(start, SizeOf(start), #0); start.cb := SizeOf(start); start.dwFlags := start.dwFlags or STARTF_USESTDHANDLES; start.hStdInput := GetStdHandle(STD_INPUT_HANDLE); start.hStdOutput := writeableEndOfPipe; start.hStdError := writeableEndOfPipe; start.dwFlags := start.dwFlags + STARTF_USESHOWWINDOW; start.wShowWindow := SW_HIDE; ProcessInfo := Default(TProcessInformation); UniqueString(DosApp); if CreateProcess(nil, PChar(DosApp), nil, nil, True, NORMAL_PRIORITY_CLASS, nil, nil, start, ProcessInfo) then begin repeat AppRunning := WaitForSingleObject(ProcessInfo.hProcess, 100); Application.ProcessMessages; until (AppRunning <> WAIT_TIMEOUT); repeat BytesRead := 0; ReadFile(readableEndOfPipe, Buffer[0], READ_BUFFER_SIZE, BytesRead, nil); Buffer[BytesRead] := #0; OemToAnsi(Buffer, Buffer); AMemo.Text := AMemo.text + string(Buffer); until (BytesRead < READ_BUFFER_SIZE); end; FreeMem(Buffer); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); CloseHandle(readableEndOfPipe); CloseHandle(writeableEndOfPipe); end; end; function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string; var SA: TSecurityAttributes; SI: TStartupInfo; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; Buffer: array[0..255] of AnsiChar; BytesRead: Cardinal; WorkDir: string; Handle: Boolean; begin Result := ''; with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0); try with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; WorkDir := Work; Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI); CloseHandle(StdOutPipeWrite); if Handle then try repeat WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil); if BytesRead > 0 then begin Buffer[BytesRead] := #0; Result := Result + Buffer; end; until not WasOK or (BytesRead = 0); WaitForSingleObject(PI.hProcess, INFINITE); finally CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; finally CloseHandle(StdOutPipeRead); end; end; function SelectFolder(const InitialPath: string = ''): string; var Directory: string; const SELDIRHELP = 1000; begin Result := ''; if InitialPath <> '' then Directory := IncludeTrailingPathDelimiter(InitialPath); if FileCtrl.SelectDirectory(Directory, [sdAllowCreate, sdPerformCreate, sdPrompt], SELDIRHELP) then Result := Directory; end; end.
{ Copyright (C) 2012-2013 Matthias Bolte <matthias@tinkerforge.com> Redistribution and use in source and binary forms of this file, with or without modification, are permitted. See the Creative Commons Zero (CC0 1.0) License for more details. } unit LEConverter; {$ifdef FPC}{$mode OBJFPC}{$H+}{$endif} interface type TByteArray = array of byte; PByteArray = ^TByteArray; PByte = ^byte; TFloatAsBytes = record case boolean of true: (bytes : packed array [0..3] of byte); false: (float : single); end; procedure LEConvertInt8To(const value: shortint; const offset: longint; var data: TByteArray); procedure LEConvertUInt8To(const value: byte; const offset: longint; var data: TByteArray); procedure LEConvertInt16To(const value: smallint; const offset: longint; var data: TByteArray); procedure LEConvertUInt16To(const value: word; const offset: longint; var data: TByteArray); procedure LEConvertInt32To(const value: longint; const offset: longint; var data: TByteArray); procedure LEConvertUInt32To(const value: longword; const offset: longint; var data: TByteArray); procedure LEConvertInt64To(const value: int64; const offset: longint; var data: TByteArray); procedure LEConvertUInt64To(const value: uint64; const offset: longint; var data: TByteArray); procedure LEConvertFloatTo(const value: single; const offset: longint; var data: TByteArray); procedure LEConvertBooleanTo(const value: boolean; const offset: longint; var data: TByteArray); procedure LEConvertStringTo(const value: string; const offset: longint; const len: longint; var data: TByteArray); procedure LEConvertCharTo(const value: char; const offset: longint; var data: TByteArray); function LEConvertInt8From(const offset: longint; const data: TByteArray): shortint; function LEConvertUInt8From(const offset: longint; const data: TByteArray): byte; function LEConvertInt16From(const offset: longint; const data: TByteArray): smallint; function LEConvertUInt16From(const offset: longint; const data: TByteArray): word; function LEConvertInt32From(const offset: longint; const data: TByteArray): longint; function LEConvertUInt32From(const offset: longint; const data: TByteArray): longword; function LEConvertInt64From(const offset: longint; const data: TByteArray): int64; function LEConvertUInt64From(const offset: longint; const data: TByteArray): uint64; function LEConvertFloatFrom(const offset: longint; const data: TByteArray): single; function LEConvertBooleanFrom(const offset: longint; const data: TByteArray): boolean; function LEConvertStringFrom(const offset: longint; const len: longint; const data: TByteArray): string; function LEConvertCharFrom(const offset: longint; const data: TByteArray): char; implementation procedure LEConvertInt8To(const value: shortint; const offset: longint; var data: TByteArray); begin LEConvertUInt8To(byte(value), offset, data); end; procedure LEConvertUInt8To(const value: byte; const offset: longint; var data: TByteArray); begin data[offset] := value; end; procedure LEConvertInt16To(const value: smallint; const offset: longint; var data: TByteArray); begin LEConvertUInt16To(word(value), offset, data); end; procedure LEConvertUInt16To(const value: word; const offset: longint; var data: TByteArray); begin data[offset + 0] := byte((value shr 0) and $FF); data[offset + 1] := byte((value shr 8) and $FF); end; procedure LEConvertInt32To(const value: longint; const offset: longint; var data: TByteArray); begin LEConvertUInt32To(longword(value), offset, data); end; procedure LEConvertUInt32To(const value: longword; const offset: longint; var data: TByteArray); var i: longint; begin for i := 0 to 3 do begin data[offset + i] := byte((value shr (i * 8)) and $FF); end; end; procedure LEConvertInt64To(const value: int64; const offset: longint; var data: TByteArray); begin LEConvertUInt64To(uint64(value), offset, data); end; procedure LEConvertUInt64To(const value: uint64; const offset: longint; var data: TByteArray); var i: longint; begin for i := 0 to 7 do begin data[offset + i] := byte((value shr (i * 8)) and $FF); end; end; procedure LEConvertFloatTo(const value: single; const offset: longint; var data: TByteArray); var i: longint; fab: TFloatAsBytes; begin fab.float := value; for i := 0 to 3 do begin data[offset + i] := fab.bytes[i]; end; end; procedure LEConvertBooleanTo(const value: boolean; const offset: longint; var data: TByteArray); begin if (value) then begin data[offset] := 1; end else begin data[offset] := 0; end; end; procedure LEConvertStringTo(const value: string; const offset: longint; const len: longint; var data: TByteArray); var i: longint; begin i := 0; while ((i < len) and (i < Length(value))) do begin data[offset + i] := byte(value[i + 1]); i := i + 1; end; while (i < len) do begin data[offset + i] := 0; i := i + 1; end; end; procedure LEConvertCharTo(const value: char; const offset: longint; var data: TByteArray); begin data[offset] := byte(value); end; function LEConvertInt8From(const offset: longint; const data: TByteArray): shortint; begin result := shortint(LEConvertUInt8From(offset, data)); end; function LEConvertUInt8From(const offset: longint; const data: TByteArray): byte; begin result := data[offset]; end; function LEConvertInt16From(const offset: longint; const data: TByteArray): smallint; begin result := smallint(LEConvertUInt16From(offset, data)); end; function LEConvertUInt16From(const offset: longint; const data: TByteArray): word; begin result := word(data[offset + 0]) shl 0 or word(data[offset + 1]) shl 8; end; function LEConvertInt32From(const offset: longint; const data: TByteArray): longint; begin result := longint(LEConvertUInt32From(offset, data)); end; function LEConvertUInt32From(const offset: longint; const data: TByteArray): longword; var i: longint; begin result := 0; for i := 0 to 3 do begin result := result or (longword(data[offset + i]) shl (i * 8)); end; end; function LEConvertInt64From(const offset: longint; const data: TByteArray): int64; begin result := int64(LEConvertUInt64From(offset, data)); end; function LEConvertUInt64From(const offset: longint; const data: TByteArray): uint64; var i: longint; begin { Avoid compiler bug when assigning constants to a uint64 variable: https://qc.embarcadero.com/wc/qcmain.aspx?d=9411 } result := uint64(0); for i := 0 to 7 do begin result := result or (uint64(data[offset + i]) shl (i * 8)); end; end; function LEConvertFloatFrom(const offset: longint; const data: TByteArray): single; var i: longint; fab: TFloatAsBytes; begin for i := 0 to 3 do begin fab.bytes[i] := data[offset + i]; end; result := fab.float; end; function LEConvertBooleanFrom(const offset: longint; const data: TByteArray): boolean; begin result := data[offset] <> 0; end; function LEConvertStringFrom(const offset: longint; const len: longint; const data: TByteArray): string; var i: longint; begin result := ''; for i := offset to offset + len - 1 do begin if (data[i] = 0) then begin break; end; result := result + char(data[i]); end; end; function LEConvertCharFrom(const offset: longint; const data: TByteArray): char; begin result := char(data[offset]); end; end.
unit ufmMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufmBase, Vcl.StdCtrls, Vcl.ExtCtrls, uDrawingArea, uEventModel, uDrawingEvent, JvWndProcHook, JvComponentBase, JvMouseGesture, uGraphicPrimitive; const WM_PLEASEREPAINT = WM_USER+ 1; type TfmMain = class(TfmBase) pb: TPaintBox; Panel1: TPanel; ColorBox1: TColorBox; pbBackground: TPaintBox; Panel2: TPanel; Timer1: TTimer; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure pbPaint(Sender: TObject); procedure ColorBox1Change(Sender: TObject); procedure pbBackgroundPaint(Sender: TObject); procedure pbMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure Panel2MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure pbDragDrop(Sender, Source: TObject; X, Y: Integer); private FArea: TDrawingArea; pt : TPrimitiveType; procedure Rep ( var aMsg : TMessage ); message WM_PLEASEREPAINT; protected procedure ProcessEvent( const aEventID: TEventID; const aEventData: variant ); override; public { Public declarations } end; var fmMain: TfmMain; implementation {$R *.dfm} uses uEnvironment; procedure TfmMain.ColorBox1Change(Sender: TObject); begin FArea.BackgroundColor := ColorBox1.Selected; end; procedure TfmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Env.EventModel.UnRegister(Self); Application.Terminate; end; procedure TfmMain.FormCreate(Sender: TObject); begin FArea := TDrawingArea.Create(Env.EventModel); Env.EventModel.RegisterSubscriber( EVENT_BACKGROUND_COLOR, Self); Env.EventModel.RegisterSubscriber( EVENT_PLEASE_REPAINT, Self ); ColorBox1Change(nil); end; procedure TfmMain.FormResize(Sender: TObject); begin FArea.OnNewSize(pb.Width, pb.Height); end; procedure TfmMain.Panel2MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ( Sender as TControl ).BeginDrag( false ); pt := ptBox; end; procedure TfmMain.pbBackgroundPaint(Sender: TObject); begin pbBackground.Canvas.Brush.Color := pbBackground.Color; pbBackground.Canvas.FillRect(pbBackground.ClientRect); end; procedure TfmMain.pbDragDrop(Sender, Source: TObject; X, Y: Integer); begin FArea.CreatePrimitive( X, Y, pt ); end; procedure TfmMain.pbDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Source = Panel2; end; procedure TfmMain.pbMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FArea.OnMouseDown( Button, X, Y ); end; procedure TfmMain.pbMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin FArea.OnMouseMove( X, Y ); end; procedure TfmMain.pbMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FArea.OnMouseUp( Button, X, Y ); end; procedure TfmMain.pbPaint(Sender: TObject); var Bmp : TBitMap; begin pb.Canvas.Draw(0, 0, FArea.AreaBitmap); end; procedure TfmMain.ProcessEvent( const aEventID: TEventID; const aEventData: variant ); begin if aEventID = EVENT_BACKGROUND_COLOR then begin pbBackground.Color := TDrawingCommandData.ExtractColor( aEventData ); pb.Repaint; end else if aEventID = EVENT_PLEASE_REPAINT then begin pbPaint(nil); end; end; procedure TfmMain.Rep(var aMsg: TMessage); begin pbPaint(nil); end; end.
unit Unit2; interface procedure mMain(a: Real); implementation uses Vcl.Dialogs, System.Math; procedure mMain(a: Real); var b, c: Real; begin if (a < 1) then begin b := Power(a, 2); c := Sqrt(b); if (c = a) then begin ShowMessage('a >= 0'); end else begin ShowMessage('a < 0'); end; end else begin ShowMessage('a >= 1'); end; end; end.
{ ******************************************************************************* Copyright 2016-2019 Daniele Spinetti 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 EventBus.Core; interface uses System.SyncObjs, EventBus.Subscribers, Generics.Collections, System.SysUtils, System.Classes, Router4D.Props; type TEventBus = class(TInterfacedObject, IEventBus) var FTypesOfGivenSubscriber: TObjectDictionary<TObject, TList<TClass>>; FSubscriptionsOfGivenEventType : TObjectDictionary<TClass, TObjectList<TSubscription>>; FCustomClonerDict: TDictionary<String, TCloneEventMethod>; FOnCloneEvent: TCloneEventCallback; procedure Subscribe(ASubscriber: TObject; ASubscriberMethod: TSubscriberMethod); procedure UnsubscribeByEventType(ASubscriber: TObject; AEventType: TClass); procedure InvokeSubscriber(ASubscription: TSubscription; AEvent: TObject); function GenerateTProc(ASubscription: TSubscription; AEvent: TObject): TProc; function GenerateThreadProc(ASubscription: TSubscription; AEvent: TObject) : TThreadProcedure; protected procedure SetOnCloneEvent(const aCloneEvent: TCloneEventCallback); function CloneEvent(AEvent: TObject): TObject; virtual; procedure PostToSubscription(ASubscription: TSubscription; AEvent: TObject; AIsMainThread: Boolean); virtual; public constructor Create; virtual; destructor Destroy; override; procedure RegisterSubscriber(ASubscriber: TObject); virtual; function IsRegistered(ASubscriber: TObject): Boolean; procedure Unregister(ASubscriber: TObject); virtual; procedure Post(AEvent: TObject; const AContext: String = ''; AEventOwner: Boolean = true); virtual; property TypesOfGivenSubscriber: TObjectDictionary < TObject, TList < TClass >> read FTypesOfGivenSubscriber; property SubscriptionsOfGivenEventType: TObjectDictionary < TClass, TObjectList < TSubscription >> read FSubscriptionsOfGivenEventType; property OnCloneEvent: TCloneEventCallback write SetOnCloneEvent; procedure AddCustomClassCloning(const AQualifiedClassName: String; const aCloneEvent: TCloneEventMethod); procedure RemoveCustomClassCloning(const AQualifiedClassName: String); end; implementation uses System.Rtti, {$IF CompilerVersion >= 28.0} System.Threading, {$ENDIF} RTTIUtilsU; var FMREWSync: TMultiReadExclusiveWriteSynchronizer; { TEventBus } constructor TEventBus.Create; begin inherited Create; FSubscriptionsOfGivenEventType := TObjectDictionary < TClass, TObjectList < TSubscription >>.Create([doOwnsValues]); FTypesOfGivenSubscriber := TObjectDictionary < TObject, TList < TClass >>.Create([doOwnsValues]); FCustomClonerDict := TDictionary<String, TCloneEventMethod>.Create; end; destructor TEventBus.Destroy; begin FreeAndNil(FSubscriptionsOfGivenEventType); FreeAndNil(FTypesOfGivenSubscriber); FreeAndNil(FCustomClonerDict); inherited; end; procedure TEventBus.AddCustomClassCloning(const AQualifiedClassName: String; const aCloneEvent: TCloneEventMethod); begin FCustomClonerDict.Add(AQualifiedClassName, aCloneEvent); end; function TEventBus.CloneEvent(AEvent: TObject): TObject; var LCloneEvent: TCloneEventMethod; begin if FCustomClonerDict.TryGetValue(AEvent.QualifiedClassName, LCloneEvent) then Result := LCloneEvent(AEvent) else if Assigned(FOnCloneEvent) then Result := FOnCloneEvent(AEvent) else Result := TRTTIUtils.Clone(AEvent); end; function TEventBus.GenerateThreadProc(ASubscription: TSubscription; AEvent: TObject): TThreadProcedure; begin Result := procedure begin if ASubscription.Active then begin ASubscription.SubscriberMethod.Method.Invoke(ASubscription.Subscriber, [AEvent]); end; end; end; function TEventBus.GenerateTProc(ASubscription: TSubscription; AEvent: TObject): TProc; begin Result := procedure begin if ASubscription.Active then begin ASubscription.SubscriberMethod.Method.Invoke(ASubscription.Subscriber, [AEvent]); end; end; end; procedure TEventBus.InvokeSubscriber(ASubscription: TSubscription; AEvent: TObject); begin try ASubscription.SubscriberMethod.Method.Invoke(ASubscription.Subscriber, [AEvent]); except on E: Exception do begin raise Exception.CreateFmt ('Error invoking subscriber method. Subscriber class: %s. Event type: %s. Original exception: %s: %s', [ASubscription.Subscriber.ClassName, ASubscription.SubscriberMethod.EventType.ClassName, E.ClassName, E.Message]); end; end; end; function TEventBus.IsRegistered(ASubscriber: TObject): Boolean; begin FMREWSync.BeginRead; try Result := FTypesOfGivenSubscriber.ContainsKey(ASubscriber); finally FMREWSync.EndRead; end; end; procedure TEventBus.Post(AEvent: TObject; const AContext: String = ''; AEventOwner: Boolean = true); var LSubscriptions: TObjectList<TSubscription>; LSubscription: TSubscription; LEvent: TObject; LIsMainThread: Boolean; begin FMREWSync.BeginRead; try try LIsMainThread := MainThreadID = TThread.CurrentThread.ThreadID; FSubscriptionsOfGivenEventType.TryGetValue(AEvent.ClassType, LSubscriptions); if (not Assigned(LSubscriptions)) then Exit; for LSubscription in LSubscriptions do begin if not LSubscription.Active then continue; if ((not AContext.IsEmpty) and (LSubscription.Context <> AContext)) then continue; LEvent := CloneEvent(AEvent); PostToSubscription(LSubscription, LEvent, LIsMainThread); end; finally if (AEventOwner and Assigned(AEvent)) then AEvent.Free; end; finally FMREWSync.EndRead; end; end; procedure TEventBus.PostToSubscription(ASubscription: TSubscription; AEvent: TObject; AIsMainThread: Boolean); begin if not Assigned(ASubscription.Subscriber) then Exit; case ASubscription.SubscriberMethod.ThreadMode of Posting: InvokeSubscriber(ASubscription, AEvent); Main: if (AIsMainThread) then InvokeSubscriber(ASubscription, AEvent) else TThread.Queue(nil, GenerateThreadProc(ASubscription, AEvent)); Background: if (AIsMainThread) then {$IF CompilerVersion >= 28.0} TTask.Run(GenerateTProc(ASubscription, AEvent)) {$ELSE} TThread.CreateAnonymousThread(GenerateTProc(ASubscription, AEvent)).Start {$ENDIF} else InvokeSubscriber(ASubscription, AEvent); Async: {$IF CompilerVersion >= 28.0} TTask.Run(GenerateTProc(ASubscription, AEvent)); {$ELSE} TThread.CreateAnonymousThread(GenerateTProc(ASubscription, AEvent)).Start; {$ENDIF} else raise Exception.Create('Unknown thread mode'); end; end; procedure TEventBus.RegisterSubscriber(ASubscriber: TObject); var LSubscriberClass: TClass; LSubscriberMethods: TArray<TSubscriberMethod>; LSubscriberMethod: TSubscriberMethod; begin FMREWSync.BeginWrite; try LSubscriberClass := ASubscriber.ClassType; LSubscriberMethods := TSubscribersFinder.FindSubscriberMethods (LSubscriberClass, true); for LSubscriberMethod in LSubscriberMethods do Subscribe(ASubscriber, LSubscriberMethod); finally FMREWSync.EndWrite; end; end; procedure TEventBus.RemoveCustomClassCloning(const AQualifiedClassName: String); begin // No exception is thrown if the key is not in the dictionary FCustomClonerDict.Remove(AQualifiedClassName); end; procedure TEventBus.SetOnCloneEvent(const aCloneEvent: TCloneEventCallback); begin FOnCloneEvent := aCloneEvent; end; procedure TEventBus.Subscribe(ASubscriber: TObject; ASubscriberMethod: TSubscriberMethod); var LEventType: TClass; LNewSubscription: TSubscription; LSubscriptions: TObjectList<TSubscription>; LSubscribedEvents: TList<TClass>; begin LEventType := ASubscriberMethod.EventType; LNewSubscription := TSubscription.Create(ASubscriber, ASubscriberMethod); if (not FSubscriptionsOfGivenEventType.ContainsKey(LEventType)) then begin LSubscriptions := TObjectList<TSubscription>.Create(); FSubscriptionsOfGivenEventType.Add(LEventType, LSubscriptions); end else begin LSubscriptions := FSubscriptionsOfGivenEventType.Items[LEventType]; if (LSubscriptions.Contains(LNewSubscription)) then raise Exception.CreateFmt('Subscriber %s already registered to event %s ', [ASubscriber.ClassName, LEventType.ClassName]); end; LSubscriptions.Add(LNewSubscription); if (not FTypesOfGivenSubscriber.TryGetValue(ASubscriber, LSubscribedEvents)) then begin LSubscribedEvents := TList<TClass>.Create; FTypesOfGivenSubscriber.Add(ASubscriber, LSubscribedEvents); end; LSubscribedEvents.Add(LEventType); end; procedure TEventBus.Unregister(ASubscriber: TObject); var LSubscribedTypes: TList<TClass>; LEventType: TClass; begin FMREWSync.BeginWrite; try if FTypesOfGivenSubscriber.TryGetValue(ASubscriber, LSubscribedTypes) then begin for LEventType in LSubscribedTypes do UnsubscribeByEventType(ASubscriber, LEventType); FTypesOfGivenSubscriber.Remove(ASubscriber); end; // else { // Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass()); // } finally FMREWSync.EndWrite; end; end; procedure TEventBus.UnsubscribeByEventType(ASubscriber: TObject; AEventType: TClass); var LSubscriptions: TObjectList<TSubscription>; LSize, I: Integer; LSubscription: TSubscription; begin LSubscriptions := FSubscriptionsOfGivenEventType.Items[AEventType]; if (not Assigned(LSubscriptions)) or (LSubscriptions.Count < 1) then Exit; LSize := LSubscriptions.Count; for I := LSize - 1 downto 0 do begin LSubscription := LSubscriptions[I]; // Notes: In case the subscriber has been freed but it didn't unregister itself, calling // LSubscription.Subscriber.Equals() will cause Access Violation, so we use '=' instead. if LSubscription.Subscriber = ASubscriber then begin LSubscription.Active := false; LSubscriptions.Delete(I); end; end; end; initialization FMREWSync := TMultiReadExclusiveWriteSynchronizer.Create; finalization FMREWSync.Free; end.
(* Method Better Combination *) procedure Combination(Left, Right: Real; var Root: Real; var Time: Integer); begin Time := 0; // Time: loop counting if F(Left)*F(Right) = 0 then begin if F(Left) = 0 then (* optimize method *) Root := Left else Root := Right; end else if F(Left)*F(Right) < 0 then // main algorithm begin if F(Left) < 0 then while Abs(Left - Right) > Eps do begin Left := Left - F(Left) * (Right - Left)/(F(Right) - F(Left)); Right := Right - F(Right)/DF(Right); Root := (Left + Right)/2; Inc(Time); if Time > T0 then break; end else while Abs(Left - Right) > Eps do begin Right := Right - F(Right) * (Right - Left)/(F(Right) - F(Left)); Left := Left - F(Left)/DF(Left); Root := (Left + Right)/2; Inc(Time); if Time > T0 then break; // condition of break time end; end; end; // NE: in case of other functions, CHECK DF(X)!!!!!!!!
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DSServerScriptGen; interface uses Windows, DSCreators, DSServerFeatures, ToolsAPI; /// <summary>Returns the absolute path to the active project.</summary> function CurrentProjectPath: String; /// <summary>Adds JavaScript REST related files to the active project's directory.</summary> procedure AddScriptFiles(const APersonality: string; const IncludeBasicProxy: Boolean = true); /// <summary>Adds JavaScript REST sample files to the active project's directory.</summary> procedure AddSampleScriptFiles(const APersonality: string); procedure AddFileRemotePath(AProject: IOTAProject; const ADestPath, APlatform, AConfiguration: string); procedure AddRemotePaths; /// <summary>Adds DataSnap Connector related files to the given directory or active project.</summary> /// <remarks>If set, APath specifies the directory to copy the files to. Otherwise, the /// root directory of the active project is used. /// </remarks> procedure AddConnectorFiles(const APersonality: string; const APath: String = ''); /// <summary>Sets the current project's post-build script, if required for active features.</summary> procedure SetCurrentProjectBuildScript(const Features: TDSServerFeatures); // Utilities procedure CopyDirExcludingSVN(const SourceDir, TargetDir: String); procedure AddSourceAsFile(AProject: IOTAProject; const ATemplateFileName: string; const ADestPath: string; IsUnit: Boolean = False; AddFileAfterCopy: Boolean = True); overload; procedure AddResourceAsFile(AProject: IOTAProject; ALibHandle: THandle; const AResourceName: string; const ADestPath: string); implementation uses SysUtils, IOUtils, Classes, Controls, StrUtils, DSServerReg, DSSource, DCCStrs, CommonOptionStrs, Types, DeploymentAPI; procedure CopyDirExcludingSVN(const SourceDir, TargetDir: String); var FilePredicate, DirPredicate: TDirectory.TFilterPredicate; LTargetPath, LSourcePath: String; begin LSourcePath := IncludeTrailingPathDelimiter(SourceDir); LTargetPath := IncludeTrailingPathDelimiter(TargetDir); //predicate which uses recursion to get and copy all files FilePredicate := function(const Path: string; const SearchRec: TSearchRec): Boolean begin Result := False; System.SysUtils.ForceDirectories(TargetDir); TFile.Copy(LSourcePath + SearchRec.Name, LTargetPath + SearchRec.Name); end; //predicate which uses recursion to get and copy all files DirPredicate := function(const Path: string; const SearchRec: TSearchRec): Boolean begin Result := False; //recursively call into CopyDirExcludingSVN if (not AnsiSameStr(SearchRec.Name, '.svn')) then CopyDirExcludingSVN(LSourcePath + SearchRec.Name, LTargetPath + SearchRec.Name); end; //copy this directory's files TDirectory.GetFiles(SourceDir, FilePredicate); //recursively get all directories TDirectory.GetDirectories(SourceDir, DirPredicate); end; function CurrentProjectPath: String; var LProject: IOTAProject; begin LProject := GetActiveProject; Result := ExtractFilePath(LProject.FileName); end; procedure AddSourceAsFile(AProject: IOTAProject; const ATemplateFileName: string; const ADestPath: string; IsUnit: Boolean = False; AddFileAfterCopy: Boolean = True); overload; var LSource: string; LStreamWriter: TStreamWriter; LFileStream: TStream; LEncoding: TEncoding; begin ForceDirectories(ExtractFilePath(ADestPath)); LEncoding := DSSource.GetTemplateFileEncoding(ATemplateFileName); LSource := DSSource.GetSourceFromTemplateFile(ATemplateFileName); LFileStream := TFileStream.Create(ADestPath, fmCreate); try LStreamWriter := TStreamWriter.Create(LFileStream, LEncoding); try LStreamWriter.Write(LSource); finally LStreamWriter.Free; end; finally LFileStream.Free; end; if AddFileAfterCopy then AProject.AddFile(ADestPath, IsUnit); end; procedure AddResourceAsFile(AProject: IOTAProject; ALibHandle: THandle; const AResourceName: string; const ADestPath: string); var DescrResInfo: HRSRC; DescrResData: HGLOBAL; LBytes: PByte; LLength: Integer; LFileStream: TStream; begin DescrResInfo := FindResource(ALibHandle, PChar(AResourceName), RT_RCDATA); if DescrResInfo <> 0 then begin DescrResData := LoadResource(ALibHandle, DescrResInfo); if DescrResData <> 0 then begin LBytes := LockResource(DescrResData); LLength := SizeofResource(ALibHandle, DescrResInfo); ForceDirectories(ExtractFilePath(ADestPath)); LFileStream := TFileStream.Create(ADestPath, fmCreate); try LFileStream.Write(LBytes[0], LLength) finally LFileStream.Free; end; AProject.AddFile(ADestPath, False); end; end; end; procedure AddSampleScriptFiles(const APersonality: string); var LProject: IOTAProject; LPath: string; begin LProject := GetActiveProject; LPath := CurrentProjectPath; AddSourceAsFile(LProject, 'dsrest\connection.js', LPath + 'js\connection.js'); AddSourceAsFile(LProject, 'dsrest\serverfunctioninvoker.js', LPath + 'js\serverfunctioninvoker.js'); AddSourceAsFile(LProject, 'dsrest\main.css', LPath + 'css\main.css'); AddSourceAsFile(LProject, 'dsrest\serverfunctioninvoker.css', LPath + 'css\serverfunctioninvoker.css'); AddSourceAsFile(LProject, 'dsrest\reversestring.html', LPath + 'templates\reversestring.html'); AddSourceAsFile(LProject, 'dsrest\serverfunctioninvoker.html', LPath + 'templates\serverfunctioninvoker.html'); AddResourceAsFile(LProject, hinstance, 'COLLAPSEJPG', LPath + 'images\collapse.png'); AddResourceAsFile(LProject, hinstance, 'EXPANDJPG', LPath + 'images\expand.png'); end; procedure AddFileRemotePath(AProject: IOTAProject; const ADestPath, APlatform, AConfiguration: string); var LPD: IProjectDeployment; LPOC: IOTAProjectOptionsConfigurations; LBC: IOTABuildConfiguration; LDeploymentFile: IProjectDeploymentFile; LDeploymentFiles: TDeploymentFileArray; LRemotePath: string; I: Integer; begin if Supports(AProject, IProjectDeployment, LPD) then begin if MatchStr(APlatform, AProject.SupportedPlatforms) then begin case IndexStr(ExtractFileExt(ADestPath), ['.js', '.html', '.css', '.png']) of 0: LRemotePath := '.\js\'; 1: LRemotePath := '.\templates\'; 2: LRemotePath := '.\css\'; 3: LRemotePath := '.\images\'; else LRemotePath := '.\'; end; LDeploymentFiles := LPD.FindFiles(ADestPath, AConfiguration, APlatform, dcProfectFile); if Length(LDeploymentFiles) > 0 then begin LDeploymentFile := LDeploymentFiles[0]; LDeploymentFile.RemoteDir[APlatform] := LRemotePath; end else if Supports(AProject.ProjectOptions, IOTAProjectOptionsConfigurations, LPOC) then begin for I := 0 to LPOC.ConfigurationCount - 1 do begin LBC := LPOC.Configurations[I]; if (LBC.Name = AConfiguration) then begin LDeploymentFile := LPD.CreateFile(LBC.Name, APlatform, ADestPath); if LDeploymentFile <> nil then begin LDeploymentFile.DeploymentClass := dcProfectFile; LDeploymentFile.Enabled[APlatform] := True; LDeploymentFile.RemoteDir[APlatform] := LRemotePath; LDeploymentFile.RemoteName[APlatform] := ExtractFileName(ADestPath); end; break; end; end; end; end; end; end; procedure AddRemotePaths; var LProject: IOTAProject; LPlatform: string; LPOC: IOTAProjectOptionsConfigurations; LBC: IOTABuildConfiguration; I: Integer; begin LProject := GetActiveProject; for LPlatform in LProject.SupportedPlatforms do if Supports(LProject.ProjectOptions, IOTAProjectOptionsConfigurations, LPOC) then for I := 0 to LPOC.ConfigurationCount - 1 do begin LBC := LPOC.Configurations[I]; if LBC.Name <> ToolsAPI.sBaseConfigurationKey then begin AddFileRemotePath(LProject, 'js\base64.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\serverfunctionexecutor.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\json2.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\callbackframework.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\serverfunctions.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\base64-min.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\json2-min.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\serverfunctionexecutor-min.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\callbackframework-min.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\serverfunctions.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\connection.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'js\serverfunctioninvoker.js', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'css\main.css', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'css\serverfunctioninvoker.css', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'templates\reversestring.html', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'templates\serverfunctioninvoker.html', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'images\collapse.png', LPlatform, LBC.Name); AddFileRemotePath(LProject, 'images\expand.png', LPlatform, LBC.Name); end; end; end; procedure AddScriptFiles(const APersonality: string; const IncludeBasicProxy: Boolean); var LProject: IOTAProject; LPath: string; begin LProject := GetActiveProject; LPath := CurrentProjectPath; AddSourceAsFile(LProject, 'dsrest\base64.js', LPath + 'js\base64.js'); AddSourceAsFile(LProject, 'dsrest\serverfunctionexecutor.js', LPath + 'js\serverfunctionexecutor.js'); AddSourceAsFile(LProject, 'dsrest\json2.js', LPath + 'js\json2.js'); AddSourceAsFile(LProject, 'dsrest\callbackframework.js', LPath + 'js\callbackframework.js'); //optionally include the basic proxy (which assumes TServerMethods1 is the class, with the sample methods) if IncludeBasicProxy then AddSourceAsFile(LProject, 'dsrest\serverfunctions.js', LPath + 'js\serverfunctions.js'); //add the -min version of JS framework files AddSourceAsFile(LProject, 'dsrest\base64-min.js', LPath + 'js\base64-min.js'); AddSourceAsFile(LProject, 'dsrest\json2-min.js', LPath + 'js\json2-min.js'); AddSourceAsFile(LProject, 'dsrest\serverfunctionexecutor-min.js', LPath + 'js\serverfunctionexecutor-min.js'); AddSourceAsFile(LProject, 'dsrest\callbackframework-min.js', LPath + 'js\callbackframework-min.js'); // Set directory so that save dialog will default to project directory SetCurrentDir(LPath); end; procedure AddConnectorFiles(const APersonality, APath: string); var LPath, LProxyDir, LTemplateDirectory, LConnectorDir: string; begin if Trim(APath) = EmptyStr then LPath := CurrentProjectPath else LPath := IncludeTrailingPathDelimiter(APath); LProxyDir := LPath + 'proxy'; LTemplateDirectory := (BorlandIDEServices as IOTAServices).GetTemplateDirectory; LConnectorDir := SysUtils.GetLocaleDirectory(LTemplateDirectory + 'dsrest\connectors'); //delete the proxy directory in the project folder if it already existed. if TDirectory.Exists(LProxyDir) then TDirectory.Delete(LProxyDir, True); //add the connector static proxy source files to the project CopyDirExcludingSVN(LConnectorDir, LProxyDir); // Set directory so that save dialog will default to project directory SetCurrentDir(LPath); end; procedure SetCurrentProjectBuildScript(const Features: TDSServerFeatures); const cOutputDir = 'OutputDir'; cFinalOutputDir = 'FinalOutputDir'; var LProject: IOTAProject; BEP: IOTABuildEventProvider; BuildEvent: ToolsAPI.IOTABuildEvent; begin //If dsConnectors enabled, or if including Web Files, then add the post-build command to copy files if (dsWebFiles in Features) or (dsConnectors in Features) then begin LProject := GetActiveProject; if Supports(LProject, IOTABuildEventProvider, BEP) then begin BuildEvent := BEP.GetBuildEvent(betOTAPostCompile, sBaseConfigurationKey, '', True); //Cerify batch file exists, then execute it. The batch file will do the file copying BuildEvent.Commands := 'if exist "$(BDS)\ObjRepos\en\dsrest\dsPostBuild.bat" (' + ' call "$(BDS)\ObjRepos\en\dsrest\dsPostBuild.bat" "$(PROJECTDIR)" "$(OUTPUTDIR)" )'; end; end; end; end.
unit AES_CFB8; (************************************************************************* DESCRIPTION : AES CFB8 functions REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : [3] http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf [1] http://csrc.nist.gov/fips/fips-197.pdf Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 25.12.07 W.Ehrhardt Initial encrypt version 0.11 25.12.07 we AES_CFB8_Decrypt 0.12 16.11.08 we Use Ptr2Inc, pByte from BTypes 0.13 27.07.10 we Longint ILen in AES_CFB8_En/Decrypt **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2007-2010 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} interface uses BTypes, AES_Type, AES_Base, AES_Encr; {$ifdef CONST} function AES_CFB8_Init(const Key; KeyBits: word; const IV: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, store IV} {$ifdef DLL} stdcall; {$endif} {$else} function AES_CFB8_Init(var Key; KeyBits: word; var IV: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, store IV} {$endif} function AES_CFB8_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CFB8 mode} {$ifdef DLL} stdcall; {$endif} function AES_CFB8_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CFB8 mode} {$ifdef DLL} stdcall; {$endif} implementation {---------------------------------------------------------------------------} {$ifdef CONST} function AES_CFB8_Init(const Key; KeyBits: word; const IV: TAESBlock; var ctx: TAESContext): integer; {$else} function AES_CFB8_Init(var Key; KeyBits: word; var IV: TAESBlock; var ctx: TAESContext): integer; {$endif} {-AES key expansion, error if invalid key size, store IV} var err: integer; begin {-AES key expansion, error if invalid key size} err := AES_Init_Encr(Key, KeyBits, ctx); AES_CFB8_Init := err; if err=0 then ctx.IV := IV; end; {---------------------------------------------------------------------------} function AES_CFB8_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CFB8 mode} begin AES_CFB8_Encrypt := 0; if ctx.Decrypt<>0 then begin AES_CFB8_Encrypt := AES_Err_Invalid_Mode; exit; end; if (ptp=nil) or (ctp=nil) then begin if ILen>0 then begin AES_CFB8_Encrypt := AES_Err_NIL_Pointer; exit; end; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin AES_CFB8_Encrypt := AES_Err_Invalid_16Bit_Length; exit; end; {$endif} {Encrypt ILen bytes from ptp^ to ctp^ in CFB8 mode} while ILen>0 do with ctx do begin AES_Encrypt(ctx, IV, buf); {encrypt next btye} pByte(ctp)^ := buf[0] xor pByte(ptp)^; {shift 8 bits} move(IV[1],IV[0],AESBLKSIZE-1); IV[AESBLKSIZE-1] := pByte(ctp)^; {increment pointers} inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); dec(ILen); end; end; {---------------------------------------------------------------------------} function AES_CFB8_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CFB8 mode} begin AES_CFB8_Decrypt := 0; if ctx.Decrypt<>0 then begin AES_CFB8_Decrypt := AES_Err_Invalid_Mode; exit; end; if (ptp=nil) or (ctp=nil) then begin if ILen>0 then begin AES_CFB8_Decrypt := AES_Err_NIL_Pointer; exit; end; end; {$ifdef BIT16} if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin AES_CFB8_Decrypt := AES_Err_Invalid_16Bit_Length; exit; end; {$endif} {Decrypt ILen bytes from ctp^ to ptp^ in CFB8 mode} while ILen>0 do with ctx do begin AES_Encrypt(ctx, IV, buf); {shift 8 bits} move(IV[1],IV[0],AESBLKSIZE-1); IV[AESBLKSIZE-1] := pByte(ctp)^; {decrypt next byte} pByte(ptp)^ := buf[0] xor pByte(ctp)^; {increment pointers} inc(Ptr2Inc(ptp)); inc(Ptr2Inc(ctp)); dec(ILen); end; end; end.
{$A8} {$R-} {*************************************************************} { } { Embarcadero Delphi Visual Component Library } { InterBase Express core components } { } { Copyright (c) 1998-2017 Embarcadero Technologies, Inc.} { All rights reserved } { } { Additional code created by Jeff Overcash and used } { with permission. } {*************************************************************} unit IBX.IBBind.Consts; interface resourcestring sArgCount = 'Unexpected argument count'; sDatasetType = 'First argument is not a TIBCustomDataset descendant'; sInvalidSecondArg = 'Second argument must be either a FieldIndex (integer) or FieldName (string)'; implementation end.
unit PaymentData; interface uses System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TdmPayment = class(TDataModule) dstPayment: TADODataSet; dscPayment: TDataSource; dstPaymentDetail: TADODataSet; dscPaymentDetail: TDataSource; dstActiveLoans: TADODataSet; dscActiveLoans: TDataSource; dstPaymentMethod: TADODataSet; dscPaymentMethod: TDataSource; dstWithdrawal: TADODataSet; dscWithdrawal: TDataSource; dstAcctInfo: TADODataSet; dscAcctInfo: TDataSource; dscSchedule: TDataSource; dstSchedule: TADODataSet; dstInterests: TADODataSet; dstLoans: TADODataSet; dscLedger: TDataSource; dstLedger: TADODataSet; dstLedgerdue: TDateTimeField; dstLedgerdebit_amt_p: TBCDField; dstLedgercredit_amt_p: TBCDField; dstLedgerbalance_p: TBCDField; dstLedgerdebit_amt_i: TBCDField; dstLedgercredit_amt_i: TBCDField; dstLedgerbalance_i: TBCDField; dstLedgersort_order: TSmallintField; dstLedgerdocument_no: TStringField; dstLedgerid: TStringField; dstLedgerprincipal_deficit: TBCDField; dstLedgerinterest_deficit: TBCDField; fmtPaymentDetail: TFDMemTable; dscDetail: TDataSource; dstLastInterestPostDate: TADODataSet; dstRebate: TADODataSet; procedure dstPaymentBeforeOpen(DataSet: TDataSet); procedure dstPaymentNewRecord(DataSet: TDataSet); procedure dstActiveLoansBeforeOpen(DataSet: TDataSet); procedure dstPaymentBeforePost(DataSet: TDataSet); procedure dstPaymentDetailBeforeOpen(DataSet: TDataSet); procedure dstPaymentDetailAfterOpen(DataSet: TDataSet); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure dstWithdrawalNewRecord(DataSet: TDataSet); procedure dstAcctInfoBeforeOpen(DataSet: TDataSet); procedure dstWithdrawalAfterPost(DataSet: TDataSet); procedure dstLedgerBeforeOpen(DataSet: TDataSet); procedure dstRebateBeforePost(DataSet: TDataSet); private { Private declarations } procedure GetPaymentMethods; public { Public declarations } end; var dmPayment: TdmPayment; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses AppData, Payment, IFinanceGlobal, DBUtil, PaymentMethod, Withdrawal; procedure TdmPayment.DataModuleCreate(Sender: TObject); begin // get payment methods GetPaymentMethods; end; procedure TdmPayment.DataModuleDestroy(Sender: TObject); begin pmtMethods := []; end; procedure TdmPayment.dstAcctInfoBeforeOpen(DataSet: TDataSet); begin (DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := wd.Client.Id; end; procedure TdmPayment.dstActiveLoansBeforeOpen(DataSet: TDataSet); begin (DataSet as TADODataSet).Parameters.ParamByName('@entity_id').Value := pmt.Client.Id; (DataSet as TADODataSet).Parameters.ParamByName('@status').Value := 'R'; end; procedure TdmPayment.dstLedgerBeforeOpen(DataSet: TDataSet); begin (DataSet as TADODataSet).Parameters.ParamByName('@loan_id').Value := pmt.Details[pmt.DetailCount-1].Loan.Id; (DataSet as TADODataSet).Parameters.ParamByName('@as_of_date').Value := ifn.AppDate; end; procedure TdmPayment.dstPaymentBeforeOpen(DataSet: TDataSet); begin (DataSet as TADODataSet).Parameters.ParamByName('@payment_id').Value := pmt.PaymentId; end; procedure TdmPayment.dstPaymentBeforePost(DataSet: TDataSet); var id, refNo: string; begin if DataSet.State = dsInsert then begin id := GetPaymentId; refNo := FormatDateTime('mmddyyyyhhmmsszzz',Now); DataSet.FieldByName('payment_id').AsString := id; DataSet.FieldByName('entity_id').AsString := pmt.Client.Id; DataSet.FieldByName('loc_code').AsString := ifn.LocationCode; DataSet.FieldByName('ref_no').AsString := refNo; DataSet.FieldByName('pmt_method').AsInteger := Integer(pmt.PaymentMethod.Method); DataSet.FieldByName('post_date').AsDateTime := Now; if pmt.PaymentMethod.Method = mdBankWithdrawal then DataSet.FieldByName('wd_id').AsString := pmt.WithdrawalId; SetCreatedFields(DataSet); pmt.PaymentId := id; pmt.ReferenceNo := refNo; end; end; procedure TdmPayment.dstPaymentDetailAfterOpen(DataSet: TDataSet); begin (DataSet as TADODataSet).Properties['Unique table'].Value := 'PaymentDetail'; end; procedure TdmPayment.dstPaymentDetailBeforeOpen(DataSet: TDataSet); begin (DataSet as TADODataSet).Parameters.ParamByName('@payment_id').Value := pmt.PaymentId; end; procedure TdmPayment.dstPaymentNewRecord(DataSet: TDataSet); begin DataSet.FieldByName('payment_date').AsDateTime := ifn.AppDate; end; procedure TdmPayment.dstRebateBeforePost(DataSet: TDataSet); begin DataSet.FieldByName('rebate_id').AsString := GetRebateId; DataSet.FieldByName('rebate_date').AsDateTime := ifn.AppDate; end; Procedure TdmPayment.dstWithdrawalAfterPost(DataSet: TDataSet); var id: string; begin id := DataSet.FieldByName('wd_id').AsString; RefreshDataSet(id,'wd_id',DataSet); end; procedure TdmPayment.dstWithdrawalNewRecord(DataSet: TDataSet); begin DataSet.FieldByName('wd_id').AsString := GetGenericId; DataSet.FieldByName('wd_date').AsDateTime := ifn.AppDate; end; procedure TdmPayment.GetPaymentMethods; var paymentMethod: TPaymentMethod; begin with dstPaymentMethod do begin Open; while not Eof do begin paymentMethod := TPaymentMethod.Create; paymentMethod.Method := TMethod(FieldByName('pmt_method').AsInteger); paymentMethod.Name := FieldByName('pmt_method_name').AsString; paymentMethod.Charge := FieldByName('pmt_charge').AsCurrency; // add the method SetLength(pmtMethods,Length(pmtMethods) + 1); pmtMethods[Length(pmtMethods) - 1] := paymentMethod; Next; end; Close; end; end; end.
unit PPermits_Subform; {$H+} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, Wwtable, wwdblook, Buttons, ToolWin, ComCtrls, Mask, ExtCtrls, StdCtrls; type TPermitsEntryDialogForm = class(TForm) MainToolBar: TToolBar; SaveButton: TSpeedButton; CancelButton: TSpeedButton; NoteInformationGroupBox: TGroupBox; WorkDescription: TMemo; Label4: TLabel; Label6: TLabel; SaveAndExitButton: TSpeedButton; PermitNumber: TEdit; Entered: TCheckBox; Inspected: TCheckBox; MainQuery: TQuery; ButtonsStateTimer: TTimer; PermitDate: TMaskEdit; Label1: TLabel; Cost: TEdit; COIssued: TCheckBox; procedure EditChange(Sender: TObject); procedure ButtonsStateTimerTimer(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure SaveAndExitButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } DataChanged : Boolean; UnitName, SwisSBLKey, EditMode, _TableName : String; Permit_ID : Integer; Procedure Load; Function MeetsRequirements : Boolean; Function Save : Boolean; Procedure InitializeForm(_SwisSBLKey : String; _Permit_ID : Integer; _EditMode : String); end; var PermitsEntryDialogForm: TPermitsEntryDialogForm; implementation {$R *.DFM} uses PASUtils, DataAccessUnit, GlblCnst, Utilitys, GlblVars, WinUtils; {=========================================================================} Procedure TPermitsEntryDialogForm.Load; begin with MainQuery do try SQL.Clear; SQL.Add('Select * from ' + _TableName); SQL.Add('where (Permit_ID = ' + IntToStr(Permit_ID) + ')'); Open; except end; DatasetLoadToForm(Self, MainQuery); end; {Load} {=========================================================================} Function TPermitsEntryDialogForm.MeetsRequirements : Boolean; begin Result := True; end; {MeetsRequirements} {=========================================================================} Function TPermitsEntryDialogForm.Save : Boolean; begin Result := False; If (DataChanged and MeetsRequirements) then Result := SQLUpdateFromForm(Self, MainQuery, _TableName, '(Permit_ID = ' + IntToStr(Permit_ID) + ')'); DataChanged := False; end; {Save} {=========================================================================} Procedure TPermitsEntryDialogForm.EditChange(Sender: TObject); begin DataChanged := GetDataChangedStateForComponent(Sender); end; {EditChange} {=========================================================================} Procedure TPermitsEntryDialogForm.ButtonsStateTimerTimer(Sender: TObject); var Enabled : Boolean; begin Enabled := DataChanged; SaveButton.Enabled := Enabled; CancelButton.Enabled := Enabled; SaveAndExitButton.Enabled := Enabled; end; {ButtonsStateTimerTimer} {=========================================================================} Procedure TPermitsEntryDialogForm.InitializeForm(_SwisSBLKey : String; _Permit_ID : Integer; _EditMode : String); begin UnitName := 'PPermits_Subform'; Permit_ID := _Permit_ID; SwisSBLKey := _SwisSBLKey; _TableName := 'PBuildingPermits'; If _Compare(_EditMode, emInsert, coEqual) then begin with MainQuery do try SQL.Add('Insert into ' + _TableName + ' (SwisSBLKey)'); SQL.Add('Values (' + FormatSQLString(SwisSBLKey) + ')'); ExecSQL; except end; with MainQuery do try SQL.Clear; SQL.Add('Select MAX(Permit_ID) as PermitCount from ' + _TableName); Open; except end; Permit_ID := MainQuery.FieldByName('PermitCount').AsInteger; end; {If _Compare(_EditMode, emInsert, coEqual)} Load; Caption := 'Permit #' + MainQuery.FieldByName('PermitNumber').AsString + ' for parcel ' + ConvertSwisSBLToDashDot(SwisSBLKey); If _Compare(_EditMode, emBrowse, coEqual) then SetComponentsToReadOnly(Self); DataChanged := False; ButtonsStateTimer.Enabled := True; end; {InitializeForm} {=========================================================================} Procedure TPermitsEntryDialogForm.FormKeyPress( Sender: TObject; var Key: Char); begin If ((Key = #13) and (not (ActiveControl is TMemo))) then begin Perform(WM_NEXTDLGCTL, 0, 0); Key := #0; end; end; {FormKeyPress} {=========================================================================} Procedure TPermitsEntryDialogForm.SaveAndExitButtonClick(Sender: TObject); begin If Save then Close; end; {SaveAndExitButtonClick} {=========================================================================} Procedure TPermitsEntryDialogForm.SaveButtonClick(Sender: TObject); begin Save; end; {=========================================================================} Procedure TPermitsEntryDialogForm.CancelButtonClick(Sender: TObject); begin If DataChanged then begin If (MessageDlg('Do you want to cancel your changes?', mtConfirmation, [mbYes, mbNo], 0) = idYes) then begin DataChanged := False; ModalResult := mrCancel; end; end else ModalResult := mrCancel; end; {CancelButtonClick} {=========================================================================} Procedure TPermitsEntryDialogForm.FormCloseQuery( Sender: TObject; var CanClose: Boolean); var ReturnCode : Integer; begin If DataChanged then begin ReturnCode := MessageDlg('Do you want to save your changes?', mtConfirmation, [mbYes, mbNo, mbCancel], 0); case ReturnCode of idYes : begin Save; ModalResult := mrOK; end; idNo : ModalResult := mrCancel; idCancel : CanClose := False; end; {case ReturnCode of} end; {If DataChanged} end; {FormCloseQuery} end.
unit mml_types; {------------------------------------------------------------------------------- ソフト:テキスト音楽「サクラ」 作 者:クジラ飛行机 https://sakuramml.com 説 明:MMLのトラック情報、ソング情報を管理するクラス 履 歴: 2002/06/03 15:13 雛型作成 -------------------------------------------------------------------------------} interface uses SysUtils, Classes, hashUnit, mml_const, mml_var, Math; const MAX_NOTE_INFO = 11;//v と v__0 ... v__9 type TNoteOnType = (noteNormal, noteOnNote, noteOnTime, noteOnCycle, noteOnWave, noteOnWaveEx, noteOnWaveR, noteOff, noteCCSine, noteOnSine); TTrackInfo = class; TMRange = class low, high: Integer; constructor Create(l,h: Integer); end; //ノート情報 TNoteInfo = class private track: TTrackInfo; FValue: Integer; FIndex: Integer; public ValueChangeTime: Integer; //先行指定の起点 DelayTime: Integer; //先行指定の遅延時間 RepeatMode: Integer; //0=off / 1=on RandomValue: Integer; //最終的な値へ及ぼすランダムの値 StepMode: Boolean; //Stepmode reserve: TMArray; noteOnType: TNoteOnType; constructor Create(tr: TTrackInfo); destructor Destroy; override; function GetValue: Integer; function GetQGateValue(len: Integer; qmax: Integer): Integer; procedure SetValue(value: Integer); procedure SetReserveValue(nType: TNoteOnType; v:TMArray; timePtr: Integer); property Value: Integer read GetValue write SetValue; property ROValue: Integer read FValue; //止む無く直接値を参照したいとき end; //ノート情報配列 TNoteInfos = class private track: TTrackInfo; public Range: TMRange; //値の最終的な上限と下限(0,127) ArrayNote: array [0..MAX_NOTE_INFO-1] of TNoteInfo;//0 が defaultのノート情報 で、v__0 は、ArrayNote[1]に当たる constructor Create(tr: TTrackInfo); destructor Destroy; override; procedure Clear; function GetValue: Integer; function GetQGateValue(len, qmax: Integer): Integer; procedure SetValue(Index, value: Integer); procedure IncValue(Index, value: Integer); procedure CreateArrayNote(Index: Integer); procedure SetReserveValue(Index: Integer; nType: TNoteOnType; v:TMArray; timePtr: Integer); end; //コントロールチェンジのイベント管理 TNoteCC = class public FIndex: Integer; Time: Integer; noteOnType : TNoteOnType ; No: Integer; RandomValue: Integer; DelayTime: Integer; RepeatMode: Integer; LastValue: Integer; reserve: TMArray; Range: TMRange; constructor Create; destructor Destroy; override; procedure Clear; end; //コントロールチェンジリスト TCCList = class(TList) public procedure Clear; override; function FindCC(no: Integer): TNoteCC;//検索のみ function GetCC(no: Integer): TNoteCC;//なかったら作成して返す destructor Destroy; override; end; //トラック情報 TTrackInfo = class private FCCNoMute: array[0..63] of Byte; function GetCCNoMute(Index: Integer): Boolean; procedure SetCCNoMute(Index: Integer; const Value: Boolean); //特定のコントロールチェンジのみミュート public TrackNo: Integer; Channel: Integer; //channel = 1-15 Port: Integer; //PORT番号 Voice: Integer; //音色 TimePtr: Integer; //タイムポインタ Stepmode: Boolean; //StepMode Length: TNoteInfos; //Length Velocity: TNoteInfos; //velocity Qgate: TNoteInfos; //gate time Octave: TNoteInfos; //Octave Timing: TNoteInfos; //timing Mute: Boolean; //mute Q2: Integer; //ゲート加算 TieMode: Integer; //スラーの動作 TieValue: Integer; Key: Integer; //トラックごとのキー ArgOrder: string; //引数の並び順 CCMute: Boolean; //コントロールチェンジのミュート constructor Create(SongStepmode: Boolean); destructor Destroy; override; procedure InitValue; property CCNoMute[Index: Integer]: Boolean read GetCCNoMute write SetCCNoMute; end; TTimeKeyFlag = class public KeyFlag: array [0..6] of Integer; timeFrom, timeTo: Integer; constructor Create; end; TTimeKey = class key,timeFrom, timeTo: Integer; constructor Create; end; //トラック管理クラス //曲情報 TSongInfo = class(TList) public X68Mode: Boolean; //Octave記号<>を入れ替えるか Stepmode: Boolean; //Step単位を標準にするか(<-->n分音符単位) qMax: Integer; //q(ゲートパーセント)の最大値(100) vMax: Integer; //v(ベロシティ)の最大値(127) vAdd: Integer; //v+でベロシティの追加値(8) qAdd: Integer; //q+パーセント指定 " (10) q2Add: Integer; //q ステップ指定 " (10) TimeBase: Integer; //四分音符分解能の指定 (96) RandomSeed: Integer; //乱数の種 Keyshift: Integer; //キーシフト値 MeasureShift: Integer; //小節数のシフト値 VoiceNoShift: Integer; //プログラムチェンジのシフト値(0) @=1~128 OctaveRangeShift: Integer; //オクターブのシフト値 KeyFlag: array [0..6] of Integer; //キーフラグ値(a,b,c,d,e,f,g) TimeKeyFlag: TList; //Time指定付きのキーフラグ TimeKey: TList; //Time指定付きのキーフラグ TimeKey2: TList; //Time指定付きのキーフラグ その2 ControllerShift: Integer; //ベンドやコントロールチェンジなどの出力タイミングを早めるか(1) SoundType: Integer; //音源の種類 CC: array [0..15] of TCCList; //コントロールチェンジ管理クラス CCFreq: Integer; //書き込み頻度(3step) Tempo: Integer; //テンポ(120) TimeSigKo,TimeSigHa:Integer; //分子,分母(4,4) BendRange: array [0..15] of Integer; //ベンドレンジ値(初期値は、2) UseKeyShift: Boolean; //キーシフトを適用するかどうか TrackSyncTime: Integer; //最後にTrackSyncした個所を覚えておく。新しいトラック生成に備える AllowMuliLine: Boolean; //和音で改行を許すか? MetaTextEOL: Integer; //1でLFに2でCRに、0でCRLFする機能を追加。 constructor Create; destructor Destroy;override; procedure Clear; override; function GetTrack(Index: Integer; DefTimebase: Integer = 96): TTrackInfo; function GetTrackCount: Integer; end; implementation { TSongInfo } procedure TSongInfo.Clear; var i: Integer; p: TTrackInfo ; begin for i:=0 to Count-1 do begin p := Items[i]; if p<>nil then p.Free ; end; inherited Clear; //Song の初期設定 X68Mode := False; // Octave記号<>を入れ替えるか Stepmode := False; //Step単位を標準にするか(<-->n分音符単位) qMax :=100; vMax :=127; vAdd := 8; qAdd := 10; q2Add := 8; TimeBase := 96; RandomSeed := RandSeed; Keyshift := 0; MeasureShift := 0; VoiceNoShift := 0; OctaveRangeShift := 0; for i:=0 to 6 do KeyFlag[i] := 0; ControllerShift := 1; //ベンドやコントロールチェンジなどの出力タイミングを早めるか(1) SoundType := SOUND_TYPE_GM; //大多数の人は、GM音源 CCFreq := 2; Tempo := 120; TimeSigKo := 4; TimeSigHa := 4; UseKeyShift := True; TrackSyncTime := 0; //未設定 MetaTextEOL := 0; AllowMuliLine := True; end; constructor TSongInfo.Create; var i: Integer; begin inherited; for i:=0 to 15 do begin CC[i] := TCCList.Create ; end; for i:=0 to 15 do begin BendRange[i] := 2; end; TimeKeyFlag := TList.Create ; TimeKey := TList.Create ; TimeKey2 := TList.Create ; Clear; //音源の初期化は、こちら end; destructor TSongInfo.Destroy; var i: Integer; t: TTimeKeyFlag; tk: TTimeKey; begin for i:=0 to 15 do begin CC[i].Free ; end; for i:=0 to TimeKeyFlag.Count -1 do begin t := TimeKeyFlag.Items[i]; if t<>nil then t.Free ; end; for i:=0 to TimeKey.Count -1 do begin tk := TimeKey.Items[i]; if tk<>nil then tk.Free ; end; for i:=0 to TimeKey2.Count -1 do begin tk := TimeKey2.Items[i]; if tk<>nil then tk.Free ; end; TimeKeyFlag.Free ; TimeKey.Free ; TimeKey2.Free ; inherited; end; function TSongInfo.GetTrack(Index: Integer; DefTimebase: Integer = 96): TTrackInfo; begin //なければ作る while Index >= Count do begin Self.Add(nil); end; if Items[Index]=nil then begin Items[Index] := TTrackInfo.Create(Stepmode); TTrackInfo(Items[Index]).TrackNo := Index; TTrackInfo(Items[Index]).Length.ArrayNote[0].Value := DefTimebase; //トラックによるチャンネルの初期設定を適当に決める if Index=0 then TTrackInfo(Items[Index]).Channel := 0 else TTrackInfo(Items[Index]).Channel := (Index-1) mod 16; //初期タイムポインタをセット TTrackInfo(Items[Index]).TimePtr := TrackSyncTime; end; Result := Items[Index]; end; function TSongInfo.GetTrackCount: Integer; begin Result := Self.Count; end; { TTrackInfo } constructor TTrackInfo.Create(SongStepmode: Boolean); begin Stepmode := SongStepmode; Length := TNoteInfos.Create(Self) ; Velocity := TNoteInfos.Create(Self) ; Qgate := TNoteInfos.Create(Self) ; Timing := TNoteInfos.Create(Self) ; Octave := TNoteInfos.Create(Self) ; InitValue; end; destructor TTrackInfo.Destroy; begin Velocity.Free ; Qgate.Free ; Timing.Free ; Octave.Free ; Length.Free ; inherited; end; function TTrackInfo.GetCCNoMute(Index: Integer): Boolean; var b: Byte; shift: Integer; begin // 特定のバイトを選び出しそのなかでビットを得る b := FCCNoMute[Trunc(Index / 8)]; shift := Index mod 8; b := (b shr shift) and 1; Result := (b = 1); end; procedure TTrackInfo.InitValue; var i: Integer; begin Length.ArrayNote[0].Value := 96;//n=4 Velocity.ArrayNote[0].Value := 100; Qgate.ArrayNote[0].Value := 80; Octave.ArrayNote[0].Value := 5; Timing.ArrayNote[0].Value := 0; Mute := False; TimePtr := 0; TieMode := TIE_PORT; TieValue := 12; Key := 0; Port := 0; Q2 := 0; ArgOrder := 'lqvto'; CCMute := False; for i := 0 to High(FCCNoMute) do FCCNoMute[i] := 0; end; procedure TTrackInfo.SetCCNoMute(Index: Integer; const Value: Boolean); var m: Byte; ai, bi: Integer; begin // 特定のバイトを選び出しそのなかでビットを得る ai := Trunc(Index / 8); bi := Index mod 8; m := 1 shl bi; // 反転させたいかどうか if ((FCCNoMute[ai] shr bi) <> 0) <> Value then begin // 反転させる FCCNoMute[ai] := FCCNoMute[ai] xor m; end; end; { TNoteInfo } constructor TNoteInfo.Create(tr: TTrackInfo); begin noteOnType := noteNormal ; reserve := TMArray.Create ; track := tr; RepeatMode := BOOL_TRUE; RandomValue := 0; FValue := 0; Stepmode := False; end; destructor TNoteInfo.Destroy; begin reserve.Free ; inherited; end; function TNoteInfo.GetQGateValue(len: Integer; qmax: Integer): Integer; var r: Extended; v: Integer; begin if StepMode then begin Result := GetValue; end else begin v := GetValue ; r := v / qmax; Result := Trunc(len * r); if (Result=0)and(v>0)and(len>0) then Result := 1; end; end; function TNoteInfo.GetValue: Integer; function CalcOnNote: Integer; begin if reserve.Count = 0 then begin Result := FValue; Exit; end; Result := reserve.IntItems[ FIndex ]; Inc(FIndex); if reserve.Count <= FIndex then begin if RepeatMode = BOOL_FALSE then //繰り返し指定か begin SetValue(Result); end; FIndex := 0; end; end; function CalcOnTime: Integer; var kiten, n, len, i,idx, x1, x2, x3, kyori, takasa, low, high: Integer; a: Extended; { kiten i i+1 |-------------+----+------+--------| x1 x3 x2 } begin kiten := ValueChangeTime + DelayTime ; n := track.TimePtr ;//現在位置 //もし、起点以前だったら、以前の値を参照して抜ける if kiten > n then begin Result := FValue; Exit; end; //low,high,len, low,high,len... の、どの範囲か得る i := 0; x1 := kiten; x2 := kiten; low:=0; high:=0; //引数なしのダミーなら抜ける if reserve.Count = 0 then begin Result := FValue; Exit; end; if (reserve.Count mod 3) <> 0 then begin raise Exception.Create('".onTime"で引数の個数が不正です。'); end; while True do begin idx := i * 3 + 2; //len if idx>=reserve.Count then begin // RangeOver if RepeatMode <> BOOL_FALSE then begin kiten := x1; i := 0; Continue; //Indexを0に戻して再計算 end else begin //抜ける Result := FValue; Exit; end; end; len := reserve.IntItems[idx]; x2 := x1 + len; if (x1<=n)and(n<=x2) then begin low := reserve.IntItems[i*3+0]; high := reserve.IntItems[i*3+1]; Break; end; FValue := reserve.IntItems[idx-1]; //前回の最大値 Inc(i); x1 := x2; end; //起点(x1)終点(x2)が得られたので角度aを求め、現在位置の値を割り出す kyori := x2 - x1; x3 := n - kiten; takasa := high - low; if kyori=0 then a:=0 else a := takasa / kyori; Result := Trunc( x3 * a ) + low; end; function CalcOnCycle: Integer; var kiten, n, len, i,idx: Integer; { kiten len |---+---+---+---+---| x1 x2 x3 x4 x5 x6 } begin kiten := ValueChangeTime + DelayTime ; n := track.TimePtr ;//現在位置 //もし、起点以前だったら、以前の値を参照して抜ける if kiten > n then begin Result := FValue; Exit; end; len := reserve.IntItems[0]; // int n := n - kiten; if len=0 then i := 0 else i := n div len; if reserve.Count >= 0 then begin if reserve.Count = 1 then idx := 0 else idx := ( i mod (reserve.Count-1) ) + 1; Result := reserve.IntItems[idx]; end else Result := FValue; end; begin case noteOnType of noteNormal: begin Result := FValue; end; noteOnNote: begin Result := CalcOnNote; end; noteOnTime: begin Result := CalcOnTime; end; noteOnCycle: begin Result := CalcOnCycle; end; else Result := 0; end; //Random if RandomValue > 0 then Result := Result - (RandomValue div 2) + Random(RandomValue); end; procedure TNoteInfo.SetReserveValue(nType: TNoteOnType; v:TMArray; timePtr: Integer); begin noteOnType := nType; reserve.Assign(v); ValueChangeTime := timePtr; FIndex := 0; end; procedure TNoteInfo.SetValue(value: Integer); begin noteOnType := noteNormal ; FValue := value; end; { TNoteInfos } procedure TNoteInfos.Clear; var i: Integer; begin for i:=0 to MAX_NOTE_INFO -1 do begin if ArrayNote[i] <> nil then begin ArrayNote[i].Free ; ArrayNote[i] := nil; end; end; if Range <> nil then Range.Free; Range := nil; end; constructor TNoteInfos.Create(tr: TTrackInfo); var i: Integer; begin for i:=1 to MAX_NOTE_INFO -1 do begin ArrayNote[i] := nil; end; track := tr; ArrayNote[0] := TNoteInfo.Create(tr) ; Range := nil; end; procedure TNoteInfos.CreateArrayNote(Index: Integer); begin if ArrayNote[Index] = nil then begin ArrayNote[Index] := TNoteInfo.Create(track) ; end; end; destructor TNoteInfos.Destroy; begin Clear; inherited; end; function TNoteInfos.GetQGateValue(len, qmax: Integer): Integer; var i: Integer; begin //オプション__0~9 までの、ゲートステップを得る Result := 0; for i:=1 to MAX_NOTE_INFO -1 do //defaultの0は、NoteOnイベントで計算するので。 begin if ArrayNote[i] <> nil then begin Result := Result + ArrayNote[i].GetQGateValue(len,qmax) ; end; end; if Range<>nil then //範囲の制限 begin Result := Max(Range.low, Min(Range.high, Result)); end; end; function TNoteInfos.GetValue: Integer; var i: Integer; begin Result := 0; for i:=0 to MAX_NOTE_INFO -1 do begin if ArrayNote[i] <> nil then begin Result := Result + ArrayNote[i].Value ; end; end; if Range<>nil then //範囲の制限 begin Result := Max(Range.low, Min(Range.high, Result)); end; end; procedure TNoteInfos.IncValue(Index, value: Integer); begin if ArrayNote[Index] = nil then begin ArrayNote[Index] := TNoteInfo.Create(track) ; end; ArrayNote[Index].Value := ArrayNote[Index].Value + value; end; procedure TNoteInfos.SetReserveValue(Index: Integer; nType: TNoteOnType; v: TMArray; timePtr: Integer); begin if ArrayNote[Index] = nil then begin ArrayNote[Index] := TNoteInfo.Create(track) ; end; ArrayNote[Index].SetReserveValue(nType, v, timePtr); end; procedure TNoteInfos.SetValue(Index, value: Integer); begin if ArrayNote[Index] = nil then begin ArrayNote[Index] := TNoteInfo.Create(track) ; end; ArrayNote[Index].Value := value; end; { TMRange } constructor TMRange.Create(l, h: Integer); begin low := l; high := h; end; { TNoteCC } procedure TNoteCC.Clear; begin if Range <> nil then Range.Free ; Range := nil; RandomValue := 0; DelayTime := 0; RepeatMode := BOOL_TRUE; FIndex := 0; Reserve.Clear ; end; constructor TNoteCC.Create; begin Reserve := TMArray.Create ; noteOnType := noteNormal ; no := -1; Time := 0; LastValue := -1;// 2003/7/1 -1 から 0 に修正 Clear ; //値の初期化 end; destructor TNoteCC.Destroy; begin Clear; Reserve.Free ; inherited; end; { TCCList } procedure TCCList.Clear; var i: Integer; c: TNoteCC ; begin for i:=0 to Count-1 do begin c := Items[i]; if c<>nil then c.Free ; end; inherited; end; destructor TCCList.Destroy; begin Clear; inherited; end; function TCCList.FindCC(no: Integer): TNoteCC; var i: Integer; begin for i:=0 to Count-1 do begin Result := Items[i]; if Result <> nil then begin if Result.No = no then Exit; end; end; Result := nil; end; function TCCList.GetCC(no: Integer): TNoteCC; begin Result := FindCC(no); if Result=nil then begin Result := TNoteCC.Create ; Result.No := no; Result.LastValue := -1; //未定義 { //混乱の元だから、なし case no of CC_NO_VOLUME: Result.LastValue := 100; CC_NO_EXPRESSION: Result.LastValue := 127; CC_NO_PANPOT: Result.LastValue := 64; CC_NO_BEND : Result.LastValue := 64; CC_NO_BEND_FULL: Result.LastValue := 0; end; } Add(Result); end; end; { TTimeKeyFlag } constructor TTimeKeyFlag.Create; var i: Integer; begin for i:=0 to 6 do KeyFlag[i] := 0; timeFrom := -1; timeTo := -1; end; { TTimeKey } constructor TTimeKey.Create; begin timeFrom := -1; timeTo := -1; key := 0; end; end.
unit Rx.Observable.Filter; interface uses Rx, Rx.Subjects; type TFilter<T> = class(TPublishSubject<T>) strict private FRoutine: Rx.TFilter<T>; FRoutineStatic: Rx.TFilterStatic<T>; public constructor Create(Source: IObservable<T>; const Routine: Rx.TFilter<T>); constructor CreateStatic(Source: IObservable<T>; const Routine: Rx.TFilterStatic<T>); procedure OnNext(const Data: T); override; end; implementation { TFilter<T> } constructor TFilter<T>.Create(Source: IObservable<T>; const Routine: Rx.TFilter<T>); begin inherited Create; FRoutine := Routine; Merge(Source); end; constructor TFilter<T>.CreateStatic(Source: IObservable<T>; const Routine: Rx.TFilterStatic<T>); begin inherited Create; FRoutineStatic := Routine; Merge(Source); end; procedure TFilter<T>.OnNext(const Data: T); begin if Assigned(FRoutine) then begin if FRoutine(Data) then inherited; end else if FRoutineStatic(Data) then inherited; end; end.
unit TestCapitalisation; { AFS June 2005 Test the caps processe } {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is TestCapitalisation, released June 2005. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 2005 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"). you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/NPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface uses Classes, TestFrameWork, BaseTestProcess, SettingsTypes; type TTestCapitalisation = class(TBaseTestProcess) private fbSaveEnabled: boolean; feSaveReservedWords: TCapitalisationType; feSaveOperators: TCapitalisationType; feSaveDirectives: TCapitalisationType; feSaveConstants: TCapitalisationType; feSaveTypes: TCapitalisationType; fbSaveAnyWordCapsEnabled: boolean; fSaveIdentifierCaps: boolean; fSaveNotIdentifierCaps: boolean; fSaveIdentifierCapsWords: TStringList; fSaveNotIdentifierCapsWords: TStringList; protected procedure SetUp; override; procedure TearDown; override; published procedure TestPropertyCapsNull; procedure TestPropertyCapsUpper; procedure TestPropertyCapsMixed; procedure TestPropertyCapsLower; procedure TestIdentifierCaps; end; implementation uses SysUtils, { local } JcfStringUtils, Capitalisation, JcfSettings, SetCaps, IdentifierCaps; procedure TTestCapitalisation.Setup; var lcSetCaps: TSetCaps; begin inherited; lcSetCaps := JcfFormatSettings.Caps; fbSaveEnabled := lcSetCaps.Enabled; feSaveReservedWords := lcSetCaps.ReservedWords; feSaveOperators := lcSetCaps.Operators; feSaveDirectives := lcSetCaps.Directives; feSaveConstants := lcSetCaps.Constants; feSaveTypes := lcSetCaps.Types; fbSaveAnyWordCapsEnabled := JcfFormatSettings.SpecificWordCaps.Enabled; fSaveIdentifierCaps := JcfFormatSettings.IdentifierCaps.Enabled; fSaveNotIdentifierCaps := JcfFormatSettings.NotIdentifierCaps.Enabled; fSaveIdentifierCapsWords := TStringList.Create; fSaveIdentifierCapsWords.Assign(JcfFormatSettings.IdentifierCaps.Words); fSaveNotIdentifierCapsWords := TStringList.Create; fSaveNotIdentifierCapsWords.Assign(JcfFormatSettings.NotIdentifierCaps.Words); // default setup JcfFormatSettings.Caps.Enabled := True; JcfFormatSettings.SpecificWordCaps.Enabled := False; end; procedure TTestCapitalisation.Teardown; var lcSetCaps: TSetCaps; begin inherited; lcSetCaps := JcfFormatSettings.Caps; lcSetCaps.Enabled := fbSaveEnabled; lcSetCaps.ReservedWords := feSaveReservedWords; lcSetCaps.Operators := feSaveOperators; lcSetCaps.Directives := feSaveDirectives; lcSetCaps.Constants := feSaveConstants; lcSetCaps.Types := feSaveTypes; JcfFormatSettings.IdentifierCaps.Enabled := fSaveIdentifierCaps; JcfFormatSettings.NotIdentifierCaps.Enabled := fSaveNotIdentifierCaps; JcfFormatSettings.IdentifierCaps.Words.Assign(fSaveIdentifierCapsWords); FreeAndNil(fSaveIdentifierCapsWords); JcfFormatSettings.NotIdentifierCaps.Words.Assign(fSaveNotIdentifierCapsWords); FreeAndNil(fSaveNotIdentifierCapsWords); JcfFormatSettings.SpecificWordCaps.Enabled := fbSaveAnyWordCapsEnabled; end; const LOWER_PROPERTY = 'private' + NativeLineBreak + 'fiFoo: integer;' + NativeLineBreak + 'public' + NativeLineBreak + ' property foo read fiFoo write fiFoo;' + NativeLineBreak; UPPER_PROPERTY = 'PRIVATE' + NativeLineBreak + 'fiFoo: integer;' + NativeLineBreak + 'PUBLIC' + NativeLineBreak + ' property foo READ fiFoo WRITE fiFoo;' + NativeLineBreak; MIXED_PROPERTY = 'Private' + NativeLineBreak + 'fiFoo: integer;' + NativeLineBreak + 'Public' + NativeLineBreak + ' property foo Read fiFoo Write fiFoo;' + NativeLineBreak; UNIT_TEXT_PREFIX = UNIT_HEADER + 'type TFoo = class' + NativeLineBreak; UNIT_TEXT_SUFFIX = 'end;' + NativeLineBreak + UNIT_FOOTER; LOWER_UNIT = UNIT_TEXT_PREFIX + LOWER_PROPERTY + UNIT_TEXT_SUFFIX; UPPER_UNIT = UNIT_TEXT_PREFIX + UPPER_PROPERTY + UNIT_TEXT_SUFFIX; MIXED_UNIT = UNIT_TEXT_PREFIX + MIXED_PROPERTY + UNIT_TEXT_SUFFIX; procedure TTestCapitalisation.TestPropertyCapsNull; begin // stay the same JcfFormatSettings.Caps.Directives := ctLeaveALone; // stay the same TestProcessResult(TCapitalisation, LOWER_UNIT, LOWER_UNIT); TestProcessResult(TCapitalisation, UPPER_UNIT, UPPER_UNIT); TestProcessResult(TCapitalisation, MIXED_UNIT, MIXED_UNIT); end; procedure TTestCapitalisation.TestPropertyCapsUpper; begin JcfFormatSettings.Caps.Directives := ctUpper; TestProcessResult(TCapitalisation, LOWER_UNIT, UPPER_UNIT); TestProcessResult(TCapitalisation, UPPER_UNIT, UPPER_UNIT); TestProcessResult(TCapitalisation, MIXED_UNIT, UPPER_UNIT); end; procedure TTestCapitalisation.TestPropertyCapsLower; begin JcfFormatSettings.Caps.Directives := ctLower; TestProcessResult(TCapitalisation, LOWER_UNIT, LOWER_UNIT); TestProcessResult(TCapitalisation, UPPER_UNIT, LOWER_UNIT); TestProcessResult(TCapitalisation, MIXED_UNIT, LOWER_UNIT); end; procedure TTestCapitalisation.TestPropertyCapsMixed; begin JcfFormatSettings.Caps.Directives := ctMixed; TestProcessResult(TCapitalisation, LOWER_UNIT, MIXED_UNIT); TestProcessResult(TCapitalisation, UPPER_UNIT, MIXED_UNIT); TestProcessResult(TCapitalisation, MIXED_UNIT, MIXED_UNIT); end; const TEST_IDENTIFIER_CAPS_IN = 'unit testCaps;' + NativeLineBreak + 'interface' + NativeLineBreak + 'type' + NativeLineBreak + ' TTester = class' + NativeLineBreak + ' private' + NativeLineBreak + ' fbRead: boolean;' + NativeLineBreak + ' fbWrite: boolean;' + NativeLineBreak + ' procedure SetRead(const Value: boolean);' + NativeLineBreak + ' public' + NativeLineBreak + ' property read: boolean read fbRead write SetRead;' + NativeLineBreak + ' property write: boolean read fbWrite write fbWrite;' + NativeLineBreak + ' end;' + NativeLineBreak + 'implementation' + NativeLineBreak + 'procedure TTester.SetRead(const Value: boolean);' + NativeLineBreak + 'var' + NativeLineBreak + ' strict: integer;' + NativeLineBreak + ' public: boolean;' + NativeLineBreak + ' override: boolean;' + NativeLineBreak + 'begin' + NativeLineBreak + ' fbRead := Value;' + NativeLineBreak + 'end;' + NativeLineBreak + 'end.'; TEST_IDENTIFIER_CAPS_OUT_IDS = 'unit testCaps;' + NativeLineBreak + 'interface' + NativeLineBreak + 'type' + NativeLineBreak + ' TTester = class' + NativeLineBreak + ' private' + NativeLineBreak + ' fbRead: boolean;' + NativeLineBreak + ' fbWrite: boolean;' + NativeLineBreak + ' procedure SetRead(const Value: boolean);' + NativeLineBreak + ' public' + NativeLineBreak + ' property Read: boolean read fbRead write SetRead;' + NativeLineBreak + ' property Write: boolean read fbWrite write fbWrite;' + NativeLineBreak + ' end;' + NativeLineBreak + 'implementation' + NativeLineBreak + 'procedure TTester.SetRead(const Value: boolean);' + NativeLineBreak + 'var' + NativeLineBreak + ' Strict: integer;' + NativeLineBreak + ' Public: boolean;' + NativeLineBreak + ' override: boolean;' + NativeLineBreak + 'begin' + NativeLineBreak + ' fbRead := Value;' + NativeLineBreak + 'end;' + NativeLineBreak + 'end.'; TEST_IDENTIFIER_CAPS_OUT_BOTH = 'unit testCaps;' + NativeLineBreak + 'interface' + NativeLineBreak + 'type' + NativeLineBreak + ' TTester = class' + NativeLineBreak + ' private' + NativeLineBreak + ' fbRead: boolean;' + NativeLineBreak + ' fbWrite: boolean;' + NativeLineBreak + ' procedure SetRead(const Value: boolean);' + NativeLineBreak + ' PUBLIC' + NativeLineBreak + ' property Read: boolean READ fbRead WRITE SetRead;' + NativeLineBreak + ' property Write: boolean READ fbWrite WRITE fbWrite;' + NativeLineBreak + ' end;' + NativeLineBreak + 'implementation' + NativeLineBreak + 'procedure TTester.SetRead(const Value: boolean);' + NativeLineBreak + 'var' + NativeLineBreak + ' Strict: integer;' + NativeLineBreak + ' Public: boolean;' + NativeLineBreak + ' override: boolean;' + NativeLineBreak + 'begin' + NativeLineBreak + ' fbRead := Value;' + NativeLineBreak + 'end;' + NativeLineBreak + 'end.'; procedure TTestCapitalisation.TestIdentifierCaps; begin JcfFormatSettings.IdentifierCaps.Enabled := False; JcfFormatSettings.IdentifierCaps.Words.Clear; JcfFormatSettings.NotIdentifierCaps.Enabled := False; JcfFormatSettings.NotIdentifierCaps.Words.Clear; // no change TestProcessResult(TIdentifierCaps, TEST_IDENTIFIER_CAPS_IN, TEST_IDENTIFIER_CAPS_IN); JcfFormatSettings.IdentifierCaps.Enabled := True; JcfFormatSettings.NotIdentifierCaps.Enabled := True; // no change TestProcessResult(TIdentifierCaps, TEST_IDENTIFIER_CAPS_IN, TEST_IDENTIFIER_CAPS_IN); JcfFormatSettings.IdentifierCaps.Add('Read'); JcfFormatSettings.IdentifierCaps.Add('Write'); JcfFormatSettings.IdentifierCaps.Add('Public'); JcfFormatSettings.IdentifierCaps.Add('Strict'); // identifiers capitalised TestProcessResult(TIdentifierCaps, TEST_IDENTIFIER_CAPS_IN, TEST_IDENTIFIER_CAPS_OUT_IDS); JcfFormatSettings.NotIdentifierCaps.Add('READ'); JcfFormatSettings.NotIdentifierCaps.Add('WRITE'); JcfFormatSettings.NotIdentifierCaps.Add('PUBLIC'); // both identifers and reserved words TestProcessResult(TIdentifierCaps, TEST_IDENTIFIER_CAPS_IN, TEST_IDENTIFIER_CAPS_OUT_BOTH); end; initialization TestFramework.RegisterTest('Processes', TTestCapitalisation.Suite); end.
unit fxLists; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, fBase508Form, VA508AccessibilityManager; type TfrmDbgList = class(TfrmBase508Form) memData: TMemo; procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; procedure DebugListItems(AListBox: TListBox); implementation {$R *.DFM} uses ORFn, ORCtrls; procedure DebugListItems(AListBox: TListBox); var frmDbgList: TfrmDbgList; begin frmDbgList := TfrmDbgList.Create(Application); try ResizeAnchoredFormToFont(frmDbgList); with frmDbgList do begin if AListBox is TORListBox then FastAssign(TORListBox(AListBox).Items, memData.Lines) else memData.Lines.Assign(AListBox.Items); ShowModal; end; finally frmDbgList.Release; end; end; procedure TfrmDbgList.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin Key := 0; Close; end; end; end.
{ BP compatible printer unit with extensions Copyright (C) 1998-2005 Free Software Foundation, Inc. Author: Frank Heckenbach <frank@pascal.gnu.de> This file is part of GNU Pascal. GNU Pascal is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Pascal is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Pascal; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, if you link this file with files compiled with a GNU compiler to produce an executable, this does not cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. } {$gnu-pascal,I-} {$if __GPC_RELEASE__ < 20030303} {$error This unit requires GPC release 20030303 or newer.} {$endif} unit Printer; interface uses GPC {$ifndef __OS_DOS__}, Pipes {$endif}; var { Dos-like systems: writing to a printer device } { The file name to write printer output into } PrinterDeviceName: PString = @'prn'; { Unix-like systems: printing via a printer program } { The file name of the printer program. If it contains a '/', it will be taken as a complete path, otherwise the file name will be searched for in the PATH with FSearchExecutable. } PrinterCommand: PString = @'lpr'; { Optional command line parameters for the printer program. Ignored when nil. } PrinterArguments: PPStrings = nil; { How to deal with the printer spooler after the printer pipe is closed, cf. the Pipes unit. } PrinterPipeSignal : Integer = 0; PrinterPipeSeconds: Integer = 0; PrinterPipeWait : Boolean = True; { Text file opened to default printer } var Lst: Text; { Assign a file to the printer. Lst will be assigned to the default printer at program start, but other files can be assigned to the same or other printers (possibly after changing the variables above). SpoolerOutput, if not Null, will be redirected from the printer spooler's standard output and error. If you use this, note that a deadlock might arise when trying to write data to the spooler while its output is not being read, though this seems quite unlikely, since most printer spoolers don't write so much output that could fill a pipe. Under Dos, where no spooler is involved, SpoolerOutput, if not Null, will be reset to an empty file for compatibility. } procedure AssignPrinter (var f: AnyFile; var SpoolerOutput: AnyFile); implementation {$ifdef __OS_DOS__} procedure AssignPrinter (var f: AnyFile; var SpoolerOutput: AnyFile); begin SetReturnAddress (ReturnAddress (0)); Assign (f, PrinterDeviceName^); RestoreReturnAddress; if @SpoolerOutput <> nil then begin Unbind (SpoolerOutput); Rewrite (SpoolerOutput); Reset (SpoolerOutput) end end; {$else} type TPrinterTFDDData = record f, SpoolerOutput: PAnyFile end; procedure OpenPrinter (var PrivateData; Mode: TOpenMode); begin Discard (PrivateData); if not (Mode in [fo_Rewrite, fo_Append]) then IOError (EPrinterRead, False) end; procedure PrinterDone (var PrivateData); begin Dispose (@PrivateData) end; { Be very lazy: don't open the pipe until data are written to it -- not as soon as the file is opened because that happens already in the initialization of this unit (BP compatibility). } function WritePrinter (var PrivateData; const Buffer; Size: SizeType): SizeType; var Data: TPrinterTFDDData absolute PrivateData; CharBuf: array [1 .. Size] of Char absolute Buffer; Process: PPipeProcess; begin { @@ Check status in Close } WritePrinter := 0; Pipe (Data.f^, Data.SpoolerOutput^, Data.SpoolerOutput^, PrinterCommand^, PrinterArguments^, GetCEnvironment, Process, nil); { this also makes sure this function won't be called again for this file } if InOutRes <> 0 then Exit; Process^.Signal := PrinterPipeSignal; Process^.Seconds := PrinterPipeSeconds; Process^.Wait := PrinterPipeWait; BlockWrite (Data.f^, CharBuf, Size); Dispose (@Data); if InOutRes = 0 then WritePrinter := Size end; procedure AssignPrinter (var f: AnyFile; var SpoolerOutput: AnyFile); var p: ^TPrinterTFDDData; begin if @SpoolerOutput <> nil then begin Unbind (SpoolerOutput); Rewrite (SpoolerOutput); Reset (SpoolerOutput) end; SetReturnAddress (ReturnAddress (0)); New (p); RestoreReturnAddress; p^.f := @f; p^.SpoolerOutput := @SpoolerOutput; AssignTFDD (f, OpenPrinter, nil, nil, nil, WritePrinter, nil, nil, PrinterDone, p) end; {$endif} to begin do begin AssignPrinter (Lst, Null); Rewrite (Lst) end; to end do Close (Lst); end.
unit Renderer; interface {Процедура инциализации рендера } procedure InitRenderer(); {Процедура рисования игрока } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } { player_id - номер игрока, player_name - имя игрока } procedure RenderPlayer(x, y, offset_x, offset_y : integer; player_id : byte; player_name : string); {Процедура рисования щита } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderShield(x, y, offset_x, offset_y : integer); {Процедура рисования врага } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } { enemy_type - тип монстра } procedure RenderEnemy(x, y, offset_x, offset_y : integer; enemy_type : byte); {Процедура рисования земли } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderGrass(x, y, offset_x, offset_y : integer); {Процедура рисования блока земли } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderGrassBlock(x, y, offset_x, offset_y : integer); {Процедура рисования неломаемых блоков } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderIron(x, y, offset_x, offset_y : integer); {Процедура рисования ломаемых блоков } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderBrick(x, y, offset_x, offset_y : integer); {Процедура рисования бомб } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderBomb(x, y, offset_x, offset_y : integer); {Процедура рисования огня } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderFire(x, y, offset_x, offset_y : integer); {Процедура рисования портала игроков } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderPlayerSpawner(x, y, offset_x, offset_y : integer); {Процедура рисования портала монстров } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderEnemySpawner(x, y, offset_x, offset_y : integer); {Процедура рисования иконки бомбы } {Параметры: x, y - позиция, offset_x, offset_y - смещение на экране } procedure RenderBombIcon(x, y, offset_x, offset_y : integer); implementation uses GraphABC, GlobalVars; const TileSize = 64; Player1_Sprite = 1; //Номер первого игрока Player2_Sprite = 2; //Номер второго игрока Bomb_Sprite = 3; //Номер бомбы Iron_Sprite = 4; //Номер неломаемого блока Brick_Sprite = 5; //Номер ломаемого блока Enemy1_Sprite = 6; //Номер обычного монстра Enemy2_Sprite = 7; //Номер быстрого монстра Enemy3_Sprite = 8; //Номер взрывного монстра EnemySpawner_Sprite = 9; //Номер портала монстра PlayerSpawner_Sprite = 10; //Номер портала игрока PlayerShield_Sprite = 11; //Номер щита игрока Fire_Sprite = 12; //Номер огня var Sprites : array[1..12] of Picture; //Массив всех картинок HighGraphics : boolean; //Использовать спрайты для блоков или нет procedure InitRenderer(); begin HighGraphics := false; Sprites[Player1_Sprite] := new Picture('assets/Player1.png'); Sprites[Player2_Sprite] := new Picture('assets/Player2.png'); Sprites[Bomb_Sprite] := new Picture('assets/Bomb.png'); Sprites[Iron_Sprite] := new Picture('assets/Iron.png'); Sprites[Brick_Sprite] := new Picture('assets/Brick.png'); Sprites[Enemy1_Sprite] := new Picture('assets/Enemy1.png'); Sprites[Enemy2_Sprite] := new Picture('assets/Enemy2.png'); Sprites[Enemy3_Sprite] := new Picture('assets/Enemy3.png'); Sprites[EnemySpawner_Sprite] := new Picture('assets/EnemyPortal.png'); Sprites[Fire_Sprite] := new Picture('assets/Fire.png'); Sprites[PlayerSpawner_Sprite] := new Picture('assets/HeroPortal.png'); Sprites[PlayerShield_Sprite] := new Picture('assets/Shield.png'); end; procedure RenderEnemy; var sprite_id : integer; begin SetBrushStyle(bsSolid); sprite_id := 1; case enemy_type of SlowEnemy : sprite_id := Enemy1_Sprite; FastEnemy : sprite_id := Enemy2_Sprite; BlowupEnemy : sprite_id := Enemy3_Sprite; end; Sprites[sprite_id].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end; procedure RenderGrass; begin SetBrushStyle(bsSolid); SetBrushColor(RGB(255, 219, 123)); FillRectangle(x + offset_x, y + offset_y, 15 * TileSize + offset_x, 11 * TileSize + offset_y); end; procedure RenderGrassBlock; begin SetBrushStyle(bsSolid); SetBrushColor(RGB(255, 219, 123)); FillRectangle(x + offset_x, y + offset_y, x + offset_x + TileSize, y + offset_y + TileSize); end; procedure RenderIron; begin SetBrushStyle(bsSolid); if (HighGraphics) then begin Sprites[Iron_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end else begin SetBrushColor(clLightGray); FillRectangle(x + offset_x, y + offset_y, x + offset_x + TileSize, y + offset_y + TileSize); SetBrushColor(clDarkGray); FillRectangle(x + offset_x, y + offset_y + 56, x + offset_x + TileSize, y + offset_y + TileSize); FillRectangle(x + offset_x + 56, y + offset_y, x + offset_x + TileSize, y + offset_y + TileSize); end; end; procedure RenderBrick; begin SetBrushStyle(bsSolid); if (HighGraphics) then begin Sprites[Brick_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end else begin SetBrushColor(clOrangeRed); FillRectangle(x + offset_x, y + offset_y, x + offset_x + TileSize, y + offset_y + TileSize); end; end; procedure RenderBomb; begin SetBrushStyle(bsSolid); Sprites[Bomb_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end; procedure RenderBombIcon; begin SetBrushStyle(bsSolid); Sprites[Bomb_Sprite].Draw(x + offset_x, y + offset_y, 32, 32); end; procedure RenderPlayer; begin SetBrushStyle(bsClear); SetFontSize(8); DrawTextCentered(x + offset_x + TileSize div 2, y + offset_y, player_name); if (player_id = 1) then begin Sprites[Player1_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end else begin Sprites[Player2_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end; end; procedure RenderShield; begin SetBrushStyle(bsSolid); Sprites[PlayerShield_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end; procedure RenderFire; begin Sprites[Fire_Sprite].Draw(x + offset_X, y + offset_Y, TileSize, TileSize); end; procedure RenderPlayerSpawner; begin SetBrushStyle(bsSolid); Sprites[PlayerSpawner_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end; procedure RenderEnemySpawner; begin SetBrushStyle(bsSolid); Sprites[EnemySpawner_Sprite].Draw(x + offset_x, y + offset_y, TileSize, TileSize); end; begin end.
Program clase5parte2; Uses sysutils; Type tweet = record codigoUsuario: integer; nombreUsuario: string; mensaje: string; esRetweet: boolean; end; listaTweets = ^nodoLista; nodoLista = record dato: tweet; sig: listaTweets; end; {Completar agregando aqu� las estructuras de datos necesarias en el ejercicio 1} listaMensajes = ^nodoMensaje; nodoMensaje = record dato: string; sig: listaMensajes; end; usuario = record codigoUsuario: integer; nombreUsuario: string; mensajes: listaMensajes; end; arbol = ^nodoArbol; nodoArbol = record dato: usuario; hi, hd: arbol; end; {----------------------------------------------------------------------------- AgregarAdelante - Agrega nro adelante de l} Procedure agregarAdelante(var l: listaTweets; t: tweet); var aux: listaTweets; begin new(aux); aux^.dato := t; aux^.sig := l; l:= aux; end; {----------------------------------------------------------------------------- CREARLISTA - Genera una lista con tweets aleatorios } procedure crearLista(var l: listaTweets); var t: tweet; texto: string; v : array [1..10] of string; begin v[1]:= 'juan'; v[2]:= 'pedro'; v[3]:= 'carlos'; v[4]:= 'julia'; v[5]:= 'mariana'; v[6]:= 'gonzalo'; v[7]:='alejandra'; v[8]:= 'silvana'; v[9]:= 'angie'; v[10]:= 'hernan'; l:= nil; t.codigoUsuario := random (1000); while (t.codigoUsuario <> 0) do Begin texto:= Concat(v[(t.codigoUsuario mod 10)], '-mensaje-', IntToStr(random (100))); t.nombreUsuario := v[(t.codigoUsuario mod 10)]; t.mensaje := texto; t.esRetweet := (random (1) = 0); agregarAdelante(l, t); t.codigoUsuario := random (1000); End; end; {----------------------------------------------------------------------------- IMPRIMIRLISTA - Muestra en pantalla la lista l } procedure imprimirLista(l: listaTweets); begin While (l <> nil) do begin writeln('---'); writeln('usuario: ',l^.dato.nombreUsuario,' ', l^.dato.codigoUsuario); writeln('mensaje: ',l^.dato.mensaje); writeln('---'); l:= l^.sig; End; end; {----------------------------------------------------------------------------- AGREGARELEMENTO - Resuelve la inserci�n de la estructura de la ACTIVIDAD 1 agregarElemento ( VAR arbolUsuarios, elementoLista) Completar } procedure agregarMensaje (m:string ; var listaM:listaMensajes); var aux:listaMensajes; begin new(aux); aux^.dato:=m; aux^.sig:=listaM; listaM:=aux; end; procedure agregarElemento(registro:tweet; var a:arbol); begin if (a=nil) then begin new(a); a^.hd:=nil; a^.hi:=nil; a^.dato.codigoUsuario:=registro.codigoUsuario; a^.dato.nombreUsuario:=registro.nombreUsuario; a^.dato.mensajes:=nil; agregarMensaje(registro.mensaje ,a^.dato.mensajes); end else begin if (registro.codigoUsuario < a^.dato.codigoUsuario) then agregarElemento(registro, a^.hi) else if (registro.codigoUsuario>a^.dato.codigoUsuario) then agregarElemento(registro, a^.hd) else agregarMensaje(registro.mensaje ,a^.dato.mensajes) end; end; {----------------------------------------------------------------------------- GENERARNUEVAESTRUCTURA - Resuelve la generaci�n de la ACTIVIDAD 1 generarNuevaEstructura (listaTweets, VAR arbolUsuarios) mientras (no llegue al final de la lista de tweets) agregarElemento (arbolUsuarios, elementoLista); avanzar en el recorrido de la lista } procedure GenerarNuevasEstructuras (listaT: listaTweets; var a:arbol); begin if (listaT<>nil) then begin agregarElemento(listaT^.dato, a); GenerarNuevasEstructuras(listaT^.sig, a); end; end; {----------------------------------------------------------------------------- CANTIDADTWEETS - Resuelve la cuenta de elementos de la ACTIVIDAD 2 cantidadTweets (usuario) // recorrer la lista de tweets } {----------------------------------------------------------------------------- RECORRERARBOL - Resuelve el recorrido de la ACTIVIDAD 2 recorrerArbol (arbolUsuarios) si (tenemos un nodo en la ra�z) si (el c�digo de usuario > 200) si (el c�digo de usuario < 700) informar (cantidadTweets (usuarioActual)); recorrerArbol (hijoIzquierdo) recorrerArbol (hijoDerecho) sino recorrerArbol (hijoIzquierdo) sino recorrerArbol (hijoDerecho) } procedure imprimir(l:listaMensajes); begin if (l<>nil) then begin writeln(l^.dato, ' . '); imprimir(l^.sig); end; end; Procedure enOrden( a: arbol ); begin if ( a <> nil ) then begin enOrden (a^.HI); writeln (a^.dato.codigoUsuario, ':'); imprimir(a^.dato.mensajes); enOrden (a^.HD) end; end; Var l: listaTweets; {Completar agregando variables} a:arbol; begin Randomize; a:=nil; crearLista(l); writeln ('Lista generada: '); imprimirLista(l); {Completar el programa} GenerarNuevasEstructuras(l,a); enOrden(a); writeln('Fin del programa'); readln; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995-2001 Borland Software Corporation } { } {*******************************************************} unit StdActnMenus; interface uses Windows, Messages, Classes, Controls, Graphics, Buttons, ActnMenus; type { TStandardMenuItem } TStandardMenuItem = class(TCustomMenuItem) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawGlyph(const Location: TPoint); override; procedure DrawSeparator(const Offset: Integer); override; procedure DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); override; end; { TStandardMenuButton } TStandardMenuButton = class(TCustomMenuButton); { TStarndardMenuPopup } TStandardMenuPopup = class(TCustomActionPopupMenu) protected procedure NCPaint(DC: HDC); override; procedure WMNCCalcSize(var Message: TWMNCCalcSize); message WM_NCCALCSIZE; public constructor Create(AOwner: TComponent); override; end; { TStandardAddRemoveItem } TStandardAddRemoveItem = class(TCustomAddRemoveItem) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawGlyph(const Location: TPoint); override; procedure DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); override; end; { TStandardCustomizePopup } TStandardCustomizePopup = class(TCustomizeActionToolBar) public constructor Create(AOwner: TComponent); override; end; procedure RegisterStandardMenus; implementation uses Menus, ActnList, ToolWin, GraphUtil; const FillStyles: array[Boolean] of Integer = (BF_MIDDLE, 0); FrameStyle: array[Boolean] of Integer = (BDR_RAISEDINNER, BDR_SUNKENOUTER); EdgesOffset: array[Boolean] of Integer = (0, 1); { TStandardMenuItem } procedure TStandardMenuItem.DrawSeparator(const Offset: Integer); begin inherited DrawSeparator(13); end; procedure TStandardMenuItem.DrawBackground(var PaintRect: TRect); begin if ActionClient = nil then exit; // TODO -oSDT: Need to check BiDi flags here to determine the size of the rect if ((Selected and Enabled) or (Selected and not MouseSelected)) and not ActionBar.DesignMode then begin Canvas.Brush.Color := clHighlight; if ActionClient.HasGlyph or IsChecked then Inc(PaintRect.Left, 21) else Inc(PaintRect.Left); Dec(PaintRect.Right, 2); end else if ActionClient.Unused or ActionClient.Separator and ((ActionClient.Index > 0) and ActionClient.ActionClients[ActionClient.Index - 1].Unused) and ((ActionClient.Index < ActionClient.Collection.Count - 1) and ActionClient.ActionClients[ActionClient.Index + 1].Unused) then Canvas.Brush.Color := GetHighLightColor(Color) else Canvas.Brush.Color := clMenu; inherited DrawBackground(PaintRect); end; procedure TStandardMenuItem.DrawGlyph(const Location: TPoint); var FrameRect: TRect; begin if (HasGlyph and ActionClient.ShowGlyph) or IsChecked then begin FrameRect := Rect(Location.X - 1, 0, Location.X + 18, Self.Height); if ((Selected and Enabled) or (Selected and not MouseSelected)) or IsChecked then begin Inc(FrameRect.Top, EdgesOffset[ebTop in Edges]); Dec(FrameRect.Bottom, EdgesOffset[ebBottom in Edges]); // if not (csDesigning in ComponentState) then Windows.DrawEdge(Canvas.Handle, FrameRect, FrameStyle[IsChecked], FillStyles[Transparent] or BF_RECT); if not Transparent then begin if not Selected and IsChecked then Canvas.Brush.Bitmap := AllocPatternBitmap(Color, GetHighLightColor(Color)) else if ActionClient.Unused then Canvas.Brush.Color := GetHighLightColor(Color) else Canvas.Brush.Color := Color; InflateRect(FrameRect, -1, -1); Canvas.FillRect(FrameRect); end; end; end; if not HasGlyph and IsChecked then begin Canvas.Pen.Color := clBlack; DrawCheck(Canvas, Point(Location.X + 4, Location.Y + 4), 2); end; inherited DrawGlyph(Location); end; procedure TStandardMenuItem.DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); begin if Enabled or (csDesigning in ComponentState) then begin if Selected then Canvas.Font.Color := clHighlightText else Canvas.Font.Color := clMenuText; inherited DrawText(Rect, Flags, Text) end else begin Canvas.Brush.Style := bsClear; if not Selected or (csDesigning in ComponentState) then begin OffsetRect(Rect, 1, 1); Canvas.Font.Color := clWhite; Windows.DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); OffsetRect(Rect, -1, -1); end; Canvas.Font.Color := clGrayText; Windows.DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); end; end; { TStandardMenuPopup } constructor TStandardMenuPopup.Create(AOwner: TComponent); begin inherited Create(AOwner); ParentColor := False; Color := clMenu; end; procedure TStandardMenuPopup.NCPaint(DC: HDC); const InnerStyles: array[TEdgeStyle] of Integer = (0, BDR_RAISEDINNER, BDR_SUNKENINNER); OuterStyles: array[TEdgeStyle] of Integer = (0, BDR_RAISEDOUTER, BDR_SUNKENOUTER); Ctl3DStyles: array[Boolean] of Integer = (BF_MONO, 0); var RC, RW: TRect; EdgeBdrs: TEdgeBorders; EdgeStyle: Integer; begin Windows.GetClientRect(Handle, RC); GetWindowRect(Handle, RW); MapWindowPoints(0, Handle, RW, 2); OffsetRect(RC, -RW.Left, -RW.Top); ExcludeClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom); { Draw borders in non-client area } OffsetRect(RW, -RW.Left, -RW.Top); if Expanded and ActionClient.Items.HideUnused then begin EdgeBdrs := [ebTop, ebLeft]; DrawEdge(DC, RW, InnerStyles[EdgeInner] or OuterStyles[EdgeOuter], Byte(EdgeBdrs) or Ctl3DStyles[Ctl3D] or BF_ADJUST); if (FindLastVisibleItem <> nil) and not FindLastVisibleItem.Unused then EdgeStyle := BDR_RAISEDINNER else EdgeStyle := 0; EdgeBdrs := [ebBottom]; DrawEdge(DC, RW, EdgeStyle or OuterStyles[EdgeOuter], Byte(EdgeBdrs) or Ctl3DStyles[Ctl3D] or BF_ADJUST); EdgeBdrs := [ebRight]; DrawEdge(DC, RW, OuterStyles[EdgeOuter], Byte(EdgeBdrs) or Ctl3DStyles[Ctl3D] or BF_ADJUST) end else DrawEdge(DC, RW, InnerStyles[EdgeInner] or OuterStyles[EdgeOuter], Byte(EdgeBorders) or Ctl3DStyles[Ctl3D] or BF_ADJUST); { Erase parts not drawn } IntersectClipRect(DC, RW.Left, RW.Top, RW.Right, RW.Bottom); Windows.FillRect(DC, RW, Brush.Handle); end; procedure TStandardMenuPopup.WMNCCalcSize(var Message: TWMNCCalcSize); begin inherited; Message.Result := WVR_VALIDRECTS; if Expanded then Inc(Message.CalcSize_Params^.rgrc[0].Right); end; { TStandardAddRemoveItem } procedure TStandardAddRemoveItem.DrawGlyph(const Location: TPoint); var FrameRect: TRect; begin if HasGlyph then begin FrameRect := Rect(Location.X - 1, 0, Location.X + 18, Self.Height); if ((Selected and Enabled) or (Selected and not MouseSelected)) or IsChecked then begin Inc(FrameRect.Top, EdgesOffset[ebTop in Edges]); Dec(FrameRect.Bottom, EdgesOffset[ebBottom in Edges]); if not (csDesigning in ComponentState) then Windows.DrawEdge(Canvas.Handle, FrameRect, FrameStyle[IsChecked], FillStyles[Transparent] or BF_RECT); if not Transparent then begin if not Selected then Canvas.Brush.Bitmap := AllocPatternBitmap(Color, GetHighLightColor(Color)) else Canvas.Brush.Color := Color; InflateRect(FrameRect, -1, -1); Canvas.FillRect(FrameRect); end; end; end; if not HasGlyph and IsChecked then begin Canvas.Pen.Color := clBlack; DrawCheck(Canvas, Point(Location.X + 4, Location.Y + 4), 2); end; inherited DrawGlyph(Location); if Menu.RootMenu.ParentControl.ActionBar.ActionClient.Items[ActionClient.Index].Visible then begin FrameRect := Rect(2 - 1, 0, 18, Self.Height); Inc(FrameRect.Top, EdgesOffset[ebTop in Edges]); Dec(FrameRect.Bottom, EdgesOffset[ebBottom in Edges]); if not (csDesigning in ComponentState) then Windows.DrawEdge(Canvas.Handle, FrameRect, FrameStyle[True], FillStyles[False] or BF_RECT); if not Transparent then begin if not Selected then Canvas.Brush.Bitmap := AllocPatternBitmap(Color, GetHighLightColor(Color)) else Canvas.Brush.Color := GetHighLightColor(Color); InflateRect(FrameRect, -1, -1); Canvas.FillRect(FrameRect); end; DrawCheck(Canvas, Point(6, Height div 2 + 1), 2, True); end; end; procedure TStandardAddRemoveItem.DrawBackground(var PaintRect: TRect); begin if ActionClient = nil then exit; // TODO -oSDT: Need to check BiDi flags here to determine the size of the rect if ((Selected and Enabled) or (Selected and not MouseSelected)) and not ActionBar.DesignMode then begin Canvas.Brush.Color := clHighlight; if ActionClient.HasGlyph or IsChecked then Inc(PaintRect.Left, 22) else Inc(PaintRect.Left); Dec(PaintRect.Right, 2); end else Canvas.Brush.Color := clMenu; inherited DrawBackground(PaintRect); end; procedure TStandardAddRemoveItem.DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); begin if Selected then Canvas.Font.Color := clHighlightText else Canvas.Font.Color := clMenuText; inherited DrawText(Rect, Flags, Text) end; { TStandardCustomizePopup } constructor TStandardCustomizePopup.Create(AOwner: TComponent); begin inherited Create(AOwner); ParentColor := False; Color := clMenu; end; procedure RegisterStandardMenus; begin MenuItemControlClass := TStandardMenuItem; MenuAddRemoveItemClass := TStandardAddRemoveItem; MenuButtonControlClass := TStandardMenuButton; MenuPopupClass := TStandardMenuPopup; MenuCustomizePopupClass := TStandardCustomizePopup; end; initialization RegisterStandardMenus; end.
unit TestDadosDoTempo; interface uses TestFramework, InterfaceDadosTempo, InterfaceObservadorTempo, System.Generics.Collections, DadosDoTempo, System.SysUtils; type TestTDadosDoTempo = class(TTestCase) strict private FDadosDoTempo: TDadosDoTempo; public procedure SetUp; override; procedure TearDown; override; published procedure NovoObservador_TDadosDoTempo_1; procedure DeletarObservador_TDadosDoTempo_0; end; implementation uses ExibirTempoAtual; procedure TestTDadosDoTempo.DeletarObservador_TDadosDoTempo_0; begin FDadosDoTempo.NovoObservador(TExibirTempoAtual.Create); FDadosDoTempo.DeletarObservador(TExibirTempoAtual.Create); CheckEquals(0, FDadosDoTempo.ListaDeObservadores.Count); end; procedure TestTDadosDoTempo.NovoObservador_TDadosDoTempo_1; begin FDadosDoTempo.NovoObservador(TExibirTempoAtual.Create); CheckEquals(1, FDadosDoTempo.ListaDeObservadores.Count); end; procedure TestTDadosDoTempo.SetUp; begin FDadosDoTempo := TDadosDoTempo.Create; end; procedure TestTDadosDoTempo.TearDown; begin FDadosDoTempo.Free; end; initialization // Register any test cases with the test runner RegisterTest(TestTDadosDoTempo.Suite); end.
unit UnitFormExpander; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TFormExpander = class(TForm) Panel1: TPanel; Button1: TButton; Label1: TLabel; procedure Button1Click(Sender: TObject); procedure Label1Click(Sender: TObject); private { Private declarations } FControl: TWinControl; public { Public declarations } procedure Setup(s: string; c: TWinControl); procedure Expand; procedure Collapse; end; var FormExpander: TFormExpander; implementation {$R *.dfm} uses UnitAppIni; procedure TFormExpander.Button1Click(Sender: TObject); begin if Button1.Caption = '+' then Expand else Collapse; AppIni.WriteBool('FormExpander', Label1.Caption, Button1.Caption = '-'); end; procedure TFormExpander.Label1Click(Sender: TObject); begin Button1.Click; end; procedure TFormExpander.Expand; begin //FControl.Align := alClient; Height := Panel1.Height + FControl.Height + FControl.Margins.Top + FControl.Margins.Bottom + 5; Button1.Caption := '-'; end; procedure TFormExpander.Collapse; begin Height := Panel1.Height; Button1.Caption := '+'; end; procedure TFormExpander.Setup(s: string; c: TWinControl); begin FControl := c; Label1.Caption := s; FControl.Parent := self; FControl.Align := alTop; FControl.AlignWithMargins := true; FControl.Margins.Top := 5; FControl.Margins.Bottom := 5; FControl.Margins.Left := 5; FControl.Margins.Right := 5; FControl.Top := 100500; FControl.Show; if AppIni.ReadBool('FormExpander', Label1.Caption, true) then Expand else Collapse; end; end.
{******************************************} { TeeChart Tools Editor } { Copyright (c) 2000-2004 by David Berneda } {******************************************} unit TeeEditTools; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QExtCtrls, QStdCtrls, QButtons, Types, {$ELSE} Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, {$ENDIF} TeCanvas, TeEngine, Chart, TeePenDlg, TeeProcs; type TFormTeeTools = class(TForm) LBTools: TListBox; PanelToolEditor: TPanel; PTop: TPanel; BAdd: TButtonColor; BDelete: TButtonColor; CBActive: TCheckBox; PBottom: TPanel; Splitter1: TSplitter; Panel2: TPanel; BMoveUp: TSpeedButton; BMoveDown: TSpeedButton; procedure LBToolsClick(Sender: TObject); procedure BDeleteClick(Sender: TObject); procedure CBActiveClick(Sender: TObject); procedure BAddClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BMoveUpClick(Sender: TObject); procedure BMoveDownClick(Sender: TObject); {$IFNDEF CLX} procedure LBToolsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); {$ELSE} procedure LBToolsDrawItem(Sender: TObject; Index: Integer; Rect: TRect; State: TOwnerDrawState; var Handled: Boolean); {$ENDIF} private { Private declarations } {$IFDEF CLX} ICreating : Boolean; {$ENDIF} Function CurrentTool:TTeeCustomTool; procedure DeleteForm; procedure EnableButtons; procedure FillAndSet; procedure FillTools; procedure SwapTool(A,B:Integer); {$IFNDEF CLX} procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED; {$ENDIF} protected OnAdded, OnDeleted : TNotifyEvent; // 6.02 public { Public declarations } Chart : TCustomChart; Procedure Reload; end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeConst, TeeToolsGallery; type TElementAccess=class(TCustomChartElement); procedure TFormTeeTools.FillTools; var t : Integer; begin PBottom.Caption:=''; With LBTools do begin Clear; for t:=0 to Chart.Tools.Count-1 do if not TElementAccess(Chart.Tools[t]).InternalUse then Items.AddObject(Chart.Tools[t].Description,Chart.Tools[t]); end; CBActive.Enabled:=LBTools.Items.Count>0; BDelete.Enabled:=CBActive.Enabled; end; type TToolAccess=class(TTeeCustomTool); procedure TFormTeeTools.DeleteForm; begin if PanelToolEditor.ControlCount>0 then PanelToolEditor.Controls[0].Free; end; procedure TFormTeeTools.LBToolsClick(Sender: TObject); var tmpClass : TClass; tmp : TForm; begin {$IFDEF CLX} if not ICreating then if (PanelToolEditor.ControlCount=0) or (PanelToolEditor.Controls[0].Tag<>Integer(CurrentTool)) then {$ENDIF} if CurrentTool<>nil then begin if PanelToolEditor.ControlCount>0 then begin if not TForm(PanelToolEditor.Controls[0]).CloseQuery then LBTools.ItemIndex:=Chart.Tools.IndexOf(TTeeCustomTool(PanelToolEditor.Controls[0].Tag)); end; CBActive.Checked:=CurrentTool.Active; DeleteForm; tmpClass:=GetClass(TToolAccess(CurrentTool).GetEditorClass); if Assigned(tmpClass) then begin tmp:=TFormClass(tmpClass).Create(Self); TeeTranslateControl(tmp); tmp.Align:=alClient; AddFormTo(tmp,PanelToolEditor,CurrentTool); end; EnableButtons; if PBottom.Visible and (CurrentTool<>nil) then PBottom.Caption:=CurrentTool.Name; end; end; procedure TFormTeeTools.BDeleteClick(Sender: TObject); var tmp : Integer; begin if (CurrentTool<>nil) and { 5.01 } TeeYesNoDelete(CurrentTool.Description,Self) then begin tmp:=LBTools.ItemIndex; if Assigned(OnDeleted) then OnDeleted(CurrentTool); CurrentTool.Free; DeleteForm; FillTools; With LBTools do { 5.01 } if tmp>1 then ItemIndex:=tmp-1 else if Items.Count>0 then ItemIndex:=Items.Count-1; BDelete.Enabled:=LBTools.ItemIndex<>-1; if BDelete.Enabled then LBToolsClick(Self); end; end; procedure TFormTeeTools.CBActiveClick(Sender: TObject); begin CurrentTool.Active:=CBActive.Checked; end; procedure TFormTeeTools.BAddClick(Sender: TObject); var AOwner : TComponent; t : Integer; tmpTool : TTeeCustomTool; begin With TTeeToolsGallery.Create(Owner) do try {$IFDEF D5} if Assigned(Owner) then Position:=poOwnerFormCenter else {$ENDIF} Position:=poScreenCenter; if ShowModal=mrOk then begin {$IFDEF CLX} ICreating:=True; {$ENDIF} AOwner:=Chart.Owner; for t:=0 to Chart.Tools.Count-1 do { 5.01 } if Chart.Tools[t].Owner=Chart then begin AOwner:=Chart; break; end; tmpTool:=SelectedTool.Create(AOwner); with tmpTool do begin ParentChart:=Chart; Name:=TeeGetUniqueName(AOwner,TeeMsg_DefaultToolName); end; if Assigned(OnAdded) then OnAdded(tmpTool); FillTools; {$IFDEF CLX} ICreating:=False; {$ENDIF} LBTools.ItemIndex:=LBTools.Items.Count-1; LBTools.SetFocus; LBToolsClick(Self); end; finally Free; end; end; function TFormTeeTools.CurrentTool: TTeeCustomTool; begin if LBTools.ItemIndex=-1 then result:=nil else result:=TTeeCustomTool(LBTools.Items.Objects[LBTools.ItemIndex]); end; procedure TFormTeeTools.FillAndSet; begin FillTools; With LBTools do if Items.Count>0 then begin ItemIndex:=0; LBToolsClick(Self); end else EnableButtons; end; procedure TFormTeeTools.FormShow(Sender: TObject); begin Chart:=TCustomChart(Tag); if Assigned(Chart) then begin PBottom.Visible:=csDesigning in Chart.ComponentState; FillAndSet; end; {$IFDEF CLX} ICreating:=False; if LBTools.Items.Count>0 then begin if LBTools.ItemIndex=-1 then LBTools.ItemIndex:=0; LBToolsClick(Self); end; {$ENDIF} TeeTranslateControl(Self); end; procedure TFormTeeTools.FormCreate(Sender: TObject); begin {$IFDEF CLX} ICreating:=True; {$ENDIF} TeeLoadArrowBitmaps(BMoveUp.Glyph,BMoveDown.Glyph); end; procedure TFormTeeTools.SwapTool(A,B:Integer); var tmpIndex : Integer; begin LBTools.Items.Exchange(A,B); {$IFDEF CLX} if LBTools.ItemIndex=A then LBTools.ItemIndex:=B; {$ENDIF} LBTools.Invalidate; With Chart do begin Tools.Exchange(A,B); tmpIndex:=Tools[A].ComponentIndex; Tools[A].ComponentIndex:=Tools[B].ComponentIndex; Tools[B].ComponentIndex:=tmpIndex; Invalidate; end; EnableButtons; end; procedure TFormTeeTools.EnableButtons; begin With LBTools do begin BMoveUp.Enabled :=ItemIndex>0; BMoveDown.Enabled:=ItemIndex<Items.Count-1; end; end; procedure TFormTeeTools.BMoveUpClick(Sender: TObject); begin With LBTools do SwapTool(ItemIndex,ItemIndex-1); end; procedure TFormTeeTools.BMoveDownClick(Sender: TObject); begin With LBTools do SwapTool(ItemIndex,ItemIndex+1); end; Procedure TFormTeeTools.Reload; begin if Chart<>nil then if Chart.Tools.Count<>LBTools.Items.Count then FillAndSet; if LBTools.ItemIndex<>-1 then LBToolsClick(Self); end; {$IFNDEF CLX} procedure TFormTeeTools.LBToolsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); {$ELSE} procedure TFormTeeTools.LBToolsDrawItem(Sender: TObject; Index: Integer; Rect: TRect; State: TOwnerDrawState; var Handled: Boolean); {$ENDIF} begin TeeDrawTool(LBTools,Index,Rect,State,TTeeCustomTool(LBTools.Items.Objects[Index])); end; {$IFNDEF CLX} procedure TFormTeeTools.CMShowingChanged(var Message: TMessage); begin inherited; if Assigned(Parent) then Parent.UpdateControlState; end; {$ENDIF} end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Sensors.Components; interface uses System.Sensors, System.Classes, System.SysUtils, System.Math; const pidSensorSupportPlatforms = (pfidWindows or pfidOSX or pfidiOS or pfidAndroid); type { TSensor<T: TCustomSensor> } TOnSensorChoosing = procedure (Sender: TObject; const Sensors: TSensorArray; var ChoseSensorIndex: Integer) of object; EGettingSensor = class(Exception); TSensor<T: TCustomSensor> = class (TComponent) strict private FDesignTimeActivation : Boolean; FOnSensorRemoved: TNotifyEvent; FOnStateChanged: TNotifyEvent; FOnSensorChoosing: TOnSensorChoosing; procedure SetActive(const Value: Boolean); function GetActive: Boolean; procedure SetOnSensorRemoved(const Value: TNotifyEvent); procedure SetOnStateChanged(const Value: TNotifyEvent); protected FCategorySensor: TSensorCategory; FManager: TSensorManager; FSensor: T; function GetSensor: T; virtual; procedure UpdateSensorProperties; virtual; procedure DoSensorRemoved(Sender: TObject); virtual; procedure DoSensorChoosing(const ASensors: TSensorArray; var AChoseSensorIndex: Integer); virtual; procedure DoStart; virtual; procedure DoStop; virtual; function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall; public constructor Create(AOwner: TComponent); override; property Sensor: T read FSensor; published property Active: Boolean read GetActive write SetActive default False; { Events } property OnSensorChoosing: TOnSensorChoosing read FOnSensorChoosing write FOnSensorChoosing; property OnSensorRemoved: TNotifyEvent read FOnSensorRemoved write SetOnSensorRemoved; property OnStateChanged: TNotifyEvent read FOnStateChanged write SetOnStateChanged; end; { TLocationSensor } [ComponentPlatformsAttribute(pidSensorSupportPlatforms)] TLocationSensor = class (TSensor<TCustomLocationSensor>) strict private FOptimize: Boolean; FLocationChange: TLocationChangeType; FAccuracy: TLocationAccuracy; FDistance: TLocationDistance; FOnLocationChanged: TLocationChangedEvent; FOnEnterRegion: TRegionProximityEvent; FOnExitRegion: TRegionProximityEvent; FOnHeadingChanged : THeadingChangedEvent; procedure SetOptimize(const Value: Boolean); procedure SetOnLocationChanged(const Value: TLocationChangedEvent); procedure SetOnEnterRegion(const Value: TRegionProximityEvent); procedure SetOnExitRegion(const Value: TRegionProximityEvent); procedure SetLocationChange(const Value: TLocationChangeType); procedure SetAccuracy(const Value: TLocationAccuracy); procedure SetDistance(const Value: TLocationDistance); procedure SetOnHeadingChanged(const Value: THeadingChangedEvent); protected procedure UpdateSensorProperties; override; procedure DoStart; override; procedure DoStop; override; function GetRegion(const AIndex: Integer): TLocationRegion; function GetRegionCount: Integer; public constructor Create(AOwner: TComponent); override; procedure AddRegion(const Value: TLocationRegion); procedure RemoveRegion(const Value: TLocationRegion); procedure ClearRegions; property RegionCount: Integer read GetRegionCount; property Regions[const AIndex: Integer]: TLocationRegion read GetRegion; published property Optimize: Boolean read FOptimize write SetOptimize default True; property LocationChange: TLocationChangeType read FLocationChange write SetLocationChange default TLocationChangeType.lctSmall; property Accuracy: TLocationAccuracy read FAccuracy write SetAccuracy; property Distance: TLocationDistance read FDistance write SetDistance; { Events } property OnLocationChanged: TLocationChangedEvent read FOnLocationChanged write SetOnLocationChanged; property OnEnterRegion: TRegionProximityEvent read FOnEnterRegion write SetOnEnterRegion; property OnExitRegion: TRegionProximityEvent read FOnExitRegion write SetOnExitRegion; property OnHeadingChanged : THeadingChangedEvent read FOnHeadingChanged write SetOnHeadingChanged; end; { TMotionSensor } [ComponentPlatformsAttribute(pidSensorSupportPlatforms)] TMotionSensor = class (TSensor<TCustomMotionSensor>) protected procedure DoStart; override; procedure DoStop; override; public constructor Create(AOwner: TComponent); override; end; { TEnvironmentalSensor } TEnvironmentalSensor = class (TSensor<TCustomEnvironmentalSensor>) public constructor Create(AOwner: TComponent); override; end; { TOrientationSensor } [ComponentPlatformsAttribute(pidSensorSupportPlatforms)] TOrientationSensor = class (TSensor<TCustomOrientationSensor>) protected procedure DoStart; override; procedure DoStop; override; public constructor Create(AOwner: TComponent); override; end; { TElectricalSensor } TElectricalSensor = class (TSensor<TCustomElectricalSensor>) public constructor Create(AOwner: TComponent); override; end; { TMechanicalSensor } TMechanicalSensor = class (TSensor<TCustomMechanicalSensor>) public constructor Create(AOwner: TComponent); override; end; { TBiometricSensor } TBiometricSensor = class (TSensor<TCustomBiometricSensor>) public constructor Create(AOwner: TComponent); override; end; { TLightSensor } TLightSensor = class (TSensor<TCustomLightSensor>) public constructor Create(AOwner: TComponent); override; end; { TScannerSensor } TScannerSensor = class (TSensor<TCustomScannerSensor>) public constructor Create(AOwner: TComponent); override; end; implementation uses System.Generics.Collections, System.RTLConsts; { TSensor } constructor TSensor<T>.Create(AOwner: TComponent); begin inherited Create(AOwner); try FManager := TSensorManager.Current; except on ESensorManagerException do FManager := nil; end; end; procedure TSensor<T>.DoSensorRemoved(Sender: TObject); begin FSensor := nil; if Assigned(FOnSensorRemoved) then FOnSensorRemoved(Sender); end; procedure TSensor<T>.DoStart; begin end; procedure TSensor<T>.DoStop; begin end; procedure TSensor<T>.DoSensorChoosing(const ASensors: TSensorArray; var AChoseSensorIndex: Integer); begin if Assigned(FOnSensorChoosing) then FOnSensorChoosing(Self, ASensors, AChoseSensorIndex); end; function TSensor<T>.GetActive: Boolean; begin if csDesigning in ComponentState then Result := FDesignTimeActivation else Result := Assigned(FManager) and FManager.Active and Assigned(FSensor) and not (FSensor.State in [TSensorState.Removed, TSensorState.AccessDenied, TSensorState.Error]); end; function TSensor<T>.GetSensor: T; var Sensors: TSensorArray; Category: TSensorCategory; SelectedSensorIndex: Integer; begin if not Assigned(FManager) then Exit(nil); FManager.Active := True; Sensors := FManager.GetSensorsByCategory(FCategorySensor); if Length(Sensors) > 0 then begin SelectedSensorIndex := 0; DoSensorChoosing(Sensors, SelectedSensorIndex); if InRange(SelectedSensorIndex, 0, High(Sensors)) then Result := Sensors[SelectedSensorIndex] as T else raise EGettingSensor.Create(Format(SSensorIndexError, [SelectedSensorIndex])); end else Result := nil; end; function TSensor<T>.QueryInterface(const IID: TGUID; out Obj): HResult; begin Result := inherited QueryInterface(IID, Obj); if (Result <> S_OK) and (FSensor <> nil) then Result := FSensor.GetInterface(IID, Obj); end; procedure TSensor<T>.SetActive(const Value: Boolean); var CanActive: Boolean; begin if csDesigning in ComponentState then FDesignTimeActivation := Value else begin if Assigned(FManager) and (Active <> Value) then begin FManager.Active := True; // Try to get sensor if not Assigned(FSensor) then FSensor := GetSensor; UpdateSensorProperties; end; if Value then DoStart else begin DoStop; FSensor := nil; end; end; end; procedure TSensor<T>.SetOnSensorRemoved(const Value: TNotifyEvent); begin FOnSensorRemoved := Value; UpdateSensorProperties; end; procedure TSensor<T>.SetOnStateChanged(const Value: TNotifyEvent); begin FOnStateChanged := Value; UpdateSensorProperties; end; procedure TSensor<T>.UpdateSensorProperties; begin if Assigned(FSensor) then begin FSensor.OnSensorRemoved := DoSensorRemoved; FSensor.OnStateChanged := FOnStateChanged; end; end; { TLocationSensor } procedure TLocationSensor.SetOptimize(const Value: Boolean); begin if FOptimize <> Value then begin FOptimize := Value; UpdateSensorProperties; end; end; procedure TLocationSensor.UpdateSensorProperties; begin inherited UpdateSensorProperties; if Assigned(FSensor) then begin FSensor.OnLocationChanged := FOnLocationChanged; FSensor.OnHeadingChanged := FOnHeadingChanged; FSensor.OnEnterRegion := FOnEnterRegion; FSensor.OnExitRegion := FOnExitRegion; FSensor.Optimize := FOptimize; FSensor.LocationChange := FLocationChange; FSensor.Accuracy := FAccuracy; FSensor.Distance := FDistance; end; end; procedure TLocationSensor.SetOnLocationChanged(const Value: TLocationChangedEvent); begin FOnLocationChanged := Value; UpdateSensorProperties; end; procedure TLocationSensor.DoStart; begin if Assigned(FSensor) then FSensor.Start; end; procedure TLocationSensor.DoStop; begin if Assigned(FSensor) then FSensor.Stop; end; function TLocationSensor.GetRegionCount: Integer; begin if Assigned(FSensor) then Result := FSensor.Regions.Count else Result := 0; end; function TLocationSensor.GetRegion(const AIndex: Integer): TLocationRegion; begin if Assigned(FSensor) then Result := FSensor.Regions.Items[AIndex] else Result := TLocationRegion.Empty; end; procedure TLocationSensor.RemoveRegion(const Value: TLocationRegion); begin if Assigned(FSensor) and FSensor.Regions.Contains(Value) then FSensor.Regions.Remove(Value); end; procedure TLocationSensor.SetAccuracy(const Value: TLocationAccuracy); begin FAccuracy := Value; UpdateSensorProperties; end; procedure TLocationSensor.SetDistance(const Value: TLocationDistance); begin FDistance := Value; UpdateSensorProperties; end; procedure TLocationSensor.SetLocationChange(const Value: TLocationChangeType); begin FLocationChange := Value; UpdateSensorProperties; end; procedure TLocationSensor.SetOnEnterRegion(const Value: TRegionProximityEvent); begin FOnEnterRegion := Value; UpdateSensorProperties; end; procedure TLocationSensor.SetOnExitRegion(const Value: TRegionProximityEvent); begin FOnExitRegion := Value; UpdateSensorProperties; end; procedure TLocationSensor.SetOnHeadingChanged(const Value: THeadingChangedEvent); begin FOnHeadingChanged := Value; UpdateSensorProperties; end; procedure TLocationSensor.AddRegion(const Value: TLocationRegion); begin if not Assigned(FSensor) then FSensor := GetSensor; if not FSensor.Regions.Contains(Value) then FSensor.Regions.Add(Value); end; procedure TLocationSensor.ClearRegions; begin if Assigned(FSensor) then begin FSensor.Regions.Clear; UpdateSensorProperties; end; end; constructor TLocationSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Location; FOptimize := True; FLocationChange := TLocationChangeType.lctSmall; FAccuracy := 0; FDistance := 0; end; { TLightSensor } constructor TLightSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Light; end; { TEnvironmentalSensor } constructor TEnvironmentalSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Environmental; end; { TOrientationSensor } constructor TOrientationSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Orientation; end; procedure TOrientationSensor.DoStart; begin if Assigned(FSensor) then FSensor.Start; end; procedure TOrientationSensor.DoStop; begin if Assigned(FSensor) then FSensor.Stop; end; { TElectricalSensor } constructor TElectricalSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Electrical; end; { TMechanicalSensor } constructor TMechanicalSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Mechanical; end; { TBiometricSensor } constructor TBiometricSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Biometric; end; { TScannerSensor } constructor TScannerSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Scanner; end; { TMotionSensor } constructor TMotionSensor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCategorySensor := TSensorCategory.Motion; end; procedure TMotionSensor.DoStart; begin if Assigned(FSensor) then FSensor.Start; end; procedure TMotionSensor.DoStop; begin if Assigned(FSensor) then FSensor.Stop; end; end.
unit DropFileSource3; // ----------------------------------------------------------------------------- // // *** NOT FOR RELEASE *** // // *** INTERNAL USE ONLY *** // // ----------------------------------------------------------------------------- // Project: Drag and Drop Component Suite // Module: DropFileSource3 // Description: Test case for deprecated TDropSource class. // Version: 4.0 // Date: 25-JUN-2000 // Target: Win32, Delphi 3-6 and C++ Builder 3-5 // Authors: Angus Johnson, ajohnson@rpi.net.au // Anders Melander, anders@melander.dk, http://www.melander.dk // Copyright © 1997-2000 Angus Johnson & Anders Melander // ----------------------------------------------------------------------------- interface uses DragDrop, DragDropPIDL, DragDropFormats, DragDropFile, DropSource3, ActiveX, Classes; {$include DragDrop.inc} type TDropFileSourceX = class(TDropSource) private fFiles: TStrings; fMappedNames: TStrings; FFileClipboardFormat: TFileClipboardFormat; FPIDLClipboardFormat: TPIDLClipboardFormat; FPreferredDropEffectClipboardFormat: TPreferredDropEffectClipboardFormat; FFilenameMapClipboardFormat: TFilenameMapClipboardFormat; FFilenameMapWClipboardFormat: TFilenameMapWClipboardFormat; procedure SetFiles(files: TStrings); procedure SetMappedNames(names: TStrings); protected function DoGetData(const FormatEtcIn: TFormatEtc; out Medium: TStgMedium):HRESULT; override; function CutOrCopyToClipboard: boolean; override; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; published property Files: TStrings read fFiles write SetFiles; //MappedNames is only needed if files need to be renamed during a drag op //eg dragging from 'Recycle Bin'. property MappedNames: TStrings read fMappedNames write SetMappedNames; end; procedure Register; implementation uses Windows, ShlObj, SysUtils, ClipBrd; procedure Register; begin RegisterComponents(DragDropComponentPalettePage, [TDropFileSourceX]); end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- constructor TDropFileSourceX.Create(aOwner: TComponent); begin inherited Create(aOwner); fFiles := TStringList.Create; fMappedNames := TStringList.Create; FFileClipboardFormat := TFileClipboardFormat.Create; FPIDLClipboardFormat := TPIDLClipboardFormat.Create; FPreferredDropEffectClipboardFormat := TPreferredDropEffectClipboardFormat.Create; FFilenameMapClipboardFormat := TFilenameMapClipboardFormat.Create; FFilenameMapWClipboardFormat := TFilenameMapWClipboardFormat.Create; AddFormatEtc(FFileClipboardFormat.GetClipboardFormat, NIL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL); AddFormatEtc(FPIDLClipboardFormat.GetClipboardFormat, NIL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL); AddFormatEtc(FPreferredDropEffectClipboardFormat.GetClipboardFormat, NIL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL); AddFormatEtc(FFilenameMapClipboardFormat.GetClipboardFormat, NIL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL); AddFormatEtc(FFilenameMapWClipboardFormat.GetClipboardFormat, NIL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL); end; // ----------------------------------------------------------------------------- destructor TDropFileSourceX.destroy; begin FFileClipboardFormat.Free; FPIDLClipboardFormat.Free; FPreferredDropEffectClipboardFormat.Free; FFilenameMapClipboardFormat.Free; FFilenameMapWClipboardFormat.Free; fFiles.Free; fMappedNames.free; inherited Destroy; end; // ----------------------------------------------------------------------------- procedure TDropFileSourceX.SetFiles(files: TStrings); begin fFiles.assign(files); end; // ----------------------------------------------------------------------------- procedure TDropFileSourceX.SetMappedNames(names: TStrings); begin fMappedNames.assign(names); end; // ----------------------------------------------------------------------------- function TDropFileSourceX.CutOrCopyToClipboard: boolean; var FormatEtcIn: TFormatEtc; Medium: TStgMedium; begin FormatEtcIn.cfFormat := CF_HDROP; FormatEtcIn.dwAspect := DVASPECT_CONTENT; FormatEtcIn.tymed := TYMED_HGLOBAL; if (Files.count = 0) then result := false else if GetData(formatetcIn,Medium) = S_OK then begin Clipboard.SetAsHandle(CF_HDROP,Medium.hGlobal); result := true; end else result := false; end; // ----------------------------------------------------------------------------- function TDropFileSourceX.DoGetData(const FormatEtcIn: TFormatEtc; out Medium: TStgMedium):HRESULT; begin Medium.tymed := 0; Medium.UnkForRelease := NIL; Medium.hGlobal := 0; result := E_UNEXPECTED; if fFiles.count = 0 then exit; //-------------------------------------------------------------------------- if FFileClipboardFormat.AcceptFormat(FormatEtcIn) then begin FFileClipboardFormat.Files.Assign(FFiles); if FFileClipboardFormat.SetDataToMedium(FormatEtcIn, Medium) then result := S_OK; end else //-------------------------------------------------------------------------- if FFilenameMapClipboardFormat.AcceptFormat(FormatEtcIn) then begin FFilenameMapClipboardFormat.FileMaps.Assign(fMappedNames); if FFilenameMapClipboardFormat.SetDataToMedium(FormatEtcIn, Medium) then result := S_OK; end else //-------------------------------------------------------------------------- if FFilenameMapWClipboardFormat.AcceptFormat(FormatEtcIn) then begin FFilenameMapWClipboardFormat.FileMaps.Assign(fMappedNames); if FFilenameMapWClipboardFormat.SetDataToMedium(FormatEtcIn, Medium) then result := S_OK; end else //-------------------------------------------------------------------------- if FPIDLClipboardFormat.AcceptFormat(FormatEtcIn) then begin FPIDLClipboardFormat.Filenames.Assign(FFiles); if FPIDLClipboardFormat.SetDataToMedium(FormatEtcIn, Medium) then result := S_OK; end else //-------------------------------------------------------------------------- //This next format does not work for Win95 but should for Win98, WinNT ... //It stops the shell from prompting (with a popup menu) for the choice of //Copy/Move/Shortcut when performing a file 'Shortcut' onto Desktop or Explorer. if FPreferredDropEffectClipboardFormat.AcceptFormat(FormatEtcIn) then begin FPreferredDropEffectClipboardFormat.Value := FeedbackEffect; if FPreferredDropEffectClipboardFormat.SetDataToMedium(FormatEtcIn, Medium) then result := S_OK; end else result := DV_E_FORMATETC; end; end.
{ *********************************************************************** } { } { Delphi / Kylix Cross-Platform Runtime Library } { } { Copyright (c) 1995-2001 Borland Software Corporation } { } { *********************************************************************** } unit ShareMem; interface {$IFDEF MEMORY_DIAG} type TBlockEnumProc = function (Block: Pointer): Boolean; {$ENDIF} function SysGetMem(Size: Integer): Pointer; function SysFreeMem(P: Pointer): Integer; function SysReallocMem(P: Pointer; Size: Integer): Pointer; function GetHeapStatus: THeapStatus; function GetAllocMemCount: Integer; function GetAllocMemSize: Integer; procedure DumpBlocks; {$IFDEF MEMORY_DIAG} function InitBlockMarking: Boolean; function MarkBlocks: Integer; function GetMarkedBlocks(MarkID: Integer; Proc: TBlockEnumProc): Boolean; {$ENDIF} implementation {$IFDEF GLOBALALLOC} uses Windows; {$ENDIF} {$IFDEF MEMORY_DIAG} type TInitBlockMarking = function: Boolean; TMarkBlocks = function: Integer; TGetMarkedBlocks = function (MarkID: Integer; Proc: TBlockEnumProc): Boolean; var MMHandle: Integer = 0; SysInitBlockMarking: TInitBlockMarking = nil; SysMarkBlocks: TMarkBlocks = nil; SysGetMarkedBlocks: TGetMarkedBlocks = nil; {$ENDIF} const DelphiMM = 'borlndmm.dll'; function SysGetMem(Size: Integer): Pointer; external DelphiMM name '@Borlndmm@SysGetMem$qqri'; function SysFreeMem(P: Pointer): Integer; external DelphiMM name '@Borlndmm@SysFreeMem$qqrpv'; function SysReallocMem(P: Pointer; Size: Integer): Pointer; external DelphiMM name '@Borlndmm@SysReallocMem$qqrpvi'; function GetHeapStatus: THeapStatus; external DelphiMM; function GetAllocMemCount: Integer; external DelphiMM; function GetAllocMemSize: Integer; external DelphiMM; procedure DumpBlocks; external DelphiMM; function GetModuleHandle(lpModuleName: PChar): Integer; stdcall; external 'kernel32.dll' name 'GetModuleHandleA'; function GetProcAddress(hModule: Integer; lpProcName: PChar): Pointer; stdcall; external 'kernel32.dll' name 'GetProcAddress'; {$IFDEF MEMORY_DIAG} procedure InitMMHandle; begin if MMHandle = 0 then MMHandle := GetModuleHandle(DelphiMM); end; function InitBlockMarking: Boolean; begin InitMMHandle; if @SysInitBlockMarking = nil then @SysInitBlockMarking := GetProcAddress(MMHandle, 'InitBlockMarking'); if @SysInitBlockMarking <> nil then Result := SysInitBlockMarking else Result := False; end; function MarkBlocks: Integer; begin InitMMHandle; if @SysMarkBlocks = nil then @SysMarkBlocks := GetProcAddress(MMHandle, 'MarkBlocks'); if @SysMarkBlocks <> nil then Result := SysMarkBlocks else Result := -1; end; function GetMarkedBlocks(MarkID: Integer; Proc: TBlockEnumProc): Boolean; begin InitMMHandle; if @SysGetMarkedBlocks = nil then @SysGetMarkedBlocks := GetProcAddress(MMHandle, 'GetMarkedBlocks'); if @SysGetMarkedBlocks <> nil then Result := SysGetMarkedBlocks(MarkID, Proc) else Result := False; end; {$ENDIF} {$IFDEF GLOBALALLOC} function xSysGetMem(Size: Integer): Pointer; begin Result := GlobalAllocPtr(HeapAllocFlags, Size); end; function xSysFreeMem(P: Pointer): Integer; begin Result := GlobalFreePtr(P); end; function xSysReallocMem(P: Pointer; Size: Integer): Pointer; begin Result := GlobalReallocPtr(P, Size, 0); end; {$ENDIF} procedure InitMemoryManager; var SharedMemoryManager: TMemoryManager; MM: Integer; begin // force a static reference to borlndmm.dll, so we don't have to LoadLibrary SharedMemoryManager.GetMem := SysGetMem; MM := GetModuleHandle(DelphiMM); {$IFDEF GLOBALALLOC} SharedMemoryManager.GetMem := xSysGetMem; SharedMemoryManager.FreeMem := xSysFreeMem; SharedMemoryManager.ReallocMem := xSysReallocMem; {$ELSE} SharedMemoryManager.GetMem := GetProcAddress(MM,'@Borlndmm@SysGetMem$qqri'); SharedMemoryManager.FreeMem := GetProcAddress(MM,'@Borlndmm@SysFreeMem$qqrpv'); SharedMemoryManager.ReallocMem := GetProcAddress(MM, '@Borlndmm@SysReallocMem$qqrpvi'); {$ENDIF} SetMemoryManager(SharedMemoryManager); end; initialization if not IsMemoryManagerSet then InitMemoryManager; end.
unit nested_procs; interface var G1: Int32; G2: Int32; procedure Test; export; implementation procedure Test; function GetValue: Int32; begin Result := 11; end; procedure SetValue(V: Int32); begin G2 := V; end; begin G1 := GetValue(); SetValue(12); end; initialization Test(); finalization Assert(G1 = 11); Assert(G2 = 12); end.
unit u_J16SlopeCalibrateMeasureImp; interface uses Classes, SysUtils, u_ExamineImp, u_J08TaskIntf, u_J08Task, u_J16CommonDef; type TSlopeCalibrateMeasure = Class(TCustomExamineItem) Private Procedure InternalCheck(const Value: Boolean; const ExceptionInfo: String); Protected Procedure Init; Override; Procedure DoProcess; Override; Public End; implementation uses u_GPIB_DEV2, u_J16Receiver, u_ExamineGlobal, u_J08WeakGlobal, PlumUtils, u_J16Utils, u_CommonDef; { TSlopeCalibrateMeasure } procedure TSlopeCalibrateMeasure.DoProcess; const CONST_MODULS: Array[0..1] of TJ08_ModuType = (mtAM, mtFM); CONST_MODULS_FREQS: Array[0..1] of Integer = (15000, 98000); CONST_AMP_STATES: Array[0..2] of TJ08_DevManualMode = (dmmAttent, dmmDirect, dmmAmpli ); CONST_LEVELS_PER_MODE: Array[0..2] of Array[0..1] of Integer = ( (-10, -30), (-30, -60), (-60, -90) ); CONST_YXRATIO: array[0..1] of Double = (9.2, 480.00); var SG: ISignalGenerator; Radio: IJ08Receiver; Calibrator: ISlopeCalibrate; bid, pid, sid: integer; i, j, k, m: Integer; SampledLevels: Array[0..1] of Array[0..2] of Array[0..1] of Single; CoeffSrc: Array[0..1] of TSlopCoffRecArray; ReadBackCoff: TCoffReport; Coffs2Write: Array of TCoffs; Procedure _Load_Coffs2Write_FromCoeffSrc(); var i: Integer; begin SetLength(Coffs2Write, Length(CoeffSrc)); for i := 0 to Length(CoeffSrc) - 1 do begin Coffs2Write[i, 0, 0]:= CoeffSrc[i, 2].PrimaryCoeff; Coffs2Write[i, 0, 1]:= CoeffSrc[i, 2].ConstantTerm; Coffs2Write[i, 1, 0]:= CoeffSrc[i, 1].PrimaryCoeff; Coffs2Write[i, 1, 1]:= CoeffSrc[i, 1].ConstantTerm; Coffs2Write[i, 2, 0]:= CoeffSrc[i, 0].PrimaryCoeff; Coffs2Write[i, 2, 1]:= CoeffSrc[i, 0].ConstantTerm; end; end; Function _CompareCoffs(const V1: TCoffs; const V2: TCoffs): Boolean; var i, j: Integer; begin Result:= True; for i := 0 to Length(V1) - 1 do begin for j := 0 to Length(V1[i]) - 1 do begin if V1[i, j] <> V2[i, j] then begin Result:= False; Log(Format(' 比较失败: %.8f <> %.8f', [V1[i, j], V2[i, j]])); Break; end; end; if Not Result then Break; end; end; var CurrStep, TotalStep: Integer; InsLost: Double; LevelRead: Double; StableDelay: Integer; begin // inherited; CurrStep:= 0; TotalStep:= 15; Log('-----------准备进行斜率校准------------'); // Inc(CurrStep); // FUI.set_Percent((CurrStep / TotalStep) * 100); // CheckWishStop(); // FUI.set_Percent((CurrStep / TotalStep) * 100); //------------------ //初始化设备 //------------------ get_UI.SyncUI(@StableDelay); Radio:= TJ16Receiver.Create; Calibrator:= Radio as ISlopeCalibrate; try {$IFNDEF Debug_Emu} SG:= TMG36XX.Create; With SG do begin pid:= 3; Iden:= 'SG'; LoadInstrumentParam(bid, pid, sid); Connnect(bid, pid, sid); end; if not Radio.ReceiverTrunedOn then Radio.OpenReceiver; // WaitMS(100000); Calibrator.SetCoeffValid(False); Calibrator.LevelDataFormat(0); {$ENDIF} InsLost:= FUI.ExamineItem.InlineInsertLost; Log('打开接收机,并设置为上报原始数据'); //------------------- //AM斜率测试 //------------------- // //打开信号源,设置为15M, -60dB 单音 // Log('信号源输出 15MHz'); // SetLength(CoeffSrc[0], 3); SetLength(CoeffSrc[1], 3); //AM测试条件 CoeffSrc[0, 0].AX := -10; CoeffSrc[0, 0].BX := -30; CoeffSrc[0, 0].AYWish := -60; CoeffSrc[0, 0].BYWish := -244; CoeffSrc[0, 1].AX := -30; CoeffSrc[0, 1].BX := -60; CoeffSrc[0, 1].AYWish:= -244; CoeffSrc[0, 1].BYWish:= -520; CoeffSrc[0, 2].AX := -60; CoeffSrc[0, 2].BX := -90; CoeffSrc[0, 2].AYWish:= -520; CoeffSrc[0, 2].BYWish:= -796; //FM测试条件 CoeffSrc[1, 0].AX := -10; CoeffSrc[1, 0].BX := -30; CoeffSrc[1, 0].AYWish := 20000; CoeffSrc[1, 0].BYWish := 10400; CoeffSrc[1, 1].AX := -30; CoeffSrc[1, 1].BX := -60; CoeffSrc[1, 1].AYWish:= 10400; CoeffSrc[1, 1].BYWish:= -4000; CoeffSrc[1, 2].AX := -60; CoeffSrc[1, 2].BX := -90; CoeffSrc[1, 2].AYWish:= -4000; CoeffSrc[1, 2].BYWish:= -18400; {$IFDEF DEBUG_EMU} SampledLevels[0, 0, 0]:= -85; SampledLevels[0, 0, 1]:= -275; SampledLevels[0, 1, 0]:= -38; SampledLevels[0, 1, 1]:= -391; SampledLevels[0, 2, 0]:= -102; SampledLevels[0, 2, 1]:= -385; SampledLevels[1, 0, 0]:= 9004; SampledLevels[1, 0, 1]:= -763; SampledLevels[1, 1, 0]:= 11219; SampledLevels[1, 1, 1]:= -3015; SampledLevels[1, 2, 0]:= 8748; SampledLevels[1, 2, 1]:= -5783; {$ENDIF} //读取电平值并计算 for i:= 0 to Length(CONST_MODULS) - 1 do begin {$IFNDEF Debug_Emu} SG.SetFreqency(CONST_MODULS_FREQS[i] / 1000); SG.SetOnOff(True); {$ENDIF} Log(Format('信号源输出 %.0fMHz', [CONST_MODULS_FREQS[i] / 1000])); WaitMS(200); {$IFNDEF Debug_Emu} InternalCheck(Radio.SetFrequency(CONST_MODULS[i], CONST_MODULS_FREQS[i] * 1000), '设置频率失败'); {$ENDIF} Log(Format('接收机设置: %s %d KHz', [CONST_STR_MODUL[CONST_MODULS[i]], CONST_MODULS_FREQS[i] ])); for j := 0 to Length(CONST_AMP_STATES) - 1 do begin {$IFNDEF Debug_Emu} InternalCheck(Radio.SetHiGain(damManual, CONST_AMP_STATES[j]), '设置手动增益模式失败'); {$ENDIF} if CONST_AMP_STATES[j] = dmmAttent then WaitMS(500); Log(Format('------%s------', [CONST_STR_DEVMANUALMODE[CONST_AMP_STATES[j]]])); for k := 0 to Length(CONST_LEVELS_PER_MODE[j]) - 1 do begin {$IFNDEF Debug_Emu} SG.SetLevelDbm(CONST_LEVELS_PER_MODE[j, k] + InsLost); {$ENDIF} WaitMS(StableDelay); if (CONST_MODULS[i]) = mtFM then WaitMS(1000); {$IFDEF DEBUG} //InternalCheck(Radio.ReadLevel(SampledLevels[i, j, k], mtAM, L_DummyHint), '读取电平值失败'); //使用预置数模拟 {$ELSE} InternalCheck(Radio.ReadLevel(LevelRead, CONST_MODULS[i]), '读取电平值失败'); SampledLevels[i, j, k]:= LevelRead; {$ENDIF} // Log(Format('信号源电平设置: %d dBm', [])); Log(Format(' %5.0f @ %3d dBm', [SampledLevels[i, j, k], CONST_LEVELS_PER_MODE[j, k]])); if k = 0 then begin CoeffSrc[i, j].AX:= CONST_LEVELS_PER_MODE[j, k]; CoeffSrc[i, j].AY:= SampledLevels[i, j, k]; end else begin CoeffSrc[i, j].BX:= CONST_LEVELS_PER_MODE[j, k]; CoeffSrc[i, j].BY:= SampledLevels[i, j, k]; end; Inc(CurrStep); FUI.set_Percent((CurrStep / TotalStep) * 100); CheckWishStop(); end; end; end; //curr step count value should be 12 now //计算系数 for i:= 0 to Length(CoeffSrc) - 1 do begin CalcuSlopeCoff(CoeffSrc[i], CONST_YXRATIO[i]); Log('计算系数完成:' ); for m := 0 to Length(CoeffSrc[i]) - 1 do begin Log(Format(' [%d] :%.8f, %.8f', [m + 1, CoeffSrc[i, m].PrimaryCoeff, CoeffSrc[i, m].ConstantTerm])); end; end; Inc(CurrStep); FUI.set_Percent((CurrStep / TotalStep) * 100); //curr step count value should be 13 CheckWishStop(); //写入接收机,校验成功后存储 _Load_Coffs2Write_FromCoeffSrc(); // Calibrator.SetAMCoeff(CoeffSrc[0, 2].PrimaryCoeff, CoeffSrc[0, 2].ConstantTerm, // CoeffSrc[0, 1].PrimaryCoeff, CoeffSrc[0, 1].ConstantTerm, // CoeffSrc[0, 0].PrimaryCoeff, CoeffSrc[0, 0].ConstantTerm ); // WaitMS(50); // Calibrator.SetFMCoeff(CoeffSrc[1, 2].PrimaryCoeff, CoeffSrc[1, 2].ConstantTerm, // CoeffSrc[1, 1].PrimaryCoeff, CoeffSrc[1, 1].ConstantTerm, // CoeffSrc[1, 0].PrimaryCoeff, CoeffSrc[1, 0].ConstantTerm ); // WaitMS(50); Calibrator.SetAMCoeff2( Coffs2Write[0] ); WaitMS(50); Calibrator.SetFMCoeff2( Coffs2Write[1] ); WaitMS(50); Calibrator.SetCoeffValid(True); WaitMS(10); Calibrator.LevelDataFormat(1); WaitMS(100); Log('设置系数完成,准备校验....'); if Calibrator.QueryCoeffInfo(ReadBackCoff) then begin Log('校验AM写入数据...'); if Not _CompareCoffs(Coffs2Write[0], ReadBackCoff.AMCoff) then begin {$IFNDEF Debug_Emu} Raise Exception.Create('AM数据校验不正确'); {$ENDIF} end; Log('校验FM写入数据...'); if Not _CompareCoffs(Coffs2Write[1], ReadBackCoff.FMCoff) then begin {$IFNDEF Debug_Emu} Raise Exception.Create('FM数据校验不正确'); {$ENDIF} end; Log('校验完成'); Calibrator.WriteToE2PROM; WaitMS(100); Log('写入完成'); Inc(CurrStep); FUI.set_Percent((CurrStep / TotalStep) * 100); CheckWishStop(); end else begin Raise Exception.Create('从接收机读取数据失败, 校准中断'); end; Inc(CurrStep); FUI.set_Percent((CurrStep / TotalStep) * 100); //curr step count value should be 13 CheckWishStop(); finally Set_Status(esComplete); end; end; procedure TSlopeCalibrateMeasure.Init; begin inherited; FExamineCaption:= '斜率校准'; // FExamineCaption:= '一本振'; // ExtractFileFromRes('LIB_INOUT32', 'inpout32.dll'); // ExtractFileFromRes('LIB_ELEXS', 'ELEXS.dll'); // ExtractFileFromRes('EXE_LO1', '一本振.exe'); end; procedure TSlopeCalibrateMeasure.InternalCheck(const Value: Boolean; const ExceptionInfo: String); begin if Not Value then Raise Exception.Create(ExceptionInfo); end; end.
unit ncaDocEdit; interface uses sysutils, classes, cxEdit, cxButtonEdit; type TncDocEdit = class ( TcxButtonEdit ) private FTipoDoc : Byte; FIDDoc : String; FOnAlterou : TNotifyEvent; procedure SetIDDoc(const Value: String); public constructor Create(AOwner: TComponent); override; procedure ButtonClick(Sender: TObject; AButtonIndex: Integer); published property OnAlterou: TNotifyEvent read FOnAlterou write FOnAlterou; property Tipo: Byte read FTipoDoc write FTipoDoc; property IDDoc : String read FIDDoc write SetIDDoc; end; TncBaseDocEditHelper = class function ObtemNome(aDocID: String): String; virtual; abstract; function RunDocMgr(aDocEdit: TncDocEdit): Boolean; virtual; abstract; end; procedure Register; var gDocEditHelper : TncBaseDocEditHelper; implementation { TncDocEdit } procedure TncDocEdit.ButtonClick(Sender: TObject; AButtonIndex: Integer); var SID: String; begin if Assigned(gDocEditHelper) then begin SID := FIDDoc; gDocEditHelper.RunDocMgr(Self); if Assigned(FOnAlterou) and (FIDDOC <> SID) then FOnAlterou(Self); end; end; constructor TncDocEdit.Create(AOwner: TComponent); begin inherited; FTipoDoc := 0; FIDDoc := ''; FOnAlterou := nil; Properties.Buttons[0].Kind := bkDown; Properties.OnButtonClick := ButtonClick; end; procedure TncDocEdit.SetIDDoc(const Value: String); begin FIDDoc := Value; if FIDDoc>'' then begin if Assigned(gDocEditHelper) then begin Text := gDocEditHelper.ObtemNome(FIDDoc); if Trim(Text)='' then FIDDoc := ''; end; end else Text := ''; // Properties.Buttons[0].Caption := Text; end; procedure Register; begin RegisterComponents('NEX', [TncDocEdit]); // do not localize end; initialization gDocEditHelper := nil; finalization if Assigned(gDocEditHelper) then FreeAndNil(gDocEditHelper); end.
unit PanelImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ExtCtrls; type TPanelX = class(TActiveXControl, IPanelX) private { Private declarations } FDelphiControl: TPanel; FEvents: IPanelXEvents; procedure CanResizeEvent(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); procedure ClickEvent(Sender: TObject); procedure ConstrainedResizeEvent(Sender: TObject; var MinWidth, MinHeight, MaxWidth, MaxHeight: Integer); procedure DblClickEvent(Sender: TObject); procedure ResizeEvent(Sender: TObject); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_Alignment: TxAlignment; safecall; function Get_AutoSize: WordBool; safecall; function Get_BevelInner: TxBevelCut; safecall; function Get_BevelOuter: TxBevelCut; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_BorderStyle: TxBorderStyle; safecall; function Get_Caption: WideString; safecall; function Get_Color: OLE_COLOR; safecall; function Get_Ctl3D: WordBool; safecall; function Get_Cursor: Smallint; safecall; function Get_DockSite: WordBool; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_Font: IFontDisp; safecall; function Get_FullRepaint: WordBool; safecall; function Get_Locked: WordBool; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_UseDockManager: WordBool; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_Alignment(Value: TxAlignment); safecall; procedure Set_AutoSize(Value: WordBool); safecall; procedure Set_BevelInner(Value: TxBevelCut); safecall; procedure Set_BevelOuter(Value: TxBevelCut); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_BorderStyle(Value: TxBorderStyle); safecall; procedure Set_Caption(const Value: WideString); safecall; procedure Set_Color(Value: OLE_COLOR); safecall; procedure Set_Ctl3D(Value: WordBool); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DockSite(Value: WordBool); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_FullRepaint(Value: WordBool); safecall; procedure Set_Locked(Value: WordBool); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_UseDockManager(Value: WordBool); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation uses ComObj, About22; { TPanelX } procedure TPanelX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_PanelXPage); } end; procedure TPanelX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IPanelXEvents; end; procedure TPanelX.InitializeControl; begin FDelphiControl := Control as TPanel; FDelphiControl.OnCanResize := CanResizeEvent; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnConstrainedResize := ConstrainedResizeEvent; FDelphiControl.OnDblClick := DblClickEvent; FDelphiControl.OnResize := ResizeEvent; end; function TPanelX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TPanelX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TPanelX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TPanelX.Get_Alignment: TxAlignment; begin Result := Ord(FDelphiControl.Alignment); end; function TPanelX.Get_AutoSize: WordBool; begin Result := FDelphiControl.AutoSize; end; function TPanelX.Get_BevelInner: TxBevelCut; begin Result := Ord(FDelphiControl.BevelInner); end; function TPanelX.Get_BevelOuter: TxBevelCut; begin Result := Ord(FDelphiControl.BevelOuter); end; function TPanelX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TPanelX.Get_BorderStyle: TxBorderStyle; begin Result := Ord(FDelphiControl.BorderStyle); end; function TPanelX.Get_Caption: WideString; begin Result := WideString(FDelphiControl.Caption); end; function TPanelX.Get_Color: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.Color); end; function TPanelX.Get_Ctl3D: WordBool; begin Result := FDelphiControl.Ctl3D; end; function TPanelX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TPanelX.Get_DockSite: WordBool; begin Result := FDelphiControl.DockSite; end; function TPanelX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TPanelX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TPanelX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TPanelX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TPanelX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TPanelX.Get_FullRepaint: WordBool; begin Result := FDelphiControl.FullRepaint; end; function TPanelX.Get_Locked: WordBool; begin Result := FDelphiControl.Locked; end; function TPanelX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TPanelX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TPanelX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TPanelX.Get_UseDockManager: WordBool; begin Result := FDelphiControl.UseDockManager; end; function TPanelX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TPanelX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TPanelX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TPanelX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TPanelX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TPanelX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TPanelX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TPanelX.AboutBox; begin ShowPanelXAbout; end; procedure TPanelX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TPanelX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TPanelX.Set_Alignment(Value: TxAlignment); begin FDelphiControl.Alignment := TAlignment(Value); end; procedure TPanelX.Set_AutoSize(Value: WordBool); begin FDelphiControl.AutoSize := Value; end; procedure TPanelX.Set_BevelInner(Value: TxBevelCut); begin FDelphiControl.BevelInner := TBevelCut(Value); end; procedure TPanelX.Set_BevelOuter(Value: TxBevelCut); begin FDelphiControl.BevelOuter := TBevelCut(Value); end; procedure TPanelX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TPanelX.Set_BorderStyle(Value: TxBorderStyle); begin FDelphiControl.BorderStyle := TBorderStyle(Value); end; procedure TPanelX.Set_Caption(const Value: WideString); begin FDelphiControl.Caption := TCaption(Value); end; procedure TPanelX.Set_Color(Value: OLE_COLOR); begin FDelphiControl.Color := TColor(Value); end; procedure TPanelX.Set_Ctl3D(Value: WordBool); begin FDelphiControl.Ctl3D := Value; end; procedure TPanelX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TPanelX.Set_DockSite(Value: WordBool); begin FDelphiControl.DockSite := Value; end; procedure TPanelX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TPanelX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TPanelX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TPanelX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TPanelX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TPanelX.Set_FullRepaint(Value: WordBool); begin FDelphiControl.FullRepaint := Value; end; procedure TPanelX.Set_Locked(Value: WordBool); begin FDelphiControl.Locked := Value; end; procedure TPanelX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TPanelX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TPanelX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TPanelX.Set_UseDockManager(Value: WordBool); begin FDelphiControl.UseDockManager := Value; end; procedure TPanelX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TPanelX.CanResizeEvent(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); var TempNewWidth: Integer; TempNewHeight: Integer; TempResize: WordBool; begin TempNewWidth := Integer(NewWidth); TempNewHeight := Integer(NewHeight); TempResize := WordBool(Resize); if FEvents <> nil then FEvents.OnCanResize(TempNewWidth, TempNewHeight, TempResize); NewWidth := Integer(TempNewWidth); NewHeight := Integer(TempNewHeight); Resize := Boolean(TempResize); end; procedure TPanelX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TPanelX.ConstrainedResizeEvent(Sender: TObject; var MinWidth, MinHeight, MaxWidth, MaxHeight: Integer); var TempMinWidth: Integer; TempMinHeight: Integer; TempMaxWidth: Integer; TempMaxHeight: Integer; begin TempMinWidth := Integer(MinWidth); TempMinHeight := Integer(MinHeight); TempMaxWidth := Integer(MaxWidth); TempMaxHeight := Integer(MaxHeight); if FEvents <> nil then FEvents.OnConstrainedResize(TempMinWidth, TempMinHeight, TempMaxWidth, TempMaxHeight); MinWidth := Integer(TempMinWidth); MinHeight := Integer(TempMinHeight); MaxWidth := Integer(TempMaxWidth); MaxHeight := Integer(TempMaxHeight); end; procedure TPanelX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; procedure TPanelX.ResizeEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnResize; end; initialization TActiveXControlFactory.Create( ComServer, TPanelX, TPanel, Class_PanelX, 22, '{695CDB82-02E5-11D2-B20D-00C04FA368D4}', OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL, tmApartment); end.